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
What's the easiest way to escape HTML in Python?
1,061,697
<p>cgi.escape seems like one possible choice. Does it work well? Is there something that is considered better?</p>
93
2009-06-30T04:15:54Z
33,940,254
<p>There is also the excellent <a href="https://github.com/mitsuhiko/markupsafe" rel="nofollow">markupsafe package</a>.</p> <pre><code>&gt;&gt;&gt; from markupsafe import Markup, escape &gt;&gt;&gt; escape("&lt;script&gt;alert(document.cookie);&lt;/script&gt;") Markup(u'&amp;lt;script&amp;gt;alert(document.cookie);&amp;lt;/script&amp;gt;') </code></pre> <p>The <code>markupsafe</code> package is well engineered, and probably the most versatile and Pythonic way to go about escaping, IMHO, because:</p> <ol> <li>the return (<code>Markup</code>) is a class derived from unicode (i.e. <code>isinstance(escape('str'), unicode) == True</code></li> <li>it properly handles unicode input</li> <li>it works in Python (2.6, 2.7, 3.3, and pypy)</li> <li>it respects custom methods of objects (i.e. objects with a <code>__html__</code> property) and template overloads (<code>__html_format__</code>).</li> </ol>
2
2015-11-26T13:43:50Z
[ "python", "html" ]
Django with system timezone setting vs user's individual timezones
1,061,911
<p>How well does Django handle the case of different timezones for each user? Ideally I would like to run the server in the UTC timezone (eg, in settings.py set TIME_ZONE="UTC") so all datetimes were stored in the database as UTC. Stuff like <a href="http://stackoverflow.com/questions/689831/changing-timezone-on-an-existing-django-project">this</a> scares me which is why I prefer UTC everywhere.</p> <p>But how hard will it be to store a timezone for each user and still use the standard django datetime formatting and modelform wrappers. Do I anticipate having to write date handling code everywhere to convert dates into the user's timezone and back to UTC again?</p> <p>I am still going through the django tutorial but I know how much of a pain it can be to deal with user timezones in some other frameworks that assume system timezone everywhere so I thought I'd ask now.</p> <p>My research at the moment consisted of searching the django documentation and only finding <a href="http://docs.djangoproject.com/en/dev/ref/settings/#time-zone">one reference</a> to timezones.</p> <hr> <p>Additional: </p> <ul> <li>There are a <a href="http://code.djangoproject.com/ticket/2626">few bugs submitted</a> concerning Django and timezone handling.</li> <li>Babel has <a href="http://svn.edgewall.org/repos/babel/contrib/django/">some contrib code for django</a> that seems to deal with timezone formatting in locales.</li> </ul>
15
2009-06-30T05:45:08Z
1,061,921
<p>You could start by taking a look at the <a href="http://code.google.com/p/django-timezones/" rel="nofollow">django-timezones</a> application. It makes available a number of timezone-based model fields (and their corresponding form fields, and some decorators), which you could use to at least <em>store</em> different timezone values per user (if nothing else). </p>
1
2009-06-30T05:50:47Z
[ "python", "django", "timezone" ]
Django with system timezone setting vs user's individual timezones
1,061,911
<p>How well does Django handle the case of different timezones for each user? Ideally I would like to run the server in the UTC timezone (eg, in settings.py set TIME_ZONE="UTC") so all datetimes were stored in the database as UTC. Stuff like <a href="http://stackoverflow.com/questions/689831/changing-timezone-on-an-existing-django-project">this</a> scares me which is why I prefer UTC everywhere.</p> <p>But how hard will it be to store a timezone for each user and still use the standard django datetime formatting and modelform wrappers. Do I anticipate having to write date handling code everywhere to convert dates into the user's timezone and back to UTC again?</p> <p>I am still going through the django tutorial but I know how much of a pain it can be to deal with user timezones in some other frameworks that assume system timezone everywhere so I thought I'd ask now.</p> <p>My research at the moment consisted of searching the django documentation and only finding <a href="http://docs.djangoproject.com/en/dev/ref/settings/#time-zone">one reference</a> to timezones.</p> <hr> <p>Additional: </p> <ul> <li>There are a <a href="http://code.djangoproject.com/ticket/2626">few bugs submitted</a> concerning Django and timezone handling.</li> <li>Babel has <a href="http://svn.edgewall.org/repos/babel/contrib/django/">some contrib code for django</a> that seems to deal with timezone formatting in locales.</li> </ul>
15
2009-06-30T05:45:08Z
1,061,967
<p>Not a Django expert here, but afaik Django has no magic, and I can't even imagine any such magic that would work. </p> <p>For example: you don't always want to save times in UTC. In a calendar application, for example, you want to save the datetime in the local time that the calendar event happens. Which can be different both from the servers and the users time zone. So having code that automatically converts every selected datetime to the servers time zone would be a Very Bad Thing.</p> <p>So yes, you will have to handle this yourself. I'd recommend to store the time zone for everything, and of course run the server in UTC, and let all the datetimes generated by the application use UTC, and then convert them to the users time zone when displaying. It's not difficult, just annoying to remember. when it comes to datetimes that are inputted by the user, it's dependant on the application if you should convert to UTC or not. I would as a general recommendation not convert to UTC but save in the users time zone, with the information of which time zone that is.</p> <p>Yes, time zones is a big problem. I've written a couple of blog posts on the annoying issue, like here: <a href="http://regebro.wordpress.com/2007/12/18/python-and-time-zones-fighting-the-beast/" rel="nofollow">http://regebro.wordpress.com/2007/12/18/python-and-time-zones-fighting-the-beast/</a></p> <p>In the end you will have to take care of time zone issues yourself, because there is no real correct answer to most of the issues. </p>
2
2009-06-30T06:02:52Z
[ "python", "django", "timezone" ]
Django with system timezone setting vs user's individual timezones
1,061,911
<p>How well does Django handle the case of different timezones for each user? Ideally I would like to run the server in the UTC timezone (eg, in settings.py set TIME_ZONE="UTC") so all datetimes were stored in the database as UTC. Stuff like <a href="http://stackoverflow.com/questions/689831/changing-timezone-on-an-existing-django-project">this</a> scares me which is why I prefer UTC everywhere.</p> <p>But how hard will it be to store a timezone for each user and still use the standard django datetime formatting and modelform wrappers. Do I anticipate having to write date handling code everywhere to convert dates into the user's timezone and back to UTC again?</p> <p>I am still going through the django tutorial but I know how much of a pain it can be to deal with user timezones in some other frameworks that assume system timezone everywhere so I thought I'd ask now.</p> <p>My research at the moment consisted of searching the django documentation and only finding <a href="http://docs.djangoproject.com/en/dev/ref/settings/#time-zone">one reference</a> to timezones.</p> <hr> <p>Additional: </p> <ul> <li>There are a <a href="http://code.djangoproject.com/ticket/2626">few bugs submitted</a> concerning Django and timezone handling.</li> <li>Babel has <a href="http://svn.edgewall.org/repos/babel/contrib/django/">some contrib code for django</a> that seems to deal with timezone formatting in locales.</li> </ul>
15
2009-06-30T05:45:08Z
1,064,928
<p><strong>Update, January 2013</strong>: Django 1.4 now has <a href="https://docs.djangoproject.com/en/1.4/topics/i18n/timezones/" rel="nofollow">time zone support</a>!!</p> <hr> <p>Old answer for historical reasons:</p> <p>I'm going to be working on this problem myself for my application. My first approach to this problem would be to go with django core developer Malcom Tredinnick's advice in <a href="http://groups.google.com/group/django-users/msg/ee174701c960ff2d" rel="nofollow">this django-user's post</a>. You'll want to store the user's timezone setting in their user profile, probably.</p> <p>I would also highly encourage you to look into the <a href="http://pytz.sourceforge.net/" rel="nofollow">pytz module</a>, which makes working with timezones less painful. For the front end, I created a "timezone picker" based on the common timezones in pytz. I have one select box for the area, and another for the location (e.g. US/Central is rendered with two select boxes). It makes picking timezones slightly more convenient than wading through a list of 400+ choices.</p>
7
2009-06-30T17:24:47Z
[ "python", "django", "timezone" ]
Django with system timezone setting vs user's individual timezones
1,061,911
<p>How well does Django handle the case of different timezones for each user? Ideally I would like to run the server in the UTC timezone (eg, in settings.py set TIME_ZONE="UTC") so all datetimes were stored in the database as UTC. Stuff like <a href="http://stackoverflow.com/questions/689831/changing-timezone-on-an-existing-django-project">this</a> scares me which is why I prefer UTC everywhere.</p> <p>But how hard will it be to store a timezone for each user and still use the standard django datetime formatting and modelform wrappers. Do I anticipate having to write date handling code everywhere to convert dates into the user's timezone and back to UTC again?</p> <p>I am still going through the django tutorial but I know how much of a pain it can be to deal with user timezones in some other frameworks that assume system timezone everywhere so I thought I'd ask now.</p> <p>My research at the moment consisted of searching the django documentation and only finding <a href="http://docs.djangoproject.com/en/dev/ref/settings/#time-zone">one reference</a> to timezones.</p> <hr> <p>Additional: </p> <ul> <li>There are a <a href="http://code.djangoproject.com/ticket/2626">few bugs submitted</a> concerning Django and timezone handling.</li> <li>Babel has <a href="http://svn.edgewall.org/repos/babel/contrib/django/">some contrib code for django</a> that seems to deal with timezone formatting in locales.</li> </ul>
15
2009-06-30T05:45:08Z
4,719,790
<p>Looking at the <a href="https://github.com/brosner/django-timezones" rel="nofollow">django-timezones</a> application I found that it doesn't support MySQL DBMS, since MySQL doesn't store any timezone reference within datetimes.</p> <p>Well, I think I manage to work around this by forking the <a href="https://github.com/brosner/django-timezones" rel="nofollow">Brosner library</a> and modifying it to work transparently within your models.</p> <p>There, I'm doing the same thing the django translation system do, so you can get user unique timezone conversion. There you should find a Field class and some datetime utils to always get datetimes converted to the user timezone. So everytime you make a request and do a query, everything will be timezoned.</p> <p><a href="https://github.com/FernandoEscher/django-timezones" rel="nofollow">Give it a try!</a></p>
1
2011-01-18T01:52:20Z
[ "python", "django", "timezone" ]
Django with system timezone setting vs user's individual timezones
1,061,911
<p>How well does Django handle the case of different timezones for each user? Ideally I would like to run the server in the UTC timezone (eg, in settings.py set TIME_ZONE="UTC") so all datetimes were stored in the database as UTC. Stuff like <a href="http://stackoverflow.com/questions/689831/changing-timezone-on-an-existing-django-project">this</a> scares me which is why I prefer UTC everywhere.</p> <p>But how hard will it be to store a timezone for each user and still use the standard django datetime formatting and modelform wrappers. Do I anticipate having to write date handling code everywhere to convert dates into the user's timezone and back to UTC again?</p> <p>I am still going through the django tutorial but I know how much of a pain it can be to deal with user timezones in some other frameworks that assume system timezone everywhere so I thought I'd ask now.</p> <p>My research at the moment consisted of searching the django documentation and only finding <a href="http://docs.djangoproject.com/en/dev/ref/settings/#time-zone">one reference</a> to timezones.</p> <hr> <p>Additional: </p> <ul> <li>There are a <a href="http://code.djangoproject.com/ticket/2626">few bugs submitted</a> concerning Django and timezone handling.</li> <li>Babel has <a href="http://svn.edgewall.org/repos/babel/contrib/django/">some contrib code for django</a> that seems to deal with timezone formatting in locales.</li> </ul>
15
2009-06-30T05:45:08Z
5,806,918
<p>It's not that hard to write timezone aware code in django:</p> <p>I've written simple django application which helps handle timezones issue in django projects: <a href="https://github.com/paluh/django-tz" rel="nofollow">https://github.com/paluh/django-tz</a>. It's based on Brosner (django-timezone) code but takes different approach to solve the problem - I think it implements something similar to yours and FernandoEscher propositions.</p> <p>All datetime values are stored in data base in one timezone (according to TIME_ZONE setting) and conversion to appropriate value (i.e. user timezone) are done in templates and forms (there is form widget for datetimes fields which contains additional subwidget with timezone). Every datetime conversion is explicit - no magic.</p> <p>Additionally there is per thread cache which allows you simplify these datatime conversions (implementation is based on django i18n translation machinery).</p> <p>When you want to remember user timezone, you should add timezone field to profile model and write simple middleware (follow the example from doc).</p>
4
2011-04-27T15:51:12Z
[ "python", "django", "timezone" ]
Django with system timezone setting vs user's individual timezones
1,061,911
<p>How well does Django handle the case of different timezones for each user? Ideally I would like to run the server in the UTC timezone (eg, in settings.py set TIME_ZONE="UTC") so all datetimes were stored in the database as UTC. Stuff like <a href="http://stackoverflow.com/questions/689831/changing-timezone-on-an-existing-django-project">this</a> scares me which is why I prefer UTC everywhere.</p> <p>But how hard will it be to store a timezone for each user and still use the standard django datetime formatting and modelform wrappers. Do I anticipate having to write date handling code everywhere to convert dates into the user's timezone and back to UTC again?</p> <p>I am still going through the django tutorial but I know how much of a pain it can be to deal with user timezones in some other frameworks that assume system timezone everywhere so I thought I'd ask now.</p> <p>My research at the moment consisted of searching the django documentation and only finding <a href="http://docs.djangoproject.com/en/dev/ref/settings/#time-zone">one reference</a> to timezones.</p> <hr> <p>Additional: </p> <ul> <li>There are a <a href="http://code.djangoproject.com/ticket/2626">few bugs submitted</a> concerning Django and timezone handling.</li> <li>Babel has <a href="http://svn.edgewall.org/repos/babel/contrib/django/">some contrib code for django</a> that seems to deal with timezone formatting in locales.</li> </ul>
15
2009-06-30T05:45:08Z
6,051,905
<p>Django doesn't handle it at all, largely because Python doesn't either. Python (Guido?) has so far decided not to support timezones since although a reality of the world are "<a href="http://docs.python.org/library/datetime.html#module-datetime" rel="nofollow">more political than rational, and there is no standard suitable for every application</a>."</p> <p>The best solution for most is to not worry about it initially and rely on what Django provides by default in the settings.py file <code>TIME_ZONE = 'America/Los_Angeles'</code> to help later on.</p> <p>Given your situation <a href="http://pytz.sourceforge.net/#example-usage" rel="nofollow">pytz</a> is the way to go (it's already been mentioned). You can install it with <code>easy_install</code>. I recommend converting times on the server to UTC on the fly when they are asked for by the client, and then converting these UTC times to the user's local timezone on the client (via Javascript in the browser or via the OS with iOS/Android).</p> <p>The server code to convert times stored in the database with the <code>America/Los_Angeles</code> timezone to UTC looks like this:</p> <pre><code>&gt;&gt;&gt; # Get a datetime from the database somehow and store into "x" &gt;&gt;&gt; x = ... &gt;&gt;&gt; &gt;&gt;&gt; # Create an instance of the Los_Angeles timezone &gt;&gt;&gt; la_tz = pytz.timezone(settings.TIME_ZONE) &gt;&gt;&gt; &gt;&gt;&gt; # Attach timezone information to the datetime from the database &gt;&gt;&gt; x_localized = la_tz.localize(x) &gt;&gt;&gt; &gt;&gt;&gt; # Finally, convert the localized time to UTC &gt;&gt;&gt; x_utc = x_localized.astimezone(pytz.utc) </code></pre> <p>If you send <code>x_utc</code> down to a web page, Javascript can convert it to the user's operating system timezone. If you send <code>x_utc</code> down to an iPhone, iOS can do the same thing, etc. I hope that helps.</p>
3
2011-05-18T22:49:15Z
[ "python", "django", "timezone" ]
Modifying list contents in Python
1,061,937
<p>I have a list like:</p> <pre><code>list = [[1,2,3],[4,5,6],[7,8,9]] </code></pre> <p>I want to append a number at the start of every value in the list programmatically, say the number is 9. I want the new list to be like:</p> <pre><code>list = [[9,1,2,3],[9,4,5,6],[9,7,8,9]] </code></pre> <p>How do I go about doing this in Python? I know it is a very trivial question but I couldn't find a way to get this done.</p>
3
2009-06-30T05:55:24Z
1,061,956
<p>Use the insert method, which <strong>modifies the list in place</strong>:</p> <pre><code>&gt;&gt;&gt; numberlists = [[1,2,3],[4,5,6]] &gt;&gt;&gt; for numberlist in numberlists: ... numberlist.insert(0,9) ... &gt;&gt;&gt; numberlists [[9, 1, 2, 3], [9, 4, 5, 6]] </code></pre> <p>or, more succintly</p> <pre><code>[numberlist.insert(0,9) for numberlist in numberlists] </code></pre> <p>or, differently, using list concatenation, which <strong>creates a new list</strong></p> <pre><code>newnumberlists = [[9] + numberlist for numberlist in numberlists] </code></pre>
2
2009-06-30T06:00:05Z
[ "python", "list" ]
Modifying list contents in Python
1,061,937
<p>I have a list like:</p> <pre><code>list = [[1,2,3],[4,5,6],[7,8,9]] </code></pre> <p>I want to append a number at the start of every value in the list programmatically, say the number is 9. I want the new list to be like:</p> <pre><code>list = [[9,1,2,3],[9,4,5,6],[9,7,8,9]] </code></pre> <p>How do I go about doing this in Python? I know it is a very trivial question but I couldn't find a way to get this done.</p>
3
2009-06-30T05:55:24Z
1,061,957
<pre><code>&gt;&gt;&gt; someList = [[1,2,3],[4,5,6],[7,8,9]] &gt;&gt;&gt; someList = [[9] + i for i in someList] &gt;&gt;&gt; someList [[9, 1, 2, 3], [9, 4, 5, 6], [9, 7, 8, 9]] </code></pre> <p>(someList because list is already used by python)</p>
11
2009-06-30T06:00:08Z
[ "python", "list" ]
Modifying list contents in Python
1,061,937
<p>I have a list like:</p> <pre><code>list = [[1,2,3],[4,5,6],[7,8,9]] </code></pre> <p>I want to append a number at the start of every value in the list programmatically, say the number is 9. I want the new list to be like:</p> <pre><code>list = [[9,1,2,3],[9,4,5,6],[9,7,8,9]] </code></pre> <p>How do I go about doing this in Python? I know it is a very trivial question but I couldn't find a way to get this done.</p>
3
2009-06-30T05:55:24Z
1,061,960
<pre><code>for sublist in thelist: sublist.insert(0, 9) </code></pre> <p><strong>don't</strong> use built-in names such as <code>list</code> for your own stuff, that's just a stupid accident in the making -- call YOUR stuff <code>mylist</code> or <code>thelist</code> or the like, <strong>not</strong> <code>list</code>.</p> <p><strong>Edit</strong>: as the OP aks how to insert > 1 item at the start of each sublist, let me point out that the most efficient way is by assignment of the multiple items to a slice of each sublist (most list mutators can be seen as readable alternatives to slice assignments;-), i.e.:</p> <pre><code>for sublist in thelist: sublist[0:0] = 8, 9 </code></pre> <p><code>sublist[0:0]</code> is the empty slice at the start of <code>sublist</code>, and by assigning items to it you're inserting the items at that very spot.</p>
16
2009-06-30T06:01:22Z
[ "python", "list" ]
Modifying list contents in Python
1,061,937
<p>I have a list like:</p> <pre><code>list = [[1,2,3],[4,5,6],[7,8,9]] </code></pre> <p>I want to append a number at the start of every value in the list programmatically, say the number is 9. I want the new list to be like:</p> <pre><code>list = [[9,1,2,3],[9,4,5,6],[9,7,8,9]] </code></pre> <p>How do I go about doing this in Python? I know it is a very trivial question but I couldn't find a way to get this done.</p>
3
2009-06-30T05:55:24Z
1,062,017
<pre><code>#!/usr/bin/env python def addNine(val): val.insert(0,9) return val if __name__ == '__main__': s = [[1,2,3],[4,5,6],[7,8,9]] print map(addNine,s) </code></pre> <p>Output:</p> <pre><code>[[9, 1, 2, 3], [9, 4, 5, 6], [9, 7, 8, 9]] </code></pre>
0
2009-06-30T06:22:33Z
[ "python", "list" ]
Modifying list contents in Python
1,061,937
<p>I have a list like:</p> <pre><code>list = [[1,2,3],[4,5,6],[7,8,9]] </code></pre> <p>I want to append a number at the start of every value in the list programmatically, say the number is 9. I want the new list to be like:</p> <pre><code>list = [[9,1,2,3],[9,4,5,6],[9,7,8,9]] </code></pre> <p>How do I go about doing this in Python? I know it is a very trivial question but I couldn't find a way to get this done.</p>
3
2009-06-30T05:55:24Z
1,062,138
<p>If you're going to be doing a lot of prepending, <br /> perhaps consider using <a href="http://docs.python.org/library/collections.html#deque-objects" rel="nofollow">deques</a>* instead of lists:</p> <pre><code>&gt;&gt;&gt; mylist = [[1,2,3],[4,5,6],[7,8,9]] &gt;&gt;&gt; from collections import deque &gt;&gt;&gt; mydeque = deque() &gt;&gt;&gt; for li in mylist: ... mydeque.append(deque(li)) ... &gt;&gt;&gt; mydeque deque([deque([1, 2, 3]), deque([4, 5, 6]), deque([7, 8, 9])]) &gt;&gt;&gt; for di in mydeque: ... di.appendleft(9) ... &gt;&gt;&gt; mydeque deque([deque([9, 1, 2, 3]), deque([9, 4, 5, 6]), deque([9, 7, 8, 9])]) </code></pre> <p>*Deques are a generalization of stacks and queues (the name is pronounced "deck" and is short for "double-ended queue"). Deques support thread-safe, memory-efficient appends and pops from either side of the deque with approximately the same O(1) performance in either direction.</p> <p>And, as others have mercifully mentioned: <br /> For the love of all things dull and ugly, <br /> <strong>please do not</strong> name variables after your favorite data-structures.<br /></p>
2
2009-06-30T07:03:33Z
[ "python", "list" ]
python decimal comparison
1,062,008
<p>python decimal comparison</p> <pre><code>&gt;&gt;&gt; from decimal import Decimal &gt;&gt;&gt; Decimal('1.0') &gt; 2.0 True </code></pre> <p>I was expecting it to convert 2.0 correctly, but after reading thru <a href="http://www.python.org/dev/peps/pep-0327">PEP 327</a> I understand there were some reason for not implictly converting float to Decimal, but shouldn't in that case it should raise TypeError as it does in this case</p> <pre><code>&gt;&gt;&gt; Decimal('1.0') + 2.0 Traceback (most recent call last): File "&lt;string&gt;", line 1, in &lt;string&gt; TypeError: unsupported operand type(s) for +: 'Decimal' and 'float' </code></pre> <p>so does all other operator / - % // etc</p> <p>so my questions are</p> <ol> <li>is this right behavior? (not to raise exception in cmp)</li> <li>What if I derive my own class and right a float converter basically Decimal(repr(float_value)), are there any caveats? my use case involves only comparison of prices</li> </ol> <p>System details: Python 2.5.2 on Ubuntu 8.04.1</p>
12
2009-06-30T06:18:56Z
1,062,024
<p>If it's "right" is a matter of opinion, but the rationale of why there is no automatic conversion exists in the PEP, and that was the decision taken. The caveat basically is that you can't always exactly convert between float and decimal. Therefore the conversion should not be implicit. If you in your application know that you never have enough significant numbers for this to affect you, making classes that allow this implicit behaviour shouldn't be a problem.</p> <p>Also, one main argument is that real world use cases doesn't exist. It's likely to be simpler if you just use Decimal everywhere.</p>
1
2009-06-30T06:24:55Z
[ "python", "comparison", "decimal" ]
python decimal comparison
1,062,008
<p>python decimal comparison</p> <pre><code>&gt;&gt;&gt; from decimal import Decimal &gt;&gt;&gt; Decimal('1.0') &gt; 2.0 True </code></pre> <p>I was expecting it to convert 2.0 correctly, but after reading thru <a href="http://www.python.org/dev/peps/pep-0327">PEP 327</a> I understand there were some reason for not implictly converting float to Decimal, but shouldn't in that case it should raise TypeError as it does in this case</p> <pre><code>&gt;&gt;&gt; Decimal('1.0') + 2.0 Traceback (most recent call last): File "&lt;string&gt;", line 1, in &lt;string&gt; TypeError: unsupported operand type(s) for +: 'Decimal' and 'float' </code></pre> <p>so does all other operator / - % // etc</p> <p>so my questions are</p> <ol> <li>is this right behavior? (not to raise exception in cmp)</li> <li>What if I derive my own class and right a float converter basically Decimal(repr(float_value)), are there any caveats? my use case involves only comparison of prices</li> </ol> <p>System details: Python 2.5.2 on Ubuntu 8.04.1</p>
12
2009-06-30T06:18:56Z
1,062,027
<p>The greater-than comparison works because, by default, it works for all objects.</p> <pre><code>&gt;&gt;&gt; 'abc' &gt; 123 True </code></pre> <p><code>Decimal</code> is right merely because it correctly follows the spec. Whether the spec was the correct approach is a separate question. :)</p> <p>Only the normal caveats when dealing with floats, which briefly summarized are: beware of edge cases such as negative zero, +/-infinity, and NaN, don't test for equality (related to the next point), and count on math being slightly inaccurate.</p> <pre><code>&gt;&gt;&gt; print (1.1 + 2.2 == 3.3) False </code></pre>
2
2009-06-30T06:25:40Z
[ "python", "comparison", "decimal" ]
python decimal comparison
1,062,008
<p>python decimal comparison</p> <pre><code>&gt;&gt;&gt; from decimal import Decimal &gt;&gt;&gt; Decimal('1.0') &gt; 2.0 True </code></pre> <p>I was expecting it to convert 2.0 correctly, but after reading thru <a href="http://www.python.org/dev/peps/pep-0327">PEP 327</a> I understand there were some reason for not implictly converting float to Decimal, but shouldn't in that case it should raise TypeError as it does in this case</p> <pre><code>&gt;&gt;&gt; Decimal('1.0') + 2.0 Traceback (most recent call last): File "&lt;string&gt;", line 1, in &lt;string&gt; TypeError: unsupported operand type(s) for +: 'Decimal' and 'float' </code></pre> <p>so does all other operator / - % // etc</p> <p>so my questions are</p> <ol> <li>is this right behavior? (not to raise exception in cmp)</li> <li>What if I derive my own class and right a float converter basically Decimal(repr(float_value)), are there any caveats? my use case involves only comparison of prices</li> </ol> <p>System details: Python 2.5.2 on Ubuntu 8.04.1</p>
12
2009-06-30T06:18:56Z
1,062,030
<p>Re 1, it's indeed the behavior we designed -- right or wrong as it may be (sorry if that trips your use case up, but we were trying to be general!).</p> <p>Specifically, it's long been the case that every Python object could be subject to inequality comparison with every other -- objects of types that aren't really comparable get arbitrarily compared (consistently in a given run, not necessarily across runs); main use case was sorting a heterogeneous list to group elements in it by type.</p> <p>An exception was introduced for complex numbers only, making them non-comparable to anything -- but that was still many years ago, when we were occasionally cavalier about breaking perfectly good user code. Nowadays we're much stricter about backwards compatibility within a major release (e.g. along the <code>2.*</code> line, and separately along the <code>3.*</code> one, though incompatibilities <em>are</em> allowed between 2 and 3 -- indeed that's the whole point of <em>having</em> a <code>3.*</code> series, letting us fix past design decisions even in incompatible ways).</p> <p>The arbitrary comparisons turned out to be more trouble than they're worth, causing user confusion; and the grouping by type can now be obtained easily e.g. with a <code>key=lambda x: str(type(x))</code> argument to <code>sort</code>; so in Python 3 comparisons between objects of different types, unless the objects themselves specifically allow it in the comparison methods, does raise an exception:</p> <pre><code>&gt;&gt;&gt; decimal.Decimal('2.0') &gt; 1.2 Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: unorderable types: Decimal() &gt; float() </code></pre> <p>In other words, in Python 3 this behaves exactly as you think it should; but in Python 2 it doesn't (and never will in any Python <code>2.*</code>).</p> <p>Re 2, you'll be fine -- though, look to <a href="http://code.google.com/p/gmpy/">gmpy</a> for what I hope is an interesting way to convert doubles to infinite-precision fractions through Farey trees. If the prices you're dealing with are precise to no more than cents, use <code>'%.2f' % x</code> rather than <code>repr(x)</code>!-)</p> <p>Rather than a subclass of Decimal, I'd use a factory function such as</p> <pre><code>def to_decimal(float_price): return decimal.Decimal('%.2f' % float_price) </code></pre> <p>since, once produced, the resulting Decimal is a perfectly ordinary one.</p>
22
2009-06-30T06:26:26Z
[ "python", "comparison", "decimal" ]
Python NotImplemented constant
1,062,096
<p>Looking through <code>decimal.py</code>, it uses <code>NotImplemented</code> in many special methods. e.g.</p> <pre><code>class A(object): def __lt__(self, a): return NotImplemented def __add__(self, a): return NotImplemented </code></pre> <p>The <a href="http://docs.python.org/library/constants.html" rel="nofollow">Python docs say</a>:</p> <blockquote> <p><strong>NotImplemented</strong></p> <p>Special value which can be returned by the “rich comparison” special methods (<code>__eq__()</code>, <code>__lt__()</code>, and friends), to indicate that the comparison is not implemented with respect to the other type.</p> </blockquote> <p>It doesn't talk about other special methods and neither does it describe the behavior.</p> <p>It seems to be a magic object which if returned from other special methods raises <code>TypeError</code>, and in “rich comparison” special methods does nothing.</p> <p>e.g.</p> <pre><code>print A() &lt; A() </code></pre> <p>prints <code>True</code>, but</p> <pre><code>print A() + 1 </code></pre> <p>raises <code>TypeError</code>, so I am curious as to what's going on and what is the usage/behavior of NotImplemented.</p>
22
2009-06-30T06:52:12Z
1,062,124
<p><code>NotImplemented</code> allows you to indicate that a comparison between the two given operands has not been implemented (rather than indicating that the comparison is valid, but yields <code>False</code>, for the two operands).</p> <p>From the <a href="http://www.network-theory.co.uk/docs/pylang/Coercionrules.html">Python Language Reference</a>:</p> <blockquote> <p>For objects x and y, first <code>x.__op__(y)</code> is tried. If this is not implemented or returns NotImplemented, <code>y.__rop__(x)</code> is tried. If this is also not implemented or returns NotImplemented, a TypeError exception is raised. But see the following exception: </p> <p>Exception to the previous item: if the left operand is an instance of a built-in type or a new-style class, and the right operand is an instance of a proper subclass of that type or class and overrides the base's <code>__rop__()</code> method, the right operand's <code>__rop__()</code> method is tried before the left operand's <code>__op__()</code> method. This is done so that a subclass can completely override binary operators. Otherwise, the left operand's <code>__op__()</code> method would always accept the right operand: when an instance of a given class is expected, an instance of a subclass of that class is always acceptable.</p> </blockquote>
25
2009-06-30T07:00:04Z
[ "python" ]
Python NotImplemented constant
1,062,096
<p>Looking through <code>decimal.py</code>, it uses <code>NotImplemented</code> in many special methods. e.g.</p> <pre><code>class A(object): def __lt__(self, a): return NotImplemented def __add__(self, a): return NotImplemented </code></pre> <p>The <a href="http://docs.python.org/library/constants.html" rel="nofollow">Python docs say</a>:</p> <blockquote> <p><strong>NotImplemented</strong></p> <p>Special value which can be returned by the “rich comparison” special methods (<code>__eq__()</code>, <code>__lt__()</code>, and friends), to indicate that the comparison is not implemented with respect to the other type.</p> </blockquote> <p>It doesn't talk about other special methods and neither does it describe the behavior.</p> <p>It seems to be a magic object which if returned from other special methods raises <code>TypeError</code>, and in “rich comparison” special methods does nothing.</p> <p>e.g.</p> <pre><code>print A() &lt; A() </code></pre> <p>prints <code>True</code>, but</p> <pre><code>print A() + 1 </code></pre> <p>raises <code>TypeError</code>, so I am curious as to what's going on and what is the usage/behavior of NotImplemented.</p>
22
2009-06-30T06:52:12Z
1,062,128
<p>It actually has the same meaning when returned from <code>__add__</code> as from <code>__lt__</code>, the difference is Python 2.x is trying other ways of comparing the objects before giving up. Python 3.x does raise a TypeError. In fact, Python can try other things for <code>__add__</code> as well, look at <code>__radd__</code> and (though I'm fuzzy on it) <code>__coerce__</code>.</p> <pre><code># 2.6 &gt;&gt;&gt; class A(object): ... def __lt__(self, other): ... return NotImplemented &gt;&gt;&gt; A() &lt; A() True # 3.1 &gt;&gt;&gt; class A(object): ... def __lt__(self, other): ... return NotImplemented &gt;&gt;&gt; A() &lt; A() Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: unorderable types: A() &lt; A() </code></pre> <p>See <a href="http://docs.python.org/3.0/whatsnew/3.0.html#ordering-comparisons" rel="nofollow">Ordering Comparisions (3.0 docs)</a> for more info.</p>
3
2009-06-30T07:00:46Z
[ "python" ]
Python NotImplemented constant
1,062,096
<p>Looking through <code>decimal.py</code>, it uses <code>NotImplemented</code> in many special methods. e.g.</p> <pre><code>class A(object): def __lt__(self, a): return NotImplemented def __add__(self, a): return NotImplemented </code></pre> <p>The <a href="http://docs.python.org/library/constants.html" rel="nofollow">Python docs say</a>:</p> <blockquote> <p><strong>NotImplemented</strong></p> <p>Special value which can be returned by the “rich comparison” special methods (<code>__eq__()</code>, <code>__lt__()</code>, and friends), to indicate that the comparison is not implemented with respect to the other type.</p> </blockquote> <p>It doesn't talk about other special methods and neither does it describe the behavior.</p> <p>It seems to be a magic object which if returned from other special methods raises <code>TypeError</code>, and in “rich comparison” special methods does nothing.</p> <p>e.g.</p> <pre><code>print A() &lt; A() </code></pre> <p>prints <code>True</code>, but</p> <pre><code>print A() + 1 </code></pre> <p>raises <code>TypeError</code>, so I am curious as to what's going on and what is the usage/behavior of NotImplemented.</p>
22
2009-06-30T06:52:12Z
1,062,147
<p>If you return it from <code>__add__</code> it will behave like the object has no <code>__add__</code> method, and raise a <code>TypeError</code>.</p> <p>If you return <code>NotImplemented</code> from a rich comparison function, Python will behave like the method wasn't implemented, that is, it will defer to using <code>__cmp__</code>. </p>
0
2009-06-30T07:05:34Z
[ "python" ]
obtain collection_name from parent's key in GAE
1,062,108
<p>is it possible to ask parent for its refered collection_name based on one of its keys, lets say i have a parent db model and its key, can i know ths children who refer to this parent through collection name or otherwise</p> <pre><code>class Parent(db.Model): user = db.UserProperty() class Childs(db.Model): refer = db.ReferenceProperty(Parent,collection_name='children') </code></pre>
0
2009-06-30T06:56:31Z
1,062,184
<p>I think you're asking "can I get the set of all the children that refer to a given parent".</p> <p>In which case, yes you can, it's a property of the Parent class.</p> <p>Assuming you have a Parent object p then the children that reference it will be in p.children</p> <p>If you hadn't specified the collection_name on the ReferenceProperty they would be in p.childs_set</p> <p>Check out the <a href="http://code.google.com/appengine/docs/python/datastore/typesandpropertyclasses.html#ReferenceProperty" rel="nofollow">documentation</a>.</p>
1
2009-06-30T07:15:24Z
[ "python", "google-app-engine" ]
obtain collection_name from parent's key in GAE
1,062,108
<p>is it possible to ask parent for its refered collection_name based on one of its keys, lets say i have a parent db model and its key, can i know ths children who refer to this parent through collection name or otherwise</p> <pre><code>class Parent(db.Model): user = db.UserProperty() class Childs(db.Model): refer = db.ReferenceProperty(Parent,collection_name='children') </code></pre>
0
2009-06-30T06:56:31Z
1,062,267
<p>Yes, you can.</p> <blockquote> <p><a href="http://code.google.com/appengine/docs/python/datastore/entitiesandmodels.html#References" rel="nofollow">ReferenceProperty has another handy feature: back-references. When a model has a ReferenceProperty to another model, each referenced entity gets a property whose value is a Query that returns all of the entities of the first model that refer to it.</a></p> </blockquote> <pre><code># To fetch and iterate over every Childs entity that refers to the # Parent instance p: for child in p.children: # ... </code></pre>
0
2009-06-30T07:38:13Z
[ "python", "google-app-engine" ]
Python win32 com : how to handle 'out' parameter?
1,062,129
<p>I need to access a third-party COM server with following interface definition (idl):</p> <pre><code>interface IDisplay : IDispatch { HRESULT getFramebuffer ( [in] ULONG aScreenId, [out] IFramebuffer * * aFramebuffer, [out] LONG * aXOrigin, [out] LONG * aYOrigin ); }; </code></pre> <p>As you can see, it returns 3 values via [out] parameter modificators. How to handle this via python win32 COM api? For example, i create an object and get IDisplay from it:</p> <pre><code>object = win32com.client.Dispatch( "VirtualBox.VirtualBox" ) display = object.display </code></pre> <p>How to call display.getFrameBuffer() so it will work? I have tried different ways, but it's always 'type mismatch' on second argument ([out] for IFrameBuffer)</p>
5
2009-06-30T07:00:50Z
1,062,295
<p>Since those are out parameters, can't you simply do the following?</p> <pre><code>Framebuffer, XOrigin, YOrigin = display.getFrameBuffer(ScreenId) </code></pre> <p>There is some good references in <a href="http://oreilly.com/catalog/pythonwin32/chapter/ch12.html">Python Programming on Win32 Chapter 12 Advanced Python and COM</a></p> <p>And they indicate that the syntax should be like above. They also mention using MakePy for COM objects:</p> <p>There are a number of good reasons to use MakePy: (copied from the book)</p> <ul> <li><p>The Python interface to automation objects is faster for objects supported by a MakePy module.</p></li> <li><p>Any constants defined by the type library are made available to the Python program. We discuss COM constants in more detail later in the chapter.</p></li> <li><p>There is much better support for advanced parameter types, specifically, parameters declared by COM as BYREF can be used only with MakePy-supported objects. We discuss passing parameters later in the chapter.</p></li> </ul>
7
2009-06-30T07:48:48Z
[ "python", "com" ]
Python win32 com : how to handle 'out' parameter?
1,062,129
<p>I need to access a third-party COM server with following interface definition (idl):</p> <pre><code>interface IDisplay : IDispatch { HRESULT getFramebuffer ( [in] ULONG aScreenId, [out] IFramebuffer * * aFramebuffer, [out] LONG * aXOrigin, [out] LONG * aYOrigin ); }; </code></pre> <p>As you can see, it returns 3 values via [out] parameter modificators. How to handle this via python win32 COM api? For example, i create an object and get IDisplay from it:</p> <pre><code>object = win32com.client.Dispatch( "VirtualBox.VirtualBox" ) display = object.display </code></pre> <p>How to call display.getFrameBuffer() so it will work? I have tried different ways, but it's always 'type mismatch' on second argument ([out] for IFrameBuffer)</p>
5
2009-06-30T07:00:50Z
1,062,546
<p>Use the <code>makepy</code> module, invoking it as follows:</p> <pre><code>&gt;&gt;&gt; import win32com.client.makepy as makepy &gt;&gt;&gt; makepy.main() </code></pre> <p>A window will open with a list of type libraries. Scroll to "Virtual Box Type Library" and select it, then click "OK". A Python module will be created in a location which is printed out (typically <code>%TEMP%\gen_py\2.x\</code>).</p> <p>The generated class will automatically be used by <code>win32com.client.Dispatch</code>, but if you need it explicitly you can access it via functions in the <code>win32com.client.gencache</code> module.</p>
3
2009-06-30T08:53:18Z
[ "python", "com" ]
Python - Reading multiple lines into list
1,062,171
<p>OK guys/gals stuck again on something simple<br /> I have a text file which has multiple lines per entry, the data is in the following format </p> <p>firstword word word word<br /> wordx word word word <strong>interesting1</strong> word word word word<br /> wordy word word word<br /> wordz word word word <strong>interesting2</strong> word word word lastword </p> <p>this sequence repeats a hundred or so times, all other words are the same apart from interesting1 and interesting2, no blank lines. The interesting2 is pertinent to interesting1 but not to anything else and I want to link the two interesting items together, discarding the rest such as </p> <p>interesting1 = interesting2<br /> interesting1 = interesting2<br /> interesting1 = interesting2<br /> etc, 1 lne per sequence </p> <p>Each line begins with a different word<br /> my attempt was to read the file and do an "if wordx in line" statement to identify the first interesting line, slice out the value, find the second line, ("if wordz in line) slice out the value and concatenate the second with the first.<br /> It's clumsy though, I had to use global variables, temp variables etc, and I'm sure there must be a way of identifying the range between firstword and lastword and placing that into a single list, then slicing both values out together. </p> <p>Any suggestions gratefully acknowledged, thanks for your time</p>
1
2009-06-30T07:11:37Z
1,062,200
<p>In that case, make a regexp that matches the repeating text, and has groups for the interesting bits. Then you should be able to use findall to find all cases of interesting1 and interesting2.</p> <p>Like so: import re</p> <pre><code>text = open("foo.txt").read() RE = re.compile('firstword.*?wordx word word word (.*?) word.*?wordz word word word (.*?) word', re.DOTALL) print RE.findall(text) </code></pre> <p>Although as mentioned in the comments, the islice is definitely a neater solution.</p>
0
2009-06-30T07:20:54Z
[ "python", "text", "parsing", "line" ]
Python - Reading multiple lines into list
1,062,171
<p>OK guys/gals stuck again on something simple<br /> I have a text file which has multiple lines per entry, the data is in the following format </p> <p>firstword word word word<br /> wordx word word word <strong>interesting1</strong> word word word word<br /> wordy word word word<br /> wordz word word word <strong>interesting2</strong> word word word lastword </p> <p>this sequence repeats a hundred or so times, all other words are the same apart from interesting1 and interesting2, no blank lines. The interesting2 is pertinent to interesting1 but not to anything else and I want to link the two interesting items together, discarding the rest such as </p> <p>interesting1 = interesting2<br /> interesting1 = interesting2<br /> interesting1 = interesting2<br /> etc, 1 lne per sequence </p> <p>Each line begins with a different word<br /> my attempt was to read the file and do an "if wordx in line" statement to identify the first interesting line, slice out the value, find the second line, ("if wordz in line) slice out the value and concatenate the second with the first.<br /> It's clumsy though, I had to use global variables, temp variables etc, and I'm sure there must be a way of identifying the range between firstword and lastword and placing that into a single list, then slicing both values out together. </p> <p>Any suggestions gratefully acknowledged, thanks for your time</p>
1
2009-06-30T07:11:37Z
1,062,288
<pre><code>from itertools import izip, tee, islice i1, i2 = tee(open("foo.txt")) for line2, line4 in izip(islice(i1,1, None, 4), islice(i2, 3, None, 4)) : print line2.split(" ")[4], "=", line4.split(" ")[4] </code></pre>
6
2009-06-30T07:46:01Z
[ "python", "text", "parsing", "line" ]
Python - Reading multiple lines into list
1,062,171
<p>OK guys/gals stuck again on something simple<br /> I have a text file which has multiple lines per entry, the data is in the following format </p> <p>firstword word word word<br /> wordx word word word <strong>interesting1</strong> word word word word<br /> wordy word word word<br /> wordz word word word <strong>interesting2</strong> word word word lastword </p> <p>this sequence repeats a hundred or so times, all other words are the same apart from interesting1 and interesting2, no blank lines. The interesting2 is pertinent to interesting1 but not to anything else and I want to link the two interesting items together, discarding the rest such as </p> <p>interesting1 = interesting2<br /> interesting1 = interesting2<br /> interesting1 = interesting2<br /> etc, 1 lne per sequence </p> <p>Each line begins with a different word<br /> my attempt was to read the file and do an "if wordx in line" statement to identify the first interesting line, slice out the value, find the second line, ("if wordz in line) slice out the value and concatenate the second with the first.<br /> It's clumsy though, I had to use global variables, temp variables etc, and I'm sure there must be a way of identifying the range between firstword and lastword and placing that into a single list, then slicing both values out together. </p> <p>Any suggestions gratefully acknowledged, thanks for your time</p>
1
2009-06-30T07:11:37Z
1,062,363
<p>I've thrown in a bagful of assertions to check the regularity of your data layout.</p> <pre><code>C:\SO&gt;type words.py # sample pseudo-file contents guff = """\ firstword word word word wordx word word word interesting1-1 word word word word wordy word word word wordz word word word interesting2-1 word word word lastword miscellaneous rubbish firstword word word word wordx word word word interesting1-2 word word word word wordy word word word wordz word word word interesting2-2 word word word lastword firstword word word word wordx word word word interesting1-3 word word word word wordy word word word wordz word word word interesting2-3 word word word lastword """ # change the RHS of each of these to reflect reality FIRSTWORD = 'firstword' WORDX = 'wordx' WORDY = 'wordy' WORDZ = 'wordz' LASTWORD = 'lastword' from StringIO import StringIO f = StringIO(guff) while True: a = f.readline() if not a: break # end of file a = a.split() if not a: continue # empty line if a[0] != FIRSTWORD: continue # skip extraneous matter assert len(a) == 4 b = f.readline().split(); assert len(b) == 9 c = f.readline().split(); assert len(c) == 4 d = f.readline().split(); assert len(d) == 9 assert a[0] == FIRSTWORD assert b[0] == WORDX assert c[0] == WORDY assert d[0] == WORDZ assert d[-1] == LASTWORD print b[4], d[4] C:\SO&gt;\python26\python words.py interesting1-1 interesting2-1 interesting1-2 interesting2-2 interesting1-3 interesting2-3 C:\SO&gt; </code></pre>
0
2009-06-30T08:08:57Z
[ "python", "text", "parsing", "line" ]
Python Script Executed with Makefile
1,062,436
<p>I am writing python scripts and execute them in a Makefile. The python script is used to process data in a pipeline. I would like Makefile to execute the script every time I make a change to my python scripts.</p> <p>Does anyone have an idea of how to do this?</p>
7
2009-06-30T08:28:39Z
1,062,466
<p>That's not a lot of information, so this answer is a bit vague. The basic principle of Makefiles is to list dependencies for each target; in this case, your target (let's call it foo) depends on your python script (let's call it do-foo.py):</p> <pre><code>foo: do-foo.py python do-foo.py &gt; foo </code></pre> <p>Now foo will be rerun whenever do-foo.py changes (provided, of course, you call make).</p>
14
2009-06-30T08:38:17Z
[ "python", "makefile" ]
Python Script Executed with Makefile
1,062,436
<p>I am writing python scripts and execute them in a Makefile. The python script is used to process data in a pipeline. I would like Makefile to execute the script every time I make a change to my python scripts.</p> <p>Does anyone have an idea of how to do this?</p>
7
2009-06-30T08:28:39Z
1,062,484
<p>If you want that Makefile to be automatically "maked" immediately after saving, <a href="http://pyinotify.sourceforge.net/" rel="nofollow"><code>pyinotify</code></a>, which is a wrapper for <a href="http://en.wikipedia.org/wiki/Inotify" rel="nofollow"><code>inotify</code></a>, might be the only possibility under Linux. It registers at the kernel to detect FS changes and calls back your function.</p> <p>See my <a href="http://stackoverflow.com/questions/1030966/login-input/1031130#1031130">previous post</a> on that topic.</p>
0
2009-06-30T08:42:56Z
[ "python", "makefile" ]
Python Script Executed with Makefile
1,062,436
<p>I am writing python scripts and execute them in a Makefile. The python script is used to process data in a pipeline. I would like Makefile to execute the script every time I make a change to my python scripts.</p> <p>Does anyone have an idea of how to do this?</p>
7
2009-06-30T08:28:39Z
1,062,502
<p>And in case when the scripts that need to be run don't produce any useful output file that can be used as a target, you can just use a dummy target:</p> <pre><code>scripts=a.py b.py c.py checkfile=.pipeline_up_to_date $(checkfile): $(scripts) touch $(checkfile) echo "Launching some commands now." default: $(checkfile) </code></pre>
3
2009-06-30T08:45:54Z
[ "python", "makefile" ]
Python Script Executed with Makefile
1,062,436
<p>I am writing python scripts and execute them in a Makefile. The python script is used to process data in a pipeline. I would like Makefile to execute the script every time I make a change to my python scripts.</p> <p>Does anyone have an idea of how to do this?</p>
7
2009-06-30T08:28:39Z
1,179,141
<p>This is not a direct answer to your question, but I suggest you to read this tutorial dedicated to scientists approaching bioinformatics: - <a href="http://swc.scipy.org/lec/build.html" rel="nofollow">http://swc.scipy.org/lec/build.html</a></p> <p>And all the info related to this page: - <a href="http://biowiki.org/MakeComparison" rel="nofollow">http://biowiki.org/MakeComparison</a></p>
0
2009-07-24T17:49:51Z
[ "python", "makefile" ]
Calling a non-returning python function from a python script
1,062,562
<p>I want to call a wrapped C++ function from a python script which is not returning immediately (in detail: it is a function which starts a QApplication window and the last line in that function is QApplication->exec()). So after that function call I want to move on to my next line in the python script but on executing this script and the previous line it hangs forever.</p> <p>In contrast when I manually type my script line for line in the python command line I can go on to my next line after pressing enter a second time on the non-returning function call line.</p> <p>So how to solve the issue when executing the script?</p> <p>Thanks!!</p> <p>Edit:</p> <p>My python interpreter is embedded in an application. I want to write an extension for this application as a separate Qt4 window. All the python stuff is only for make my graphical plugin accessible per script (per boost.python wrapping).</p> <p>My python script:</p> <pre><code>import imp import os Plugin = imp.load_dynamic('Plugin', os.getcwd() + 'Plugin.dll') qt = Plugin.StartQt4() # it hangs here when executing as script pl = PluginCPP.PluginCPP() # Creates a QMainWindow pl.ShowWindow() # shows the window </code></pre> <p>The C++ code for the Qt start function looks like this:</p> <pre><code>class StartQt4 { public: StartQt4() { int i = 0; QApplication* qapp = new QApplication(i, NULL); qapp-&gt;exec(); } }; </code></pre>
0
2009-06-30T08:57:54Z
1,062,584
<p>Use a thread (<a href="http://www.wellho.net/solutions/python-python-threads-a-first-example.html" rel="nofollow">longer example here</a>):</p> <pre><code>from threading import Thread class WindowThread(Thread): def run(self): callCppFunctionHere() WindowThread().start() </code></pre>
2
2009-06-30T09:04:22Z
[ "c++", "python", "function", "scripting" ]
Calling a non-returning python function from a python script
1,062,562
<p>I want to call a wrapped C++ function from a python script which is not returning immediately (in detail: it is a function which starts a QApplication window and the last line in that function is QApplication->exec()). So after that function call I want to move on to my next line in the python script but on executing this script and the previous line it hangs forever.</p> <p>In contrast when I manually type my script line for line in the python command line I can go on to my next line after pressing enter a second time on the non-returning function call line.</p> <p>So how to solve the issue when executing the script?</p> <p>Thanks!!</p> <p>Edit:</p> <p>My python interpreter is embedded in an application. I want to write an extension for this application as a separate Qt4 window. All the python stuff is only for make my graphical plugin accessible per script (per boost.python wrapping).</p> <p>My python script:</p> <pre><code>import imp import os Plugin = imp.load_dynamic('Plugin', os.getcwd() + 'Plugin.dll') qt = Plugin.StartQt4() # it hangs here when executing as script pl = PluginCPP.PluginCPP() # Creates a QMainWindow pl.ShowWindow() # shows the window </code></pre> <p>The C++ code for the Qt start function looks like this:</p> <pre><code>class StartQt4 { public: StartQt4() { int i = 0; QApplication* qapp = new QApplication(i, NULL); qapp-&gt;exec(); } }; </code></pre>
0
2009-06-30T08:57:54Z
1,062,590
<p>QApplication::exec() starts the main loop of the application and will only return after the application quits. If you want to run code after the application has been started, you should resort to Qt's event handling mechanism.</p> <p>From <a href="http://doc.trolltech.com/4.5/qapplication.html#exec" rel="nofollow">http://doc.trolltech.com/4.5/qapplication.html#exec</a> :</p> <blockquote> <p>To make your application perform idle processing, i.e. executing a special function whenever there are no pending events, use a QTimer with 0 timeout. More advanced idle processing schemes can be achieved using processEvents().</p> </blockquote>
1
2009-06-30T09:05:40Z
[ "c++", "python", "function", "scripting" ]
Calling a non-returning python function from a python script
1,062,562
<p>I want to call a wrapped C++ function from a python script which is not returning immediately (in detail: it is a function which starts a QApplication window and the last line in that function is QApplication->exec()). So after that function call I want to move on to my next line in the python script but on executing this script and the previous line it hangs forever.</p> <p>In contrast when I manually type my script line for line in the python command line I can go on to my next line after pressing enter a second time on the non-returning function call line.</p> <p>So how to solve the issue when executing the script?</p> <p>Thanks!!</p> <p>Edit:</p> <p>My python interpreter is embedded in an application. I want to write an extension for this application as a separate Qt4 window. All the python stuff is only for make my graphical plugin accessible per script (per boost.python wrapping).</p> <p>My python script:</p> <pre><code>import imp import os Plugin = imp.load_dynamic('Plugin', os.getcwd() + 'Plugin.dll') qt = Plugin.StartQt4() # it hangs here when executing as script pl = PluginCPP.PluginCPP() # Creates a QMainWindow pl.ShowWindow() # shows the window </code></pre> <p>The C++ code for the Qt start function looks like this:</p> <pre><code>class StartQt4 { public: StartQt4() { int i = 0; QApplication* qapp = new QApplication(i, NULL); qapp-&gt;exec(); } }; </code></pre>
0
2009-06-30T08:57:54Z
1,062,839
<p>I assume you're already using <a href="http://www.riverbankcomputing.co.uk/software/pyqt/intro" rel="nofollow">PyQT</a>?</p>
0
2009-06-30T10:04:18Z
[ "c++", "python", "function", "scripting" ]
Get the items not repeated in a list
1,062,803
<p>Take two lists, second with same items than first plus some more:</p> <pre><code>a = [1,2,3] b = [1,2,3,4,5] </code></pre> <p>I want to get a third one, containing only the new items (the ones not repeated):</p> <pre><code>c = [4,5] </code></pre> <p>The solution I have right now is:</p> <pre><code>&gt;&gt;&gt; c = [] &gt;&gt;&gt; for i in ab: ... if ab.count(i) == 1: ... c.append(i) &gt;&gt;&gt; c [4, 5] </code></pre> <p>Is there any other way more pythonic than this?</p> <p>Thanx folks!</p>
1
2009-06-30T09:57:34Z
1,062,824
<p>at the very least use a list comprehension:</p> <pre><code>[x for x in a + b if (a + b).count(x) == 1] </code></pre> <p>otherwise use the <a href="http://docs.python.org/library/stdtypes.html#set-types-set-frozenset" rel="nofollow">set</a> class:</p> <pre><code>list(set(a).symmetric_difference(set(b))) </code></pre> <p>there is also a more compact form:</p> <pre><code>list(set(a) ^ set(b)) </code></pre>
11
2009-06-30T10:01:15Z
[ "python" ]
Get the items not repeated in a list
1,062,803
<p>Take two lists, second with same items than first plus some more:</p> <pre><code>a = [1,2,3] b = [1,2,3,4,5] </code></pre> <p>I want to get a third one, containing only the new items (the ones not repeated):</p> <pre><code>c = [4,5] </code></pre> <p>The solution I have right now is:</p> <pre><code>&gt;&gt;&gt; c = [] &gt;&gt;&gt; for i in ab: ... if ab.count(i) == 1: ... c.append(i) &gt;&gt;&gt; c [4, 5] </code></pre> <p>Is there any other way more pythonic than this?</p> <p>Thanx folks!</p>
1
2009-06-30T09:57:34Z
1,062,853
<p>If the order is not important and you can ignore repetitions within <code>a</code> and <code>b</code>, I would simply use sets:</p> <pre><code>&gt;&gt;&gt; set(b) - set(a) set([4, 5]) </code></pre> <p>Sets are iterable, so most of the times you do not need to explicitly convert them back to list. If you have to, this does it:</p> <pre><code>&gt;&gt;&gt; list(set(b) - set(a)) [4, 5] </code></pre>
8
2009-06-30T10:10:01Z
[ "python" ]
Get the items not repeated in a list
1,062,803
<p>Take two lists, second with same items than first plus some more:</p> <pre><code>a = [1,2,3] b = [1,2,3,4,5] </code></pre> <p>I want to get a third one, containing only the new items (the ones not repeated):</p> <pre><code>c = [4,5] </code></pre> <p>The solution I have right now is:</p> <pre><code>&gt;&gt;&gt; c = [] &gt;&gt;&gt; for i in ab: ... if ab.count(i) == 1: ... c.append(i) &gt;&gt;&gt; c [4, 5] </code></pre> <p>Is there any other way more pythonic than this?</p> <p>Thanx folks!</p>
1
2009-06-30T09:57:34Z
1,062,860
<p>Items in b that aren't in a, if you need to preserve order or duplicates in b:</p> <pre><code>&gt;&gt;&gt; a = [1, 2, 3] &gt;&gt;&gt; b = [1, 2, 3, 4, 4, 5] &gt;&gt;&gt; a_set = set(a) &gt;&gt;&gt; [x for x in b if x not in a_set] [4, 4, 5] </code></pre> <p>Items in b that aren't in a, not preserving order, and not preserving duplicates in b:</p> <pre><code>&gt;&gt;&gt; list(set(b) - set(a)) [4, 5] </code></pre>
4
2009-06-30T10:12:26Z
[ "python" ]
Get the items not repeated in a list
1,062,803
<p>Take two lists, second with same items than first plus some more:</p> <pre><code>a = [1,2,3] b = [1,2,3,4,5] </code></pre> <p>I want to get a third one, containing only the new items (the ones not repeated):</p> <pre><code>c = [4,5] </code></pre> <p>The solution I have right now is:</p> <pre><code>&gt;&gt;&gt; c = [] &gt;&gt;&gt; for i in ab: ... if ab.count(i) == 1: ... c.append(i) &gt;&gt;&gt; c [4, 5] </code></pre> <p>Is there any other way more pythonic than this?</p> <p>Thanx folks!</p>
1
2009-06-30T09:57:34Z
1,062,980
<p>I'd say go for the set variant, where</p> <pre><code> set(b) ^ set(a) (set.symmetric_difference()) </code></pre> <p>only applies if you can be certain that a is always a subset of b, but in that case has the advantage of being commutative, ie. you don't have to worry about calculating set(b) ^ set(a) or set(a) ^ set(b); or</p> <pre><code> set(b) - set(a) (set.difference()) </code></pre> <p>which matches your description more closely, allows a to have extra elements not in b which will not be in the result set, but you have to mind the order (set(a) - set(b) will give you a different result).</p>
3
2009-06-30T10:38:20Z
[ "python" ]
Get the items not repeated in a list
1,062,803
<p>Take two lists, second with same items than first plus some more:</p> <pre><code>a = [1,2,3] b = [1,2,3,4,5] </code></pre> <p>I want to get a third one, containing only the new items (the ones not repeated):</p> <pre><code>c = [4,5] </code></pre> <p>The solution I have right now is:</p> <pre><code>&gt;&gt;&gt; c = [] &gt;&gt;&gt; for i in ab: ... if ab.count(i) == 1: ... c.append(i) &gt;&gt;&gt; c [4, 5] </code></pre> <p>Is there any other way more pythonic than this?</p> <p>Thanx folks!</p>
1
2009-06-30T09:57:34Z
1,063,320
<p>Another solution using only lists:</p> <pre><code>a = [1, 2, 3] b = [1, 2, 3, 4, 5] c = [n for n in a + b if n not in a or n not in b] </code></pre>
0
2009-06-30T12:15:09Z
[ "python" ]
Get the items not repeated in a list
1,062,803
<p>Take two lists, second with same items than first plus some more:</p> <pre><code>a = [1,2,3] b = [1,2,3,4,5] </code></pre> <p>I want to get a third one, containing only the new items (the ones not repeated):</p> <pre><code>c = [4,5] </code></pre> <p>The solution I have right now is:</p> <pre><code>&gt;&gt;&gt; c = [] &gt;&gt;&gt; for i in ab: ... if ab.count(i) == 1: ... c.append(i) &gt;&gt;&gt; c [4, 5] </code></pre> <p>Is there any other way more pythonic than this?</p> <p>Thanx folks!</p>
1
2009-06-30T09:57:34Z
1,063,343
<p>Here are some different possibilities with the sets</p> <pre> >>> a = [1, 2, 3, 4, 5, 1, 2] >>> b = [1, 2, 5, 6] >>> print list(set(a)^set(b)) [3, 4, 6] >>> print list(set(a)-set(b)) [3, 4] >>> print list(set(b)-set(a)) [6] >>> print list(set(a)-set(b))+list(set(b)-set(a)) [3, 4, 6] >>> </pre>
1
2009-06-30T12:20:25Z
[ "python" ]
Python Encryption: Encrypting password using PGP public key
1,063,014
<p>I have the key pair generated by the GPG. Now I want to use the public key for encrypting the password. I need to make a function in Python. Can somebody guide me on how to do this?</p> <p>I studied the Crypto package but was unable to find out how to encrypt the password using the public key.</p> <p>I also read about the chilkat Python encryption library, but it is not giving the desired output. Maybe I don't how to use this library at the SSH secure shell client. Please guide me.</p> <p>Thanks</p>
1
2009-06-30T10:44:23Z
1,063,050
<p>Have a look at <a href="https://www.ohloh.net/p/pygpgme" rel="nofollow" title="PyGPGME">PyGPGME</a></p>
2
2009-06-30T10:51:41Z
[ "python", "encryption", "cryptography", "gnupg" ]
Python Encryption: Encrypting password using PGP public key
1,063,014
<p>I have the key pair generated by the GPG. Now I want to use the public key for encrypting the password. I need to make a function in Python. Can somebody guide me on how to do this?</p> <p>I studied the Crypto package but was unable to find out how to encrypt the password using the public key.</p> <p>I also read about the chilkat Python encryption library, but it is not giving the desired output. Maybe I don't how to use this library at the SSH secure shell client. Please guide me.</p> <p>Thanks</p>
1
2009-06-30T10:44:23Z
1,063,080
<p>See also the answers provided to the following questions found in this search <code>Python Encryption</code> questions at <a href="http://stackoverflow.com/questions/tagged/encryption+python">Stack Overflow</a> :</p> <ul> <li><a href="http://stackoverflow.com/questions/1048722">Python and PGP/encryption</a></li> <li><a href="http://stackoverflow.com/questions/1043382">Encrypt a string using a public key</a></li> <li><a href="http://stackoverflow.com/questions/1020320">How to do PGP in Python (generate keys, encrypt/decrypt)</a></li> </ul>
0
2009-06-30T11:02:10Z
[ "python", "encryption", "cryptography", "gnupg" ]
How can I make a list of files, modification dates and paths?
1,063,037
<p>I have directory with subdirectories and I have to make a list like:</p> <pre><code>file_name1 modification_date1 path1 file_name2 modification_date2 path2 </code></pre> <p>and write the list into text file how can i do it in python?</p>
1
2009-06-30T10:48:42Z
1,063,063
<p>For traversing the subdirectories, use os.walk().</p> <p>For getting modification date, use os.stat()</p> <p>The modification time will be a timestamp counting seconds from epoch, there are various methods in the time module that help you convert those to something easier to use.</p>
3
2009-06-30T10:56:05Z
[ "python" ]
How can I make a list of files, modification dates and paths?
1,063,037
<p>I have directory with subdirectories and I have to make a list like:</p> <pre><code>file_name1 modification_date1 path1 file_name2 modification_date2 path2 </code></pre> <p>and write the list into text file how can i do it in python?</p>
1
2009-06-30T10:48:42Z
1,063,120
<pre><code>import os import time for root, dirs, files in os.walk('your_root_directory'): for f in files: modification_time_seconds = os.stat(os.path.join(root, f)).st_mtime local_mod_time = time.localtime(modification_time_seconds) print '%s %s.%s.%s %s' % (f, local_mod_time.tm_mon, local_mod_time.tm_mday, local_mod_time.tm_year, root) </code></pre>
3
2009-06-30T11:15:01Z
[ "python" ]
Custom Python exception with different include paths
1,063,228
<p><strong>Update:</strong> This is, as I was told, no principle Python related problem, but seems to be more specific. See below for more explanations to my problem.</p> <p>I have a custom exception (let's call it <code>CustomException</code>), that lives in a file named <code>exceptions.py</code>. Now imagine, that I can import this file via two paths:</p> <pre><code>import application.exceptions </code></pre> <p>or</p> <pre><code>import some.application.exceptions </code></pre> <p>with the same result. Furthermore I have no control over which way the module is imported in other modules.</p> <p>Now to show my problem: Assume that the function <code>do_something</code> comes from another module that imports exceptions.py in a way I don't know. If I do this:</p> <pre><code>import application.exceptions try: do_something () except application.exceptions.CustomException: catch_me () </code></pre> <p>it <strong>might</strong> work or not, depending on how the sub-module imported <code>exceptions.py</code> (which I do not know).</p> <p><strong>Question:</strong> Is there a way to circumvent this problem, i.e., a name for the exception that will always be understood regardless of inclusion path? If not, what would be best practices to avoid these name clashes?</p> <p>Cheers,</p> <h2>Update</h2> <p>It is a Django app. <code>some</code> would be the name of the Django 'project', <code>application</code> the name of one Django app. My code with the try..except clause sits in another app, <code>frontend</code>, and lives there as a view in a file <code>some/frontend/views.py</code>.</p> <p>The PYTHONPATH is clean, that is, from my project only <code>/path/to/project</code> is in the path. In the <code>frontend/views.py</code> I import the exceptions.py via <code>import application.exceptions</code>, which seems to work. (Now, in retrospective, I don't know exactly, <strong>why</strong> it works...)</p> <p>The exception is raised in the <code>exceptions.py</code> file itself.</p> <h2>Update 2</h2> <p>It might be interesting for some readers, that I finally found the place, where imports went wrong.</p> <p>The <code>sys.path</code> didn't show any suspect irregularities. My Django project lay in <code>/var/www/django/project</code>. I had installed the apps <code>app1</code> and <code>app2</code>, but noted them in the settings.py as</p> <pre><code>INSTALLED_APPS = [ 'project.app1', 'project.app2', ] </code></pre> <p>The additional <strong><code>project.</code></strong> was the culprit for messing up <code>sys.modules</code>. Rewriting the settings to</p> <pre><code>INSTALLED_APPS = [ 'app1', 'app2', ] </code></pre> <p>solved the problem.</p>
1
2009-06-30T11:45:32Z
1,063,249
<p>Why that would be a problem? exception would me matched based on class type and it would be same however it is imported e.g.</p> <pre><code>import exceptions l=[] try: l[1] except exceptions.IndexError,e: print e try: l[1] except IndexError,e: print e </code></pre> <p>both catch the same exception</p> <p>you can even assign it to a new name, though not recommended usually</p> <pre><code>import os os.myerror = exceptions.IndexError try: l[1] except os.myerror,e: print e </code></pre>
1
2009-06-30T11:51:36Z
[ "python", "django", "exception" ]
Custom Python exception with different include paths
1,063,228
<p><strong>Update:</strong> This is, as I was told, no principle Python related problem, but seems to be more specific. See below for more explanations to my problem.</p> <p>I have a custom exception (let's call it <code>CustomException</code>), that lives in a file named <code>exceptions.py</code>. Now imagine, that I can import this file via two paths:</p> <pre><code>import application.exceptions </code></pre> <p>or</p> <pre><code>import some.application.exceptions </code></pre> <p>with the same result. Furthermore I have no control over which way the module is imported in other modules.</p> <p>Now to show my problem: Assume that the function <code>do_something</code> comes from another module that imports exceptions.py in a way I don't know. If I do this:</p> <pre><code>import application.exceptions try: do_something () except application.exceptions.CustomException: catch_me () </code></pre> <p>it <strong>might</strong> work or not, depending on how the sub-module imported <code>exceptions.py</code> (which I do not know).</p> <p><strong>Question:</strong> Is there a way to circumvent this problem, i.e., a name for the exception that will always be understood regardless of inclusion path? If not, what would be best practices to avoid these name clashes?</p> <p>Cheers,</p> <h2>Update</h2> <p>It is a Django app. <code>some</code> would be the name of the Django 'project', <code>application</code> the name of one Django app. My code with the try..except clause sits in another app, <code>frontend</code>, and lives there as a view in a file <code>some/frontend/views.py</code>.</p> <p>The PYTHONPATH is clean, that is, from my project only <code>/path/to/project</code> is in the path. In the <code>frontend/views.py</code> I import the exceptions.py via <code>import application.exceptions</code>, which seems to work. (Now, in retrospective, I don't know exactly, <strong>why</strong> it works...)</p> <p>The exception is raised in the <code>exceptions.py</code> file itself.</p> <h2>Update 2</h2> <p>It might be interesting for some readers, that I finally found the place, where imports went wrong.</p> <p>The <code>sys.path</code> didn't show any suspect irregularities. My Django project lay in <code>/var/www/django/project</code>. I had installed the apps <code>app1</code> and <code>app2</code>, but noted them in the settings.py as</p> <pre><code>INSTALLED_APPS = [ 'project.app1', 'project.app2', ] </code></pre> <p>The additional <strong><code>project.</code></strong> was the culprit for messing up <code>sys.modules</code>. Rewriting the settings to</p> <pre><code>INSTALLED_APPS = [ 'app1', 'app2', ] </code></pre> <p>solved the problem.</p>
1
2009-06-30T11:45:32Z
1,063,250
<p>Even if the same module is imported several times and in different ways, the CustomException class is still the same object, so it doesn't matter how you refer to it.</p>
0
2009-06-30T11:51:41Z
[ "python", "django", "exception" ]
Custom Python exception with different include paths
1,063,228
<p><strong>Update:</strong> This is, as I was told, no principle Python related problem, but seems to be more specific. See below for more explanations to my problem.</p> <p>I have a custom exception (let's call it <code>CustomException</code>), that lives in a file named <code>exceptions.py</code>. Now imagine, that I can import this file via two paths:</p> <pre><code>import application.exceptions </code></pre> <p>or</p> <pre><code>import some.application.exceptions </code></pre> <p>with the same result. Furthermore I have no control over which way the module is imported in other modules.</p> <p>Now to show my problem: Assume that the function <code>do_something</code> comes from another module that imports exceptions.py in a way I don't know. If I do this:</p> <pre><code>import application.exceptions try: do_something () except application.exceptions.CustomException: catch_me () </code></pre> <p>it <strong>might</strong> work or not, depending on how the sub-module imported <code>exceptions.py</code> (which I do not know).</p> <p><strong>Question:</strong> Is there a way to circumvent this problem, i.e., a name for the exception that will always be understood regardless of inclusion path? If not, what would be best practices to avoid these name clashes?</p> <p>Cheers,</p> <h2>Update</h2> <p>It is a Django app. <code>some</code> would be the name of the Django 'project', <code>application</code> the name of one Django app. My code with the try..except clause sits in another app, <code>frontend</code>, and lives there as a view in a file <code>some/frontend/views.py</code>.</p> <p>The PYTHONPATH is clean, that is, from my project only <code>/path/to/project</code> is in the path. In the <code>frontend/views.py</code> I import the exceptions.py via <code>import application.exceptions</code>, which seems to work. (Now, in retrospective, I don't know exactly, <strong>why</strong> it works...)</p> <p>The exception is raised in the <code>exceptions.py</code> file itself.</p> <h2>Update 2</h2> <p>It might be interesting for some readers, that I finally found the place, where imports went wrong.</p> <p>The <code>sys.path</code> didn't show any suspect irregularities. My Django project lay in <code>/var/www/django/project</code>. I had installed the apps <code>app1</code> and <code>app2</code>, but noted them in the settings.py as</p> <pre><code>INSTALLED_APPS = [ 'project.app1', 'project.app2', ] </code></pre> <p>The additional <strong><code>project.</code></strong> was the culprit for messing up <code>sys.modules</code>. Rewriting the settings to</p> <pre><code>INSTALLED_APPS = [ 'app1', 'app2', ] </code></pre> <p>solved the problem.</p>
1
2009-06-30T11:45:32Z
1,063,253
<p>I don't know if there is a way to handle this inclusion path issue. My suggestion would be to use the 'as' keyword in your import</p> <p>Something like:</p> <p><code>import some.application.exceptions as my_exceptions</code></p> <p>or </p> <p><code>import application.exceptions as my_exceptions</code></p>
0
2009-06-30T11:52:38Z
[ "python", "django", "exception" ]
Custom Python exception with different include paths
1,063,228
<p><strong>Update:</strong> This is, as I was told, no principle Python related problem, but seems to be more specific. See below for more explanations to my problem.</p> <p>I have a custom exception (let's call it <code>CustomException</code>), that lives in a file named <code>exceptions.py</code>. Now imagine, that I can import this file via two paths:</p> <pre><code>import application.exceptions </code></pre> <p>or</p> <pre><code>import some.application.exceptions </code></pre> <p>with the same result. Furthermore I have no control over which way the module is imported in other modules.</p> <p>Now to show my problem: Assume that the function <code>do_something</code> comes from another module that imports exceptions.py in a way I don't know. If I do this:</p> <pre><code>import application.exceptions try: do_something () except application.exceptions.CustomException: catch_me () </code></pre> <p>it <strong>might</strong> work or not, depending on how the sub-module imported <code>exceptions.py</code> (which I do not know).</p> <p><strong>Question:</strong> Is there a way to circumvent this problem, i.e., a name for the exception that will always be understood regardless of inclusion path? If not, what would be best practices to avoid these name clashes?</p> <p>Cheers,</p> <h2>Update</h2> <p>It is a Django app. <code>some</code> would be the name of the Django 'project', <code>application</code> the name of one Django app. My code with the try..except clause sits in another app, <code>frontend</code>, and lives there as a view in a file <code>some/frontend/views.py</code>.</p> <p>The PYTHONPATH is clean, that is, from my project only <code>/path/to/project</code> is in the path. In the <code>frontend/views.py</code> I import the exceptions.py via <code>import application.exceptions</code>, which seems to work. (Now, in retrospective, I don't know exactly, <strong>why</strong> it works...)</p> <p>The exception is raised in the <code>exceptions.py</code> file itself.</p> <h2>Update 2</h2> <p>It might be interesting for some readers, that I finally found the place, where imports went wrong.</p> <p>The <code>sys.path</code> didn't show any suspect irregularities. My Django project lay in <code>/var/www/django/project</code>. I had installed the apps <code>app1</code> and <code>app2</code>, but noted them in the settings.py as</p> <pre><code>INSTALLED_APPS = [ 'project.app1', 'project.app2', ] </code></pre> <p>The additional <strong><code>project.</code></strong> was the culprit for messing up <code>sys.modules</code>. Rewriting the settings to</p> <pre><code>INSTALLED_APPS = [ 'app1', 'app2', ] </code></pre> <p>solved the problem.</p>
1
2009-06-30T11:45:32Z
1,063,297
<p>"If not, what would be best practices to avoid these name clashes?"</p> <p>That depends entirely on why they happen. In a normal installation, you can not import from both application.exceptions and somepath.application.exceptions, unless the first case is a relative path from within the module somepath. And in that case Python will understand that the modules are the same, and you won't have a problem.</p> <p>You are unclear on if you really have a problem or if it's theory. If you do have a problem, I'd guess that there is something fishy with your PYTHONPATH. Maybe both a directory and it's subdirectory is in the PATH?</p>
1
2009-06-30T12:09:29Z
[ "python", "django", "exception" ]
Reversible dictionary for python
1,063,319
<p>I'd like to store some data in Python in a similar form to a dictionary: <code>{1:'a', 2:'b'}</code>. Every value will be unique, not just among other values, but among keys too.</p> <p>Is there a simple data structure that I can use to get the corresponding object no matter if I ask using the 'key' or the 'value'? For example:</p> <pre><code>&gt;&gt;&gt; a = {1:'a', 2:'b'} &gt;&gt;&gt; a[1] 'a' &gt;&gt;&gt; a['b'] 2 &gt;&gt;&gt; a[3] KeyError </code></pre> <p>The 'keys' are standard python ints, an the values are short (&lt;256char) strings.</p> <p>My current solution is creating a reversed dictionary and searching it if I can't find a result in the original dictionary:</p> <pre><code>pointsreversed = dict((v, k) for k, v in points.iteritems()) def lookup(key): return points.get(key) or pointsreversed.key() </code></pre> <p>This uses twice as much space, which isn't great (my dictionaries can be up to a few hundred megs) and is 50% slower on average.</p> <p>EDIT: as mentioned in a few answers, two dicts doesn't double memory usage, as it's only the dictionary, not the items within, that is duplication.</p> <p>Is there a solution that improves on this?</p>
6
2009-06-30T12:15:07Z
1,063,356
<p>Related posts:</p> <p><a href="http://stackoverflow.com/questions/483666/python-reverse-inverse-a-mapping/483833">Python mapping inverse</a></p> <p><a href="http://stackoverflow.com/questions/863935/a-data-structure-for-11-mappings-in-python">Python 1:1 mappings</a></p> <p>Of course, if all values and keys are unique, couldn't you just use a single dictionary, and insert both key:value and value:key initially?</p>
7
2009-06-30T12:22:31Z
[ "python", "dictionary", "hashtable" ]
Reversible dictionary for python
1,063,319
<p>I'd like to store some data in Python in a similar form to a dictionary: <code>{1:'a', 2:'b'}</code>. Every value will be unique, not just among other values, but among keys too.</p> <p>Is there a simple data structure that I can use to get the corresponding object no matter if I ask using the 'key' or the 'value'? For example:</p> <pre><code>&gt;&gt;&gt; a = {1:'a', 2:'b'} &gt;&gt;&gt; a[1] 'a' &gt;&gt;&gt; a['b'] 2 &gt;&gt;&gt; a[3] KeyError </code></pre> <p>The 'keys' are standard python ints, an the values are short (&lt;256char) strings.</p> <p>My current solution is creating a reversed dictionary and searching it if I can't find a result in the original dictionary:</p> <pre><code>pointsreversed = dict((v, k) for k, v in points.iteritems()) def lookup(key): return points.get(key) or pointsreversed.key() </code></pre> <p>This uses twice as much space, which isn't great (my dictionaries can be up to a few hundred megs) and is 50% slower on average.</p> <p>EDIT: as mentioned in a few answers, two dicts doesn't double memory usage, as it's only the dictionary, not the items within, that is duplication.</p> <p>Is there a solution that improves on this?</p>
6
2009-06-30T12:15:07Z
1,063,390
<p>Insert reversed pair of (key, value) into same dict:</p> <pre><code>a = {1:'a', 2:'b'} a.update(dict((v, k) for k, v in a.iteritems())) </code></pre> <p>Then you will be able to do both, as you required:</p> <pre><code>print a[1] print a['a'] </code></pre>
0
2009-06-30T12:30:10Z
[ "python", "dictionary", "hashtable" ]
Reversible dictionary for python
1,063,319
<p>I'd like to store some data in Python in a similar form to a dictionary: <code>{1:'a', 2:'b'}</code>. Every value will be unique, not just among other values, but among keys too.</p> <p>Is there a simple data structure that I can use to get the corresponding object no matter if I ask using the 'key' or the 'value'? For example:</p> <pre><code>&gt;&gt;&gt; a = {1:'a', 2:'b'} &gt;&gt;&gt; a[1] 'a' &gt;&gt;&gt; a['b'] 2 &gt;&gt;&gt; a[3] KeyError </code></pre> <p>The 'keys' are standard python ints, an the values are short (&lt;256char) strings.</p> <p>My current solution is creating a reversed dictionary and searching it if I can't find a result in the original dictionary:</p> <pre><code>pointsreversed = dict((v, k) for k, v in points.iteritems()) def lookup(key): return points.get(key) or pointsreversed.key() </code></pre> <p>This uses twice as much space, which isn't great (my dictionaries can be up to a few hundred megs) and is 50% slower on average.</p> <p>EDIT: as mentioned in a few answers, two dicts doesn't double memory usage, as it's only the dictionary, not the items within, that is duplication.</p> <p>Is there a solution that improves on this?</p>
6
2009-06-30T12:15:07Z
1,063,393
<p>If your keys and values are non-overlapping, one obvious approach is to simply store them in the same dict. ie:</p> <pre><code>class BidirectionalDict(dict): def __setitem__(self, key, val): dict.__setitem__(self, key, val) dict.__setitem__(self, val, key) def __delitem__(self, key): dict.__delitem__(self, self[key]) dict.__delitem__(self, key) d = BidirectionalDict() d['foo'] = 4 print d[4] # Prints 'foo' </code></pre> <p>(You'll also probably want to implement things like the <code>__init__</code>, <code>update</code> and <code>iter*</code> methods to act like a real dict, depending on how much functionality you need).</p> <p>This should only involve one lookup, though may not save you much in memory (you still have twice the number of dict entries after all). Note however that neither this nor your original will use up twice as much space: the dict only takes up space for the references (effectively pointers), plus an overallocation overhead. The space taken up by your data itself will not be repeated twice since the same objects are pointed to.</p>
9
2009-06-30T12:30:19Z
[ "python", "dictionary", "hashtable" ]
Reversible dictionary for python
1,063,319
<p>I'd like to store some data in Python in a similar form to a dictionary: <code>{1:'a', 2:'b'}</code>. Every value will be unique, not just among other values, but among keys too.</p> <p>Is there a simple data structure that I can use to get the corresponding object no matter if I ask using the 'key' or the 'value'? For example:</p> <pre><code>&gt;&gt;&gt; a = {1:'a', 2:'b'} &gt;&gt;&gt; a[1] 'a' &gt;&gt;&gt; a['b'] 2 &gt;&gt;&gt; a[3] KeyError </code></pre> <p>The 'keys' are standard python ints, an the values are short (&lt;256char) strings.</p> <p>My current solution is creating a reversed dictionary and searching it if I can't find a result in the original dictionary:</p> <pre><code>pointsreversed = dict((v, k) for k, v in points.iteritems()) def lookup(key): return points.get(key) or pointsreversed.key() </code></pre> <p>This uses twice as much space, which isn't great (my dictionaries can be up to a few hundred megs) and is 50% slower on average.</p> <p>EDIT: as mentioned in a few answers, two dicts doesn't double memory usage, as it's only the dictionary, not the items within, that is duplication.</p> <p>Is there a solution that improves on this?</p>
6
2009-06-30T12:15:07Z
1,063,408
<p>Here's <a href="http://www.daniweb.com/code/snippet806.html" rel="nofollow">another solution</a> using a user defined class.</p> <p>And the code...</p> <pre><code># search a dictionary for key or value # using named functions or a class # tested with Python25 by Ene Uran 01/19/2008 def find_key(dic, val): """return the key of dictionary dic given the value""" return [k for k, v in symbol_dic.iteritems() if v == val][0] def find_value(dic, key): """return the value of dictionary dic given the key""" return dic[key] class Lookup(dict): """ a dictionary which can lookup value by key, or keys by value """ def __init__(self, items=[]): """items can be a list of pair_lists or a dictionary""" dict.__init__(self, items) def get_key(self, value): """find the key(s) as a list given a value""" return [item[0] for item in self.items() if item[1] == value] def get_value(self, key): """find the value given a key""" return self[key] </code></pre>
0
2009-06-30T12:33:17Z
[ "python", "dictionary", "hashtable" ]
Reversible dictionary for python
1,063,319
<p>I'd like to store some data in Python in a similar form to a dictionary: <code>{1:'a', 2:'b'}</code>. Every value will be unique, not just among other values, but among keys too.</p> <p>Is there a simple data structure that I can use to get the corresponding object no matter if I ask using the 'key' or the 'value'? For example:</p> <pre><code>&gt;&gt;&gt; a = {1:'a', 2:'b'} &gt;&gt;&gt; a[1] 'a' &gt;&gt;&gt; a['b'] 2 &gt;&gt;&gt; a[3] KeyError </code></pre> <p>The 'keys' are standard python ints, an the values are short (&lt;256char) strings.</p> <p>My current solution is creating a reversed dictionary and searching it if I can't find a result in the original dictionary:</p> <pre><code>pointsreversed = dict((v, k) for k, v in points.iteritems()) def lookup(key): return points.get(key) or pointsreversed.key() </code></pre> <p>This uses twice as much space, which isn't great (my dictionaries can be up to a few hundred megs) and is 50% slower on average.</p> <p>EDIT: as mentioned in a few answers, two dicts doesn't double memory usage, as it's only the dictionary, not the items within, that is duplication.</p> <p>Is there a solution that improves on this?</p>
6
2009-06-30T12:15:07Z
1,063,463
<p>In The Art of Computer Programming, Vokume 3 Knuth has a section on lookups of secondary keys. For purposes of your question, the value could be considered the secondary key.</p> <p>The first suggestion is to do what you have done: make an efficient index of the keys by value.</p> <p>The second suggestion is to setup a large btree that is a composite index of the clustered data, where the branch nodes contain values and the leaves contain the key data and pointers to the larger record (if there is one.)</p> <p>If the data is geometric (as yours appears to be) there are things called post-office trees. It can answer questions like, what is the nearest object to point x. A few examples are here: <a href="http://simsearch.yury.name/russir/01nncourse-hand.pdf" rel="nofollow">http://simsearch.yury.name/russir/01nncourse-hand.pdf</a> Another simple option for this kind of query is the quadtree and the k-d tree. <a href="http://en.wikipedia.org/wiki/Quadtree" rel="nofollow">http://en.wikipedia.org/wiki/Quadtree</a></p> <p>Another final option is combinatorial hashing, where you combine the key and value into a special kind of hash that lets you do efficient lookups on the hash, even when you don't have both values. I couldn't find a good combinatorial hash explanation online, but it is in TAoCP, Volume 3 Second Edition on page 573.</p> <p>Granted, for some of these you may have to write your own code. But if memory or performance is really key, you might want to take the time.</p>
2
2009-06-30T12:46:10Z
[ "python", "dictionary", "hashtable" ]
Reversible dictionary for python
1,063,319
<p>I'd like to store some data in Python in a similar form to a dictionary: <code>{1:'a', 2:'b'}</code>. Every value will be unique, not just among other values, but among keys too.</p> <p>Is there a simple data structure that I can use to get the corresponding object no matter if I ask using the 'key' or the 'value'? For example:</p> <pre><code>&gt;&gt;&gt; a = {1:'a', 2:'b'} &gt;&gt;&gt; a[1] 'a' &gt;&gt;&gt; a['b'] 2 &gt;&gt;&gt; a[3] KeyError </code></pre> <p>The 'keys' are standard python ints, an the values are short (&lt;256char) strings.</p> <p>My current solution is creating a reversed dictionary and searching it if I can't find a result in the original dictionary:</p> <pre><code>pointsreversed = dict((v, k) for k, v in points.iteritems()) def lookup(key): return points.get(key) or pointsreversed.key() </code></pre> <p>This uses twice as much space, which isn't great (my dictionaries can be up to a few hundred megs) and is 50% slower on average.</p> <p>EDIT: as mentioned in a few answers, two dicts doesn't double memory usage, as it's only the dictionary, not the items within, that is duplication.</p> <p>Is there a solution that improves on this?</p>
6
2009-06-30T12:15:07Z
1,529,173
<p>It shouldn't use "twice the space". Dictionaries just store references to data, not the data itself. So, if you have a million strings taking up a billion bytes, then each dictionary takes maybe an extra 10-20 million bytes--a tiny fraction of the overall storage. Using two dictionaries is the right thing to do.</p>
1
2009-10-07T02:21:03Z
[ "python", "dictionary", "hashtable" ]
Python IRC client: write from scratch or write plugin for existing framework?
1,063,409
<p>For our company I'd like to have a Python based IRC bot which checks whether the websites of our clients are still up and running. More specific: I want to list a number of URL which should be visited every, say, 15 minutes. If it fails, the URL should be checked again after 5 minutes. If retrieving the URL still doesn't result in an HTTP status code 200, it should echo the failing URL in the channel so we can investigate it.</p> <p>I've written a plugin for <a href="http://sourceforge.net/projects/supybot/" rel="nofollow">Supybot</a> some time ago that basically does some of the above in a crude but effective way. If I want to expand the functionality of the current code to the above 'specs' I need to do some major refactoring; basically it would mean starting from scratch.</p> <p>Which raises the question: should I write a better plugin for Supybot, matching the new requirements, or go for something else altogether? Should I start from scratch (learning the most, implementing the <a href="http://stackoverflow.com/questions/24310/programming-a-simple-irc-internet-relay-chat-client/844821#844821">relevant RFCs</a> myself, spending more time than planned) or is there a suitable framework which handles the basic IRC stuff?</p>
4
2009-06-30T12:33:19Z
1,063,480
<p>To me it sounds like a case of your application wanting to talk IRC, and my gut reaction would be to use Twisted, which has IRC clients. This may or may not be the right solution for you, but at least it's worth investigating.</p>
3
2009-06-30T12:48:53Z
[ "python", "irc" ]
Python IRC client: write from scratch or write plugin for existing framework?
1,063,409
<p>For our company I'd like to have a Python based IRC bot which checks whether the websites of our clients are still up and running. More specific: I want to list a number of URL which should be visited every, say, 15 minutes. If it fails, the URL should be checked again after 5 minutes. If retrieving the URL still doesn't result in an HTTP status code 200, it should echo the failing URL in the channel so we can investigate it.</p> <p>I've written a plugin for <a href="http://sourceforge.net/projects/supybot/" rel="nofollow">Supybot</a> some time ago that basically does some of the above in a crude but effective way. If I want to expand the functionality of the current code to the above 'specs' I need to do some major refactoring; basically it would mean starting from scratch.</p> <p>Which raises the question: should I write a better plugin for Supybot, matching the new requirements, or go for something else altogether? Should I start from scratch (learning the most, implementing the <a href="http://stackoverflow.com/questions/24310/programming-a-simple-irc-internet-relay-chat-client/844821#844821">relevant RFCs</a> myself, spending more time than planned) or is there a suitable framework which handles the basic IRC stuff?</p>
4
2009-06-30T12:33:19Z
1,063,485
<p>I vote for a completely new plugin for Supybot. Learn more ;)</p> <p>If you won't do so much, try <strong>python <a href="http://sourceforge.net/project/showfiles.php?group%5Fid=38297" rel="nofollow">irclib</a></strong>. It's a (still maintained) python lib for IRC.</p> <p><a href="http://twistedmatrix.com/trac/" rel="nofollow">Twisted</a> may also be ok, but it's a little but too much...</p>
4
2009-06-30T12:49:25Z
[ "python", "irc" ]
Python IRC client: write from scratch or write plugin for existing framework?
1,063,409
<p>For our company I'd like to have a Python based IRC bot which checks whether the websites of our clients are still up and running. More specific: I want to list a number of URL which should be visited every, say, 15 minutes. If it fails, the URL should be checked again after 5 minutes. If retrieving the URL still doesn't result in an HTTP status code 200, it should echo the failing URL in the channel so we can investigate it.</p> <p>I've written a plugin for <a href="http://sourceforge.net/projects/supybot/" rel="nofollow">Supybot</a> some time ago that basically does some of the above in a crude but effective way. If I want to expand the functionality of the current code to the above 'specs' I need to do some major refactoring; basically it would mean starting from scratch.</p> <p>Which raises the question: should I write a better plugin for Supybot, matching the new requirements, or go for something else altogether? Should I start from scratch (learning the most, implementing the <a href="http://stackoverflow.com/questions/24310/programming-a-simple-irc-internet-relay-chat-client/844821#844821">relevant RFCs</a> myself, spending more time than planned) or is there a suitable framework which handles the basic IRC stuff?</p>
4
2009-06-30T12:33:19Z
1,063,724
<p>Writing a simple IRC bot isn't that hard. I have a template I keep using for my bots, which range from SVN bots to voting-status bots to bots which check connections to certain IPs and change the channel's topic according to the result.</p> <p>I can share the source if you'd like, though there's nothing like writing your own :)</p>
1
2009-06-30T13:33:44Z
[ "python", "irc" ]
Python IRC client: write from scratch or write plugin for existing framework?
1,063,409
<p>For our company I'd like to have a Python based IRC bot which checks whether the websites of our clients are still up and running. More specific: I want to list a number of URL which should be visited every, say, 15 minutes. If it fails, the URL should be checked again after 5 minutes. If retrieving the URL still doesn't result in an HTTP status code 200, it should echo the failing URL in the channel so we can investigate it.</p> <p>I've written a plugin for <a href="http://sourceforge.net/projects/supybot/" rel="nofollow">Supybot</a> some time ago that basically does some of the above in a crude but effective way. If I want to expand the functionality of the current code to the above 'specs' I need to do some major refactoring; basically it would mean starting from scratch.</p> <p>Which raises the question: should I write a better plugin for Supybot, matching the new requirements, or go for something else altogether? Should I start from scratch (learning the most, implementing the <a href="http://stackoverflow.com/questions/24310/programming-a-simple-irc-internet-relay-chat-client/844821#844821">relevant RFCs</a> myself, spending more time than planned) or is there a suitable framework which handles the basic IRC stuff?</p>
4
2009-06-30T12:33:19Z
1,129,917
<p>I finally decided to create use <a href="http://twistedmatrix.com/trac/" rel="nofollow">Twisted</a> for my bot. As to the why:</p> <ul> <li><p><a href="http://sourceforge.net/projects/supybot/" rel="nofollow">Supybot</a> already has a lot of functionality. And that can be a good thing: just create a simple plugin, hook it up and start using the bot. The downside is that you may not like some of the functionality already provided for. As an example: I didn't like the fact that it responded to everything (Error: "foo" is not a valid command.). I'm sure it can be turned off somehow somewhere, but these kind of small things bothered me.</p></li> <li><p>The <a href="http://sourceforge.net/project/showfiles.php?group%5Fid=38297" rel="nofollow">Python IRC client library</a> on the other hand felt a little too bare bones. Especially since I needed threading to have the bot check a whether a number of websites are still alive while remaining responsive in the channel.</p></li> <li><p>If the irclib felt like too low level, writing a bot from scratch would certainly be. While I definitely wanted to learn something, I also wanted to focus on the actual functionality of the bot, without being bothered too much by the 'basic' stuff (e.g. I don't necessarily want to write the code to identify the bot, I like to just have some configuration setting to store the nickname and password and handle this for me.)</p></li> </ul> <p>Twisted has a nice example of a <a href="http://twistedmatrix.com/projects/words/documentation/examples/ircLogBot.py" rel="nofollow">logging bot</a> which can be used as a starting point. Furthermore: in the future it should not be too hard to write a small webserver (using Twisted obviously) to display the output of the bot.</p> <p>Tip: besides the <a href="http://twistedmatrix.com/trac/wiki/Documentation" rel="nofollow">Twisted documentation</a> you can also take a look at the <a href="http://pymag.phparch.com/c/issue/view/83" rel="nofollow">October 2008 issue of Python Magazine</a> for the article "A Twisted Logging Server" by Doug Farrell.</p> <p>Thanks to the ones who answered the question. You set me on the right track. :)</p>
2
2009-07-15T07:29:39Z
[ "python", "irc" ]
Python IRC client: write from scratch or write plugin for existing framework?
1,063,409
<p>For our company I'd like to have a Python based IRC bot which checks whether the websites of our clients are still up and running. More specific: I want to list a number of URL which should be visited every, say, 15 minutes. If it fails, the URL should be checked again after 5 minutes. If retrieving the URL still doesn't result in an HTTP status code 200, it should echo the failing URL in the channel so we can investigate it.</p> <p>I've written a plugin for <a href="http://sourceforge.net/projects/supybot/" rel="nofollow">Supybot</a> some time ago that basically does some of the above in a crude but effective way. If I want to expand the functionality of the current code to the above 'specs' I need to do some major refactoring; basically it would mean starting from scratch.</p> <p>Which raises the question: should I write a better plugin for Supybot, matching the new requirements, or go for something else altogether? Should I start from scratch (learning the most, implementing the <a href="http://stackoverflow.com/questions/24310/programming-a-simple-irc-internet-relay-chat-client/844821#844821">relevant RFCs</a> myself, spending more time than planned) or is there a suitable framework which handles the basic IRC stuff?</p>
4
2009-06-30T12:33:19Z
23,969,017
<p>irc3 is a plugable irc client library based on asyncio and venusian <a href="https://irc3.readthedocs.org/" rel="nofollow">https://irc3.readthedocs.org/</a></p>
1
2014-05-31T10:36:14Z
[ "python", "irc" ]
Equivalent to Python’s findall() method in Ruby?
1,063,593
<p>I need to extract all MP3 titles from a fuzzy list in a list.</p> <p>With Python this works for me fine:</p> <pre><code>import re for i in re.compile('mmc.+?mp3').findall(open("tracklist.txt").read()): print i </code></pre> <p>How can I do that in Ruby?</p>
2
2009-06-30T13:09:06Z
1,063,674
<p>I don't know python very well, but it should be</p> <pre><code>File.read("tracklist.txt").matches(/mmc.+?mp3/).to_a.each { |match| puts match } </code></pre> <p>or</p> <pre><code>File.read("tracklist.txt").scan(/mmc.+?mp3/) { |match| puts match } </code></pre>
3
2009-06-30T13:25:17Z
[ "python", "ruby", "regex" ]
Equivalent to Python’s findall() method in Ruby?
1,063,593
<p>I need to extract all MP3 titles from a fuzzy list in a list.</p> <p>With Python this works for me fine:</p> <pre><code>import re for i in re.compile('mmc.+?mp3').findall(open("tracklist.txt").read()): print i </code></pre> <p>How can I do that in Ruby?</p>
2
2009-06-30T13:09:06Z
1,063,684
<pre><code>f = File.new("tracklist.txt", "r") s = f.read s.scan(/mmc.+?mp3/) do |track| puts track end </code></pre> <p>What this code does is open the file for reading and reads the contents as a string into variable <code>s</code>. Then the string is scanned for the regular expression <code>/mmc.+?mp3/</code> (<a href="http://www.ruby-doc.org/core/classes/String.html#M001711"><code>String#scan</code></a> collects an array of all matches), and prints each one it finds.</p>
5
2009-06-30T13:26:05Z
[ "python", "ruby", "regex" ]
Equivalent to Python’s findall() method in Ruby?
1,063,593
<p>I need to extract all MP3 titles from a fuzzy list in a list.</p> <p>With Python this works for me fine:</p> <pre><code>import re for i in re.compile('mmc.+?mp3').findall(open("tracklist.txt").read()): print i </code></pre> <p>How can I do that in Ruby?</p>
2
2009-06-30T13:09:06Z
10,491,306
<p>even more simply:</p> <pre><code>puts File.read('tracklist.txt').scan /mmc.+?mp3/ </code></pre>
0
2012-05-08T01:23:15Z
[ "python", "ruby", "regex" ]
Python SQL Select with possible NULL values
1,063,601
<p>I'm new to python and have hit a problem with an SQL query I'm trying to perform.</p> <p>I am creating an SQL SELECT statement that is populated with values from an array as follows:</p> <pre><code>ret = conn.execute('SELECT * FROM TestTable WHERE a = ? b = ? c = ?', *values) </code></pre> <p>This works ok where I have real values in the values array. However in some cases an individual entry in values may be set to None. The query then fails because the "= NULL" test does not work since the test should be IS NULL.</p> <p>Is there an easy way around this?</p>
1
2009-06-30T13:10:06Z
1,063,624
<p>Use : "Select * from testtable where (a = ? or a is null) and (b=? or b is null) "</p> <p>This will select cases where a exactly matches the supplied value and will include the null values in the column - if that is what you want.</p>
3
2009-06-30T13:14:49Z
[ "python", "sql", null ]
Python SQL Select with possible NULL values
1,063,601
<p>I'm new to python and have hit a problem with an SQL query I'm trying to perform.</p> <p>I am creating an SQL SELECT statement that is populated with values from an array as follows:</p> <pre><code>ret = conn.execute('SELECT * FROM TestTable WHERE a = ? b = ? c = ?', *values) </code></pre> <p>This works ok where I have real values in the values array. However in some cases an individual entry in values may be set to None. The query then fails because the "= NULL" test does not work since the test should be IS NULL.</p> <p>Is there an easy way around this?</p>
1
2009-06-30T13:10:06Z
1,063,740
<p>If you're feeling adventurous, you could also check out SQLAlchemy. It provides amongst a lot of other things an SQL construction toolkit that automatically converts comparisons to None into IS NULL operations.</p>
0
2009-06-30T13:37:28Z
[ "python", "sql", null ]
Python SQL Select with possible NULL values
1,063,601
<p>I'm new to python and have hit a problem with an SQL query I'm trying to perform.</p> <p>I am creating an SQL SELECT statement that is populated with values from an array as follows:</p> <pre><code>ret = conn.execute('SELECT * FROM TestTable WHERE a = ? b = ? c = ?', *values) </code></pre> <p>This works ok where I have real values in the values array. However in some cases an individual entry in values may be set to None. The query then fails because the "= NULL" test does not work since the test should be IS NULL.</p> <p>Is there an easy way around this?</p>
1
2009-06-30T13:10:06Z
1,063,764
<p>You can always use the ternary operator to switch '=' for 'IS':<br/></p> <pre><code>("=","IS")[var is None] </code></pre> <p>Would return "IS" if var is None and "=" otherwise.</p> <p>It's not very elegant to do this in one line though, but just for demonstrating:</p> <pre><code>query = "SELECT * FROM testTable WHERE a %s %s" % ( ("=","IS")[a is None], str(a) ) </code></pre>
1
2009-06-30T13:43:51Z
[ "python", "sql", null ]
Python SQL Select with possible NULL values
1,063,601
<p>I'm new to python and have hit a problem with an SQL query I'm trying to perform.</p> <p>I am creating an SQL SELECT statement that is populated with values from an array as follows:</p> <pre><code>ret = conn.execute('SELECT * FROM TestTable WHERE a = ? b = ? c = ?', *values) </code></pre> <p>This works ok where I have real values in the values array. However in some cases an individual entry in values may be set to None. The query then fails because the "= NULL" test does not work since the test should be IS NULL.</p> <p>Is there an easy way around this?</p>
1
2009-06-30T13:10:06Z
1,063,964
<p>If you are using SQL Server then as long as you set ANSI_NULLS off for the session '= null' comparison will work. </p> <p><a href="http://msdn.microsoft.com/en-us/library/ms188048.aspx" rel="nofollow">SET ANSI_NULLS</a></p>
1
2009-06-30T14:22:56Z
[ "python", "sql", null ]
Python SQL Select with possible NULL values
1,063,601
<p>I'm new to python and have hit a problem with an SQL query I'm trying to perform.</p> <p>I am creating an SQL SELECT statement that is populated with values from an array as follows:</p> <pre><code>ret = conn.execute('SELECT * FROM TestTable WHERE a = ? b = ? c = ?', *values) </code></pre> <p>This works ok where I have real values in the values array. However in some cases an individual entry in values may be set to None. The query then fails because the "= NULL" test does not work since the test should be IS NULL.</p> <p>Is there an easy way around this?</p>
1
2009-06-30T13:10:06Z
6,719,784
<p>First and foremost, I would strongly caution you against using <code>SELECT * FROM tbl WHERE (col = :x OR col IS NULL)</code> as this will most likely disqualify your query from indexing (use a query profiler). <code>SET ANSI_NULLS</code> is also one of those things that may not be supported in your particular database type.</p> <p>A better solution (or at least a more universal solution) is, if your SQL dialect supports <code>Coalesce</code>, to write your query like this:</p> <pre><code>SELECT * FROM tbl WHERE col = COALESCE(:x, col) </code></pre> <p>Since <code>col = col</code> will always evaluate to true, passing in <code>NULL</code> for <code>:x</code> won't damage your query, and should allow for a more efficient query plan. This also has the advantage that it works from within a stored procedure, where you may not have the liberty of dynamically building a query string.</p>
0
2011-07-16T19:42:59Z
[ "python", "sql", null ]
Python SQL Select with possible NULL values
1,063,601
<p>I'm new to python and have hit a problem with an SQL query I'm trying to perform.</p> <p>I am creating an SQL SELECT statement that is populated with values from an array as follows:</p> <pre><code>ret = conn.execute('SELECT * FROM TestTable WHERE a = ? b = ? c = ?', *values) </code></pre> <p>This works ok where I have real values in the values array. However in some cases an individual entry in values may be set to None. The query then fails because the "= NULL" test does not work since the test should be IS NULL.</p> <p>Is there an easy way around this?</p>
1
2009-06-30T13:10:06Z
33,132,828
<p>The following was tested on python sqlite3 by now, however it should work in other DB types since it quite general. The approach is the same to @MoshiBin answer with some additions:</p> <p>Here is the form using cursor.execute() regular syntax, so the null variables is not supported while using this form:</p> <pre><code>import sqlite3 conn = sqlite3.connect('mydbfile.db') c = conn.cursor() c.execute('SELECT * FROM TestTable WHERE colname = ?', (a, )) </code></pre> <p>In order to support null variables you may replace the 4th line to:</p> <pre><code>request = 'SELECT * FROM TestTable WHERE colname %s' % ('= ' + str(a) if a else 'IS NULL') c.execute(request) </code></pre> <p>Besides that if the variable is in text type, you also need to include a quotes:</p> <pre><code>request = "SELECT * FROM TestTable WHERE colname %s" % ("= '" + a + "'" if a else 'IS NULL') </code></pre> <p>Finaly if a variable can contain a single quotes itself, you also need to escape it by doubling:</p> <pre><code>request = "SELECT * FROM TestTable WHERE colname %s" % ("= '" + a.replace("'", "''") + "'" if a else 'IS NULL') </code></pre> <p><em>Edit</em>:<br> Lately I have found two other approaches that also can be used in this case and uses regular cursor.execute() syntax, however I did't test this ones by now:</p> <pre><code>c.execute('SELECT * FROM TestTable WHERE colname = :1 OR (:1 IS NULL AND colname IS NULL)', {'1': a}) </code></pre> <p>(Thx to @BillKarwin <a href="http://stackoverflow.com/a/7367450">answer</a>) </p> <p>or, using the CASE expression:</p> <pre><code>c.execute('SELECT * FROM TestTable WHERE CASE :1 WHEN NOT NULL THEN colname = :1 ELSE colname IS NULL END', {'1': a}) </code></pre>
0
2015-10-14T18:22:40Z
[ "python", "sql", null ]
how to use french letters in a django template?
1,063,626
<p>I have some french letters (é, è, à...) in a django template but when it is loaded by django, an UnicodeDecodeError exception is raised.</p> <p>If I don't load the template but directly use a python string. It works ok.</p> <p>Is there something to do to use unicode with django template?</p>
5
2009-06-30T13:14:59Z
1,063,665
<p>You are probably storing the template in a non-unicode encoding, such as latin-1. I believe Django assumes that templates are in UTF-8 by default (though there is a setting to override this).</p> <p>Your editor should be capable of saving the template file in the UTF-8 encoding (probably via a dropdown on the save as page, though this may depend on your editor). Re-save the file as UTF-8, and the error should go away.</p>
7
2009-06-30T13:23:52Z
[ "python", "django", "unicode" ]
how to use french letters in a django template?
1,063,626
<p>I have some french letters (é, è, à...) in a django template but when it is loaded by django, an UnicodeDecodeError exception is raised.</p> <p>If I don't load the template but directly use a python string. It works ok.</p> <p>Is there something to do to use unicode with django template?</p>
5
2009-06-30T13:14:59Z
1,063,676
<p>This is from the <a href="http://docs.djangoproject.com/en/dev/ref/unicode/#templates" rel="nofollow">Django unicode documentation</a> related to your problem:</p> <p>" But the common case is to read templates from the filesystem, and this creates a slight complication: not all filesystems store their data encoded as UTF-8. If your template files are not stored with a UTF-8 encoding, set the <a href="http://docs.djangoproject.com/en/dev/ref/settings/#setting-FILE%5FCHARSET" rel="nofollow">FILE_CHARSET</a> setting to the encoding of the files on disk. When Django reads in a template file, it will convert the data from this encoding to Unicode. (<a href="http://docs.djangoproject.com/en/dev/ref/settings/#setting-FILE%5FCHARSET" rel="nofollow">FILE_CHARSET</a> is set to 'utf-8' by default.)</p> <p>The <a href="http://docs.djangoproject.com/en/dev/ref/settings/#setting-DEFAULT%5FCHARSET" rel="nofollow">DEFAULT_CHARSET</a> setting controls the encoding of rendered templates. This is set to UTF-8 by default. "</p>
3
2009-06-30T13:25:31Z
[ "python", "django", "unicode" ]
PyQt: Consolidating signals to a single slot
1,063,734
<p>I am attempting to reduce the amount of signals I have to use in my contextmenus. The menu consists of actions which switches the operation mode of the program, so the operation carried out by the slots is very simple. Quoting the documentation on QMenu::triggered,</p> <blockquote> <p>Normally, you connect each menu action's triggered() signal to its own custom slot, but sometimes you will want to connect several actions to a single slot, for example, when you have a group of closely related actions, such as "left justify", "center", "right justify".</p> </blockquote> <p>However, I can't figure out how to accomplish this, and the documentation does not go into any further detail.<br /> Suppose I have actions <code>actionOpMode1</code> and <code>actionOpMode2</code> in menu <code>actionMenu</code>, and a slot <code>setOpMode</code>. I want <code>setOpMode</code> to be called with a parameter which somehow relates to which of the actions was triggered. I tried various permutations on this theme:</p> <pre><code> QObject.connect(self.actionMenu, SIGNAL('triggered(QAction)'), self.setOpMode) </code></pre> <p>But I never even got it to call setOpMode, which suggests that actionMenu never "feels triggered", so to speak.</p> <p>In <a href="http://stackoverflow.com/questions/940555/pyqt-sending-parameter-to-slot-when-connecting-to-a-signal">this SO question</a>, it's suggested that it can be done with lamdbas, but this:</p> <pre><code> QObject.connect(self.actionOpMode1, SIGNAL('triggered()'), lambda t: self.setOpMode(t)) </code></pre> <p>gives <code>"&lt;lambda&gt; () takes exactly 1 argument (0 given)"</code>. I can't say I really understand how this is supposed to work, so I may have done something wrong when moving from clicked() to triggered().</p> <p>How is it done?</p>
2
2009-06-30T13:36:18Z
1,063,789
<p>You can use <a href="http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/qobject.html#sender" rel="nofollow">QObject::sender()</a> to figure out which QAction emitted the signal.</p> <p>So your slot might look like this:</p> <pre><code>def triggered(self): sender = QtCore.QObject.sender() if sender == self.actionOpMode1: # do something elif sender == self.actionOpMode2: # do something else </code></pre> <p>Regarding what's going on in the other SO question you mentioned with the lambda, what it does is create a lambda with one parameter which has a default value so to apply that to your example you'd need to do something like this:</p> <pre><code>self.connect(self.actionOpMode1, QtCore.SIGNAL('triggered()'), lambda who="mode1": self.changeMode(who)) self.connect(self.actionOpMode2, QtCore.SIGNAL('triggered()'), lambda who="mode2": self.changeMode(who)) </code></pre> <p>And then have a member function like this:</p> <pre><code>def changeMode(self, who): if who == "mode1": # ... elif who == "mode2": # ... </code></pre> <p>Personally the first approach looks cleaner and more readable to me.</p>
1
2009-06-30T13:48:34Z
[ "python", "qt" ]
PyQt: Consolidating signals to a single slot
1,063,734
<p>I am attempting to reduce the amount of signals I have to use in my contextmenus. The menu consists of actions which switches the operation mode of the program, so the operation carried out by the slots is very simple. Quoting the documentation on QMenu::triggered,</p> <blockquote> <p>Normally, you connect each menu action's triggered() signal to its own custom slot, but sometimes you will want to connect several actions to a single slot, for example, when you have a group of closely related actions, such as "left justify", "center", "right justify".</p> </blockquote> <p>However, I can't figure out how to accomplish this, and the documentation does not go into any further detail.<br /> Suppose I have actions <code>actionOpMode1</code> and <code>actionOpMode2</code> in menu <code>actionMenu</code>, and a slot <code>setOpMode</code>. I want <code>setOpMode</code> to be called with a parameter which somehow relates to which of the actions was triggered. I tried various permutations on this theme:</p> <pre><code> QObject.connect(self.actionMenu, SIGNAL('triggered(QAction)'), self.setOpMode) </code></pre> <p>But I never even got it to call setOpMode, which suggests that actionMenu never "feels triggered", so to speak.</p> <p>In <a href="http://stackoverflow.com/questions/940555/pyqt-sending-parameter-to-slot-when-connecting-to-a-signal">this SO question</a>, it's suggested that it can be done with lamdbas, but this:</p> <pre><code> QObject.connect(self.actionOpMode1, SIGNAL('triggered()'), lambda t: self.setOpMode(t)) </code></pre> <p>gives <code>"&lt;lambda&gt; () takes exactly 1 argument (0 given)"</code>. I can't say I really understand how this is supposed to work, so I may have done something wrong when moving from clicked() to triggered().</p> <p>How is it done?</p>
2
2009-06-30T13:36:18Z
1,063,960
<p>I use this approach:</p> <pre><code>from functools import partial def bind(self, action, *params): self.connect(action, QtCore.SIGNAL('triggered()'), partial(action, *params, self.onMenuAction)) def onMenuAction(self, *args): pass bind(self.actionOpMode1, 'action1') bind(self.actionOpMode2, 'action2') </code></pre>
2
2009-06-30T14:22:14Z
[ "python", "qt" ]
PyQt: Consolidating signals to a single slot
1,063,734
<p>I am attempting to reduce the amount of signals I have to use in my contextmenus. The menu consists of actions which switches the operation mode of the program, so the operation carried out by the slots is very simple. Quoting the documentation on QMenu::triggered,</p> <blockquote> <p>Normally, you connect each menu action's triggered() signal to its own custom slot, but sometimes you will want to connect several actions to a single slot, for example, when you have a group of closely related actions, such as "left justify", "center", "right justify".</p> </blockquote> <p>However, I can't figure out how to accomplish this, and the documentation does not go into any further detail.<br /> Suppose I have actions <code>actionOpMode1</code> and <code>actionOpMode2</code> in menu <code>actionMenu</code>, and a slot <code>setOpMode</code>. I want <code>setOpMode</code> to be called with a parameter which somehow relates to which of the actions was triggered. I tried various permutations on this theme:</p> <pre><code> QObject.connect(self.actionMenu, SIGNAL('triggered(QAction)'), self.setOpMode) </code></pre> <p>But I never even got it to call setOpMode, which suggests that actionMenu never "feels triggered", so to speak.</p> <p>In <a href="http://stackoverflow.com/questions/940555/pyqt-sending-parameter-to-slot-when-connecting-to-a-signal">this SO question</a>, it's suggested that it can be done with lamdbas, but this:</p> <pre><code> QObject.connect(self.actionOpMode1, SIGNAL('triggered()'), lambda t: self.setOpMode(t)) </code></pre> <p>gives <code>"&lt;lambda&gt; () takes exactly 1 argument (0 given)"</code>. I can't say I really understand how this is supposed to work, so I may have done something wrong when moving from clicked() to triggered().</p> <p>How is it done?</p>
2
2009-06-30T13:36:18Z
1,063,969
<p>Using QObject.Sender is one of the solution, although not the cleanest one.</p> <p>Use <a href="http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/qsignalmapper.html" rel="nofollow">QSignalMapper</a> to associate cleanly a value with the object that emitted the signal.</p>
3
2009-06-30T14:24:16Z
[ "python", "qt" ]
In Python, Using pyodbc, How Do You Perform Transactions?
1,063,770
<p>I have a username which I must change in numerous (up to ~25) tables. (Yeah, I know.) An atomic transaction seems to be the way to go for this sort of thing. However, I do not know how to do this with pyodbc. I've seen various tutorials on atomic transactions before, but have never used them.</p> <p>The setup: Windows platform, Python 2.6, pyodbc, Microsoft SQL 2005. I've used pyodbc for single SQL statements, but no compound statements or transactions.</p> <p>Best practices for SQL seem to suggest that creating a stored procedure is excellent for this. My fears about doing a stored procedure are as follows, in order of increasing importance: 1) I have never written a stored procedure. 2) I heard that pyodbc does not return results from stored procedures as of yet. 3) This is most definitely Not My Database. It's vendor-supplied, vendor-updated, and so forth.</p> <p>So, what's the best way to go about this? </p>
1
2009-06-30T13:45:12Z
1,063,879
<p>I don't think pyodbc has any specific support for transactions. You need to send the SQL command to start/commit/rollback transactions.</p>
-2
2009-06-30T14:05:06Z
[ "python", "transactions", "pyodbc" ]
In Python, Using pyodbc, How Do You Perform Transactions?
1,063,770
<p>I have a username which I must change in numerous (up to ~25) tables. (Yeah, I know.) An atomic transaction seems to be the way to go for this sort of thing. However, I do not know how to do this with pyodbc. I've seen various tutorials on atomic transactions before, but have never used them.</p> <p>The setup: Windows platform, Python 2.6, pyodbc, Microsoft SQL 2005. I've used pyodbc for single SQL statements, but no compound statements or transactions.</p> <p>Best practices for SQL seem to suggest that creating a stored procedure is excellent for this. My fears about doing a stored procedure are as follows, in order of increasing importance: 1) I have never written a stored procedure. 2) I heard that pyodbc does not return results from stored procedures as of yet. 3) This is most definitely Not My Database. It's vendor-supplied, vendor-updated, and so forth.</p> <p>So, what's the best way to go about this? </p>
1
2009-06-30T13:45:12Z
1,064,149
<p>By its <a href="http://code.google.com/p/pyodbc/wiki/FAQs#Connecting%5Ffails%5Fwith%5Fan%5Ferror%5Fabout%5FSQL%5FATTR%5FAUTOCOMMIT">documentation</a>, pyodbc does support transactions, but only if the odbc driver support it. Furthermore, as pyodbc is compliant with <a href="http://www.python.org/dev/peps/pep-0249/">PEP 249</a>, data is stored only when a manual commit is done.<br /> However, it also support autocommit feature, and in that case you cannot have any transaction.</p> <p>You should check the connection, when it is performed</p> <pre><code>cnxn = pyodbc.connect(cstring, autocommit=True) </code></pre> <p>or explicitely turn off the autocommit mode with</p> <pre><code>cnxn.autocommit = False </code></pre> <p>Note: you can get more information on the autocommit mode of pyodbc on its <a href="http://code.google.com/p/pyodbc/wiki/Features">wiki</a></p> <p>Once autocommit is turned off, then you have to explicitely commit() the transaction, or rollback() the entire transaction.</p>
6
2009-06-30T14:57:31Z
[ "python", "transactions", "pyodbc" ]
Hex data from socket, process and response
1,063,775
<p>Lets put it in parts.</p> <p>I got a socket receiving data OK and I got it in the <code>\x31\x31\x31</code> format.</p> <p>I know that I can get the same number, ripping the <code>\x</code> with something like </p> <pre><code>for i in data: print hex(ord(i)) </code></pre> <p>so I got <code>31</code> in each case.</p> <p>But if I want to add 1 to the data (so it shall be "<code>32 32 32</code>")to send it as response, how can I get it in <code>\x32\x32\x32</code> again?</p>
0
2009-06-30T13:45:38Z
1,063,824
<p>use the struct module</p> <p>unpack and get the 3 values in abc</p> <p><code>(a, b, c) = struct.unpack("&gt;BBB", your_string)</code></p> <p>then </p> <p><code>a, b, c = a+1, b+1, c+1</code></p> <p>and pack into the response</p> <p><code>response = struct.pack("&gt;BBB", a, b, c)</code></p> <p>see the struct module in python documentation for more details</p>
4
2009-06-30T13:55:41Z
[ "python", "sockets", "hex" ]
Hex data from socket, process and response
1,063,775
<p>Lets put it in parts.</p> <p>I got a socket receiving data OK and I got it in the <code>\x31\x31\x31</code> format.</p> <p>I know that I can get the same number, ripping the <code>\x</code> with something like </p> <pre><code>for i in data: print hex(ord(i)) </code></pre> <p>so I got <code>31</code> in each case.</p> <p>But if I want to add 1 to the data (so it shall be "<code>32 32 32</code>")to send it as response, how can I get it in <code>\x32\x32\x32</code> again?</p>
0
2009-06-30T13:45:38Z
1,063,840
<p>The opposite of ord() would be chr().</p> <p>So you could do this to add one to it:</p> <pre><code>newchar = chr(ord(i) + 1) </code></pre> <p>To use that in your example:</p> <pre><code>newdata = '' for i in data: newdata += chr(ord(i) + 1) print repr(newdata) </code></pre> <p>But if you really wanted to work in hex strings, you can use encode() and decode():</p> <pre><code>&gt;&gt;&gt; 'test string'.encode('hex') '7465737420737472696e67' &gt;&gt;&gt; '7465737420737472696e67'.decode('hex') 'test string' </code></pre>
0
2009-06-30T13:58:07Z
[ "python", "sockets", "hex" ]
Hex data from socket, process and response
1,063,775
<p>Lets put it in parts.</p> <p>I got a socket receiving data OK and I got it in the <code>\x31\x31\x31</code> format.</p> <p>I know that I can get the same number, ripping the <code>\x</code> with something like </p> <pre><code>for i in data: print hex(ord(i)) </code></pre> <p>so I got <code>31</code> in each case.</p> <p>But if I want to add 1 to the data (so it shall be "<code>32 32 32</code>")to send it as response, how can I get it in <code>\x32\x32\x32</code> again?</p>
0
2009-06-30T13:45:38Z
1,063,862
<p>The "\x31" is not a format but the text representation of the binary data. As you mention ord() will convert one byte of binary data into an int, so you can do maths on it.</p> <p>To convert it back to binary data in a string, you can use chr() if it's on just one integer. If it's many, you can use the %c formatting character of a string:</p> <pre><code>&gt;&gt;&gt; "Return value: %c%c%c" % (5,6,7) 'Return value: \x05\x06\x07' </code></pre> <p>However, a better way is probably to use struct.</p> <pre><code>&gt;&gt;&gt; import struct &gt;&gt;&gt; foo, bar, kaka = struct.unpack("BBB", '\x06\x06\x06') &gt;&gt;&gt; struct.pack("BBB", foo, bar+1, kaka+5) '\x06\x07\x0b' </code></pre> <p>You may even want to take a look at ctypes.</p>
4
2009-06-30T14:02:02Z
[ "python", "sockets", "hex" ]
Hex data from socket, process and response
1,063,775
<p>Lets put it in parts.</p> <p>I got a socket receiving data OK and I got it in the <code>\x31\x31\x31</code> format.</p> <p>I know that I can get the same number, ripping the <code>\x</code> with something like </p> <pre><code>for i in data: print hex(ord(i)) </code></pre> <p>so I got <code>31</code> in each case.</p> <p>But if I want to add 1 to the data (so it shall be "<code>32 32 32</code>")to send it as response, how can I get it in <code>\x32\x32\x32</code> again?</p>
0
2009-06-30T13:45:38Z
1,063,928
<p>OMG, what a fast answering! :D</p> <p>I think that i was stuck on the ">B" parameter to struct, as i used "h" and that sample parameters (newbie on struct.pack talking!)</p> <p>Tried the encode/decode thing but socket on the other side receive them as numbers, not the "\x" representation it wanted.</p> <p>I really enjoy the simplicity of %c format, and will use that as temporal thing (i dont process so many data so have not reason to be ultraefficient atm :D) or the struct thing after playing with it a bit.</p> <p>And in the example, to just play with one char at a time, find struct working too, usint ">B" only hehe.</p> <p>Thanks to all.</p>
0
2009-06-30T14:15:19Z
[ "python", "sockets", "hex" ]
Adding encoding alias to python
1,064,086
<p>Is there a way that I can add alias to python for encoding. There are sites on the web that are using the encoding 'windows-1251' but have their charset set to win-1251, so I would like to have win-1251 be an alias to windows-1251</p>
3
2009-06-30T14:47:20Z
1,064,191
<pre><code>&gt;&gt;&gt; import encodings &gt;&gt;&gt; encodings.aliases.aliases['win_1251'] = 'cp1251' &gt;&gt;&gt; print '\xcc\xce\xd1K\xc2\xc0'.decode('win-1251') MOCKBA </code></pre> <p>Although I personally would consider this monkey-patching, and use my own conversion table. But I can't give any good arguments for that position. :)</p>
3
2009-06-30T15:04:20Z
[ "python", "unicode", "character-encoding" ]
Adding encoding alias to python
1,064,086
<p>Is there a way that I can add alias to python for encoding. There are sites on the web that are using the encoding 'windows-1251' but have their charset set to win-1251, so I would like to have win-1251 be an alias to windows-1251</p>
3
2009-06-30T14:47:20Z
1,064,308
<p>The <code>encodings</code> module is not well documented so I'd instead use <code>codecs</code>, which <a href="http://docs.python.org/library/codecs.html">is</a>:</p> <pre><code>import codecs def encalias(oldname, newname): old = codecs.lookup(oldname) new = codecs.CodecInfo(old.encode, old.decode, streamreader=old.streamreader, streamwriter=old.streamwriter, incrementalencoder=old.incrementalencoder, incrementaldecoder=old.incrementaldecoder, name=newname) def searcher(aname): if aname == newname: return new else: return None codecs.register(searcher) </code></pre> <p>This is Python 2.6 -- the interface is different in earlier versions.</p> <p>If you don't mind relying on a specific version's undocumented internals, @Lennart's aliasing approach is OK, too, of course - and indeed simpler than this;-). But I suspect (as he appears to) that this one is more maintainable.</p>
7
2009-06-30T15:24:13Z
[ "python", "unicode", "character-encoding" ]
Adding encoding alias to python
1,064,086
<p>Is there a way that I can add alias to python for encoding. There are sites on the web that are using the encoding 'windows-1251' but have their charset set to win-1251, so I would like to have win-1251 be an alias to windows-1251</p>
3
2009-06-30T14:47:20Z
31,154,573
<p>Encoding aliases can be added by editing aliases.py file.</p> <pre><code># euc_jp codec 'eucjp' : 'euc_jp', 'ujis' : 'euc_jp', 'u_jis' : 'euc_jp', 'euc_jp_linux' : 'euc_jp', 'euc-jp-linux' : 'euc_jp', </code></pre> <p>Above I have added two aliases <strong>euc_jp_linux</strong> and <strong>euc-jp-linux</strong> to the encoding <strong>euc_jp</strong>.</p> <p>For a 64 bit linux system aliases.py file is generally located under /usr/lib64/python2.6/encodings/</p>
0
2015-07-01T07:02:11Z
[ "python", "unicode", "character-encoding" ]
How to debug the MySQL error message: Caught an exception while rendering
1,064,152
<p>I am building Django +MySQL on dreamhost, but met the error messages: <br> Caught an exception while rendering: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ') ORDER BY <code>tag</code>.<code>used_count</code> DESC, <code>tag</code>.<code>name</code> ASC' at line 1") <br></p> <p>I traced hard and found the error splot is with the function below:<br> Can you someone help me check what's wrong with this code?</p> <pre><code> def get_tags_by_questions(self, questions): question_ids = [] for question in questions: question_ids.append(question.id) question_ids_str = ','.join([force_unicode(id) for id in question_ids]) related_tags = self.extra( tables=['tag', 'question_tags'], where=["tag.id = question_tags.tag_id AND question_tags.question_id IN (" + question_ids_str + ")"] ).distinct() return related_tags </code></pre>
0
2009-06-30T14:57:58Z
1,064,179
<p>Is it possible that there are no questions, in which case the SQL will contain something like <code>"WHERE question_id IN ()"</code> which wouldn't be valid SQL.</p>
2
2009-06-30T15:02:53Z
[ "python", "mysql", "django", "dreamhost" ]
In Python 2.5, how do I kill a subprocess?
1,064,335
<p>I am using the subprocess package in Python to run a subprocess, which I later need to kill. However, the documentation of the subprocess package states that the terminate() function is only available from 2.6</p> <p>We are running Linux with 2.5 and for backwards compatibility reasons I cannot upgrade to 2.6, what is the alternative? I am guessing that these functions are convenience methods for something.</p>
26
2009-06-30T15:27:16Z
1,064,370
<p>You call os.kill on the process pid.</p> <pre><code>os.kill(process.pid, signal.SIGKILL) </code></pre> <p>You're OK because you're on on Linux. Windows users are out of luck.</p>
37
2009-06-30T15:32:06Z
[ "python", "subprocess" ]
In Python 2.5, how do I kill a subprocess?
1,064,335
<p>I am using the subprocess package in Python to run a subprocess, which I later need to kill. However, the documentation of the subprocess package states that the terminate() function is only available from 2.6</p> <p>We are running Linux with 2.5 and for backwards compatibility reasons I cannot upgrade to 2.6, what is the alternative? I am guessing that these functions are convenience methods for something.</p>
26
2009-06-30T15:27:16Z
1,064,430
<p>To complete @Gareth's answer, on Windows you do:</p> <pre><code>import ctypes PROCESS_TERMINATE = 1 handle = ctypes.windll.kernel32.OpenProcess(PROCESS_TERMINATE, False, theprocess.pid) ctypes.windll.kernel32.TerminateProcess(handle, -1) ctypes.windll.kernel32.CloseHandle(handle) </code></pre> <p>not quite as elegant as <code>os.kill(theprocess.pid, 9)</code>, but it does work;-)</p>
40
2009-06-30T15:41:43Z
[ "python", "subprocess" ]
In Python 2.5, how do I kill a subprocess?
1,064,335
<p>I am using the subprocess package in Python to run a subprocess, which I later need to kill. However, the documentation of the subprocess package states that the terminate() function is only available from 2.6</p> <p>We are running Linux with 2.5 and for backwards compatibility reasons I cannot upgrade to 2.6, what is the alternative? I am guessing that these functions are convenience methods for something.</p>
26
2009-06-30T15:27:16Z
5,080,048
<p>In order to complete @Gareth's and @Alex answers, if you don't want to bother with the underlaying system, you can use <a href="http://code.google.com/p/psutil">psutil</a>.</p> <blockquote> <p>psutil is a module providing an interface for retrieving information on running processes and system utilization (CPU, memory) in a portable way by using Python, implementing many functionalities offered by command line tools like ps, top, kill and Windows task manager.</p> <p>It currently supports Linux, OS X, FreeBSD and Windows with Python versions from 2.4 to 3.1 by using a unique code base.</p> </blockquote>
6
2011-02-22T15:22:36Z
[ "python", "subprocess" ]
In Python 2.5, how do I kill a subprocess?
1,064,335
<p>I am using the subprocess package in Python to run a subprocess, which I later need to kill. However, the documentation of the subprocess package states that the terminate() function is only available from 2.6</p> <p>We are running Linux with 2.5 and for backwards compatibility reasons I cannot upgrade to 2.6, what is the alternative? I am guessing that these functions are convenience methods for something.</p>
26
2009-06-30T15:27:16Z
8,536,476
<p>Thats a copy&amp;pase complete solution:</p> <pre><code>def terminate_process(pid): # all this shit is because we are stuck with Python 2.5 and \ we cannot use Popen.terminate() if sys.platform == 'win32': import ctypes PROCESS_TERMINATE = 1 handle = ctypes.windll.kernel32.OpenProcess(PROCESS_TERMINATE, False, pid) ctypes.windll.kernel32.TerminateProcess(handle, -1) ctypes.windll.kernel32.CloseHandle(handle) else: os.kill(pid, signal.SIGKILL) </code></pre> <p>Accepting bug reports as comments ;)</p>
4
2011-12-16T15:40:08Z
[ "python", "subprocess" ]
error while uploading project to Google App Engine(python)
1,064,422
<pre><code>2009-06-30 23:36:28,483 ERROR appcfg.py:1272 An unexpected error occurred. Aborting. Traceback (most recent call last): File "C:\Program Files\Google\google_appengine\google\appengine\tools\appcfg.py", line 1250, in DoUpload missing_files = self.Begin() File "C:\Program Files\Google\google_appengine\google\appengine\tools\appcfg.py", line 1045, in Begin version=self.version, payload=self.config.ToYAML()) File "C:\Program Files\Google\google_appengine\google\appengine\tools\appengine_rpc.py", line 344, in Send f = self.opener.open(req) File "C:\Python25\lib\urllib2.py", line 387, in open response = meth(req, response) File "C:\Python25\lib\urllib2.py", line 498, in http_response 'http', request, response, code, msg, hdrs) File "C:\Python25\lib\urllib2.py", line 425, in error return self._call_chain(*args) File "C:\Python25\lib\urllib2.py", line 360, in _call_chain result = func(*args) File "C:\Python25\lib\urllib2.py", line 506, in http_error_default raise HTTPError(req.get_full_url(), code, msg, hdrs, fp) HTTPError: HTTP Error 403: Forbidden Error 403: --- begin server output --- &lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"&gt; &lt;HTML&gt;&lt;HEAD&gt;&lt;META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=gb2312"&gt; &lt;TITLE&gt;The requested URL could not be retrieved&lt;/TITLE&gt; &lt;STYLE type="text/css"&gt;&lt;!--BODY{background-color:#ffffff;font-family:verdana,sans-serif}PRE{font-family:sans-serif}--&gt;&lt;/STYLE&gt; &lt;/HEAD&gt;&lt;BODY&gt; &lt;H3&gt;The requested URL could not be retrieved&lt;/H3&gt; Please double check or try again later. &lt;HR noshade size="1px"&gt; &lt;/BODY&gt; --- end server output --- </code></pre> <p>What's wrong?</p>
-2
2009-06-30T15:40:49Z
1,064,442
<p>I see a HTTP 403 Forbidden in there, which says to me that your authentications is probably not sorted out correctly.</p>
0
2009-06-30T15:43:38Z
[ "python", "google-app-engine", "uploading" ]
error while uploading project to Google App Engine(python)
1,064,422
<pre><code>2009-06-30 23:36:28,483 ERROR appcfg.py:1272 An unexpected error occurred. Aborting. Traceback (most recent call last): File "C:\Program Files\Google\google_appengine\google\appengine\tools\appcfg.py", line 1250, in DoUpload missing_files = self.Begin() File "C:\Program Files\Google\google_appengine\google\appengine\tools\appcfg.py", line 1045, in Begin version=self.version, payload=self.config.ToYAML()) File "C:\Program Files\Google\google_appengine\google\appengine\tools\appengine_rpc.py", line 344, in Send f = self.opener.open(req) File "C:\Python25\lib\urllib2.py", line 387, in open response = meth(req, response) File "C:\Python25\lib\urllib2.py", line 498, in http_response 'http', request, response, code, msg, hdrs) File "C:\Python25\lib\urllib2.py", line 425, in error return self._call_chain(*args) File "C:\Python25\lib\urllib2.py", line 360, in _call_chain result = func(*args) File "C:\Python25\lib\urllib2.py", line 506, in http_error_default raise HTTPError(req.get_full_url(), code, msg, hdrs, fp) HTTPError: HTTP Error 403: Forbidden Error 403: --- begin server output --- &lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"&gt; &lt;HTML&gt;&lt;HEAD&gt;&lt;META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=gb2312"&gt; &lt;TITLE&gt;The requested URL could not be retrieved&lt;/TITLE&gt; &lt;STYLE type="text/css"&gt;&lt;!--BODY{background-color:#ffffff;font-family:verdana,sans-serif}PRE{font-family:sans-serif}--&gt;&lt;/STYLE&gt; &lt;/HEAD&gt;&lt;BODY&gt; &lt;H3&gt;The requested URL could not be retrieved&lt;/H3&gt; Please double check or try again later. &lt;HR noshade size="1px"&gt; &lt;/BODY&gt; --- end server output --- </code></pre> <p>What's wrong?</p>
-2
2009-06-30T15:40:49Z
1,064,456
<p>You're trying to upload to a URL to which you lack access -- are you sure you're spelling your app name right, own its name on appspot, etc, etc?</p>
1
2009-06-30T15:45:37Z
[ "python", "google-app-engine", "uploading" ]
error while uploading project to Google App Engine(python)
1,064,422
<pre><code>2009-06-30 23:36:28,483 ERROR appcfg.py:1272 An unexpected error occurred. Aborting. Traceback (most recent call last): File "C:\Program Files\Google\google_appengine\google\appengine\tools\appcfg.py", line 1250, in DoUpload missing_files = self.Begin() File "C:\Program Files\Google\google_appengine\google\appengine\tools\appcfg.py", line 1045, in Begin version=self.version, payload=self.config.ToYAML()) File "C:\Program Files\Google\google_appengine\google\appengine\tools\appengine_rpc.py", line 344, in Send f = self.opener.open(req) File "C:\Python25\lib\urllib2.py", line 387, in open response = meth(req, response) File "C:\Python25\lib\urllib2.py", line 498, in http_response 'http', request, response, code, msg, hdrs) File "C:\Python25\lib\urllib2.py", line 425, in error return self._call_chain(*args) File "C:\Python25\lib\urllib2.py", line 360, in _call_chain result = func(*args) File "C:\Python25\lib\urllib2.py", line 506, in http_error_default raise HTTPError(req.get_full_url(), code, msg, hdrs, fp) HTTPError: HTTP Error 403: Forbidden Error 403: --- begin server output --- &lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"&gt; &lt;HTML&gt;&lt;HEAD&gt;&lt;META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=gb2312"&gt; &lt;TITLE&gt;The requested URL could not be retrieved&lt;/TITLE&gt; &lt;STYLE type="text/css"&gt;&lt;!--BODY{background-color:#ffffff;font-family:verdana,sans-serif}PRE{font-family:sans-serif}--&gt;&lt;/STYLE&gt; &lt;/HEAD&gt;&lt;BODY&gt; &lt;H3&gt;The requested URL could not be retrieved&lt;/H3&gt; Please double check or try again later. &lt;HR noshade size="1px"&gt; &lt;/BODY&gt; --- end server output --- </code></pre> <p>What's wrong?</p>
-2
2009-06-30T15:40:49Z
1,064,458
<p>HTTP Error 403: Forbidden... bad username/password for the given application (did you change app.yaml at all since the last successful update)?</p> <p>The requested URL could not be retrieved... Or maybe they had a service interruption. Try again after a bit.</p>
0
2009-06-30T15:45:53Z
[ "python", "google-app-engine", "uploading" ]
What is the best way to add an API to a Django application?
1,064,520
<p>I am adding MetaWeblog API support to a Django CMS, and am not quite sure how to layer the application.</p> <p>I am using django_xmlrpc, which allows me to map to parameterised functions for each request. It is just a case of what level do I hook in calls to the django application from the service functions (AddPage, EditPage etc)</p> <p>For django-page-cms, and I suppose many django apps, the business logic and validation is contained within the forms. In this case there is PageForm(forms.ModelForm) and PageAdmin(ModelAdmin), which both contain a lot of logic and validation.</p> <p>If I am to build an API to allow maintenance of pages and content, does this mean I should be programmatically creating and filling a PageAdmin instance? Then catching any exceptions, and converting to their api equivalent? Or would this be a bad idea - misusing what forms are intended for?</p> <p>The other option is refactoring the code so that business and logic is kept outside of the form classes. Then I would have the form and api, both go through the separate business logic.</p> <p>Any other alternatives?</p> <p>What would be the best solution? </p>
2
2009-06-30T15:56:17Z
1,064,563
<p>Web services API's are just more URL's.</p> <p>These WS API URL's map to view functions.</p> <p>The WS view functions handle GET and POST (and possibly PUT and DELETE).</p> <p>The WS view functions use Forms as well as the Models to make things happen.</p> <p>It is, in a way, like an admin interface. Except, there's no HTML.</p> <p>The WS view functions respond with JSON messages or XML messages.</p>
2
2009-06-30T16:04:08Z
[ "python", "django", "api", "django-models", "django-admin" ]
What is the best way to add an API to a Django application?
1,064,520
<p>I am adding MetaWeblog API support to a Django CMS, and am not quite sure how to layer the application.</p> <p>I am using django_xmlrpc, which allows me to map to parameterised functions for each request. It is just a case of what level do I hook in calls to the django application from the service functions (AddPage, EditPage etc)</p> <p>For django-page-cms, and I suppose many django apps, the business logic and validation is contained within the forms. In this case there is PageForm(forms.ModelForm) and PageAdmin(ModelAdmin), which both contain a lot of logic and validation.</p> <p>If I am to build an API to allow maintenance of pages and content, does this mean I should be programmatically creating and filling a PageAdmin instance? Then catching any exceptions, and converting to their api equivalent? Or would this be a bad idea - misusing what forms are intended for?</p> <p>The other option is refactoring the code so that business and logic is kept outside of the form classes. Then I would have the form and api, both go through the separate business logic.</p> <p>Any other alternatives?</p> <p>What would be the best solution? </p>
2
2009-06-30T15:56:17Z
13,488,192
<p>It seems python does not provide this out of the box. But there is something called abc module:</p> <p>I quote from <a href="http://www.doughellmann.com/PyMOTW/abc/" rel="nofollow">http://www.doughellmann.com/PyMOTW/abc/</a> "By defining an abstract base class, you can define a common API for a set of subclasses. This capability is especially useful in situations where a third-party is going to provide implementations..." => the goal of an API, defining a contract.</p>
0
2012-11-21T07:19:27Z
[ "python", "django", "api", "django-models", "django-admin" ]
Are Python commands suitable in Vim's visual mode?
1,064,644
<p>I have found the following command in AWK useful in Vim</p> <pre><code>:'&lt;,'&gt;!awk '{ print $2 }' </code></pre> <p>Python may also be useful in Vim. However, I have not found an useful command in Python for Vim's visual mode.</p> <p><strong>Which Python commands do you use in Vim</strong>?</p>
0
2009-06-30T16:19:31Z
1,064,721
<p>It's hard to make useful one-liner filters in Python. You need to import <code>sys</code> to get <code>stdin</code>, and already you're starting to push it. This isn't to say anything bad about Python. My feeling is that Python is optimized for multi-line scripts, while the languages that do well at one-liners (awk, sed, bash, I could name others but would probably be flamed...) tend work less well (IMHO) when writing scripts of any significant complexity.</p> <p>I do really like Python for writing multi-line scripts that I can invoke from Vim. For example, I've got one Python script that will, when given a signature for a Java constructor, like this:</p> <pre><code>Foo(String name, int size) { </code></pre> <p>will emit a lot of the boilerplate that goes into creating a value class:</p> <pre><code>private final String name; private final int size; public String getName() { return name; } public int getSize() { return size; } @Override public boolean equals(Object that) { return this == that || (that instanceof Foo &amp;&amp; equals((Foo) that)); } public boolean equals(Foo that) { return Objects.equal(getName(), that.getName()) &amp;&amp; this.getSize() == that.getSize(); } @Override public int hashCode() { return Objects.hashCode( getName(), getSize()); } Foo(String name, int size) { this.name = Preconditions.checkNotNull(name); this.size = size; </code></pre> <p>I use this from Vim by highlighting the signature and then typing <code>!jhelper.py</code>.</p> <p>I also used to use Python scripts I'd written to reverse characters in lines and to reverse the lines of a file before I found out about <code>rev</code> and <code>tac</code>.</p>
4
2009-06-30T16:38:27Z
[ "python", "vim" ]
Are Python commands suitable in Vim's visual mode?
1,064,644
<p>I have found the following command in AWK useful in Vim</p> <pre><code>:'&lt;,'&gt;!awk '{ print $2 }' </code></pre> <p>Python may also be useful in Vim. However, I have not found an useful command in Python for Vim's visual mode.</p> <p><strong>Which Python commands do you use in Vim</strong>?</p>
0
2009-06-30T16:19:31Z
1,064,951
<p>Python is most useful with vim when used to code vim "macros" (you need a vim compiled with <code>+python</code>, but many pre-built ones come that way). <a href="http://www.tummy.com/Community/Presentations/vimpython-20070225/vim.html" rel="nofollow">Here</a> is a nice presentation about some of the things you can do with (plenty of examples and snippets!), and <a href="http://www.vim.org/htmldoc/if%5Fpyth.html" rel="nofollow">here</a> are vim's own reference docs about this feature.</p>
4
2009-06-30T17:30:44Z
[ "python", "vim" ]
Formatting a variable in Django and autofields
1,064,953
<p>I have this problem I've been trying to tackle for a while. I have a variable that is 17 characters long, and when displaying the variable on my form, I want it to display the last seven characters of this variable in bold...how do I go about this...I'd really appreciate anybody's insight on this.</p>
0
2009-06-30T17:31:18Z
1,065,003
<pre><code>{{ thevar|slice:":-7" }}&lt;b&gt;{{ thevar|slice:"-7:" }}&lt;/b&gt; </code></pre> <p>The <code>slice</code> built-in filter in Django templates acts like slicing does in Python, so that for example <code>s[:-7]</code> is the string excluding its last 7 characters and <code>s[-7:]</code> is the substring formed by just the last 7 characters.</p>
2
2009-06-30T17:40:02Z
[ "python", "django", "string-formatting" ]
for statement in python
1,065,133
<p>When an exe file is run it prints out some stuff. I'm trying to run this on some numbers below and print out line 54 ( = blah ). It says process isn't defined and I'm really unsure how to fix this and get what I want printed to the screen. If anyone could post some code or ways to fix this thank you so very much!</p> <pre><code>for j in ('90','52.62263','26.5651','10.8123'): if j == '90': k = ('0',) elif j == '52.62263': k = ('0', '72', '144', '216', '288') elif j == '26.5651': k = (' 324', ' 36', ' 108', ' 180', ' 252') else: k = (' 288', ' 0', ' 72', ' 144', ' 216') for b in k: outputstring = process.communicate()[0] outputlist = outputstring.splitlines() blah = outputlist[53] cmd = ' -j ' + str(j) + ' -b ' + str(b) + ' blah ' process = Popen(cmd, shell=True, stderr=STDOUT, stdout=PIPE) print cmd </code></pre> <p>I am trying to print out for example:</p> <p>-j 90 -az 0 (then what blah contains) blah is line 54. Line 54 prints out a lot of information. Words mostly. I want to print out what line 54 says to the screen right after </p> <p>-j 90 -az 0</p> <p>@ Robbie: line 39</p> <pre><code>blah = outputlist[53] </code></pre> <p>Indexerror: list index out of range</p> <p>@ Robbie again. Thanks for your help and sorry for the trouble guys... </p> <p>I even tried putting in outputlist[2] and it gives same error :/</p>
1
2009-06-30T18:10:46Z
1,065,146
<p>Are you sure this is right</p> <pre><code>cmd = ' -j ' + str(el) + ' -jk ' + str(az) + ' blah ' </code></pre> <p>Where's your executable?</p>
2
2009-06-30T18:13:00Z
[ "python" ]
for statement in python
1,065,133
<p>When an exe file is run it prints out some stuff. I'm trying to run this on some numbers below and print out line 54 ( = blah ). It says process isn't defined and I'm really unsure how to fix this and get what I want printed to the screen. If anyone could post some code or ways to fix this thank you so very much!</p> <pre><code>for j in ('90','52.62263','26.5651','10.8123'): if j == '90': k = ('0',) elif j == '52.62263': k = ('0', '72', '144', '216', '288') elif j == '26.5651': k = (' 324', ' 36', ' 108', ' 180', ' 252') else: k = (' 288', ' 0', ' 72', ' 144', ' 216') for b in k: outputstring = process.communicate()[0] outputlist = outputstring.splitlines() blah = outputlist[53] cmd = ' -j ' + str(j) + ' -b ' + str(b) + ' blah ' process = Popen(cmd, shell=True, stderr=STDOUT, stdout=PIPE) print cmd </code></pre> <p>I am trying to print out for example:</p> <p>-j 90 -az 0 (then what blah contains) blah is line 54. Line 54 prints out a lot of information. Words mostly. I want to print out what line 54 says to the screen right after </p> <p>-j 90 -az 0</p> <p>@ Robbie: line 39</p> <pre><code>blah = outputlist[53] </code></pre> <p>Indexerror: list index out of range</p> <p>@ Robbie again. Thanks for your help and sorry for the trouble guys... </p> <p>I even tried putting in outputlist[2] and it gives same error :/</p>
1
2009-06-30T18:10:46Z
1,065,149
<p>The following line</p> <pre><code>outputstring = process.communicate()[0] </code></pre> <p>calls the <code>communicate()</code> method of the <code>process</code> variable, but <code>process</code> has not been defined yet. You define it later in the code. You need to move that definition higher up.</p> <p>Also, your variable names (<code>j</code>,<code>k</code>, and <code>jk</code>) are confusing.</p>
2
2009-06-30T18:13:53Z
[ "python" ]
for statement in python
1,065,133
<p>When an exe file is run it prints out some stuff. I'm trying to run this on some numbers below and print out line 54 ( = blah ). It says process isn't defined and I'm really unsure how to fix this and get what I want printed to the screen. If anyone could post some code or ways to fix this thank you so very much!</p> <pre><code>for j in ('90','52.62263','26.5651','10.8123'): if j == '90': k = ('0',) elif j == '52.62263': k = ('0', '72', '144', '216', '288') elif j == '26.5651': k = (' 324', ' 36', ' 108', ' 180', ' 252') else: k = (' 288', ' 0', ' 72', ' 144', ' 216') for b in k: outputstring = process.communicate()[0] outputlist = outputstring.splitlines() blah = outputlist[53] cmd = ' -j ' + str(j) + ' -b ' + str(b) + ' blah ' process = Popen(cmd, shell=True, stderr=STDOUT, stdout=PIPE) print cmd </code></pre> <p>I am trying to print out for example:</p> <p>-j 90 -az 0 (then what blah contains) blah is line 54. Line 54 prints out a lot of information. Words mostly. I want to print out what line 54 says to the screen right after </p> <p>-j 90 -az 0</p> <p>@ Robbie: line 39</p> <pre><code>blah = outputlist[53] </code></pre> <p>Indexerror: list index out of range</p> <p>@ Robbie again. Thanks for your help and sorry for the trouble guys... </p> <p>I even tried putting in outputlist[2] and it gives same error :/</p>
1
2009-06-30T18:10:46Z
1,065,254
<p><code>process</code> isn't defined because your statements are out of order.</p> <pre><code> outputstring = process.communicate()[0] outputlist = outputstring.splitlines() blah = outputlist[53] cmd = ' -j ' + str(j) + ' -b ' + str(b) + ' blah ' process = Popen(cmd, shell=True, stderr=STDOUT, stdout=PIPE) </code></pre> <p>cannot possibly work. <code>process</code> on the first line, is undefined. </p>
1
2009-06-30T18:36:15Z
[ "python" ]
for statement in python
1,065,133
<p>When an exe file is run it prints out some stuff. I'm trying to run this on some numbers below and print out line 54 ( = blah ). It says process isn't defined and I'm really unsure how to fix this and get what I want printed to the screen. If anyone could post some code or ways to fix this thank you so very much!</p> <pre><code>for j in ('90','52.62263','26.5651','10.8123'): if j == '90': k = ('0',) elif j == '52.62263': k = ('0', '72', '144', '216', '288') elif j == '26.5651': k = (' 324', ' 36', ' 108', ' 180', ' 252') else: k = (' 288', ' 0', ' 72', ' 144', ' 216') for b in k: outputstring = process.communicate()[0] outputlist = outputstring.splitlines() blah = outputlist[53] cmd = ' -j ' + str(j) + ' -b ' + str(b) + ' blah ' process = Popen(cmd, shell=True, stderr=STDOUT, stdout=PIPE) print cmd </code></pre> <p>I am trying to print out for example:</p> <p>-j 90 -az 0 (then what blah contains) blah is line 54. Line 54 prints out a lot of information. Words mostly. I want to print out what line 54 says to the screen right after </p> <p>-j 90 -az 0</p> <p>@ Robbie: line 39</p> <pre><code>blah = outputlist[53] </code></pre> <p>Indexerror: list index out of range</p> <p>@ Robbie again. Thanks for your help and sorry for the trouble guys... </p> <p>I even tried putting in outputlist[2] and it gives same error :/</p>
1
2009-06-30T18:10:46Z
1,065,351
<p>I can't help but clean that up a little.</p> <pre><code># aesthetically (so YMMV), I think the code would be better if it were ... # (and I've asked some questions throughout) j_map = { 90: [0], # prefer lists [] to tuples (), I say... 52.62263: [0, 72, 144, 216, 288], 26.5651: [324, 36, 108, 180, 252], 10.8123: [288, 0, 72, 144, 216] } # have a look at dict() in http://docs.python.org/tutorial/datastructures.html # to know what's going on here -- e.g. j_map['90'] is ['0',] # then the following is cleaner for j, k in j_map.iteritems(): # first iteration j = '90', k=[0] # second iteration j = '52.62263'', k= [0,...,288] for b in k: # fixed the ordering of these statements so this may actually work cmd = "program_name -j %f -b %d" % (j, b) # where program_name is the program you're calling # be wary of the printf-style %f formatting and # how program_name takes its input print cmd process = Popen(cmd, shell=True, stderr=STDOUT, stdout=PIPE) outputstring = process.communicate()[0] outputlist = outputstring.splitlines() blah = outputlist[53] </code></pre> <p>You need to define cmd -- right now it's trying to execute something like " -j 90 -b 288". I presume you want something like <strong>cmd = "program_name -j 90 -b 288"</strong>.</p> <p>Don't know if that answers your question at all, but I hope it gives food for thought.</p>
6
2009-06-30T18:53:43Z
[ "python" ]
What can you do with COM/ActiveX in Python?
1,065,844
<p>I'm thinking that I'm going to have to run monthly reports in Crystal Reports. I've read that you can automate this with COM/ActiveX but I'm not that advanced to understand what this is or what you can even do with it. </p> <p>I'm fairly familiar with Python and it looks like from what I've read, I might be able to open the report, <em>maybe</em> change some parameters, run it, and export it. </p> <p>I also do a lot of work with Excel and it looks like you also use COM/ActiveX to interface with it. </p> <p>Can someone explain how this works and maybe provide a brief example?</p>
23
2009-06-30T20:24:44Z
1,066,390
<p>You can basically do the equivalent of late binding. So whatever is exposed through IDispatch is able to be consumed. </p> <p>Here's some code I wrote this weekend to get an image from a twain device via Windows Image Acquisition 2.0 and put the data into something I can shove in a gtk based UI.</p> <pre><code>WIA_COM = "WIA.CommonDialog" WIA_DEVICE_UNSPECIFIED = 0 WIA_INTENT_UNSPECIFIED = 0 WIA_BIAS_MIN_SIZE = 65536 WIA_IMG_FORMAT_PNG = "{B96B3CAF-0728-11D3-9D7B-0000F81EF32E}" def acquire_image_wia(): wia = win32com.client.Dispatch(WIA_COM) img = wia.ShowAcquireImage(WIA_DEVICE_UNSPECIFIED, WIA_INTENT_UNSPECIFIED, WIA_BIAS_MIN_SIZE, WIA_IMG_FORMAT_PNG, False, True) fname = str(time.time()) img.SaveFile(fname) buff = gtk.gdk.pixbuf_new_from_file(fname) os.remove(fname) return buff </code></pre> <p>It's not pretty but it works. I would assert it's equivalent to what you would have to write in VB.</p>
3
2009-06-30T22:21:53Z
[ "python", "com", "crystal-reports", "activex", "pywin32" ]
What can you do with COM/ActiveX in Python?
1,065,844
<p>I'm thinking that I'm going to have to run monthly reports in Crystal Reports. I've read that you can automate this with COM/ActiveX but I'm not that advanced to understand what this is or what you can even do with it. </p> <p>I'm fairly familiar with Python and it looks like from what I've read, I might be able to open the report, <em>maybe</em> change some parameters, run it, and export it. </p> <p>I also do a lot of work with Excel and it looks like you also use COM/ActiveX to interface with it. </p> <p>Can someone explain how this works and maybe provide a brief example?</p>
23
2009-06-30T20:24:44Z
1,067,842
<p>First you have to install the wonderful <a href="http://sourceforge.net/projects/pywin32/" rel="nofollow">pywin32</a> module.</p> <p>It provides COM support. You need to run the makepy utility. It is located at C:...\Python26\Lib\site-packages\win32com\client. On Vista, it must be ran with admin rights.</p> <p>This utility will show all available COM objects. You can find yours and it will generate a python wrapper for this object.</p> <p>The wrapper is a python module generated in the C:...\Python26\Lib\site-packages\win32com\gen_py folder. The module contains the interface of the COM objects. The name of the file is the COM unique id. If you have many files, it is sometimes difficult to find the right one.</p> <p>After that you just have to call the right interface. It is magical :)</p> <p>A short example with excel</p> <pre> import win32com.client xlApp = win32com.client.Dispatch("Excel.Application") xlApp.Visible=1 workBook = xlApp.Workbooks.Open(r"C:\MyTest.xls") print str(workBook.ActiveSheet.Cells(i,1)) workBook.ActiveSheet.Cells(1, 1).Value = "hello" workBook.Close(SaveChanges=0) xlApp.Quit() </pre>
25
2009-07-01T07:59:48Z
[ "python", "com", "crystal-reports", "activex", "pywin32" ]
What can you do with COM/ActiveX in Python?
1,065,844
<p>I'm thinking that I'm going to have to run monthly reports in Crystal Reports. I've read that you can automate this with COM/ActiveX but I'm not that advanced to understand what this is or what you can even do with it. </p> <p>I'm fairly familiar with Python and it looks like from what I've read, I might be able to open the report, <em>maybe</em> change some parameters, run it, and export it. </p> <p>I also do a lot of work with Excel and it looks like you also use COM/ActiveX to interface with it. </p> <p>Can someone explain how this works and maybe provide a brief example?</p>
23
2009-06-30T20:24:44Z
1,067,876
<p>You can also find useful tips here : <a href="http://timgolden.me.uk/python/win32_how_do_i.html">http://timgolden.me.uk/python/win32_how_do_i.html</a> it's easy to adapt to any kind of application.</p>
5
2009-07-01T08:08:18Z
[ "python", "com", "crystal-reports", "activex", "pywin32" ]