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 quickest way for a Ruby programmer to pick up Python? | 846,139 | <p>I've been programming Ruby pretty extensively for the past four years or so, and I'm extremely comfortable with the language. For no particular reason, I've decided to learn some Python this week. Is there a specific book, tutorial, or reference that would be well-suited to someone coming from a nearly-identical language, or should I just "Dive into Python"?</p>
<p>Thanks!</p>
| 10 | 2009-05-10T21:25:18Z | 846,168 | <p>After running through some tutorials on-line (the ones posted so far look pretty good), find a current Ruby project you've done (or are working on) and re-write it in Python. I've used this technique to transition from various languages, and it's helped enormously.</p>
| 3 | 2009-05-10T21:37:33Z | [
"python",
"ruby"
] |
I get "parent_id may not be NULL" when creating my Django model | 846,298 | <p>I'm creating my own <code>Group</code> model; I'm not referring to the builtin <code>Group</code> model. I want each hroup to be a member of another group (it's parent), but there is the one "top" group that doesn't have a parent group.</p>
<p>The admin interface won't let me create a group without entering a parent. I get the error <code>personnel_group.parent_id may not be NULL</code>. My <code>Group</code> model looks like this:</p>
<pre><code>class Group(models.Model):
name = models.CharField(max_length=50)
parent = models.ForeignKey('self', blank=True, null=True)
order = models.IntegerField()
icon = models.ImageField(upload_to='groups', blank=True, null=True)
description = models.TextField(blank=True, null=True)
</code></pre>
<p>How can I accomplish this?</p>
<p>Thanks.</p>
| 4 | 2009-05-10T23:19:12Z | 846,858 | <p>I created the database before I added <strong><code>blank=True, null=True</code></strong> to the <strong><code>parent</code></strong> field definition. syncdb can't deal with that type of change, so Django wasn't picking up on my changes.</p>
<p>I deleted my database and let syncdb create another and it worked fine.</p>
| 6 | 2009-05-11T05:48:28Z | [
"python",
"database",
"django",
"models"
] |
I get "parent_id may not be NULL" when creating my Django model | 846,298 | <p>I'm creating my own <code>Group</code> model; I'm not referring to the builtin <code>Group</code> model. I want each hroup to be a member of another group (it's parent), but there is the one "top" group that doesn't have a parent group.</p>
<p>The admin interface won't let me create a group without entering a parent. I get the error <code>personnel_group.parent_id may not be NULL</code>. My <code>Group</code> model looks like this:</p>
<pre><code>class Group(models.Model):
name = models.CharField(max_length=50)
parent = models.ForeignKey('self', blank=True, null=True)
order = models.IntegerField()
icon = models.ImageField(upload_to='groups', blank=True, null=True)
description = models.TextField(blank=True, null=True)
</code></pre>
<p>How can I accomplish this?</p>
<p>Thanks.</p>
| 4 | 2009-05-10T23:19:12Z | 18,942,663 | <p>Django evolution would get you out of this kind of problem without dropping your complete database </p>
| 0 | 2013-09-22T10:08:31Z | [
"python",
"database",
"django",
"models"
] |
Snapshot Movies | 846,343 | <p>I'm currently learning Python and have taken up several small projects to help learn the language. Are there currently any libraries (possibly PythonMagick) out there that are capable of extracting snapshots from .wmv, .avi, .mpg, or other movie formats with only command-line options (no GUI)? And if so, can anyone provide links to examples of code? </p>
| 1 | 2009-05-11T00:07:07Z | 846,373 | <p>A quick search in google revealed <a href="http://pymedia.org/tut/" rel="nofollow">pymedia</a>. It supports avi, dvd, wma, ...</p>
<p>Here is an <a href="http://pymedia.org/tut/src/dump%5Fvideo.py.html" rel="nofollow">example</a> on how to get snapshots from videos</p>
| 1 | 2009-05-11T00:36:22Z | [
"python",
"screenshot",
"snapshot",
"movie"
] |
Snapshot Movies | 846,343 | <p>I'm currently learning Python and have taken up several small projects to help learn the language. Are there currently any libraries (possibly PythonMagick) out there that are capable of extracting snapshots from .wmv, .avi, .mpg, or other movie formats with only command-line options (no GUI)? And if so, can anyone provide links to examples of code? </p>
| 1 | 2009-05-11T00:07:07Z | 846,392 | <p>Additionally, if the CLI situation is not mandatory <a href="http://www.pyglet.org" rel="nofollow">Pyglet</a> is exceptionally easy to use to load movies, images, etc. and is very well documented.</p>
| 0 | 2009-05-11T00:48:18Z | [
"python",
"screenshot",
"snapshot",
"movie"
] |
Problem installing pyscopg2 on Mac OS X | 846,383 | <p>I have downloaded the latest build of pyscopg2 and have tried to build and install it using the directions provided. However i always get an error saying that 'w' is undeclared. Does anybody have any experience with this? </p>
| 3 | 2009-05-11T00:41:23Z | 846,403 | <p>This is an error that crops up when the build tools cannot find your Postgresql libraries. It means one of three things:</p>
<ol>
<li><p>You don't have postgresql installed on your system. If so, download and build postgres, or download a pre-built psycopg2 binary for OS X.</p></li>
<li><p>You have postgresql installed on your system, but you installed from a binary package and therefore don't have the necessary libraries that psycopg2 needs. In this case, download and build postgres.</p></li>
<li><p>More commonly, though, this means that you have built postgres on your system and just need to instruct psycopg2 how to find the <code>pg_config</code> binary so that it can configure the compilation. Either:</p>
<p>a. put the path to pg_config in your shell path (it's usually at <code>/usr/local/pgsql/bin/</code> if you built postgres from source using the defaults.</p>
<p>b. or, edit the <code>setup.cfg</code> file in the psycopg2 source folder and provide the full path to <code>pg_config</code> on the line that starts with <code>pg_config=</code>. Be sure to uncomment this line by removing the hash symbol at the front. If you built postgres using the defaults, the line will look something like:</p>
<p><code>pg_config=/usr/local/pgsql/bin/pg_config</code></p></li>
</ol>
| 11 | 2009-05-11T00:55:08Z | [
"python",
"database",
"django",
"osx"
] |
Problem installing pyscopg2 on Mac OS X | 846,383 | <p>I have downloaded the latest build of pyscopg2 and have tried to build and install it using the directions provided. However i always get an error saying that 'w' is undeclared. Does anybody have any experience with this? </p>
| 3 | 2009-05-11T00:41:23Z | 6,702,874 | <p>using MacPorts on Snow Leopard</p>
<pre><code>pg_config=/opt/local/lib/postgresql90/bin/pg_config
</code></pre>
| 3 | 2011-07-15T05:03:02Z | [
"python",
"database",
"django",
"osx"
] |
Problem installing pyscopg2 on Mac OS X | 846,383 | <p>I have downloaded the latest build of pyscopg2 and have tried to build and install it using the directions provided. However i always get an error saying that 'w' is undeclared. Does anybody have any experience with this? </p>
| 3 | 2009-05-11T00:41:23Z | 26,741,878 | <p>I needed to install the psycopg2 library only in a virtualenv without adding it to the root python and I didn't want to fully install postgreSQL on my local machine so I came up with this solution which seems to work really well. </p>
<ol>
<li><p>Download the postgres.app from <a href="http://postgresapp.com" rel="nofollow">here</a>, and drop the app in the Applications folder.</p></li>
<li><p>In a shell, add the postgres.app bin directory to the PATH:</p></li>
</ol>
<blockquote>
<p>export PATH=$PATH:/Applications/Postgres.app/Contents/Versions/9.3/bin</p>
</blockquote>
<ol start="3">
<li>Activate the virtualenv:</li>
</ol>
<blockquote>
<p>. myvenv/bin/activate</p>
</blockquote>
<ol start="4">
<li>pip install psycopg2</li>
</ol>
<p>I tried setting the pg_config variable but that didn't work. The pip install specifically told me that I had to put the directory where pg_config was located in the path.</p>
<p>I also kinda prefer this solution because, if I want to run PostgreSQL locally, I can easily just start up the app and then close it when I'm done and it's gone -- nothing left running in the background. No system config changes or anything. It is a great way to run PostgreSQL for local development or a quick demo.</p>
| 0 | 2014-11-04T18:00:36Z | [
"python",
"database",
"django",
"osx"
] |
Is there a mod_python for Apache HTTP Server 2.2 and Python 2.6 or 3.0? | 846,420 | <p>I poked around the <a href="http://www.modpython.org/" rel="nofollow">mod_python website</a> and I only found the files for Python 2.5 and earlier for Apache HTTP Server 2.2. I Googled around a little, without significant luck. Any suggestions?</p>
| 2 | 2009-05-11T01:12:37Z | 846,430 | <p>Use mod_wsgi.</p>
<p>mod_python has been stagnant for a while now. Most of the effort for python web apps has been going into mod_wsgi.</p>
| 9 | 2009-05-11T01:17:51Z | [
"python",
"apache2",
"mod-python"
] |
Modelling a swiss tournament in Django | 846,485 | <p>I'm trying to create models that represent a <a href="http://en.wikipedia.org/wiki/Swiss%5Ftournament" rel="nofollow">swiss tournament</a>, with multiple rounds. Each round everyone will be paired up with another player, except in the case where there is an odd player out, when one player will get a bye. </p>
<p>I need to keep track of the outcome of each pairing; i.e., which player won. Also, I'd like to be able to efficiently search later for all players who have ever played against a given player.</p>
<p>The obvious stuff:</p>
<pre><code>class Tournament(models.Model):
name = models.CharField(max_length=80)
class Player(models.Model):
name = models.CharField(max_length=80)
</code></pre>
<p>At first I was planning to have a "TournamentPairing" class that looked something like this:</p>
<pre><code>class TournamentPairing(models.Model):
tournament = models.ForeignKey(Tournament)
round = models.IntegerKey()
player1 = models.ForeignKey(Player)
player2 = models.ForeignKey(Player, null = True) # In case of a bye, this is None.
outcome = models.CharField(max_length=1) # player1 wins, loses, bye, or tie
</code></pre>
<p>But that feels kind of hacky, especially the part about player2 being None sometimes. Also, I don't think it facilitates searching very well (since the player we're looking for could be in the player1 or player2 slot). </p>
<p>Is there a better way? I suspect my django noob-ness is holding me back from finding the right solution here.</p>
| 2 | 2009-05-11T01:55:17Z | 846,511 | <p>I think you should have just a single player list and not split it into player1 and player2, those can be constructed when a round is set up.</p>
<p>Your player class could include a list of players they have played, and the last player on that list would be the current player they are facing. When you pick the next player someone must play, add that player to the list.</p>
<pre><code>class Player(Models.model):
name = models.CharField(max_length=80)
playersPlayed = []
</code></pre>
<p>During each round, for a single player, simply iterate through the global list of players and compare a particular player to each element in playersPlayed. If the element does not exist, that person can be played and that player should be then added to the list. If a player cannot be found for a particular round, then that player is given a bye.</p>
<p>I hope this is at least a starting point. </p>
| 1 | 2009-05-11T02:13:36Z | [
"python",
"django",
"django-models"
] |
Modelling a swiss tournament in Django | 846,485 | <p>I'm trying to create models that represent a <a href="http://en.wikipedia.org/wiki/Swiss%5Ftournament" rel="nofollow">swiss tournament</a>, with multiple rounds. Each round everyone will be paired up with another player, except in the case where there is an odd player out, when one player will get a bye. </p>
<p>I need to keep track of the outcome of each pairing; i.e., which player won. Also, I'd like to be able to efficiently search later for all players who have ever played against a given player.</p>
<p>The obvious stuff:</p>
<pre><code>class Tournament(models.Model):
name = models.CharField(max_length=80)
class Player(models.Model):
name = models.CharField(max_length=80)
</code></pre>
<p>At first I was planning to have a "TournamentPairing" class that looked something like this:</p>
<pre><code>class TournamentPairing(models.Model):
tournament = models.ForeignKey(Tournament)
round = models.IntegerKey()
player1 = models.ForeignKey(Player)
player2 = models.ForeignKey(Player, null = True) # In case of a bye, this is None.
outcome = models.CharField(max_length=1) # player1 wins, loses, bye, or tie
</code></pre>
<p>But that feels kind of hacky, especially the part about player2 being None sometimes. Also, I don't think it facilitates searching very well (since the player we're looking for could be in the player1 or player2 slot). </p>
<p>Is there a better way? I suspect my django noob-ness is holding me back from finding the right solution here.</p>
| 2 | 2009-05-11T01:55:17Z | 846,870 | <p>You can refactor your TournamentPairing class to be more "round" centric to aid in making queries.</p>
<p>CHOICES = (
('n', 'Normal'),
('b', 'Bye'),
)</p>
<pre><code>class Round(models.Model):
number = models.IntegerField()
round_type = models.CharField(max_length=1, default="n", choices=CHOICES)
tournament = models.ForeignKey(Tournament)
players = models.ManyToManyField(Player, related_name="rounds")
winner = models.ForeignKey(Player, null=True, related_name="round_winner")
</code></pre>
<p>In the case of a tie, have winner field point to player called "Tie".</p>
<p>Then, for your search criteria, to see a list of the players that a given player has played against:</p>
<pre><code># grab a player
p = Player.objects.get(name='Tom')
# see what rounds this player played in
rounds_played = p.rounds.all()
# who did this player play against?
[r.players for r in rounds_played]
# to see all rounds this player won
p.round_winner.all()
</code></pre>
| 5 | 2009-05-11T05:55:21Z | [
"python",
"django",
"django-models"
] |
A ListView of checkboxes in PyQt | 846,684 | <p>I want to display a QListView where each item is a checkbox with some label. The checkboxes should be visible at all times. One way I can think of is using a custom delegate and QAbstractListModel. Are there simpler ways? Can you provide the simplest snippet that does this?</p>
<p>Thanks in advance</p>
| 9 | 2009-05-11T04:02:36Z | 854,535 | <p>See my reply to your question on the PyQt mailing list:</p>
<p><a href="http://www.riverbankcomputing.com/pipermail/pyqt/2009-May/023002.html">http://www.riverbankcomputing.com/pipermail/pyqt/2009-May/023002.html</a></p>
<p>Summary: You need to use the ItemIsUserCheckable flag and CheckStateRole role.</p>
| 9 | 2009-05-12T19:49:48Z | [
"python",
"qt",
"pyqt",
"qitemdelegate",
"qlistview"
] |
A ListView of checkboxes in PyQt | 846,684 | <p>I want to display a QListView where each item is a checkbox with some label. The checkboxes should be visible at all times. One way I can think of is using a custom delegate and QAbstractListModel. Are there simpler ways? Can you provide the simplest snippet that does this?</p>
<p>Thanks in advance</p>
| 9 | 2009-05-11T04:02:36Z | 855,938 | <p>I ended up using the method provided by <a href="http://stackoverflow.com/users/61047/david-boddie">David Boddie</a> in the PyQt mailing list. Here's a working snippet based on his code:</p>
<pre><code>from PyQt4.QtCore import *
from PyQt4.QtGui import *
import sys
from random import randint
app = QApplication(sys.argv)
model = QStandardItemModel()
for n in range(10):
item = QStandardItem('Item %s' % randint(1, 100))
check = Qt.Checked if randint(0, 1) == 1 else Qt.Unchecked
item.setCheckState(check)
item.setCheckable(True)
model.appendRow(item)
view = QListView()
view.setModel(model)
view.show()
app.exec_()
</code></pre>
<p>Note: changed the call of <code>setData</code> with a check role to <code>setCheckState</code> and used <code>setCheckable</code> instead of flags.</p>
| 21 | 2009-05-13T03:34:00Z | [
"python",
"qt",
"pyqt",
"qitemdelegate",
"qlistview"
] |
Read Unicode characters from command-line arguments in Python 2.x on Windows | 846,850 | <p>I want my Python script to be able to read Unicode command line arguments in Windows. But it appears that sys.argv is a string encoded in some local encoding, rather than Unicode. How can I read the command line in full Unicode?</p>
<p>Example code: <code>argv.py</code></p>
<pre><code>import sys
first_arg = sys.argv[1]
print first_arg
print type(first_arg)
print first_arg.encode("hex")
print open(first_arg)
</code></pre>
<p>On my PC set up for Japanese code page, I get:</p>
<pre><code>C:\temp>argv.py "PCã»ã½ããç³è«æ¸08.09.24.doc"
PCã»ã½ããç³è«æ¸08.09.24.doc
<type 'str'>
50438145835c83748367905c90bf8f9130382e30392e32342e646f63
<open file 'PCã»ã½ããç³è«æ¸08.09.24.doc', mode 'r' at 0x00917D90>
</code></pre>
<p>That's Shift-JIS encoded I believe, and it "works" for that filename. But it breaks for filenames with characters that aren't in the Shift-JIS character setâthe final "open" call fails:</p>
<pre><code>C:\temp>argv.py Jörgen.txt
Jorgen.txt
<type 'str'>
4a6f7267656e2e747874
Traceback (most recent call last):
File "C:\temp\argv.py", line 7,
in <module>
print open(first_arg)
IOError: [Errno 2] No such file or directory: 'Jorgen.txt'
</code></pre>
<p>NoteâI'm talking about Python 2.x, not Python 3.0. I've found that Python 3.0 gives <code>sys.argv</code> as proper Unicode. But it's a bit early yet to transition to Python 3.0 (due to lack of 3rd party library support).</p>
<p><strong>Update:</strong></p>
<p>A few answers have said I should decode according to whatever the <code>sys.argv</code> is encoded in. The problem with that is that it's not full Unicode, so some characters are not representable.</p>
<p>Here's the use case that gives me grief: I have <a href="http://stackoverflow.com/q/142844/60075">enabled drag-and-drop of files onto .py files in Windows Explorer</a>. I have file names with all sorts of characters, including some not in the system default code page. My Python script doesn't get the right Unicode filenames passed to it via sys.argv in all cases, when the characters aren't representable in the current code page encoding.</p>
<p>There is certainly some Windows API to read the command line with full Unicode (and Python 3.0 does it). I assume the Python 2.x interpreter is not using it.</p>
| 24 | 2009-05-11T05:44:02Z | 846,873 | <p>The command line might be in Windows encoding. Try decoding the arguments into <code>unicode</code> objects:</p>
<pre><code>args = [unicode(x, "iso-8859-9") for x in sys.argv]
</code></pre>
| 0 | 2009-05-11T05:57:07Z | [
"python",
"windows",
"command-line",
"unicode",
"python-2.x"
] |
Read Unicode characters from command-line arguments in Python 2.x on Windows | 846,850 | <p>I want my Python script to be able to read Unicode command line arguments in Windows. But it appears that sys.argv is a string encoded in some local encoding, rather than Unicode. How can I read the command line in full Unicode?</p>
<p>Example code: <code>argv.py</code></p>
<pre><code>import sys
first_arg = sys.argv[1]
print first_arg
print type(first_arg)
print first_arg.encode("hex")
print open(first_arg)
</code></pre>
<p>On my PC set up for Japanese code page, I get:</p>
<pre><code>C:\temp>argv.py "PCã»ã½ããç³è«æ¸08.09.24.doc"
PCã»ã½ããç³è«æ¸08.09.24.doc
<type 'str'>
50438145835c83748367905c90bf8f9130382e30392e32342e646f63
<open file 'PCã»ã½ããç³è«æ¸08.09.24.doc', mode 'r' at 0x00917D90>
</code></pre>
<p>That's Shift-JIS encoded I believe, and it "works" for that filename. But it breaks for filenames with characters that aren't in the Shift-JIS character setâthe final "open" call fails:</p>
<pre><code>C:\temp>argv.py Jörgen.txt
Jorgen.txt
<type 'str'>
4a6f7267656e2e747874
Traceback (most recent call last):
File "C:\temp\argv.py", line 7,
in <module>
print open(first_arg)
IOError: [Errno 2] No such file or directory: 'Jorgen.txt'
</code></pre>
<p>NoteâI'm talking about Python 2.x, not Python 3.0. I've found that Python 3.0 gives <code>sys.argv</code> as proper Unicode. But it's a bit early yet to transition to Python 3.0 (due to lack of 3rd party library support).</p>
<p><strong>Update:</strong></p>
<p>A few answers have said I should decode according to whatever the <code>sys.argv</code> is encoded in. The problem with that is that it's not full Unicode, so some characters are not representable.</p>
<p>Here's the use case that gives me grief: I have <a href="http://stackoverflow.com/q/142844/60075">enabled drag-and-drop of files onto .py files in Windows Explorer</a>. I have file names with all sorts of characters, including some not in the system default code page. My Python script doesn't get the right Unicode filenames passed to it via sys.argv in all cases, when the characters aren't representable in the current code page encoding.</p>
<p>There is certainly some Windows API to read the command line with full Unicode (and Python 3.0 does it). I assume the Python 2.x interpreter is not using it.</p>
| 24 | 2009-05-11T05:44:02Z | 846,877 | <p>Try this:</p>
<pre><code>import sys
print repr(sys.argv[1].decode('UTF-8'))
</code></pre>
<p>Maybe you have to substitute <code>CP437</code> or <code>CP1252</code> for <code>UTF-8</code>. You should be able to infer the proper encoding name from the registry key <code>HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Nls\CodePage\OEMCP</code></p>
| 2 | 2009-05-11T05:58:33Z | [
"python",
"windows",
"command-line",
"unicode",
"python-2.x"
] |
Read Unicode characters from command-line arguments in Python 2.x on Windows | 846,850 | <p>I want my Python script to be able to read Unicode command line arguments in Windows. But it appears that sys.argv is a string encoded in some local encoding, rather than Unicode. How can I read the command line in full Unicode?</p>
<p>Example code: <code>argv.py</code></p>
<pre><code>import sys
first_arg = sys.argv[1]
print first_arg
print type(first_arg)
print first_arg.encode("hex")
print open(first_arg)
</code></pre>
<p>On my PC set up for Japanese code page, I get:</p>
<pre><code>C:\temp>argv.py "PCã»ã½ããç³è«æ¸08.09.24.doc"
PCã»ã½ããç³è«æ¸08.09.24.doc
<type 'str'>
50438145835c83748367905c90bf8f9130382e30392e32342e646f63
<open file 'PCã»ã½ããç³è«æ¸08.09.24.doc', mode 'r' at 0x00917D90>
</code></pre>
<p>That's Shift-JIS encoded I believe, and it "works" for that filename. But it breaks for filenames with characters that aren't in the Shift-JIS character setâthe final "open" call fails:</p>
<pre><code>C:\temp>argv.py Jörgen.txt
Jorgen.txt
<type 'str'>
4a6f7267656e2e747874
Traceback (most recent call last):
File "C:\temp\argv.py", line 7,
in <module>
print open(first_arg)
IOError: [Errno 2] No such file or directory: 'Jorgen.txt'
</code></pre>
<p>NoteâI'm talking about Python 2.x, not Python 3.0. I've found that Python 3.0 gives <code>sys.argv</code> as proper Unicode. But it's a bit early yet to transition to Python 3.0 (due to lack of 3rd party library support).</p>
<p><strong>Update:</strong></p>
<p>A few answers have said I should decode according to whatever the <code>sys.argv</code> is encoded in. The problem with that is that it's not full Unicode, so some characters are not representable.</p>
<p>Here's the use case that gives me grief: I have <a href="http://stackoverflow.com/q/142844/60075">enabled drag-and-drop of files onto .py files in Windows Explorer</a>. I have file names with all sorts of characters, including some not in the system default code page. My Python script doesn't get the right Unicode filenames passed to it via sys.argv in all cases, when the characters aren't representable in the current code page encoding.</p>
<p>There is certainly some Windows API to read the command line with full Unicode (and Python 3.0 does it). I assume the Python 2.x interpreter is not using it.</p>
| 24 | 2009-05-11T05:44:02Z | 846,931 | <p>Here is a solution that is just what I'm looking for, making a call to the Windows <code>GetCommandLineArgvW </code> function:<br>
<a href="http://code.activestate.com/recipes/572200/">Get sys.argv with Unicode characters under Windows</a> (from ActiveState)</p>
<p>But I've made several changes, to simplify its usage and better handle certain uses. Here is what I use:</p>
<p><strong><code>win32_unicode_argv.py</code></strong></p>
<pre><code>"""
win32_unicode_argv.py
Importing this will replace sys.argv with a full Unicode form.
Windows only.
From this site, with adaptations:
http://code.activestate.com/recipes/572200/
Usage: simply import this module into a script. sys.argv is changed to
be a list of Unicode strings.
"""
import sys
def win32_unicode_argv():
"""Uses shell32.GetCommandLineArgvW to get sys.argv as a list of Unicode
strings.
Versions 2.x of Python don't support Unicode in sys.argv on
Windows, with the underlying Windows API instead replacing multi-byte
characters with '?'.
"""
from ctypes import POINTER, byref, cdll, c_int, windll
from ctypes.wintypes import LPCWSTR, LPWSTR
GetCommandLineW = cdll.kernel32.GetCommandLineW
GetCommandLineW.argtypes = []
GetCommandLineW.restype = LPCWSTR
CommandLineToArgvW = windll.shell32.CommandLineToArgvW
CommandLineToArgvW.argtypes = [LPCWSTR, POINTER(c_int)]
CommandLineToArgvW.restype = POINTER(LPWSTR)
cmd = GetCommandLineW()
argc = c_int(0)
argv = CommandLineToArgvW(cmd, byref(argc))
if argc.value > 0:
# Remove Python executable and commands if present
start = argc.value - len(sys.argv)
return [argv[i] for i in
xrange(start, argc.value)]
sys.argv = win32_unicode_argv()
</code></pre>
<p>Now, the way I use it is simply to do:</p>
<pre><code>import sys
import win32_unicode_argv
</code></pre>
<p>and from then on, <code>sys.argv</code> is a list of Unicode strings. The Python <code>optparse</code> module seems happy to parse it, which is great.</p>
| 24 | 2009-05-11T06:21:59Z | [
"python",
"windows",
"command-line",
"unicode",
"python-2.x"
] |
Read Unicode characters from command-line arguments in Python 2.x on Windows | 846,850 | <p>I want my Python script to be able to read Unicode command line arguments in Windows. But it appears that sys.argv is a string encoded in some local encoding, rather than Unicode. How can I read the command line in full Unicode?</p>
<p>Example code: <code>argv.py</code></p>
<pre><code>import sys
first_arg = sys.argv[1]
print first_arg
print type(first_arg)
print first_arg.encode("hex")
print open(first_arg)
</code></pre>
<p>On my PC set up for Japanese code page, I get:</p>
<pre><code>C:\temp>argv.py "PCã»ã½ããç³è«æ¸08.09.24.doc"
PCã»ã½ããç³è«æ¸08.09.24.doc
<type 'str'>
50438145835c83748367905c90bf8f9130382e30392e32342e646f63
<open file 'PCã»ã½ããç³è«æ¸08.09.24.doc', mode 'r' at 0x00917D90>
</code></pre>
<p>That's Shift-JIS encoded I believe, and it "works" for that filename. But it breaks for filenames with characters that aren't in the Shift-JIS character setâthe final "open" call fails:</p>
<pre><code>C:\temp>argv.py Jörgen.txt
Jorgen.txt
<type 'str'>
4a6f7267656e2e747874
Traceback (most recent call last):
File "C:\temp\argv.py", line 7,
in <module>
print open(first_arg)
IOError: [Errno 2] No such file or directory: 'Jorgen.txt'
</code></pre>
<p>NoteâI'm talking about Python 2.x, not Python 3.0. I've found that Python 3.0 gives <code>sys.argv</code> as proper Unicode. But it's a bit early yet to transition to Python 3.0 (due to lack of 3rd party library support).</p>
<p><strong>Update:</strong></p>
<p>A few answers have said I should decode according to whatever the <code>sys.argv</code> is encoded in. The problem with that is that it's not full Unicode, so some characters are not representable.</p>
<p>Here's the use case that gives me grief: I have <a href="http://stackoverflow.com/q/142844/60075">enabled drag-and-drop of files onto .py files in Windows Explorer</a>. I have file names with all sorts of characters, including some not in the system default code page. My Python script doesn't get the right Unicode filenames passed to it via sys.argv in all cases, when the characters aren't representable in the current code page encoding.</p>
<p>There is certainly some Windows API to read the command line with full Unicode (and Python 3.0 does it). I assume the Python 2.x interpreter is not using it.</p>
| 24 | 2009-05-11T05:44:02Z | 847,114 | <p>Dealing with encodings is very confusing.</p>
<p>I <em>believe</em> if your inputing data via the commandline it will encode the data as whatever your system encoding is and is not unicode. (Even copy/paste should do this)</p>
<p>So it should be correct to decode into unicode using the system encoding:</p>
<pre><code>import sys
first_arg = sys.argv[1]
print first_arg
print type(first_arg)
first_arg_unicode = first_arg.decode(sys.getfilesystemencoding())
print first_arg_unicode
print type(first_arg_unicode)
f = codecs.open(first_arg_unicode, 'r', 'utf-8')
unicode_text = f.read()
print type(unicode_text)
print unicode_text.encode(sys.getfilesystemencoding())
</code></pre>
<p>running the following Will output:
Prompt> python myargv.py "PCã»ã½ããç³è«æ¸08.09.24.txt"</p>
<pre><code>PCã»ã½ããç³è«æ¸08.09.24.txt
<type 'str'>
<type 'unicode'>
PCã»ã½ããç³è«æ¸08.09.24.txt
<type 'unicode'>
?æ¥æ¬èª
</code></pre>
<p>Where the "PCã»ã½ããç³è«æ¸08.09.24.txt" contained the text, "æ¥æ¬èª".
(I encoded the file as utf8 using windows notepad, I'm a little stumped as to why there's a '?' in the begining when printing. Something to do with how notepad saves utf8?)</p>
<p>The strings 'decode' method or the unicode() builtin can be used to convert an encoding into unicode.</p>
<pre><code>unicode_str = utf8_str.decode('utf8')
unicode_str = unicode(utf8_str, 'utf8')
</code></pre>
<p>Also, if your dealing with encoded files you may want to use the codecs.open() function in place of the built-in open(). It allows you to define the encoding of the file, and will then use the given encoding to transparently decode the content to unicode.</p>
<p>So when you call <code>content = codecs.open("myfile.txt", "r", "utf8").read()</code> <code>content</code> will be in unicode.</p>
<p>codecs.open:
<a href="http://docs.python.org/library/codecs.html?#codecs.open">http://docs.python.org/library/codecs.html?#codecs.open</a></p>
<p>If I'm miss-understanding something please let me know.</p>
<p>If you haven't already I recommend reading Joel's article on unicode and encoding:
<a href="http://www.joelonsoftware.com/articles/Unicode.html">http://www.joelonsoftware.com/articles/Unicode.html</a></p>
| 10 | 2009-05-11T07:45:24Z | [
"python",
"windows",
"command-line",
"unicode",
"python-2.x"
] |
Parsing in Python: what's the most efficient way to supress/normalize strings? | 846,869 | <p>I'm parsing a source file, and I want to "suppress" strings. What I mean by this is transform every string like "bla bla bla +/*" to something like "string" that is deterministic and does not contain any characters that may confuse my parser, because I don't care about the value of the strings. One of the issues here is string formatting using e.g. "%s", please see my remark about this below.</p>
<p>Take for example the following pseudo code, that may be the contents of a file I'm parsing. Assume strings start with ", and escaping the " character is done by "":</p>
<pre><code>print(i)
print("hello**")
print("hel"+"lo**")
print("h e l l o "+
"hello\n")
print("hell""o")
print(str(123)+"h e l l o")
print(uppercase("h e l l o")+"g o o d b y e")
</code></pre>
<p>Should be transformed to the following result:</p>
<pre><code>print(i)
print("string")
print("string"+"string")
print("string"
"string")
print("string")
print(str(123)+"string")
print(uppercase("string")+"string")
</code></pre>
<p>Currently I treat it as a special case in the code (i.e. detect beginning of a string, and "manually" run until its end with several sub-special cases on the way). If there's a Python library function i can use or a nice regex that may make my code more efficient, that would be great. </p>
<p>Few remarks:</p>
<ul>
<li>I would like the "start-of-string" character to be a variable, e.g. ' vs ".</li>
<li>I'm not parsing Python code at this stage, but I plan to, and there the problem obviously becomes more complex because strings can start in several ways and must end in a way corresponding to the start. I'm not attempting to deal with this right now, but if there's any well established best practice I would like to know about it.</li>
<li>The thing bothering me the most about this "suppression" is the case of string formatting with the likes of '%s', that are meaningful tokens. I'm currently not dealing with this and haven't completely thought it through, but if any of you have suggestions about how to deal with this that would be great. Please note I'm not interested in the specific type or formatting of the in-string tokens, it's enough for me to know that there are tokens inside the string (how many). Remark that may be important here: my tokenizer is not nested, because my goal is quite simple (I'm not compiling anything...). </li>
<li>I'm not quite sure about the escaping of the start-string character. What would you say are the common ways this is implemented in most programming languages? Is the assumption of double-occurrence (e.g. "") or any set of two characters (e.g. '\"') to escape enough? Do I need to treat other cases (think of languages like Java, C/C++, PHP, C#)</li>
</ul>
<p>Thanks,
Rax</p>
| 0 | 2009-05-11T05:55:03Z | 846,886 | <p>Option 1: To sanitize Python source code, try the built-in <a href="http://docs.python.org/library/tokenize.html" rel="nofollow">tokenize</a> module. It can correctly find strings and other tokens in any Python source file.</p>
<p>Option 3: Use <a href="http://pygments.org/languages/" rel="nofollow">pygments</a> with HTML output, and replace anything in blue (etc.) with <code>"string"</code>. pygments supports a few dozen languages.</p>
<p>Option 2: For most of the languages, you can build a custom regexp substitution. For example, the following sanitizes Python source code (but it doesn't work if the source file contains <code>"""</code> or <code>'''</code>):</p>
<pre><code>import re
sanitized = re.sub(r'(#.*)|\'(?:[^\'\\]+|\\.)*\'|"(?:[^"\\]+|\\.)*"',
lambda match: match.group(1) or '"string"', source_code)
</code></pre>
<p>The regexp above works properly even if the strings contain backslashes (<code>\"</code>, <code>\\</code>, <code>\n</code>, <code>\\</code>, <code>\\"</code>, <code>\\\"</code> etc. all work fine).</p>
<p>When you are building your regexp, make sure to match comments (so your regexp substitution won't touch strings inside comments) and regular expression literals (e.g. in Perl, Ruby and JavaScript), and pay attention you match backslashes and newlines properly (e.g. in Perl and Ruby a string can contain a newline).</p>
| 4 | 2009-05-11T06:01:22Z | [
"python",
"string",
"parsing"
] |
Parsing in Python: what's the most efficient way to supress/normalize strings? | 846,869 | <p>I'm parsing a source file, and I want to "suppress" strings. What I mean by this is transform every string like "bla bla bla +/*" to something like "string" that is deterministic and does not contain any characters that may confuse my parser, because I don't care about the value of the strings. One of the issues here is string formatting using e.g. "%s", please see my remark about this below.</p>
<p>Take for example the following pseudo code, that may be the contents of a file I'm parsing. Assume strings start with ", and escaping the " character is done by "":</p>
<pre><code>print(i)
print("hello**")
print("hel"+"lo**")
print("h e l l o "+
"hello\n")
print("hell""o")
print(str(123)+"h e l l o")
print(uppercase("h e l l o")+"g o o d b y e")
</code></pre>
<p>Should be transformed to the following result:</p>
<pre><code>print(i)
print("string")
print("string"+"string")
print("string"
"string")
print("string")
print(str(123)+"string")
print(uppercase("string")+"string")
</code></pre>
<p>Currently I treat it as a special case in the code (i.e. detect beginning of a string, and "manually" run until its end with several sub-special cases on the way). If there's a Python library function i can use or a nice regex that may make my code more efficient, that would be great. </p>
<p>Few remarks:</p>
<ul>
<li>I would like the "start-of-string" character to be a variable, e.g. ' vs ".</li>
<li>I'm not parsing Python code at this stage, but I plan to, and there the problem obviously becomes more complex because strings can start in several ways and must end in a way corresponding to the start. I'm not attempting to deal with this right now, but if there's any well established best practice I would like to know about it.</li>
<li>The thing bothering me the most about this "suppression" is the case of string formatting with the likes of '%s', that are meaningful tokens. I'm currently not dealing with this and haven't completely thought it through, but if any of you have suggestions about how to deal with this that would be great. Please note I'm not interested in the specific type or formatting of the in-string tokens, it's enough for me to know that there are tokens inside the string (how many). Remark that may be important here: my tokenizer is not nested, because my goal is quite simple (I'm not compiling anything...). </li>
<li>I'm not quite sure about the escaping of the start-string character. What would you say are the common ways this is implemented in most programming languages? Is the assumption of double-occurrence (e.g. "") or any set of two characters (e.g. '\"') to escape enough? Do I need to treat other cases (think of languages like Java, C/C++, PHP, C#)</li>
</ul>
<p>Thanks,
Rax</p>
| 0 | 2009-05-11T05:55:03Z | 846,900 | <p>Nowhere do you mention that you take an approach using a <a href="http://en.wikipedia.org/wiki/Lexical%5Fanalysis" rel="nofollow">lexer</a> and <a href="http://en.wikipedia.org/wiki/Parsing" rel="nofollow">parser</a>. If in fact you do not, have a look at e.g. the <a href="http://docs.python.org/library/tokenize.html" rel="nofollow">tokenize</a> module (which is probably what you want), or the 3rd party module <a href="http://www.dabeaz.com/ply/" rel="nofollow">PLY</a> (Python Lex-Yacc). Your problem needs a systematic approach, and these tools (and others) provide it.</p>
<p>(Note that once you have tokenized the code, you can apply <em>another</em> specialized tokenizer to the contents of the strings to detect special formatting directives such as <code>%s</code>. In this case a regular expression may do the job, though.)</p>
| 1 | 2009-05-11T06:06:40Z | [
"python",
"string",
"parsing"
] |
Parsing in Python: what's the most efficient way to supress/normalize strings? | 846,869 | <p>I'm parsing a source file, and I want to "suppress" strings. What I mean by this is transform every string like "bla bla bla +/*" to something like "string" that is deterministic and does not contain any characters that may confuse my parser, because I don't care about the value of the strings. One of the issues here is string formatting using e.g. "%s", please see my remark about this below.</p>
<p>Take for example the following pseudo code, that may be the contents of a file I'm parsing. Assume strings start with ", and escaping the " character is done by "":</p>
<pre><code>print(i)
print("hello**")
print("hel"+"lo**")
print("h e l l o "+
"hello\n")
print("hell""o")
print(str(123)+"h e l l o")
print(uppercase("h e l l o")+"g o o d b y e")
</code></pre>
<p>Should be transformed to the following result:</p>
<pre><code>print(i)
print("string")
print("string"+"string")
print("string"
"string")
print("string")
print(str(123)+"string")
print(uppercase("string")+"string")
</code></pre>
<p>Currently I treat it as a special case in the code (i.e. detect beginning of a string, and "manually" run until its end with several sub-special cases on the way). If there's a Python library function i can use or a nice regex that may make my code more efficient, that would be great. </p>
<p>Few remarks:</p>
<ul>
<li>I would like the "start-of-string" character to be a variable, e.g. ' vs ".</li>
<li>I'm not parsing Python code at this stage, but I plan to, and there the problem obviously becomes more complex because strings can start in several ways and must end in a way corresponding to the start. I'm not attempting to deal with this right now, but if there's any well established best practice I would like to know about it.</li>
<li>The thing bothering me the most about this "suppression" is the case of string formatting with the likes of '%s', that are meaningful tokens. I'm currently not dealing with this and haven't completely thought it through, but if any of you have suggestions about how to deal with this that would be great. Please note I'm not interested in the specific type or formatting of the in-string tokens, it's enough for me to know that there are tokens inside the string (how many). Remark that may be important here: my tokenizer is not nested, because my goal is quite simple (I'm not compiling anything...). </li>
<li>I'm not quite sure about the escaping of the start-string character. What would you say are the common ways this is implemented in most programming languages? Is the assumption of double-occurrence (e.g. "") or any set of two characters (e.g. '\"') to escape enough? Do I need to treat other cases (think of languages like Java, C/C++, PHP, C#)</li>
</ul>
<p>Thanks,
Rax</p>
| 0 | 2009-05-11T05:55:03Z | 846,905 | <p><strong>Use a dedicated parser for each language</strong> â especially since people have already done that work for you. Most of the languages you mentioned have a grammar.</p>
| 1 | 2009-05-11T06:08:02Z | [
"python",
"string",
"parsing"
] |
Is Twisted an httplib2/socket replacement? | 846,950 | <p>Many python libraries, even recently written ones, use httplib2 or the socket interface to perform networking tasks.</p>
<p>Those are obviously easier to code on than Twisted due to their blocking nature, but I think this is a drawback when integrating them with other code, especially GUI one. If you want scalability, concurrency or GUI integration while avoiding multithreading, Twisted is then a natural choice.</p>
<p>So I would be interested in opinions in those matters:</p>
<ol>
<li>Should new networking code (with the exception of small command line tools) be written with Twisted?</li>
<li>Would you mix Twisted, http2lib or socket code in the same project?</li>
<li>Is Twisted pythonic for most libraries (it is more complex than alternatives, introduce a dependency to a non-standard package...)?</li>
</ol>
<p><strong>Edit:</strong> please let me phrase this in another way. Do you feel writing new library code with Twisted may add a barrier to its adoption? Twisted has obvious benefits (especially portability and scalability as stated by gimel), but the fact that it is not a core python library may be considered by some as a drawback.</p>
| 6 | 2009-05-11T06:30:44Z | 846,984 | <p>See <a href="http://stackoverflow.com/questions/80617/asychronous-programming-in-python-twisted">asychronous-programming-in-python-twisted</a>, you'll have to decide if depending on a non-standard (external) library fits your needs. Note the answer by <a href="http://stackoverflow.com/users/13564/glyph">@Glyph</a>, he is the founder of the <code>Twisted</code> project, and can authoritatively answer any <code>Twisted</code> related question.</p>
<blockquote>
<p>At the core of libraries like Twisted, the function in the main loop is not sleep, but an operating system call like select() or poll(), as exposed by a module like the Python select module. I say "like" select, because this is an API that varies a lot between platforms, and almost every GUI toolkit has its own version. Twisted currently provides an abstract interface to 14 different variations on this theme. The common thing that such an API provides is provide a way to say "Here are a list of events that I'm waiting for. Go to sleep until one of them happens, then wake up and tell me which one of them it was."</p>
</blockquote>
| 5 | 2009-05-11T06:46:53Z | [
"python",
"networking",
"sockets",
"twisted",
"httplib2"
] |
Is Twisted an httplib2/socket replacement? | 846,950 | <p>Many python libraries, even recently written ones, use httplib2 or the socket interface to perform networking tasks.</p>
<p>Those are obviously easier to code on than Twisted due to their blocking nature, but I think this is a drawback when integrating them with other code, especially GUI one. If you want scalability, concurrency or GUI integration while avoiding multithreading, Twisted is then a natural choice.</p>
<p>So I would be interested in opinions in those matters:</p>
<ol>
<li>Should new networking code (with the exception of small command line tools) be written with Twisted?</li>
<li>Would you mix Twisted, http2lib or socket code in the same project?</li>
<li>Is Twisted pythonic for most libraries (it is more complex than alternatives, introduce a dependency to a non-standard package...)?</li>
</ol>
<p><strong>Edit:</strong> please let me phrase this in another way. Do you feel writing new library code with Twisted may add a barrier to its adoption? Twisted has obvious benefits (especially portability and scalability as stated by gimel), but the fact that it is not a core python library may be considered by some as a drawback.</p>
| 6 | 2009-05-11T06:30:44Z | 847,014 | <ol>
<li>Should new networking code (with the exception of small command line tools) be written with Twisted?
<ul>
<li>Maybe. It really depends. Sometimes its just easy enough to wrap the blocking calls in their own thread. Twisted is good for large scale network code.</li>
</ul></li>
<li>Would you mix Twisted, http2lib or socket code in the same project?
<ul>
<li>Sure. But just remember that Twisted is single threaded, and that any blocking call in Twisted will block the entire engine.</li>
</ul></li>
<li>Is Twisted pythonic for most libraries (it is more complex than alternatives, introduce a dependency to a non-standard package...)?
<ul>
<li>There are many Twisted zealots that will say it belongs in the Python standard library. But many people can implement decent networking code with asyncore/asynchat.</li>
</ul></li>
</ol>
| 0 | 2009-05-11T06:58:25Z | [
"python",
"networking",
"sockets",
"twisted",
"httplib2"
] |
Python equivalent of perl's dbi/DBD::Proxy access? (Perl DBI/DBD::Proxy for Python) | 847,032 | <p>I have a Perl script that interfaces with an existing database (type of database is unknown) through the DBI module, that I would like to access in python 2.6 on WinXP.</p>
<p>The Perl code is:</p>
<pre><code>use DBI;
my $DSN = "DBI:Proxy:hostname=some.dot.com;port=12345;dsn=DBI:XXXX:ZZZZZ";
my $dbh = DBI->connect($DSN);
</code></pre>
<p>Can this be translated into a python equivalent?</p>
<p>Following an example at (<a href="http://stackoverflow.com/questions/768250/is-there-any-pywin32-odbc-connector-documentation-available/768352#768352">Is there any pywin32 odbc connector documentation available?</a> ), I've put together the following:</p>
<pre><code>import odbc
DSN = "DBI:Proxy:hostname=some.dot.com;port=12345;dsn=DBI:XXXX:ZZZZZ"
db = odbc.odbc(DSN)
</code></pre>
<p>But I get the error:</p>
<pre><code>dbi.operation-error: [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified in LOGIN
</code></pre>
<p><strong>UPDATE</strong></p>
<p>It appears that another Perl module, DBD::Proxy is providing the actual interface to a Perl DBI::ProxyServer (server-side) implementation that handles the actual queries. </p>
<p>Can python be used to interface with the Perl-based <a href="https://metacpan.org/pod/DBI%3a%3aProxyServer" rel="nofollow">DBI::ProxyServer</a>?</p>
<p><a href="http://metacpan.org/pod/DBD%3a%3aProxy" rel="nofollow">http://metacpan.org/pod/DBD::Proxy</a></p>
<p><a href="http://hell.org.ua/Docs/oreilly/weblinux/dbi/ch08_02.htm" rel="nofollow">http://hell.org.ua/Docs/oreilly/weblinux/dbi/ch08_02.htm</a></p>
| 0 | 2009-05-11T07:08:27Z | 847,190 | <p>Your python script doesn't have to be a line by line translation of your Perl script.</p>
<p>Why not just use the Python <a href="http://www.python.org/dev/peps/pep-0249/" rel="nofollow">DB-API</a> compatible module for the database you want to access? For MySQL, use <a href="http://mysql-python.sourceforge.net/MySQLdb.html" rel="nofollow">MySQLdb</a>. For PostgreSQL, use <a href="http://www.pygresql.org/" rel="nofollow">PyGreSQL</a>. </p>
<p>Or search Google for "YourDatabaseName + python"</p>
| 5 | 2009-05-11T08:26:00Z | [
"python",
"perl",
"odbc",
"dbi"
] |
Python equivalent of perl's dbi/DBD::Proxy access? (Perl DBI/DBD::Proxy for Python) | 847,032 | <p>I have a Perl script that interfaces with an existing database (type of database is unknown) through the DBI module, that I would like to access in python 2.6 on WinXP.</p>
<p>The Perl code is:</p>
<pre><code>use DBI;
my $DSN = "DBI:Proxy:hostname=some.dot.com;port=12345;dsn=DBI:XXXX:ZZZZZ";
my $dbh = DBI->connect($DSN);
</code></pre>
<p>Can this be translated into a python equivalent?</p>
<p>Following an example at (<a href="http://stackoverflow.com/questions/768250/is-there-any-pywin32-odbc-connector-documentation-available/768352#768352">Is there any pywin32 odbc connector documentation available?</a> ), I've put together the following:</p>
<pre><code>import odbc
DSN = "DBI:Proxy:hostname=some.dot.com;port=12345;dsn=DBI:XXXX:ZZZZZ"
db = odbc.odbc(DSN)
</code></pre>
<p>But I get the error:</p>
<pre><code>dbi.operation-error: [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified in LOGIN
</code></pre>
<p><strong>UPDATE</strong></p>
<p>It appears that another Perl module, DBD::Proxy is providing the actual interface to a Perl DBI::ProxyServer (server-side) implementation that handles the actual queries. </p>
<p>Can python be used to interface with the Perl-based <a href="https://metacpan.org/pod/DBI%3a%3aProxyServer" rel="nofollow">DBI::ProxyServer</a>?</p>
<p><a href="http://metacpan.org/pod/DBD%3a%3aProxy" rel="nofollow">http://metacpan.org/pod/DBD::Proxy</a></p>
<p><a href="http://hell.org.ua/Docs/oreilly/weblinux/dbi/ch08_02.htm" rel="nofollow">http://hell.org.ua/Docs/oreilly/weblinux/dbi/ch08_02.htm</a></p>
| 0 | 2009-05-11T07:08:27Z | 852,703 | <p><a href="http://www.sqlalchemy.org/" rel="nofollow">sqlalchemy</a> is pretty nice.</p>
| 0 | 2009-05-12T13:13:43Z | [
"python",
"perl",
"odbc",
"dbi"
] |
Importing a python module to .net - "No module named signal" | 847,109 | <p>I'm trying to import a Python module in a C# code like this:</p>
<pre><code> var setup = Python.CreateRuntimeSetup(null);
var runtime = new ScriptRuntime(setup);
var engine = Python.GetEngine(runtime);
var module = engine.ImportModule("mymodule");
</code></pre>
<p>but I get an error saying "No module named signal", does this mean that IronPython just can't load the signal module, is it OS specific?</p>
<p>Can anyone think of a workaround?</p>
| 1 | 2009-05-11T07:43:22Z | 847,230 | <p>The 'signal' module is used to handle all that has to do with ... you guessed it: signals. There are special "messages" that the OS send to a process to tell it something: eg. Break, Kill, Terminate, etc... The exact set of message are generally OS specific, but as the <a href="http://docs.python.org/library/signal.html" rel="nofollow">signals</a> python manual page states, python emulates BSD style interface, except for SIGCHLD.</p>
<p>Now, in CPython, the 'signal' module is a built-in as far as I can remember, it could possibly be that IronPython has not implemented it, in fact, a quick google and look on IronPython's site leads to this: <a href="http://ironpython.codeplex.com/Wiki/View.aspx?title=IPy1.0.xCPyDifferences" rel="nofollow">IronPython and CPython differences</a> (read it, in particular, the extension modules part!)</p>
<p>Possible workaround: edit your module not to use signals when in IronPython</p>
| 1 | 2009-05-11T08:44:30Z | [
".net",
"python",
"ironpython"
] |
Is there an ipython equivalent for erlang? | 847,151 | <p>Coming from Python I am looking for some "easy to try out" shell like Python has with <code>ipython</code> (preferably with Emacs support). In the Erlang shell you always have to first compile (<code>c(...)</code>) which slows down the experimental phase very much.</p>
| 5 | 2009-05-11T08:07:52Z | 847,576 | <p>Yes it is :)
<a href="http://erlang.org/doc/man/escript.html" rel="nofollow">http://erlang.org/doc/man/escript.html</a></p>
<pre><code>$ cat /tmp/test
#!/usr/bin/env escript
main(_) ->
io:format("Hello World!\n").
$ chmod +x /tmp/test
$ /tmp/test
Hello World!
</code></pre>
| 3 | 2009-05-11T10:43:10Z | [
"python",
"emacs",
"erlang",
"ipython"
] |
Is there an ipython equivalent for erlang? | 847,151 | <p>Coming from Python I am looking for some "easy to try out" shell like Python has with <code>ipython</code> (preferably with Emacs support). In the Erlang shell you always have to first compile (<code>c(...)</code>) which slows down the experimental phase very much.</p>
| 5 | 2009-05-11T08:07:52Z | 860,807 | <p>It should be fairly easy to build a module the starts a process to autoload code changes into your shell. Erlang actually has built in support for this kind of thing. So anytime you have recompiled the code it gets loaded into your shell automatically thus eliminating the need to type c('module.erl'). yourself. You could probably even have it monitor file changes and automatically compile it for you. see:</p>
<p><a href="http://github.com/toddlipcon/mochiweb/blob/29d6ffd58aa2cd175f84cadfc1ce1697f366ef62/src/reloader.erl" rel="nofollow">http://github.com/toddlipcon/mochiweb/blob/29d6ffd58aa2cd175f84cadfc1ce1697f366ef62/src/reloader.erl</a> </p>
<p>for an example in action. </p>
<p>Currently that module just looks for recompiled modules but it should be trivial to have it look for changed source files and recompile them for you.</p>
| 1 | 2009-05-13T22:49:06Z | [
"python",
"emacs",
"erlang",
"ipython"
] |
Is there an ipython equivalent for erlang? | 847,151 | <p>Coming from Python I am looking for some "easy to try out" shell like Python has with <code>ipython</code> (preferably with Emacs support). In the Erlang shell you always have to first compile (<code>c(...)</code>) which slows down the experimental phase very much.</p>
| 5 | 2009-05-11T08:07:52Z | 24,341,588 | <p>IErlang is an Erlang language kernel for IPython. It allows users to use IPython's Notebook frontend, except where IPython executes python code, IErlang can execute erlang code and compile and execute erlang modules.</p>
<p><a href="https://github.com/robbielynch/ierlang" rel="nofollow">https://github.com/robbielynch/ierlang</a></p>
<p>There is also an IPython kernel for Elixir:</p>
<p><a href="https://github.com/pminten/ielixir" rel="nofollow">https://github.com/pminten/ielixir</a></p>
| 1 | 2014-06-21T12:27:21Z | [
"python",
"emacs",
"erlang",
"ipython"
] |
User-defined derived data in Django | 847,201 | <p>How do I let my users apply their own custom formula to a table of data to derive new fields?</p>
<p>I am working on a <a href="http://www.djangoproject.com" rel="nofollow">Django</a> application which is going to store and process a lot of data for subscribed users on the open web. Think 100-10,000 sensor readings in one page request. I am going to be drawing graphs using this data and also showing tables containing it. I expect groups of sensors to be defined by my users, who will have registered themselves on my website (i.e they correspond with a django model).</p>
<p>I would like to allow the user to be able to create fields that are derived from their sensor data (as part of a setup process). For example, the user might know that their average house temperature is (temperature sensor1 + temperature sensor2) / 2 and want to show that on the graph. They might also want something more interesting like solar hot water heated is (temp out - temp in) * flow * conversion constant. I will then save these defined formulas for them and everyone else who views this page of sensor data.</p>
<p>The main question is how do I define the formula at the centre of the system. Do I just have a user-defined string to define the formula (say 100 chars long) and parse it myself - replace the user defined with an input sample and call it toast?</p>
<p><strong>Update</strong> </p>
<p>In the end I got just the answer I asked for : A safe way to evaluate a stored user function on the server. Evaluating the same function also on the client when the function is being defined will be a great way to make the UI intuitive.</p>
| 2 | 2009-05-11T08:32:27Z | 847,223 | <p>Another user asked a <a href="http://stackoverflow.com/questions/28124/calculating-user-defined-formulas-with-c">similar question</a> in C.
In that post, Warren suggested that the formula could be parsed and converted from </p>
<pre><code>(a + c) / b
</code></pre>
<p>Into <a href="http://en.wikipedia.org/wiki/Reverse%5FPolish%5Fnotation" rel="nofollow">reverse polish notation</a></p>
<pre><code>a c + b /
</code></pre>
<p>Which is easier to process. </p>
<p>In this case, you could intercept the formula model's save and generate the postfix notation from the user-defined formula. Once you have postfix notation, it is fairly straightforward to write a loop that evaluates the formula from left to right.</p>
<p>As for implementation in Django, the core question remaining is how to map different input fields into the formula. The simple solution would be a model representing the derived field uses a many-to-many relationship with the symbol name ("a", "b" or "c") defined per-input. </p>
<p>If performance is really critical, you might somehow further pre-process the postfix formula before applying it to the data.</p>
| 0 | 2009-05-11T08:41:14Z | [
"python",
"django",
"user-defined-functions"
] |
User-defined derived data in Django | 847,201 | <p>How do I let my users apply their own custom formula to a table of data to derive new fields?</p>
<p>I am working on a <a href="http://www.djangoproject.com" rel="nofollow">Django</a> application which is going to store and process a lot of data for subscribed users on the open web. Think 100-10,000 sensor readings in one page request. I am going to be drawing graphs using this data and also showing tables containing it. I expect groups of sensors to be defined by my users, who will have registered themselves on my website (i.e they correspond with a django model).</p>
<p>I would like to allow the user to be able to create fields that are derived from their sensor data (as part of a setup process). For example, the user might know that their average house temperature is (temperature sensor1 + temperature sensor2) / 2 and want to show that on the graph. They might also want something more interesting like solar hot water heated is (temp out - temp in) * flow * conversion constant. I will then save these defined formulas for them and everyone else who views this page of sensor data.</p>
<p>The main question is how do I define the formula at the centre of the system. Do I just have a user-defined string to define the formula (say 100 chars long) and parse it myself - replace the user defined with an input sample and call it toast?</p>
<p><strong>Update</strong> </p>
<p>In the end I got just the answer I asked for : A safe way to evaluate a stored user function on the server. Evaluating the same function also on the client when the function is being defined will be a great way to make the UI intuitive.</p>
| 2 | 2009-05-11T08:32:27Z | 847,408 | <p>I would work out what operations you want to support [+,-,*,/,(,),etc] and develop client side (javascript) to edit and apply those values to new fields of the data. I don't see the need to do any of this server-side and you will end up with a more responsive and enjoyable user experience as a result.</p>
<p>If you allow the user to save their formulas and re-load them when they revisit the site, you can get their browser to do all the calculations. Just provide some generic methods to add columns of data which are generated by applying one of their forumla's to your data.</p>
<p>I imagine the next step would be to allow them to apply those operations to the newly generated columns.</p>
<p>Have you considered posting their data into a google spreadsheet? This would save a lot of the development work as they already allow you to define formulas etc. and apply it to the data. I'm not too sure of the data limit (how much data you can post and operate on) mind you.</p>
| 2 | 2009-05-11T09:44:18Z | [
"python",
"django",
"user-defined-functions"
] |
User-defined derived data in Django | 847,201 | <p>How do I let my users apply their own custom formula to a table of data to derive new fields?</p>
<p>I am working on a <a href="http://www.djangoproject.com" rel="nofollow">Django</a> application which is going to store and process a lot of data for subscribed users on the open web. Think 100-10,000 sensor readings in one page request. I am going to be drawing graphs using this data and also showing tables containing it. I expect groups of sensors to be defined by my users, who will have registered themselves on my website (i.e they correspond with a django model).</p>
<p>I would like to allow the user to be able to create fields that are derived from their sensor data (as part of a setup process). For example, the user might know that their average house temperature is (temperature sensor1 + temperature sensor2) / 2 and want to show that on the graph. They might also want something more interesting like solar hot water heated is (temp out - temp in) * flow * conversion constant. I will then save these defined formulas for them and everyone else who views this page of sensor data.</p>
<p>The main question is how do I define the formula at the centre of the system. Do I just have a user-defined string to define the formula (say 100 chars long) and parse it myself - replace the user defined with an input sample and call it toast?</p>
<p><strong>Update</strong> </p>
<p>In the end I got just the answer I asked for : A safe way to evaluate a stored user function on the server. Evaluating the same function also on the client when the function is being defined will be a great way to make the UI intuitive.</p>
| 2 | 2009-05-11T08:32:27Z | 847,566 | <p>Depends on who your clients are.</p>
<p>If this is "open to the public" on the WWW, you have to parse expressions yourself. You can use the Python compiler to compile Python syntax. You can also invent your own compiler for a subset of Python syntax. There are lots of examples; start with the <a href="http://www.dabeaz.com/ply/" rel="nofollow">ply</a> project.</p>
<p>If this is in-house ("behind the firewall") let the post a piece of Python code and exec that code.</p>
<p>Give them an environment <code>from math import *</code> functionality available.</p>
<p>Fold the following around their supplied line of code:</p>
<pre><code>def userFunc( col1, col2, col3, ... ):
result1= {{ their code goes here }}
return result1
</code></pre>
<p>Then you can exec the function definition and use the defined function without bad things happening.</p>
<p>While some folks like to crow that <code>exec</code> is "security problem", it's no more a security problem than user's sharing passwords, and admin's doing intentionally stupid things like deleting important files or turning the power off randomly while your programming is running.</p>
<p><code>exec</code> is only a security problem if you allow anyone access to it. For in-house applications, you know the users. Train them.</p>
| 2 | 2009-05-11T10:41:43Z | [
"python",
"django",
"user-defined-functions"
] |
Cross-platform way of getting temp directory in Python | 847,850 | <p>Is there a cross-platform way of getting the path to the <em><code>temp</code></em> directory in Python 2.6? </p>
<p>For example, under Linux that would be <code>/tmp</code>, while under XP <code>C:\Documents and settings\[user]\Application settings\Temp</code>.</p>
<p>Thanks!</p>
| 123 | 2009-05-11T12:21:46Z | 847,866 | <p>That would be the <a href="http://docs.python.org/library/tempfile.html">tempfile</a> module.</p>
<p>It has functions to get the temporary directory, and also has some shortcuts to create temporary files and directories in it, either named or unnamed.</p>
<p>Example:</p>
<pre><code>import tempfile
print tempfile.gettempdir() # prints the current temporary directory
f = tempfile.TemporaryFile()
f.write('something on temporaryfile')
f.seek(0) # return to beginning of file
print f.read() # reads data back from the file
f.close() # temporary file is automatically deleted here
</code></pre>
<p>For completeness, here's how it searches for the temporary directory, according to the documentation:</p>
<ol>
<li>The directory named by the <code>TMPDIR</code> environment variable.</li>
<li>The directory named by the <code>TEMP</code> environment variable.</li>
<li>The directory named by the <code>TMP</code> environment variable.</li>
<li>A platform-specific location:
<ul>
<li>On <em>RiscOS</em>, the directory named by the <code>Wimp$ScrapDir</code> environment variable.</li>
<li>On <em>Windows</em>, the directories <code>C:\TEMP</code>, <code>C:\TMP</code>, <code>\TEMP</code>, and <code>\TMP</code>, in that order.</li>
<li>On all other platforms, the directories <code>/tmp</code>, <code>/var/tmp</code>, and <code>/usr/tmp</code>, in that order.</li>
</ul></li>
<li>As a last resort, the current working directory.</li>
</ol>
| 189 | 2009-05-11T12:25:18Z | [
"python",
"cross-platform",
"temporary-directory"
] |
Cross-platform way of getting temp directory in Python | 847,850 | <p>Is there a cross-platform way of getting the path to the <em><code>temp</code></em> directory in Python 2.6? </p>
<p>For example, under Linux that would be <code>/tmp</code>, while under XP <code>C:\Documents and settings\[user]\Application settings\Temp</code>.</p>
<p>Thanks!</p>
| 123 | 2009-05-11T12:21:46Z | 847,874 | <p>This should do what you want:</p>
<pre><code>print tempfile.gettempdir()
</code></pre>
<p>For me on my Windows box, I get:</p>
<pre><code>c:\temp
</code></pre>
<p>and on my Linux box I get:</p>
<pre><code>/tmp
</code></pre>
| 35 | 2009-05-11T12:27:30Z | [
"python",
"cross-platform",
"temporary-directory"
] |
Cross-platform way of getting temp directory in Python | 847,850 | <p>Is there a cross-platform way of getting the path to the <em><code>temp</code></em> directory in Python 2.6? </p>
<p>For example, under Linux that would be <code>/tmp</code>, while under XP <code>C:\Documents and settings\[user]\Application settings\Temp</code>.</p>
<p>Thanks!</p>
| 123 | 2009-05-11T12:21:46Z | 37,147,950 | <p>Taking the important bit from @nosklo's <a href="http://stackoverflow.com/a/847866/623735">answer</a> and adding a semi-private sandbox dir:</p>
<pre><code>import os
from tempfile import gettempdir
tmp = os.path.join(gettempdir(), '.{}'.format(hash(os.times())))
os.makedirs(tmp)
</code></pre>
<p>That way you can easily clean up after yourself when you are done (for privacy, resources, security, whatever) with:</p>
<pre><code>from shutil import rmtree
rmtree(tmp, ignore_errors=True)
</code></pre>
<p>This is similar to what applications like Google Chrome and Linux <code>systemd</code> do. They just use a shorter hex hash and an app-specific prefix to "advertise" their presence.</p>
| 0 | 2016-05-10T20:04:20Z | [
"python",
"cross-platform",
"temporary-directory"
] |
How to write a vb.net code to compile C/C++ programs? | 847,860 | <p>I'm trying to make a vb.net application that has got 2 textboxes, 7 radio buttons and 2 buttons(one named compile and the other 'run'). How can I load the content of a C/C++(or any programming language) file into the 1st textbox and on clicking the compile button, i should be able to show the errors or the C/C++ program in the 2nd textbox. On clicking Run, I should be able to show the output in the 2nd textbox. In short, I want to use the 2nd textbox as a terminal/console. The radio buttons are 4 selecting the language C or C++ or python or C# or java or perl or vb.
Are the compilers of all these languages present in .net? If so how can I call them?</p>
| 1 | 2009-05-11T12:24:35Z | 847,878 | <p>Look at the <code>System.IO</code> namespace for clues as to how you go about loading the contents of a file into a text box. In particular, the <code>File</code> class.</p>
<p><a href="http://msdn.microsoft.com/en-us/library/system.io.file.aspx" rel="nofollow">System.IO.File Class</a></p>
<p>Look at the <code>System.Diagnostics</code> namespace for clues as to how to go about launching a process and capturing the output. In particular, the <code>Process</code> class.</p>
<p><a href="http://msdn.microsoft.com/en-us/library/system.diagnostics.process.aspx" rel="nofollow">System.Diagnostics.Process Class</a></p>
<p>This SO page...</p>
<p><a href="http://stackoverflow.com/questions/186822/capturing-the-console-output-in-net-c">Capturing the Console Output in .NET (C#)</a></p>
<p>... will give you some more info around capturing console output.</p>
| 2 | 2009-05-11T12:29:40Z | [
"c#",
"c++",
"python",
"c",
"vb.net"
] |
How to write a vb.net code to compile C/C++ programs? | 847,860 | <p>I'm trying to make a vb.net application that has got 2 textboxes, 7 radio buttons and 2 buttons(one named compile and the other 'run'). How can I load the content of a C/C++(or any programming language) file into the 1st textbox and on clicking the compile button, i should be able to show the errors or the C/C++ program in the 2nd textbox. On clicking Run, I should be able to show the output in the 2nd textbox. In short, I want to use the 2nd textbox as a terminal/console. The radio buttons are 4 selecting the language C or C++ or python or C# or java or perl or vb.
Are the compilers of all these languages present in .net? If so how can I call them?</p>
| 1 | 2009-05-11T12:24:35Z | 847,883 | <p>Compiling can be done by calling cl.exe which comes with Visual Studio. Of course you could also use GCC instead.</p>
| 1 | 2009-05-11T12:31:04Z | [
"c#",
"c++",
"python",
"c",
"vb.net"
] |
How do I upload pickled data to django FileField? | 847,904 | <p>I would like to store large dataset generated in Python in a Django model. My idea was to pickle the data to a string and upload it to FileField of my model. My django model is:</p>
<pre><code>#models.py
from django.db import models
class Data(models.Model):
label = models.CharField(max_length=30)
file = models.FileField(upload_to="data")
</code></pre>
<p>In my Python program I would like to do the following:</p>
<pre><code>import random, pickle
data_entry = Data(label="somedata")
somedata = [random.random() for i in range(10000)]
# Next line does NOT work
#data_entry.file.save(filename, pickle.dumps(somedata))
</code></pre>
<p>How should I modify the last line to store <code>somedata</code> in <code>file</code> preserving the paths defined with <code>upload_to</code> parameter?</p>
| 4 | 2009-05-11T12:36:38Z | 847,913 | <p>Might you not be better off storing your data in a text field? It's not a file upload, after all.</p>
| 0 | 2009-05-11T12:40:01Z | [
"python",
"django",
"file",
"upload",
"pickle"
] |
How do I upload pickled data to django FileField? | 847,904 | <p>I would like to store large dataset generated in Python in a Django model. My idea was to pickle the data to a string and upload it to FileField of my model. My django model is:</p>
<pre><code>#models.py
from django.db import models
class Data(models.Model):
label = models.CharField(max_length=30)
file = models.FileField(upload_to="data")
</code></pre>
<p>In my Python program I would like to do the following:</p>
<pre><code>import random, pickle
data_entry = Data(label="somedata")
somedata = [random.random() for i in range(10000)]
# Next line does NOT work
#data_entry.file.save(filename, pickle.dumps(somedata))
</code></pre>
<p>How should I modify the last line to store <code>somedata</code> in <code>file</code> preserving the paths defined with <code>upload_to</code> parameter?</p>
| 4 | 2009-05-11T12:36:38Z | 848,176 | <p>In you database the <em>file</em> attribute is just a path to the file. So, since you are not doing an actual upload you need to store the file on the disk and then save the path in database.</p>
<pre><code>f = open(filename, 'w')
pickle.dump(somedata, f)
f.close()
data_entry.file=filename
data_entry.save()
</code></pre>
| 1 | 2009-05-11T13:46:38Z | [
"python",
"django",
"file",
"upload",
"pickle"
] |
How do I upload pickled data to django FileField? | 847,904 | <p>I would like to store large dataset generated in Python in a Django model. My idea was to pickle the data to a string and upload it to FileField of my model. My django model is:</p>
<pre><code>#models.py
from django.db import models
class Data(models.Model):
label = models.CharField(max_length=30)
file = models.FileField(upload_to="data")
</code></pre>
<p>In my Python program I would like to do the following:</p>
<pre><code>import random, pickle
data_entry = Data(label="somedata")
somedata = [random.random() for i in range(10000)]
# Next line does NOT work
#data_entry.file.save(filename, pickle.dumps(somedata))
</code></pre>
<p>How should I modify the last line to store <code>somedata</code> in <code>file</code> preserving the paths defined with <code>upload_to</code> parameter?</p>
| 4 | 2009-05-11T12:36:38Z | 848,606 | <p>I've never done this, but based on reading a bit of the relevant code, I'd start by looking into creating an instance of django.core.files.base.ContentFile and assigning that as the value of the field.</p>
| 0 | 2009-05-11T15:21:23Z | [
"python",
"django",
"file",
"upload",
"pickle"
] |
How do I upload pickled data to django FileField? | 847,904 | <p>I would like to store large dataset generated in Python in a Django model. My idea was to pickle the data to a string and upload it to FileField of my model. My django model is:</p>
<pre><code>#models.py
from django.db import models
class Data(models.Model):
label = models.CharField(max_length=30)
file = models.FileField(upload_to="data")
</code></pre>
<p>In my Python program I would like to do the following:</p>
<pre><code>import random, pickle
data_entry = Data(label="somedata")
somedata = [random.random() for i in range(10000)]
# Next line does NOT work
#data_entry.file.save(filename, pickle.dumps(somedata))
</code></pre>
<p>How should I modify the last line to store <code>somedata</code> in <code>file</code> preserving the paths defined with <code>upload_to</code> parameter?</p>
| 4 | 2009-05-11T12:36:38Z | 848,737 | <p>Based on the answers to the questions I came up with the following solution:</p>
<pre><code>from django.core.files.base import ContentFile
import pickle
content = pickle.dumps(somedata)
fid = ContentFile(content)
data_entry.file.save(filename, fid)
fid.close()
</code></pre>
<p>All of it is done on the server side and and users are NOT allowed to upload pickles. I tested it and it works all fine, but I am open to any suggestions.</p>
| 8 | 2009-05-11T15:48:04Z | [
"python",
"django",
"file",
"upload",
"pickle"
] |
How do I upload pickled data to django FileField? | 847,904 | <p>I would like to store large dataset generated in Python in a Django model. My idea was to pickle the data to a string and upload it to FileField of my model. My django model is:</p>
<pre><code>#models.py
from django.db import models
class Data(models.Model):
label = models.CharField(max_length=30)
file = models.FileField(upload_to="data")
</code></pre>
<p>In my Python program I would like to do the following:</p>
<pre><code>import random, pickle
data_entry = Data(label="somedata")
somedata = [random.random() for i in range(10000)]
# Next line does NOT work
#data_entry.file.save(filename, pickle.dumps(somedata))
</code></pre>
<p>How should I modify the last line to store <code>somedata</code> in <code>file</code> preserving the paths defined with <code>upload_to</code> parameter?</p>
| 4 | 2009-05-11T12:36:38Z | 1,097,239 | <p><strong>NOTE: <em>See other answers and comments below</em></strong> - old info and broken links removed (can't delete a once-accepted answer).</p>
<p>Marty Alchin has a section on this in chapter 3 of Pro Django, <a href="http://ericholscher.com/blog/2009/jan/21/review-pro-django-marty-alchin/" rel="nofollow">review here</a>.</p>
| -3 | 2009-07-08T10:21:40Z | [
"python",
"django",
"file",
"upload",
"pickle"
] |
Measure Path Length in Blender Script? | 848,499 | <p>In Blender (v2.48), how can I determine the length of a path (in Blender units) from a Python script?</p>
<p>The value is available from the GUI: With the path selected, the Editing panel contains a <em>PrintLen</em> button. The length appears to the right when the button is pressed.</p>
<p>How can I obtain this value programmatically from a Python script running in Blender?</p>
<p>Note: I'm not interested in the <em>PathLen</em> value which is in frames, not Blender units.</p>
| 0 | 2009-05-11T14:53:59Z | 953,202 | <p>The best idea I've found is to create a mesh from the path and sum the length of the segments (edges).</p>
<pre><code>import Blender
def get_length(path):
"""
Return the length (in Blender distance units) of the path.
"""
mesh = Blender.Mesh.New()
mesh.getFromObject(path)
return sum(edge.length for edge in mesh.edges)
</code></pre>
| 1 | 2009-06-04T21:25:10Z | [
"python",
"blender"
] |
Python M2Crypto EC Support | 848,508 | <p>M2Crypto provides EC support for ECDSA/ECDH. I have installed OpenSSL 0.9.8i which contains support for EC. However when I run "from M2Crypto import EC,BIO" I get error saying EC_init() failed. So I added debug to print m2.OPENSSL_VERSION_TEXT value. It gets printed as "OpenSSL 0.9.7 19 Feb 2003". This version of OpenSSL doesnot support EC. </p>
<p>I tried "python setup.py build build_ext --openssl="new_path where OpenSSL 0.9.8i is installed". Though M2Crypto is built again "Python setup.py install" , I still see that it points to "Old version of OpenSSL". </p>
<p>Any Pointers on how to successfully get M2Crypto to use 0.9.8i will be useful. </p>
| 2 | 2009-05-11T14:55:46Z | 848,795 | <p>Possibly its looking up shared libs libssl.so and libcrypto.so and finding the old ones in /usr/lib if you add the new_path to the top of /etc/ld.so.conf so it gets searched first it would work. But this might break other OpenSSL applications expecting old OpenSSL.</p>
| 0 | 2009-05-11T16:03:21Z | [
"python",
"m2crypto"
] |
Python M2Crypto EC Support | 848,508 | <p>M2Crypto provides EC support for ECDSA/ECDH. I have installed OpenSSL 0.9.8i which contains support for EC. However when I run "from M2Crypto import EC,BIO" I get error saying EC_init() failed. So I added debug to print m2.OPENSSL_VERSION_TEXT value. It gets printed as "OpenSSL 0.9.7 19 Feb 2003". This version of OpenSSL doesnot support EC. </p>
<p>I tried "python setup.py build build_ext --openssl="new_path where OpenSSL 0.9.8i is installed". Though M2Crypto is built again "Python setup.py install" , I still see that it points to "Old version of OpenSSL". </p>
<p>Any Pointers on how to successfully get M2Crypto to use 0.9.8i will be useful. </p>
| 2 | 2009-05-11T14:55:46Z | 1,192,236 | <p>Some Linux distros, for example Fedora and Redhat, disable EC due to patent concerns.</p>
<p>If you build OpenSSL yourself, there are a few options you may need to specify for build_ext in addition to --openssl: --library-dirs and --include-dirs. See for example the m2crypto <a href="http://svn.osafoundation.org/chandler/trunk/external/m2crypto/Makefile" rel="nofollow">Makefile</a> in Chandler. Also the M2Crypto <a href="http://chandlerproject.org/Projects/MeTooCrypto#Code" rel="nofollow">FAQ</a> has an answer for this.</p>
| 2 | 2009-07-28T06:33:19Z | [
"python",
"m2crypto"
] |
Python M2Crypto EC Support | 848,508 | <p>M2Crypto provides EC support for ECDSA/ECDH. I have installed OpenSSL 0.9.8i which contains support for EC. However when I run "from M2Crypto import EC,BIO" I get error saying EC_init() failed. So I added debug to print m2.OPENSSL_VERSION_TEXT value. It gets printed as "OpenSSL 0.9.7 19 Feb 2003". This version of OpenSSL doesnot support EC. </p>
<p>I tried "python setup.py build build_ext --openssl="new_path where OpenSSL 0.9.8i is installed". Though M2Crypto is built again "Python setup.py install" , I still see that it points to "Old version of OpenSSL". </p>
<p>Any Pointers on how to successfully get M2Crypto to use 0.9.8i will be useful. </p>
| 2 | 2009-05-11T14:55:46Z | 39,173,448 | <p>Please file a problem report at <a href="https://gitlab.com/m2crypto/m2crypto/issues/new" rel="nofollow">https://gitlab.com/m2crypto/m2crypto/issues/new</a> and your OS, version of Python, locations and versions of all OpenSSL libraries on your system, version of your compiler, and please attach <strong>complete</strong> stdout/stderr of the <code>python setup.py clean build install</code> command. Thank you.</p>
| 0 | 2016-08-26T19:25:56Z | [
"python",
"m2crypto"
] |
Writing/parsing a fixed width file using Python | 848,537 | <p>I'm a newbie to Python and I'm looking at using it to write some hairy EDI stuff that our supplier requires.</p>
<p>Basically they need an 80-character fixed width text file, with certain "chunks" of the field with data and others left blank. I have the documentation so I know what the length of each "chunk" is. The response that I get back is easier to parse since it will already have data and I can use Python's "slices" to extract what I need, but I can't assign to a slice - I tried that already because it sounded like a good solution, and it didn't work since Python strings are immutable :)</p>
<p>Like I said I'm really a newbie to Python but I'm excited about learning it :) How would I go about doing this? Ideally I'd want to be able to say that range 10-20 is equal to "Foo" and have it be the string "Foo" with 7 additional whitespace characters (assuming said field has a length of 10) and have that be a part of the larger 80-character field, but I'm not sure how to do what I'm thinking. </p>
| 11 | 2009-05-11T15:01:36Z | 848,607 | <p>It's a little difficult to parse your question, but I'm gathering that you are receiving a file or file-like-object, reading it, and replacing some of the values with some business logic results. Is this correct?</p>
<p>The simplest way to overcome string immutability is to write a new string:</p>
<pre><code># Won't work:
test_string[3:6] = "foo"
# Will work:
test_string = test_string[:3] + "foo" + test_string[6:]
</code></pre>
<p>Having said that, it sounds like it's important to you that you do something with this string, but I'm not sure exactly what that is. Are you writing it back to an output file, trying to edit a file in place, or something else? I bring this up because the act of creating a new string (which happens to have the same variable name as the old string) should emphasize the necessity of performing an explicit write operation after the transformation.</p>
| 0 | 2009-05-11T15:21:24Z | [
"python",
"parsing",
"edi"
] |
Writing/parsing a fixed width file using Python | 848,537 | <p>I'm a newbie to Python and I'm looking at using it to write some hairy EDI stuff that our supplier requires.</p>
<p>Basically they need an 80-character fixed width text file, with certain "chunks" of the field with data and others left blank. I have the documentation so I know what the length of each "chunk" is. The response that I get back is easier to parse since it will already have data and I can use Python's "slices" to extract what I need, but I can't assign to a slice - I tried that already because it sounded like a good solution, and it didn't work since Python strings are immutable :)</p>
<p>Like I said I'm really a newbie to Python but I'm excited about learning it :) How would I go about doing this? Ideally I'd want to be able to say that range 10-20 is equal to "Foo" and have it be the string "Foo" with 7 additional whitespace characters (assuming said field has a length of 10) and have that be a part of the larger 80-character field, but I'm not sure how to do what I'm thinking. </p>
| 11 | 2009-05-11T15:01:36Z | 848,661 | <p>You don't need to assign to slices, just build the string using <a href="http://docs.python.org/library/stdtypes.html#string-formatting-operations"><code>% formatting</code></a>.</p>
<p>An example with a fixed format for 3 data items:</p>
<pre><code>>>> fmt="%4s%10s%10s"
>>> fmt % (1,"ONE",2)
' 1 ONE 2'
>>>
</code></pre>
<p>Same thing, field width supplied with the data:</p>
<pre><code>>>> fmt2 = "%*s%*s%*s"
>>> fmt2 % (4,1, 10,"ONE", 10,2)
' 1 ONE 2'
>>>
</code></pre>
<p>Separating data and field widths, and using <code>zip()</code> and <code>str.join()</code> tricks:</p>
<pre><code>>>> widths=(4,10,10)
>>> items=(1,"ONE",2)
>>> "".join("%*s" % i for i in zip(widths, items))
' 1 ONE 2'
>>>
</code></pre>
| 15 | 2009-05-11T15:32:37Z | [
"python",
"parsing",
"edi"
] |
Writing/parsing a fixed width file using Python | 848,537 | <p>I'm a newbie to Python and I'm looking at using it to write some hairy EDI stuff that our supplier requires.</p>
<p>Basically they need an 80-character fixed width text file, with certain "chunks" of the field with data and others left blank. I have the documentation so I know what the length of each "chunk" is. The response that I get back is easier to parse since it will already have data and I can use Python's "slices" to extract what I need, but I can't assign to a slice - I tried that already because it sounded like a good solution, and it didn't work since Python strings are immutable :)</p>
<p>Like I said I'm really a newbie to Python but I'm excited about learning it :) How would I go about doing this? Ideally I'd want to be able to say that range 10-20 is equal to "Foo" and have it be the string "Foo" with 7 additional whitespace characters (assuming said field has a length of 10) and have that be a part of the larger 80-character field, but I'm not sure how to do what I'm thinking. </p>
| 11 | 2009-05-11T15:01:36Z | 848,663 | <p>Hopefully I understand what you're looking for: some way to conveniently identify each part of the line by a simple variable, but output it padded to the correct width?</p>
<p>The snippet below may give you what you want</p>
<pre><code>class FixWidthFieldLine(object):
fields = (('foo', 10),
('bar', 30),
('ooga', 30),
('booga', 10))
def __init__(self):
self.foo = ''
self.bar = ''
self.ooga = ''
self.booga = ''
def __str__(self):
return ''.join([getattr(self, field_name).ljust(width)
for field_name, width in self.fields])
f = FixWidthFieldLine()
f.foo = 'hi'
f.bar = 'joe'
f.ooga = 'howya'
f.booga = 'doin?'
print f
</code></pre>
<p>This yields:</p>
<pre><code>hi joe howya doing
</code></pre>
<p>It works by storing a class-level variable, <code>fields</code> which records the order in which each field should appear in the output, together with the number of columns that field should have. There are correspondingly-named instance variables in the <code>__init__</code> that are set to an empty string initially.</p>
<p>The <code>__str__</code> method outputs these values as a string. It uses a list comprehension over the class-level <code>fields</code> attribute, looking up the instance value for each field by name, and then left-justifying it's output according to the columns. The resulting list of fields is then joined together by an empty string.</p>
<p>Note this doesn't parse input, though you could easily override the constructor to take a string and parse the columns according to the field and field widths in <code>fields</code>. It also doesn't check for instance values that are longer than their allotted width.</p>
| 6 | 2009-05-11T15:32:45Z | [
"python",
"parsing",
"edi"
] |
Writing/parsing a fixed width file using Python | 848,537 | <p>I'm a newbie to Python and I'm looking at using it to write some hairy EDI stuff that our supplier requires.</p>
<p>Basically they need an 80-character fixed width text file, with certain "chunks" of the field with data and others left blank. I have the documentation so I know what the length of each "chunk" is. The response that I get back is easier to parse since it will already have data and I can use Python's "slices" to extract what I need, but I can't assign to a slice - I tried that already because it sounded like a good solution, and it didn't work since Python strings are immutable :)</p>
<p>Like I said I'm really a newbie to Python but I'm excited about learning it :) How would I go about doing this? Ideally I'd want to be able to say that range 10-20 is equal to "Foo" and have it be the string "Foo" with 7 additional whitespace characters (assuming said field has a length of 10) and have that be a part of the larger 80-character field, but I'm not sure how to do what I'm thinking. </p>
| 11 | 2009-05-11T15:01:36Z | 848,668 | <p>You can convert the string to a list and do the slice manipulation.</p>
<pre><code>>>> text = list("some text")
>>> text[0:4] = list("fine")
>>> text
['f', 'i', 'n', 'e', ' ', 't', 'e', 'x', 't']
>>> text[0:4] = list("all")
>>> text
['a', 'l', 'l', ' ', 't', 'e', 'x', 't']
>>> import string
>>> string.join(text, "")
'all text'
</code></pre>
| 0 | 2009-05-11T15:33:43Z | [
"python",
"parsing",
"edi"
] |
Writing/parsing a fixed width file using Python | 848,537 | <p>I'm a newbie to Python and I'm looking at using it to write some hairy EDI stuff that our supplier requires.</p>
<p>Basically they need an 80-character fixed width text file, with certain "chunks" of the field with data and others left blank. I have the documentation so I know what the length of each "chunk" is. The response that I get back is easier to parse since it will already have data and I can use Python's "slices" to extract what I need, but I can't assign to a slice - I tried that already because it sounded like a good solution, and it didn't work since Python strings are immutable :)</p>
<p>Like I said I'm really a newbie to Python but I'm excited about learning it :) How would I go about doing this? Ideally I'd want to be able to say that range 10-20 is equal to "Foo" and have it be the string "Foo" with 7 additional whitespace characters (assuming said field has a length of 10) and have that be a part of the larger 80-character field, but I'm not sure how to do what I'm thinking. </p>
| 11 | 2009-05-11T15:01:36Z | 848,672 | <p>It is easy to write function to "modify" string.</p>
<pre><code>def change(string, start, end, what):
length = end - start
if len(what)<length: what = what + " "*(length-len(what))
return string[0:start]+what[0:length]+string[end:]
</code></pre>
<p>Usage:</p>
<pre><code>test_string = 'This is test string'
print test_string[5:7]
# is
test_string = change(test_string, 5, 7, 'IS')
# This IS test string
test_string = change(test_string, 8, 12, 'X')
# This IS X string
test_string = change(test_string, 8, 12, 'XXXXXXXXXXXX')
# This IS XXXX string
</code></pre>
| 0 | 2009-05-11T15:34:17Z | [
"python",
"parsing",
"edi"
] |
Writing/parsing a fixed width file using Python | 848,537 | <p>I'm a newbie to Python and I'm looking at using it to write some hairy EDI stuff that our supplier requires.</p>
<p>Basically they need an 80-character fixed width text file, with certain "chunks" of the field with data and others left blank. I have the documentation so I know what the length of each "chunk" is. The response that I get back is easier to parse since it will already have data and I can use Python's "slices" to extract what I need, but I can't assign to a slice - I tried that already because it sounded like a good solution, and it didn't work since Python strings are immutable :)</p>
<p>Like I said I'm really a newbie to Python but I'm excited about learning it :) How would I go about doing this? Ideally I'd want to be able to say that range 10-20 is equal to "Foo" and have it be the string "Foo" with 7 additional whitespace characters (assuming said field has a length of 10) and have that be a part of the larger 80-character field, but I'm not sure how to do what I'm thinking. </p>
| 11 | 2009-05-11T15:01:36Z | 848,698 | <p>You can use <a href="http://docs.python.org/library/string.html#string.ljust">justify</a> functions to left-justify, right-justify and center a string in a field of given width.</p>
<pre><code>'hi'.ljust(10) -> 'hi '
</code></pre>
| 7 | 2009-05-11T15:37:43Z | [
"python",
"parsing",
"edi"
] |
Writing/parsing a fixed width file using Python | 848,537 | <p>I'm a newbie to Python and I'm looking at using it to write some hairy EDI stuff that our supplier requires.</p>
<p>Basically they need an 80-character fixed width text file, with certain "chunks" of the field with data and others left blank. I have the documentation so I know what the length of each "chunk" is. The response that I get back is easier to parse since it will already have data and I can use Python's "slices" to extract what I need, but I can't assign to a slice - I tried that already because it sounded like a good solution, and it didn't work since Python strings are immutable :)</p>
<p>Like I said I'm really a newbie to Python but I'm excited about learning it :) How would I go about doing this? Ideally I'd want to be able to say that range 10-20 is equal to "Foo" and have it be the string "Foo" with 7 additional whitespace characters (assuming said field has a length of 10) and have that be a part of the larger 80-character field, but I'm not sure how to do what I'm thinking. </p>
| 11 | 2009-05-11T15:01:36Z | 23,917,443 | <p>I used Jarret Hardie's example and modified it slightly. This allows for selection of type of text alignment(left, right or centered.)</p>
<pre><code>class FixedWidthFieldLine(object):
def __init__(self, fields, justify = 'L'):
""" Returns line from list containing tuples of field values and lengths. Accepts
justification parameter.
FixedWidthFieldLine(fields[, justify])
fields = [(value, fieldLenght)[, ...]]
"""
self.fields = fields
if (justify in ('L','C','R')):
self.justify = justify
else:
self.justify = 'L'
def __str__(self):
if(self.justify == 'L'):
return ''.join([field[0].ljust(field[1]) for field in self.fields])
elif(self.justify == 'R'):
return ''.join([field[0].rjust(field[1]) for field in self.fields])
elif(self.justify == 'C'):
return ''.join([field[0].center(field[1]) for field in self.fields])
fieldTest = [('Alex', 10),
('Programmer', 20),
('Salem, OR', 15)]
f = FixedWidthFieldLine(fieldTest)
print f
f = FixedWidthFieldLine(fieldTest,'R')
print f
</code></pre>
<p>Returns:</p>
<pre><code>Alex Programmer Salem, OR
Alex Programmer Salem, OR
</code></pre>
| 0 | 2014-05-28T16:47:25Z | [
"python",
"parsing",
"edi"
] |
Javascript graphing library to draw a region | 848,604 | <p>As a keen windsurfer, I'm interested in how windy the next few weeks are going to be. To that end, I've been writing a little app to scrape a popular weather site (personal use only - not relaying the information or anything) and collate the data into a single graph so that I can easily see when's going to be worth heading out.</p>
<p>I have the back end working but need a way to display the data. My scraper currently gives me two series of data which tell me how strong the general wind is and how strong it's likely to gust to. What I'd like to do next is display those two data sets as a pair of lines in a graph and shade the region between them.</p>
<p>I was considering using something like <a href="http://code.google.com/p/flot/" rel="nofollow">the flot library</a> to display the data. The only problem is that I can't see a way to shade an area between two lines?</p>
<p>If anyone has suggestions of how to do this in flot or other libraries or graphing techniques (I have DJango on my server so anything pythonic or javascripty should be fine), I'd be interested to hear them. Ideally this will be a javascript solution to avoid having to serve up images.</p>
| 2 | 2009-05-11T15:20:58Z | 848,659 | <p>Take a look at the <a href="http://code.google.com/apis/visualization/documentation/gallery/areachart.html" rel="nofollow">Google chart API's</a>. They make this sort of thing pretty easy. Without some example code, I would have a hard time giving you an example, but Google has nice one on the docs.</p>
| 1 | 2009-05-11T15:32:25Z | [
"javascript",
"python",
"django",
"graph",
"screen-scraping"
] |
Javascript graphing library to draw a region | 848,604 | <p>As a keen windsurfer, I'm interested in how windy the next few weeks are going to be. To that end, I've been writing a little app to scrape a popular weather site (personal use only - not relaying the information or anything) and collate the data into a single graph so that I can easily see when's going to be worth heading out.</p>
<p>I have the back end working but need a way to display the data. My scraper currently gives me two series of data which tell me how strong the general wind is and how strong it's likely to gust to. What I'd like to do next is display those two data sets as a pair of lines in a graph and shade the region between them.</p>
<p>I was considering using something like <a href="http://code.google.com/p/flot/" rel="nofollow">the flot library</a> to display the data. The only problem is that I can't see a way to shade an area between two lines?</p>
<p>If anyone has suggestions of how to do this in flot or other libraries or graphing techniques (I have DJango on my server so anything pythonic or javascripty should be fine), I'd be interested to hear them. Ideally this will be a javascript solution to avoid having to serve up images.</p>
| 2 | 2009-05-11T15:20:58Z | 848,870 | <p>You should check out Dojo. It looks like it'd be pretty easy for you to do, just plot the bottom line with the same fill color as the background. That should get you the effect you're going for.</p>
<p><a href="http://dojocampus.org/explorer/#Dojox_Charting_2D" rel="nofollow">http://dojocampus.org/explorer/#Dojox_Charting_2D</a></p>
| 1 | 2009-05-11T16:19:07Z | [
"javascript",
"python",
"django",
"graph",
"screen-scraping"
] |
Javascript graphing library to draw a region | 848,604 | <p>As a keen windsurfer, I'm interested in how windy the next few weeks are going to be. To that end, I've been writing a little app to scrape a popular weather site (personal use only - not relaying the information or anything) and collate the data into a single graph so that I can easily see when's going to be worth heading out.</p>
<p>I have the back end working but need a way to display the data. My scraper currently gives me two series of data which tell me how strong the general wind is and how strong it's likely to gust to. What I'd like to do next is display those two data sets as a pair of lines in a graph and shade the region between them.</p>
<p>I was considering using something like <a href="http://code.google.com/p/flot/" rel="nofollow">the flot library</a> to display the data. The only problem is that I can't see a way to shade an area between two lines?</p>
<p>If anyone has suggestions of how to do this in flot or other libraries or graphing techniques (I have DJango on my server so anything pythonic or javascripty should be fine), I'd be interested to hear them. Ideally this will be a javascript solution to avoid having to serve up images.</p>
| 2 | 2009-05-11T15:20:58Z | 849,098 | <p>I'd use open flash chart, you just have to create a JSON with the data and then you've to all the flashy coolness in your page....</p>
<p><a href="http://teethgrinder.co.uk/open-flash-chart-2/" rel="nofollow">http://teethgrinder.co.uk/open-flash-chart-2/</a></p>
| 0 | 2009-05-11T17:19:15Z | [
"javascript",
"python",
"django",
"graph",
"screen-scraping"
] |
Is it possible to speed-up python IO? | 849,058 | <p>Consider this python program:</p>
<pre><code>import sys
lc = 0
for line in open(sys.argv[1]):
lc = lc + 1
print lc, sys.argv[1]
</code></pre>
<p>Running it on my 6GB text file, it completes in ~ 2minutes.</p>
<p>Question: <strong>is it possible to go faster?</strong></p>
<p>Note that the same time is required by:</p>
<pre><code>wc -l myfile.txt
</code></pre>
<p>so, I suspect the anwer to my quesion is just a plain "no".</p>
<p>Note also that my real program is doing something more interesting than just counting the lines, so please give a generic answer, <strong>not</strong> line-counting-tricks (like keeping a line count metadata in the file)</p>
<p>PS: I tagged "linux" this question, because I'm interested only in linux-specific answers. Feel free to give OS-agnostic, or even other-OS answers, if you have them.</p>
<p>See also the <a href="http://stackoverflow.com/questions/860893/is-python-automagically-parallelizing-io-and-cpu-or-memory-bound-sections">follow-up question</a></p>
| 8 | 2009-05-11T17:06:46Z | 849,113 | <p><strong>plain "no".</strong></p>
<p>You've pretty much reached maximum disk speed.</p>
<p>I mean, you could <a href="http://docs.python.org/library/mmap.html" rel="nofollow">mmap</a> the file, or read it in binary chunks, and use <code>.count('\n')</code> or something. But that is unlikely to give major improvements.</p>
| 5 | 2009-05-11T17:22:22Z | [
"python",
"linux",
"performance",
"text-files"
] |
Is it possible to speed-up python IO? | 849,058 | <p>Consider this python program:</p>
<pre><code>import sys
lc = 0
for line in open(sys.argv[1]):
lc = lc + 1
print lc, sys.argv[1]
</code></pre>
<p>Running it on my 6GB text file, it completes in ~ 2minutes.</p>
<p>Question: <strong>is it possible to go faster?</strong></p>
<p>Note that the same time is required by:</p>
<pre><code>wc -l myfile.txt
</code></pre>
<p>so, I suspect the anwer to my quesion is just a plain "no".</p>
<p>Note also that my real program is doing something more interesting than just counting the lines, so please give a generic answer, <strong>not</strong> line-counting-tricks (like keeping a line count metadata in the file)</p>
<p>PS: I tagged "linux" this question, because I'm interested only in linux-specific answers. Feel free to give OS-agnostic, or even other-OS answers, if you have them.</p>
<p>See also the <a href="http://stackoverflow.com/questions/860893/is-python-automagically-parallelizing-io-and-cpu-or-memory-bound-sections">follow-up question</a></p>
| 8 | 2009-05-11T17:06:46Z | 849,146 | <p>If you assume that a disk can read 60MB/s you'd need 6000 / 60 = 100 seconds, which is 1 minute 40 seconds. I don't think that you can get any faster because the disk is the bottleneck.</p>
| 4 | 2009-05-11T17:30:53Z | [
"python",
"linux",
"performance",
"text-files"
] |
Is it possible to speed-up python IO? | 849,058 | <p>Consider this python program:</p>
<pre><code>import sys
lc = 0
for line in open(sys.argv[1]):
lc = lc + 1
print lc, sys.argv[1]
</code></pre>
<p>Running it on my 6GB text file, it completes in ~ 2minutes.</p>
<p>Question: <strong>is it possible to go faster?</strong></p>
<p>Note that the same time is required by:</p>
<pre><code>wc -l myfile.txt
</code></pre>
<p>so, I suspect the anwer to my quesion is just a plain "no".</p>
<p>Note also that my real program is doing something more interesting than just counting the lines, so please give a generic answer, <strong>not</strong> line-counting-tricks (like keeping a line count metadata in the file)</p>
<p>PS: I tagged "linux" this question, because I'm interested only in linux-specific answers. Feel free to give OS-agnostic, or even other-OS answers, if you have them.</p>
<p>See also the <a href="http://stackoverflow.com/questions/860893/is-python-automagically-parallelizing-io-and-cpu-or-memory-bound-sections">follow-up question</a></p>
| 8 | 2009-05-11T17:06:46Z | 849,153 | <p>as others have said - "no"</p>
<p>Almost all of your time is spent waiting for IO. If this is something that you need to do more than once, <em>and</em> you have a machine with tons of ram, you could keep the file in memory. If your machine has 16GB of ram, you'll have 8GB available at /dev/shm to play with.</p>
<p>Another option:
If you have multiple machines, this problem is trivial to parallelize. Split the it among multiple machines, each of them count their newlines, and add the results.</p>
| 1 | 2009-05-11T17:33:33Z | [
"python",
"linux",
"performance",
"text-files"
] |
Is it possible to speed-up python IO? | 849,058 | <p>Consider this python program:</p>
<pre><code>import sys
lc = 0
for line in open(sys.argv[1]):
lc = lc + 1
print lc, sys.argv[1]
</code></pre>
<p>Running it on my 6GB text file, it completes in ~ 2minutes.</p>
<p>Question: <strong>is it possible to go faster?</strong></p>
<p>Note that the same time is required by:</p>
<pre><code>wc -l myfile.txt
</code></pre>
<p>so, I suspect the anwer to my quesion is just a plain "no".</p>
<p>Note also that my real program is doing something more interesting than just counting the lines, so please give a generic answer, <strong>not</strong> line-counting-tricks (like keeping a line count metadata in the file)</p>
<p>PS: I tagged "linux" this question, because I'm interested only in linux-specific answers. Feel free to give OS-agnostic, or even other-OS answers, if you have them.</p>
<p>See also the <a href="http://stackoverflow.com/questions/860893/is-python-automagically-parallelizing-io-and-cpu-or-memory-bound-sections">follow-up question</a></p>
| 8 | 2009-05-11T17:06:46Z | 849,510 | <p>You can't get any faster than the maximum disk read speed.</p>
<p>In order to reach the maximum disk speed you can use the following two tips:</p>
<ol>
<li>Read the file in with a big buffer. This can either be coded "manually" or simply by using io.BufferedReader ( available in python2.6+ ).</li>
<li>Do the newline counting in another thread, in parallel.</li>
</ol>
| 1 | 2009-05-11T18:53:41Z | [
"python",
"linux",
"performance",
"text-files"
] |
Is it possible to speed-up python IO? | 849,058 | <p>Consider this python program:</p>
<pre><code>import sys
lc = 0
for line in open(sys.argv[1]):
lc = lc + 1
print lc, sys.argv[1]
</code></pre>
<p>Running it on my 6GB text file, it completes in ~ 2minutes.</p>
<p>Question: <strong>is it possible to go faster?</strong></p>
<p>Note that the same time is required by:</p>
<pre><code>wc -l myfile.txt
</code></pre>
<p>so, I suspect the anwer to my quesion is just a plain "no".</p>
<p>Note also that my real program is doing something more interesting than just counting the lines, so please give a generic answer, <strong>not</strong> line-counting-tricks (like keeping a line count metadata in the file)</p>
<p>PS: I tagged "linux" this question, because I'm interested only in linux-specific answers. Feel free to give OS-agnostic, or even other-OS answers, if you have them.</p>
<p>See also the <a href="http://stackoverflow.com/questions/860893/is-python-automagically-parallelizing-io-and-cpu-or-memory-bound-sections">follow-up question</a></p>
| 8 | 2009-05-11T17:06:46Z | 849,521 | <p>Note that Python I/O is implemented in C, so there is not much luck speeding it up further.</p>
| 1 | 2009-05-11T18:55:30Z | [
"python",
"linux",
"performance",
"text-files"
] |
Is it possible to speed-up python IO? | 849,058 | <p>Consider this python program:</p>
<pre><code>import sys
lc = 0
for line in open(sys.argv[1]):
lc = lc + 1
print lc, sys.argv[1]
</code></pre>
<p>Running it on my 6GB text file, it completes in ~ 2minutes.</p>
<p>Question: <strong>is it possible to go faster?</strong></p>
<p>Note that the same time is required by:</p>
<pre><code>wc -l myfile.txt
</code></pre>
<p>so, I suspect the anwer to my quesion is just a plain "no".</p>
<p>Note also that my real program is doing something more interesting than just counting the lines, so please give a generic answer, <strong>not</strong> line-counting-tricks (like keeping a line count metadata in the file)</p>
<p>PS: I tagged "linux" this question, because I'm interested only in linux-specific answers. Feel free to give OS-agnostic, or even other-OS answers, if you have them.</p>
<p>See also the <a href="http://stackoverflow.com/questions/860893/is-python-automagically-parallelizing-io-and-cpu-or-memory-bound-sections">follow-up question</a></p>
| 8 | 2009-05-11T17:06:46Z | 849,645 | <p><strong>Throw hardware at the problem.</strong></p>
<p>As gs pointed out, your bottleneck is the hard disk transfer rate. So, no you can't use a better algorithm to improve your time, but you can buy a faster hard drive.</p>
<p><strong>Edit:</strong> Another good point by gs; you could also use a <a href="http://en.wikipedia.org/wiki/Redundant%5Farray%5Fof%5Findependent%5Fdisks" rel="nofollow">RAID</a> configuration to improve your speed. This can be done either with <a href="http://www.pcguide.com/ref/hdd/perf/raid/conf/ctrlHardware-c.html" rel="nofollow">hardware</a> or software (e.g. <a href="http://www.frozennorth.org/C2011481421/E20060221212020/index.html" rel="nofollow">OS X</a>, <a href="http://linux-raid.osdl.org/index.php/Linux%5FRaid" rel="nofollow">Linux</a>, <a href="http://www.techotopia.com/index.php/Creating%5Fand%5FManaging%5FWindows%5FServer%5F2008%5FStriped%5F%28RAID%5F0%29%5FVolumes" rel="nofollow">Windows Server</a>, etc).</p>
<p><hr /></p>
<p><strong>Governing Equation</strong></p>
<p><code>(Amount to transfer) / (transfer rate) = (time to transfer)</code></p>
<p><code>(6000 MB) / (60 MB/s) = 100 seconds</code></p>
<p><code>(6000 MB) / (125 MB/s) = 48 seconds</code></p>
<p><hr /></p>
<p><strong>Hardware Solutions</strong></p>
<p><a href="http://www.computerworld.com/action/article.do?command=viewArticleBasic&taxonomyName=storage&articleId=9129644&taxonomyId=19&intsrc=kc%5Ftop" rel="nofollow">The ioDrive Duo</a> is supposedly the fastest solution for a corporate setting, and "will be available in April 2009".</p>
<p>Or you could check out the WD Velociraptor hard drive (10,000 rpm).</p>
<p>Also, I hear the Seagate <a href="http://www.seagate.com/docs/pdf/datasheet/disc/ds%5Fcheetah%5F15k%5F5.pdf" rel="nofollow">Cheetah</a> is a good option (15,000 rpm with sustained 125MB/s transfer rate).</p>
| 11 | 2009-05-11T19:24:57Z | [
"python",
"linux",
"performance",
"text-files"
] |
Is it possible to speed-up python IO? | 849,058 | <p>Consider this python program:</p>
<pre><code>import sys
lc = 0
for line in open(sys.argv[1]):
lc = lc + 1
print lc, sys.argv[1]
</code></pre>
<p>Running it on my 6GB text file, it completes in ~ 2minutes.</p>
<p>Question: <strong>is it possible to go faster?</strong></p>
<p>Note that the same time is required by:</p>
<pre><code>wc -l myfile.txt
</code></pre>
<p>so, I suspect the anwer to my quesion is just a plain "no".</p>
<p>Note also that my real program is doing something more interesting than just counting the lines, so please give a generic answer, <strong>not</strong> line-counting-tricks (like keeping a line count metadata in the file)</p>
<p>PS: I tagged "linux" this question, because I'm interested only in linux-specific answers. Feel free to give OS-agnostic, or even other-OS answers, if you have them.</p>
<p>See also the <a href="http://stackoverflow.com/questions/860893/is-python-automagically-parallelizing-io-and-cpu-or-memory-bound-sections">follow-up question</a></p>
| 8 | 2009-05-11T17:06:46Z | 849,842 | <p>The trick is not to make electrons move faster (that's hard to do) but to get more work done per unit of time.</p>
<p>First, be sure your 6GB file read is I/O bound, not CPU bound.</p>
<p>If It's I/O bound, consider the "Fan-Out" design pattern.</p>
<ul>
<li><p>A parent process spawns a bunch of children.</p></li>
<li><p>The parent reads the 6Gb file, and deals rows out to the children by writing to their STDIN pipes. The 6GB read time will remain constant. The row dealing should involve as little parent processing as possible. Very simple filters or counts should be used.</p>
<p>A pipe is an in-memory channel for communication. It's a shared buffer with a reader and a writer.</p></li>
<li><p>Each child reads a row from STDIN, and does appropriate work. Each child should probably write a simple disk file with the final (summarized, reduce) results. Later, the results in those files can be consolidated.</p></li>
</ul>
| 6 | 2009-05-11T20:06:39Z | [
"python",
"linux",
"performance",
"text-files"
] |
Is it possible to speed-up python IO? | 849,058 | <p>Consider this python program:</p>
<pre><code>import sys
lc = 0
for line in open(sys.argv[1]):
lc = lc + 1
print lc, sys.argv[1]
</code></pre>
<p>Running it on my 6GB text file, it completes in ~ 2minutes.</p>
<p>Question: <strong>is it possible to go faster?</strong></p>
<p>Note that the same time is required by:</p>
<pre><code>wc -l myfile.txt
</code></pre>
<p>so, I suspect the anwer to my quesion is just a plain "no".</p>
<p>Note also that my real program is doing something more interesting than just counting the lines, so please give a generic answer, <strong>not</strong> line-counting-tricks (like keeping a line count metadata in the file)</p>
<p>PS: I tagged "linux" this question, because I'm interested only in linux-specific answers. Feel free to give OS-agnostic, or even other-OS answers, if you have them.</p>
<p>See also the <a href="http://stackoverflow.com/questions/860893/is-python-automagically-parallelizing-io-and-cpu-or-memory-bound-sections">follow-up question</a></p>
| 8 | 2009-05-11T17:06:46Z | 861,105 | <p>2 minutes sounds about right to read an entire 6gb file. Theres not really much you can do to the algorithm or the OS to speed things up. I think you have two options:</p>
<ol>
<li><p>Throw money at the problem and get better hardware. Probably the best option if this project is for your job.</p></li>
<li><p>Don't read the entire file. I don't know what your are trying to do with the data, so maybe you don't have any option but to read the whole thing. On the other hand if you are scanning the whole file for one particular thing, then maybe putting some metadata in there at the start would be helpful.</p></li>
</ol>
| 1 | 2009-05-14T00:54:28Z | [
"python",
"linux",
"performance",
"text-files"
] |
How to limit the maximum value of a numeric field in a Django model? | 849,142 | <p>Django has various numeric fields available for use in models, e.g. <a href="http://docs.djangoproject.com/en/dev/ref/models/fields/#decimalfield">DecimalField</a> and <a href="http://docs.djangoproject.com/en/dev/ref/models/fields/#positiveintegerfield">PositiveIntegerField</a>. Although the former can be restricted to the number of decimal places stored and the overall number of characters stored, is there any way to restrict it to storing <em>only</em> numbers within a certain range, e.g. 0.0-5.0 ?</p>
<p>Failing that, is there any way to restrict a PositiveIntegerField to only store, for instance, numbers up to 50?</p>
<p><em><strong>Update: now that Bug 6845 <a href="http://code.djangoproject.com/ticket/6845#comment:71">has been closed</a>, this StackOverflow question may be moot. - sampablokuper</em></strong></p>
| 87 | 2009-05-11T17:29:57Z | 849,177 | <p>There are two ways to do this. One is to use form validation to never let any number over 50 be entered by a user. <a href="http://docs.djangoproject.com/en/dev/ref/forms/validation/">Form validation docs</a>.</p>
<p>If there is no user involved in the process, or you're not using a form to enter data, then you'll have to override the model's <code>save</code> method to throw an exception or limit the data going into the field.</p>
| 9 | 2009-05-11T17:39:52Z | [
"python",
"django",
"django-models",
"numbers"
] |
How to limit the maximum value of a numeric field in a Django model? | 849,142 | <p>Django has various numeric fields available for use in models, e.g. <a href="http://docs.djangoproject.com/en/dev/ref/models/fields/#decimalfield">DecimalField</a> and <a href="http://docs.djangoproject.com/en/dev/ref/models/fields/#positiveintegerfield">PositiveIntegerField</a>. Although the former can be restricted to the number of decimal places stored and the overall number of characters stored, is there any way to restrict it to storing <em>only</em> numbers within a certain range, e.g. 0.0-5.0 ?</p>
<p>Failing that, is there any way to restrict a PositiveIntegerField to only store, for instance, numbers up to 50?</p>
<p><em><strong>Update: now that Bug 6845 <a href="http://code.djangoproject.com/ticket/6845#comment:71">has been closed</a>, this StackOverflow question may be moot. - sampablokuper</em></strong></p>
| 87 | 2009-05-11T17:29:57Z | 849,426 | <p>You could also create a custom model field type - see <a href="http://docs.djangoproject.com/en/dev/howto/custom-model-fields/#howto-custom-model-fields">http://docs.djangoproject.com/en/dev/howto/custom-model-fields/#howto-custom-model-fields</a></p>
<p>In this case, you could 'inherit' from the built-in IntegerField and override its validation logic.</p>
<p>The more I think about this, I realize how useful this would be for many Django apps. Perhaps a IntegerRangeField type could be submitted as a patch for the Django devs to consider adding to trunk.</p>
<p>This is working for me:</p>
<pre><code>from django.db import models
class IntegerRangeField(models.IntegerField):
def __init__(self, verbose_name=None, name=None, min_value=None, max_value=None, **kwargs):
self.min_value, self.max_value = min_value, max_value
models.IntegerField.__init__(self, verbose_name, name, **kwargs)
def formfield(self, **kwargs):
defaults = {'min_value': self.min_value, 'max_value':self.max_value}
defaults.update(kwargs)
return super(IntegerRangeField, self).formfield(**defaults)
</code></pre>
<p>Then in your model class, you would use it like this (field being the module where you put the above code):</p>
<pre><code>size = fields.IntegerRangeField(min_value=1, max_value=50)
</code></pre>
<p>OR for a range of negative and positive (like an oscillator range):</p>
<pre><code>size = fields.IntegerRangeField(min_value=-100, max_value=100)
</code></pre>
<p>What would be really cool is if it could be called with the range operator like this:</p>
<pre><code>size = fields.IntegerRangeField(range(1, 50))
</code></pre>
<p>But, that would require a lot more code since since you can specify a 'skip' parameter - range(1, 50, 2) - Interesting idea though...</p>
| 95 | 2009-05-11T18:31:21Z | [
"python",
"django",
"django-models",
"numbers"
] |
How to limit the maximum value of a numeric field in a Django model? | 849,142 | <p>Django has various numeric fields available for use in models, e.g. <a href="http://docs.djangoproject.com/en/dev/ref/models/fields/#decimalfield">DecimalField</a> and <a href="http://docs.djangoproject.com/en/dev/ref/models/fields/#positiveintegerfield">PositiveIntegerField</a>. Although the former can be restricted to the number of decimal places stored and the overall number of characters stored, is there any way to restrict it to storing <em>only</em> numbers within a certain range, e.g. 0.0-5.0 ?</p>
<p>Failing that, is there any way to restrict a PositiveIntegerField to only store, for instance, numbers up to 50?</p>
<p><em><strong>Update: now that Bug 6845 <a href="http://code.djangoproject.com/ticket/6845#comment:71">has been closed</a>, this StackOverflow question may be moot. - sampablokuper</em></strong></p>
| 87 | 2009-05-11T17:29:57Z | 4,047,378 | <p>I had this very same problem; here was my solution:</p>
<pre><code>SCORE_CHOICES = zip( range(1,n), range(1,n) )
score = models.IntegerField(choices=SCORE_CHOICES, blank=True)
</code></pre>
| 41 | 2010-10-28T21:38:25Z | [
"python",
"django",
"django-models",
"numbers"
] |
How to limit the maximum value of a numeric field in a Django model? | 849,142 | <p>Django has various numeric fields available for use in models, e.g. <a href="http://docs.djangoproject.com/en/dev/ref/models/fields/#decimalfield">DecimalField</a> and <a href="http://docs.djangoproject.com/en/dev/ref/models/fields/#positiveintegerfield">PositiveIntegerField</a>. Although the former can be restricted to the number of decimal places stored and the overall number of characters stored, is there any way to restrict it to storing <em>only</em> numbers within a certain range, e.g. 0.0-5.0 ?</p>
<p>Failing that, is there any way to restrict a PositiveIntegerField to only store, for instance, numbers up to 50?</p>
<p><em><strong>Update: now that Bug 6845 <a href="http://code.djangoproject.com/ticket/6845#comment:71">has been closed</a>, this StackOverflow question may be moot. - sampablokuper</em></strong></p>
| 87 | 2009-05-11T17:29:57Z | 12,026,867 | <p>You can use <a href="https://docs.djangoproject.com/en/dev/ref/validators/#built-in-validators">Django's built-in validators</a>â</p>
<pre><code>from django.db.models import IntegerField, Model
from django.core.validators import MaxValueValidator, MinValueValidator
class CoolModelBro(Model):
limited_integer_field = IntegerField(
default=1,
validators=[
MaxValueValidator(100),
MinValueValidator(1)
]
)
</code></pre>
<p><strong>Edit</strong>: Although these <a href="https://docs.djangoproject.com/en/dev/ref/validators/#how-validators-are-run">only work when you're using the model in a ModelForm</a>, not if you're using the model "on its own", sigh.</p>
| 144 | 2012-08-19T13:32:39Z | [
"python",
"django",
"django-models",
"numbers"
] |
How to limit the maximum value of a numeric field in a Django model? | 849,142 | <p>Django has various numeric fields available for use in models, e.g. <a href="http://docs.djangoproject.com/en/dev/ref/models/fields/#decimalfield">DecimalField</a> and <a href="http://docs.djangoproject.com/en/dev/ref/models/fields/#positiveintegerfield">PositiveIntegerField</a>. Although the former can be restricted to the number of decimal places stored and the overall number of characters stored, is there any way to restrict it to storing <em>only</em> numbers within a certain range, e.g. 0.0-5.0 ?</p>
<p>Failing that, is there any way to restrict a PositiveIntegerField to only store, for instance, numbers up to 50?</p>
<p><em><strong>Update: now that Bug 6845 <a href="http://code.djangoproject.com/ticket/6845#comment:71">has been closed</a>, this StackOverflow question may be moot. - sampablokuper</em></strong></p>
| 87 | 2009-05-11T17:29:57Z | 12,027,012 | <pre><code>from django.db import models
from django.core.validators import MinValueValidator, MaxValueValidator
size = models.IntegerField(validators=[MinValueValidator(0),
MaxValueValidator(5)])
</code></pre>
| 47 | 2012-08-19T13:54:25Z | [
"python",
"django",
"django-models",
"numbers"
] |
How to limit the maximum value of a numeric field in a Django model? | 849,142 | <p>Django has various numeric fields available for use in models, e.g. <a href="http://docs.djangoproject.com/en/dev/ref/models/fields/#decimalfield">DecimalField</a> and <a href="http://docs.djangoproject.com/en/dev/ref/models/fields/#positiveintegerfield">PositiveIntegerField</a>. Although the former can be restricted to the number of decimal places stored and the overall number of characters stored, is there any way to restrict it to storing <em>only</em> numbers within a certain range, e.g. 0.0-5.0 ?</p>
<p>Failing that, is there any way to restrict a PositiveIntegerField to only store, for instance, numbers up to 50?</p>
<p><em><strong>Update: now that Bug 6845 <a href="http://code.djangoproject.com/ticket/6845#comment:71">has been closed</a>, this StackOverflow question may be moot. - sampablokuper</em></strong></p>
| 87 | 2009-05-11T17:29:57Z | 25,900,058 | <p>Here is the best solution if you want some extra flexibility and don't want to change your model field. Just add this custom validator:</p>
<pre><code>#Imports
from django.core.exceptions import ValidationError
class validate_range_or_null(object):
compare = lambda self, a, b, c: a > c or a < b
clean = lambda self, x: x
message = ('Ensure this value is between %(limit_min)s and %(limit_max)s (it is %(show_value)s).')
code = 'limit_value'
def __init__(self, limit_min, limit_max):
self.limit_min = limit_min
self.limit_max = limit_max
def __call__(self, value):
cleaned = self.clean(value)
params = {'limit_min': self.limit_min, 'limit_max': self.limit_max, 'show_value': cleaned}
if value: # make it optional, remove it to make required, or make required on the model
if self.compare(cleaned, self.limit_min, self.limit_max):
raise ValidationError(self.message, code=self.code, params=params)
</code></pre>
<p>And it can be used as such:</p>
<pre><code>class YourModel(models.Model):
....
no_dependents = models.PositiveSmallIntegerField("How many dependants?", blank=True, null=True, default=0, validators=[validate_range_or_null(1,100)])
</code></pre>
<p>The two parameters are max and min, and it allows nulls. You can customize the validator if you like by getting rid of the marked if statement or change your field to be blank=False, null=False in the model. That will of course require a migration.</p>
<p>Note: I had to add the validator because Django does not validate the range on PositiveSmallIntegerField, instead it creates a smallint (in postgres) for this field and you get a DB error if the numeric specified is out of range.</p>
<p>Hope this helps :) More on <a href="https://docs.djangoproject.com/en/1.7/ref/validators/" rel="nofollow">Validators in Django</a>.</p>
<p>PS. I based my answer on BaseValidator in django.core.validators, but everything is different except for the code.</p>
| 0 | 2014-09-17T20:45:53Z | [
"python",
"django",
"django-models",
"numbers"
] |
Getting the name of document that used to launch the application bundle on OS X | 849,172 | <p>When writing an OS X Bundle application (.app), how can I get the name of the document that caused the application to be launched?</p>
<p>Say I've associated .abcd with MyApp, when I click on foo.abcd MyApp is launched.
How can I get the foo.abcd from inside MyApp? (Command line arguments only contain the process id).</p>
| 2 | 2009-05-11T17:39:09Z | 849,284 | <p>In general, these are handled through <em>Apple Events</em>. Specifically, your application will receive an <em>open document</em> event. How you would handle it depends on what type of application you are writing.</p>
<p>If you're writing a document-based app, this is easy: the document controller receives an <code>openDocumentWithContentsOfURL:display:error:</code> message (or <code>openDocumentWithContentsOfFile:display:</code> for pre-Tiger systems), and will <a href="http://developer.apple.com/documentation/Cocoa/Reference/ApplicationKit/Classes/NSDocumentController%5FClass/Reference/Reference.html#//apple%5Fref/occ/instm/NSDocumentController/openDocumentWithContentsOfURL:display:error:" rel="nofollow">handle this accordingly</a>.</p>
<p>For Cocoa apps that aren't document based, the application delegate will be sent an <code>application:openFiles:</code> message. If the delegate doesn't respond to that, it will try sending other messages until the delegate responds to one (<code>openTempFile:</code>, <code>openFiles:</code>, and <code>openFile:</code>, in that order).</p>
<p><a href="http://developer.apple.com/documentation/Cocoa/Conceptual/ScriptableCocoaApplications/SApps%5Fhandle%5FAEs/SAppsHandleAEs.html#//apple%5Fref/doc/uid/20001239-1119823" rel="nofollow">Here's the documentation</a> for handling Open Apple Events in Cocoa.</p>
<p>For Carbon apps, I can't really remember the details (been a while since I've written Carbon code), but if I recall correctly, you would install an Apple Event handler for <code>kAEOpenDocuments</code> events with <code>AEInstallEventHandler()</code>. See <a href="http://developer.apple.com/documentation/Carbon/Reference/Apple%5FEvent%5FManager/Reference/reference.html#//apple%5Fref/c/func/AEInstallEventHandler" rel="nofollow">the documentation</a> for more details.</p>
| 1 | 2009-05-11T18:01:57Z | [
"python",
"osx"
] |
Getting the name of document that used to launch the application bundle on OS X | 849,172 | <p>When writing an OS X Bundle application (.app), how can I get the name of the document that caused the application to be launched?</p>
<p>Say I've associated .abcd with MyApp, when I click on foo.abcd MyApp is launched.
How can I get the foo.abcd from inside MyApp? (Command line arguments only contain the process id).</p>
| 2 | 2009-05-11T17:39:09Z | 1,004,487 | <p>It looks like you need a GUI toolkit for that, there is an example in <a href="http://svn.python.org/view/python/trunk/Lib/idlelib/macosxSupport.py?revision=HEAD&view=markup" rel="nofollow">idlelib/macosxSupport.py</a></p>
<pre><code>def doOpenFile(*args):
for fn in args:
flist.open(fn)
# The command below is a hook in aquatk that is called whenever the app
# receives a file open event. The callback can have multiple arguments,
# one for every file that should be opened.
root.createcommand("::tk::mac::OpenDocument", doOpenFile)
</code></pre>
<p>Qt also has <a href="http://doc.trolltech.com/qq/qq18-macfeatures.html" rel="nofollow">support</a> for that.</p>
| 1 | 2009-06-17T00:01:38Z | [
"python",
"osx"
] |
Standard non-code resource location for python packages | 849,334 | <p>This should be a common scenario, but could not find any relevant post yet..</p>
<p>I plan to deploy a Python library (I guess the same applies to regular applications) which makes use of some images and other resource files. What is the standard location for such items? I imagine, for project <code>Foo</code>, the choices would be</p>
<ul>
<li>Have <code>resources</code> directory in the source repository and then move files to <code>/usr/share/foo/</code></li>
<li>Place resources directly inside the python package that goes under <code>/usr/lib/python-<version>/foo/</code></li>
</ul>
<p>Any suggestions?</p>
<p><strong>Edit:</strong> As suggested, clarifying that the main platform this will be running on is Linux.</p>
| 4 | 2009-05-11T18:13:14Z | 849,446 | <p>This question is somewhat incomplete, because a proper answer would depend on the underlying operating system, as each has its own modus operandi. In linux (and most unix based OSs) for example /usr/share/foo or /usr/local/share/foo would be the standard. In OS X you can do the same, but I would think "/Library/Application Support/Foo" (although that's usually for storing settings and whatnot) would be the place to put such things, though if you're writing libraries following the "Framework" idea, all the resources would be included in the /Library/Frameworks/Foo.Framework" ... Apps on OS X on the other hand should keeps all there resources within the Resources directory inside Foo.app</p>
| 2 | 2009-05-11T18:37:35Z | [
"python",
"resources",
"location",
"package",
"shared"
] |
Standard non-code resource location for python packages | 849,334 | <p>This should be a common scenario, but could not find any relevant post yet..</p>
<p>I plan to deploy a Python library (I guess the same applies to regular applications) which makes use of some images and other resource files. What is the standard location for such items? I imagine, for project <code>Foo</code>, the choices would be</p>
<ul>
<li>Have <code>resources</code> directory in the source repository and then move files to <code>/usr/share/foo/</code></li>
<li>Place resources directly inside the python package that goes under <code>/usr/lib/python-<version>/foo/</code></li>
</ul>
<p>Any suggestions?</p>
<p><strong>Edit:</strong> As suggested, clarifying that the main platform this will be running on is Linux.</p>
| 4 | 2009-05-11T18:13:14Z | 849,795 | <p>The <em>standard</em> location is where your standard libs goes. But it doesn't sound to me from what you've written, that you'll want your python lib there. I think you should try out <a href="http://pypi.python.org/pypi/virtualenv#what-it-does" rel="nofollow">Virtualenv</a>.</p>
<p>If you don't want to go through all the trouble (well, it really just amounts to <code>sudo easy_install virtualenv</code> for you), you could try to just dump your python lib in any dir in your <code>~/</code> and do something along the lines of</p>
<pre><code>import sys
sys.path.append( '/full/path/to/your/lib/goes/here')
</code></pre>
<p>to any given application that uses your lib.</p>
<p>Please bear in mind, that the examples given are for test-purposes only. For anything live-ish, I would recommend that you use <a href="http://docs.python.org/distutils/" rel="nofollow">distutil</a>. Examples of use are given <a href="http://docs.python.org/distutils/setupscript.html" rel="nofollow">here</a>.</p>
| 0 | 2009-05-11T19:58:44Z | [
"python",
"resources",
"location",
"package",
"shared"
] |
Standard non-code resource location for python packages | 849,334 | <p>This should be a common scenario, but could not find any relevant post yet..</p>
<p>I plan to deploy a Python library (I guess the same applies to regular applications) which makes use of some images and other resource files. What is the standard location for such items? I imagine, for project <code>Foo</code>, the choices would be</p>
<ul>
<li>Have <code>resources</code> directory in the source repository and then move files to <code>/usr/share/foo/</code></li>
<li>Place resources directly inside the python package that goes under <code>/usr/lib/python-<version>/foo/</code></li>
</ul>
<p>Any suggestions?</p>
<p><strong>Edit:</strong> As suggested, clarifying that the main platform this will be running on is Linux.</p>
| 4 | 2009-05-11T18:13:14Z | 849,803 | <p>We put non .py files in <code>/opt/foo/foo-1.2/...</code></p>
<p>Except, of course, for static media that is served by Apache, that goes to <code>/var/www/html/foo/foo-1.1/media/...</code></p>
<p>Except, of course, for customer-specific configuration files. They go to
<code>/var/opt/customer/foo/...</code></p>
<p>Those follow the Linux standards as I understand them. </p>
<p>We try to stay away from <code>/usr/lib/</code> and <code>/lib</code> kinds of locations because those feel like they're part of the distribution. We lean toward <code>/opt</code> and <code>/var</code> because they're clearly separated from the linux distro directories.</p>
| 2 | 2009-05-11T20:01:23Z | [
"python",
"resources",
"location",
"package",
"shared"
] |
How do I enumerate() over a list of tuples in Python? | 849,369 | <p>I've got some code like this:</p>
<pre><code>letters = [('a', 'A'), ('b', 'B')]
i = 0
for (lowercase, uppercase) in letters:
print "Letter #%d is %s/%s" % (i, lowercase, uppercase)
i += 1
</code></pre>
<p>I've been told that there's an enumerate() function that can take care of the "i" variable for me:</p>
<pre><code>for i, l in enumerate(['a', 'b', 'c']):
print "%d: %s" % (i, l)
</code></pre>
<p>However, I can't figure out how to combine the two: How do I use enumerate when the list in question is made of tuples? Do i have to do this?</p>
<pre><code>letters = [('a', 'A'), ('b', 'B')]
for i, tuple in enumerate(letters):
(lowercase, uppercase) = tuple
print "Letter #%d is %s/%s" % (i, lowercase, uppercase)
</code></pre>
<p>Or is there a more elegant way?</p>
| 25 | 2009-05-11T18:20:13Z | 849,388 | <p>This is a neat way to do it:</p>
<pre><code>letters = [('a', 'A'), ('b', 'B')]
for i, (lowercase, uppercase) in enumerate(letters):
print "Letter #%d is %s/%s" % (i, lowercase, uppercase)
</code></pre>
| 60 | 2009-05-11T18:23:36Z | [
"python",
"list",
"enumerate"
] |
How do I enumerate() over a list of tuples in Python? | 849,369 | <p>I've got some code like this:</p>
<pre><code>letters = [('a', 'A'), ('b', 'B')]
i = 0
for (lowercase, uppercase) in letters:
print "Letter #%d is %s/%s" % (i, lowercase, uppercase)
i += 1
</code></pre>
<p>I've been told that there's an enumerate() function that can take care of the "i" variable for me:</p>
<pre><code>for i, l in enumerate(['a', 'b', 'c']):
print "%d: %s" % (i, l)
</code></pre>
<p>However, I can't figure out how to combine the two: How do I use enumerate when the list in question is made of tuples? Do i have to do this?</p>
<pre><code>letters = [('a', 'A'), ('b', 'B')]
for i, tuple in enumerate(letters):
(lowercase, uppercase) = tuple
print "Letter #%d is %s/%s" % (i, lowercase, uppercase)
</code></pre>
<p>Or is there a more elegant way?</p>
| 25 | 2009-05-11T18:20:13Z | 849,705 | <p>This is how I'd do it:</p>
<pre><code>import itertools
letters = [('a', 'A'), ('b', 'B')]
for i, lower, upper in zip(itertools.count(),*zip(*letters)):
print "Letter #%d is %s/%s" % (i, lower, upper)
</code></pre>
<p>EDIT: unpacking becomes redundant. This is a more compact way, which might work or not depending on your use case:</p>
<pre><code>import itertools
letters = [('a', 'A'), ('b', 'B')]
for i in zip(itertools.count(),*zip(*letters)):
print "Letter #%d is %s/%s" % i
</code></pre>
| 3 | 2009-05-11T19:39:31Z | [
"python",
"list",
"enumerate"
] |
How do I enumerate() over a list of tuples in Python? | 849,369 | <p>I've got some code like this:</p>
<pre><code>letters = [('a', 'A'), ('b', 'B')]
i = 0
for (lowercase, uppercase) in letters:
print "Letter #%d is %s/%s" % (i, lowercase, uppercase)
i += 1
</code></pre>
<p>I've been told that there's an enumerate() function that can take care of the "i" variable for me:</p>
<pre><code>for i, l in enumerate(['a', 'b', 'c']):
print "%d: %s" % (i, l)
</code></pre>
<p>However, I can't figure out how to combine the two: How do I use enumerate when the list in question is made of tuples? Do i have to do this?</p>
<pre><code>letters = [('a', 'A'), ('b', 'B')]
for i, tuple in enumerate(letters):
(lowercase, uppercase) = tuple
print "Letter #%d is %s/%s" % (i, lowercase, uppercase)
</code></pre>
<p>Or is there a more elegant way?</p>
| 25 | 2009-05-11T18:20:13Z | 13,805,621 | <p>You can do this way too:</p>
<pre><code>letters = [('a', 'A'), ('b', 'B')]
for i, letter in enumerate(letters):
print "Letter #%d is %s/%s" % (i, letter[0], letter[1])
</code></pre>
| 0 | 2012-12-10T17:05:52Z | [
"python",
"list",
"enumerate"
] |
Deploying Python via CGI | 849,384 | <p>How do I deploy a Python project to a webserver that supports Python via CGI? I'm well versed in PHP, but do not understand CGI's relation to Python in the deployment process.</p>
<p>Any resource links are appreciated.</p>
<p>The web host in question is GoDaddy.</p>
| 1 | 2009-05-11T18:22:12Z | 849,472 | <p>To actually answer your question about deploying python as CGI (while it does not make a lot of sense on a high activity system - there are occasions where it does the job just fine) you just make sure that your files are executable, have the correct extension and then follow <a href="http://www.cs.virginia.edu/~lab2q/" rel="nofollow">this tutorial</a>. It is what I used to learn from.</p>
<p>EDIT: To be clear - I recommend that you look into <a href="http://www.djangoproject.com/" rel="nofollow">Django</a> to deploy web based python applications.</p>
| 0 | 2009-05-11T18:44:17Z | [
"python"
] |
Deploying Python via CGI | 849,384 | <p>How do I deploy a Python project to a webserver that supports Python via CGI? I'm well versed in PHP, but do not understand CGI's relation to Python in the deployment process.</p>
<p>Any resource links are appreciated.</p>
<p>The web host in question is GoDaddy.</p>
| 1 | 2009-05-11T18:22:12Z | 849,579 | <p>Generally, we use <a href="http://code.google.com/p/modwsgi/" rel="nofollow">mod_wsgi</a> to make a Python application respond to CGI. </p>
<p>PHP has a special role -- the language runtime IS a CGI application.</p>
<p>Python does not have this special role. Python -- by default -- is not a CGI application. It requires a piece of glue to play well with Apache. mod_wsgi is this glue.</p>
| 3 | 2009-05-11T19:12:27Z | [
"python"
] |
django template includes | 849,463 | <p>I'm having an issue with django templates at the moment. I have 3 template files basically:</p>
<ul>
<li>Base</li>
<li>story_list</li>
<li>story_detail</li>
</ul>
<p>Story_list and _detail extend Base, and that works perfectly fine. However, list and detail share some code that extend the base template for my sidebar. I'm basically repeating a chunk of code in both templates, and the programmer in me says that's just wrong. There has to be a better way, I'm sure of it. I've tried includes, however I have in the included file:</p>
<pre><code>{% block item %}
content stuff
{% endblock %}
</code></pre>
<p>for about 3 blocks. The problem is that none of that is being picked up/rendered. If I include the file in a block section that extends base, then it dumps everything properly, but if I don't include it in a block, I get nothing. Is SSI the way to go? I toyed with that, but that didn't seem to work properly either. Any help is appreciated.</p>
| 3 | 2009-05-11T18:41:24Z | 849,530 | <p>If there is common code between the story templates that isn't needed site-wide, I'd create a <code>story_base</code> (extending the original <code>base</code>) and have my story templates extend that.</p>
| 6 | 2009-05-11T18:58:14Z | [
"python",
"django",
"django-templates"
] |
django template includes | 849,463 | <p>I'm having an issue with django templates at the moment. I have 3 template files basically:</p>
<ul>
<li>Base</li>
<li>story_list</li>
<li>story_detail</li>
</ul>
<p>Story_list and _detail extend Base, and that works perfectly fine. However, list and detail share some code that extend the base template for my sidebar. I'm basically repeating a chunk of code in both templates, and the programmer in me says that's just wrong. There has to be a better way, I'm sure of it. I've tried includes, however I have in the included file:</p>
<pre><code>{% block item %}
content stuff
{% endblock %}
</code></pre>
<p>for about 3 blocks. The problem is that none of that is being picked up/rendered. If I include the file in a block section that extends base, then it dumps everything properly, but if I don't include it in a block, I get nothing. Is SSI the way to go? I toyed with that, but that didn't seem to work properly either. Any help is appreciated.</p>
| 3 | 2009-05-11T18:41:24Z | 849,559 | <p>You have an <a href="http://docs.djangoproject.com/en/dev/ref/templates/builtins/#include" rel="nofollow">{% include %}</a> tag for this.</p>
| 0 | 2009-05-11T19:07:32Z | [
"python",
"django",
"django-templates"
] |
django template includes | 849,463 | <p>I'm having an issue with django templates at the moment. I have 3 template files basically:</p>
<ul>
<li>Base</li>
<li>story_list</li>
<li>story_detail</li>
</ul>
<p>Story_list and _detail extend Base, and that works perfectly fine. However, list and detail share some code that extend the base template for my sidebar. I'm basically repeating a chunk of code in both templates, and the programmer in me says that's just wrong. There has to be a better way, I'm sure of it. I've tried includes, however I have in the included file:</p>
<pre><code>{% block item %}
content stuff
{% endblock %}
</code></pre>
<p>for about 3 blocks. The problem is that none of that is being picked up/rendered. If I include the file in a block section that extends base, then it dumps everything properly, but if I don't include it in a block, I get nothing. Is SSI the way to go? I toyed with that, but that didn't seem to work properly either. Any help is appreciated.</p>
| 3 | 2009-05-11T18:41:24Z | 849,574 | <p>Generally, using <code>include</code>s is not the answer with Django templates. Let me answer your question on several fronts.</p>
<p>First, let me address the sidebar.</p>
<ul>
<li><p><strong>Are nearly all the common pages going to be using that sidebar?</strong> Put it in <code>Base</code>. Don't override those sidebar blocks (i.e. don't write them at all in your <code>Story_*</code> templates).</p></li>
<li><p><strong>Is this sidebar unique to the <code>Story_*</code> templates?</strong> Make another template called, say, <code>Story_base</code> and extend that. This is akin to making an abstract superclass in Java. (Answer was in my head, but wording was mercilessly <a href="http://stackoverflow.com/questions/849463/django-template-includes/849530#849530" rel="nofollow" title="jpwatts's answer">ripped off</a> from jpwatts.)</p></li>
</ul>
<p>Next, let me address template inheritance. Say you have a template named <code>Story_list</code> that extends <code>Base</code>. At this point, after just putting <code>{% extends "Base" %}</code>, <code>Story_list</code> <em>is exactly</em> <code>Base</code>. Anything else you put in <code>Story_list</code> is ignored, because the template is already complete. The only thing you can do now is <em>override</em> blocks that have been defined in <code>Base</code>.</p>
<p>Finally, let me address <code>include</code>s. Try to always avoid them. Other templating engines, such as PHP, seem to encourage using <code>include</code>s. However, this can lead to less manageable templates in the long run. It's slightly harder to glance at an included snippet and immediately ascertain its place in your template hierarchy. They're also harder to refactor into the template hierarchy, especially if you include them at several levels (once in <code>Base</code>, twice in <code>Story_base</code>, once in some of the <code>Story_*</code>, etc.).</p>
| 16 | 2009-05-11T19:11:25Z | [
"python",
"django",
"django-templates"
] |
django template includes | 849,463 | <p>I'm having an issue with django templates at the moment. I have 3 template files basically:</p>
<ul>
<li>Base</li>
<li>story_list</li>
<li>story_detail</li>
</ul>
<p>Story_list and _detail extend Base, and that works perfectly fine. However, list and detail share some code that extend the base template for my sidebar. I'm basically repeating a chunk of code in both templates, and the programmer in me says that's just wrong. There has to be a better way, I'm sure of it. I've tried includes, however I have in the included file:</p>
<pre><code>{% block item %}
content stuff
{% endblock %}
</code></pre>
<p>for about 3 blocks. The problem is that none of that is being picked up/rendered. If I include the file in a block section that extends base, then it dumps everything properly, but if I don't include it in a block, I get nothing. Is SSI the way to go? I toyed with that, but that didn't seem to work properly either. Any help is appreciated.</p>
| 3 | 2009-05-11T18:41:24Z | 14,425,036 | <pre><code>{% include xxx.html %}
</code></pre>
<p>This tag works.</p>
<p>An alternative way is to use filter. Filter calls a function for rendering, template can be used while rendering.</p>
| 0 | 2013-01-20T13:33:27Z | [
"python",
"django",
"django-templates"
] |
Performing Photoshop's "Luminosity" filter programmatically | 849,654 | <p>I have two JPEG's and would like to overlay one on the other with the same results as the "Luminosity" mode available in Photoshop (and Fireworks). You can read more about Luminosity mode here: <a href="http://www.adobetutorialz.com/articles/662/1/Photoshop%92s-Luminosity-Mode" rel="nofollow">http://www.adobetutorialz.com/articles/662/1/Photoshop%92s-Luminosity-Mode</a></p>
<p>How can I do this? Programming language doesn't matter much, but I am most fluent with Python and PHP (in that order). Python Imaging Library seems like a perfect fit, but luminosity is not a built-in function and I do not know the proper procedure. See <a href="http://effbot.org/imagingbook/imagechops.htm" rel="nofollow">http://effbot.org/imagingbook/imagechops.htm</a></p>
| 3 | 2009-05-11T19:27:12Z | 849,687 | <p>The Gimp would be another option - it has a scripting interface ans a python api - here is an article on <a href="http://gimpology.com/submission/view/luminosity%5Fmasking%5Fthe%5Flight%5Fside/" rel="nofollow">luminosity and the Gimp</a>. Not sure if it is the same effect you are going for though.</p>
| 0 | 2009-05-11T19:36:31Z | [
"php",
"python",
"image",
"image-processing",
"python-imaging-library"
] |
Performing Photoshop's "Luminosity" filter programmatically | 849,654 | <p>I have two JPEG's and would like to overlay one on the other with the same results as the "Luminosity" mode available in Photoshop (and Fireworks). You can read more about Luminosity mode here: <a href="http://www.adobetutorialz.com/articles/662/1/Photoshop%92s-Luminosity-Mode" rel="nofollow">http://www.adobetutorialz.com/articles/662/1/Photoshop%92s-Luminosity-Mode</a></p>
<p>How can I do this? Programming language doesn't matter much, but I am most fluent with Python and PHP (in that order). Python Imaging Library seems like a perfect fit, but luminosity is not a built-in function and I do not know the proper procedure. See <a href="http://effbot.org/imagingbook/imagechops.htm" rel="nofollow">http://effbot.org/imagingbook/imagechops.htm</a></p>
| 3 | 2009-05-11T19:27:12Z | 849,694 | <p>First you need to understand what Photoshop does.</p>
<p>It preserves under layer perceptual color information and replaces it's luminosity with the top layer's perceptual luminosity information. To do that, you need to convert the images to the right color space.</p>
<p>Here is the shoping list of things you will need to do if you decide to implement everything by yourself:</p>
<ul>
<li>Load both the source and target JPEGs</li>
<li>Convert the pixels from RGB color space to L*a*b color space (or any other color space with luminosirty information)</li>
<li>Preserve target color channels and replace its luminosity channel by source's luminosity</li>
<li>Convert back to RGB space</li>
<li>Save the JPEG</li>
</ul>
<p>If you think Lab is too complicated, you can also use HSL color space, it's much simpler but it will give inferior results.</p>
| 5 | 2009-05-11T19:37:30Z | [
"php",
"python",
"image",
"image-processing",
"python-imaging-library"
] |
Performing Photoshop's "Luminosity" filter programmatically | 849,654 | <p>I have two JPEG's and would like to overlay one on the other with the same results as the "Luminosity" mode available in Photoshop (and Fireworks). You can read more about Luminosity mode here: <a href="http://www.adobetutorialz.com/articles/662/1/Photoshop%92s-Luminosity-Mode" rel="nofollow">http://www.adobetutorialz.com/articles/662/1/Photoshop%92s-Luminosity-Mode</a></p>
<p>How can I do this? Programming language doesn't matter much, but I am most fluent with Python and PHP (in that order). Python Imaging Library seems like a perfect fit, but luminosity is not a built-in function and I do not know the proper procedure. See <a href="http://effbot.org/imagingbook/imagechops.htm" rel="nofollow">http://effbot.org/imagingbook/imagechops.htm</a></p>
| 3 | 2009-05-11T19:27:12Z | 849,715 | <p>In pseudo-code:</p>
<pre><code>foreach rgb_pixel1, rgb_pixel2 in image1, image2 {
hsl1 = RgbToHsl(rgb_pixel1);
hsl2 = RgbToHsl(rgb_pixel2);
hsl3 = hsl(hsl1.h, hsl1.s, hsl2.l);
output_rgb = HslToRgb(hsl3);
}
</code></pre>
<p>Conversion from rgb to hsl and back is <a href="http://www.geekymonkey.com/Programming/CSharp/RGB2HSL%5FHSL2RGB.htm" rel="nofollow">here</a>.</p>
| 1 | 2009-05-11T19:41:58Z | [
"php",
"python",
"image",
"image-processing",
"python-imaging-library"
] |
Performing Photoshop's "Luminosity" filter programmatically | 849,654 | <p>I have two JPEG's and would like to overlay one on the other with the same results as the "Luminosity" mode available in Photoshop (and Fireworks). You can read more about Luminosity mode here: <a href="http://www.adobetutorialz.com/articles/662/1/Photoshop%92s-Luminosity-Mode" rel="nofollow">http://www.adobetutorialz.com/articles/662/1/Photoshop%92s-Luminosity-Mode</a></p>
<p>How can I do this? Programming language doesn't matter much, but I am most fluent with Python and PHP (in that order). Python Imaging Library seems like a perfect fit, but luminosity is not a built-in function and I do not know the proper procedure. See <a href="http://effbot.org/imagingbook/imagechops.htm" rel="nofollow">http://effbot.org/imagingbook/imagechops.htm</a></p>
| 3 | 2009-05-11T19:27:12Z | 849,725 | <p>You could have a look at the <a href="http://opencv.willowgarage.com/wiki/" rel="nofollow">OpenCV</a> image processing library. It has Python bindings and handles a lot of these lower level image manipulation tasks for you, or at least makes them easier.</p>
| 0 | 2009-05-11T19:44:39Z | [
"php",
"python",
"image",
"image-processing",
"python-imaging-library"
] |
Performing Photoshop's "Luminosity" filter programmatically | 849,654 | <p>I have two JPEG's and would like to overlay one on the other with the same results as the "Luminosity" mode available in Photoshop (and Fireworks). You can read more about Luminosity mode here: <a href="http://www.adobetutorialz.com/articles/662/1/Photoshop%92s-Luminosity-Mode" rel="nofollow">http://www.adobetutorialz.com/articles/662/1/Photoshop%92s-Luminosity-Mode</a></p>
<p>How can I do this? Programming language doesn't matter much, but I am most fluent with Python and PHP (in that order). Python Imaging Library seems like a perfect fit, but luminosity is not a built-in function and I do not know the proper procedure. See <a href="http://effbot.org/imagingbook/imagechops.htm" rel="nofollow">http://effbot.org/imagingbook/imagechops.htm</a></p>
| 3 | 2009-05-11T19:27:12Z | 850,091 | <p>I don't know about this specific filter but I can tell you how to follow Coincoin steps in <a href="http://www.pythonware.com/products/pil/" rel="nofollow">PIL</a>. I didn't actually run the code, but you can use it as a reference:</p>
<p>Load both the source and target JPEGs</p>
<pre><code>from PIL import Image
img1 = Image.open('image1.jpg')
img2 = Image.open('image2.jpg')
</code></pre>
<p>Convert the pixels from RGB color space to L*a*b color space (or any other color space with luminosirty information)</p>
<pre><code># Color matrix for Lab
colorMatrix = (
x1, y1, z1, 0,
x2, y2, z2, 0,
x3, y3, z3, 0
)
img1 = img1.convert("RGB", colorMatrix)
img2 = img2.convert("RGB", colorMatrix)
</code></pre>
<p>Preserve target color channels and replace its luminosity channel by source's luminosity</p>
<pre><code>l1, a1, b1 = img1.split()
l2, a2, b2 = img2.split()
img1.putdata(zip(l1.getdata(), a2.getdata(), b2.getdata()))
</code></pre>
<p>Convert back to RGB space</p>
<pre><code># Color matrix for RGB
RGBcolorMatrix = (
x1, y1, z1, 0,
x2, y2, z2, 0,
x3, y3, z3, 0
)
img1 = img1.convert("RGB", RGBcolorMatrix)
</code></pre>
<p>Save the JPEG</p>
<pre><code>img1.save('new_image.jpg')
</code></pre>
| 1 | 2009-05-11T21:07:00Z | [
"php",
"python",
"image",
"image-processing",
"python-imaging-library"
] |
Simple threading in Python 2.6 using thread.start_new_thread() | 849,674 | <p>I'm following a tutorial on simple threading. They give this example and when I try to use it I'm getting unintelligible errors from the interpreter. Can you please tell me why this isn't working? I'm on WinXP SP3 w/ Python 2.6 current</p>
<pre><code>import thread
def myfunction(mystring,*args):
print mystring
if __name__ == '__main__':
try:
thread.start_new_thread(myfunction,('MyStringHere',1))
except Exception as errtxt:
print errtxt
</code></pre>
<p>Executing this results in::</p>
<p>Unhandled exception in thread started by
Error in sys.excepthook:</p>
<p>Original exception was:</p>
<p>The information missing in the error is <em>actually</em> missing in the output.</p>
| 11 | 2009-05-11T19:32:17Z | 849,698 | <p>I tried it in Python 2.5 on a mac, after changing </p>
<pre><code>except Exception as errtxt:
</code></pre>
<p>to</p>
<pre><code>except Exception, errtxt:
</code></pre>
<p>The program did not throw an exception but also did not print anything. Not sure if that is helpful, but I do find it curious...</p>
| -1 | 2009-05-11T19:38:35Z | [
"python",
"multithreading",
"python-2.6"
] |
Simple threading in Python 2.6 using thread.start_new_thread() | 849,674 | <p>I'm following a tutorial on simple threading. They give this example and when I try to use it I'm getting unintelligible errors from the interpreter. Can you please tell me why this isn't working? I'm on WinXP SP3 w/ Python 2.6 current</p>
<pre><code>import thread
def myfunction(mystring,*args):
print mystring
if __name__ == '__main__':
try:
thread.start_new_thread(myfunction,('MyStringHere',1))
except Exception as errtxt:
print errtxt
</code></pre>
<p>Executing this results in::</p>
<p>Unhandled exception in thread started by
Error in sys.excepthook:</p>
<p>Original exception was:</p>
<p>The information missing in the error is <em>actually</em> missing in the output.</p>
| 11 | 2009-05-11T19:32:17Z | 849,700 | <p>When I ran this code in Python 2.6 it worked, is it possible you have open threads already that are locked on the function? I recommend closing Python completely, checking your running processes to make sure nothing of yours is running and try again.</p>
| -1 | 2009-05-11T19:38:51Z | [
"python",
"multithreading",
"python-2.6"
] |
Simple threading in Python 2.6 using thread.start_new_thread() | 849,674 | <p>I'm following a tutorial on simple threading. They give this example and when I try to use it I'm getting unintelligible errors from the interpreter. Can you please tell me why this isn't working? I'm on WinXP SP3 w/ Python 2.6 current</p>
<pre><code>import thread
def myfunction(mystring,*args):
print mystring
if __name__ == '__main__':
try:
thread.start_new_thread(myfunction,('MyStringHere',1))
except Exception as errtxt:
print errtxt
</code></pre>
<p>Executing this results in::</p>
<p>Unhandled exception in thread started by
Error in sys.excepthook:</p>
<p>Original exception was:</p>
<p>The information missing in the error is <em>actually</em> missing in the output.</p>
| 11 | 2009-05-11T19:32:17Z | 849,759 | <p>The problem is that your main thread has quit before your new thread has time to finish. The solution is to wait at your main thread.</p>
<pre><code>import thread, time
def myfunction(mystring,*args):
print mystring
if __name__ == '__main__':
try:
thread.start_new_thread(myfunction,('MyStringHere',1))
except Exception, errtxt:
print errtxt
time.sleep(5)
</code></pre>
<p>As a side note, you probably want to use the threading module. Your main thread will wait for all of those types of threads to be closed before exiting:</p>
<pre><code>from threading import Thread
def myfunction(mystring,*args):
print mystring
if __name__ == '__main__':
try:
Thread(target=myfunction, args=('MyStringHere',1)).start()
except Exception, errtxt:
print errtxt
</code></pre>
| 22 | 2009-05-11T19:53:08Z | [
"python",
"multithreading",
"python-2.6"
] |
Simple threading in Python 2.6 using thread.start_new_thread() | 849,674 | <p>I'm following a tutorial on simple threading. They give this example and when I try to use it I'm getting unintelligible errors from the interpreter. Can you please tell me why this isn't working? I'm on WinXP SP3 w/ Python 2.6 current</p>
<pre><code>import thread
def myfunction(mystring,*args):
print mystring
if __name__ == '__main__':
try:
thread.start_new_thread(myfunction,('MyStringHere',1))
except Exception as errtxt:
print errtxt
</code></pre>
<p>Executing this results in::</p>
<p>Unhandled exception in thread started by
Error in sys.excepthook:</p>
<p>Original exception was:</p>
<p>The information missing in the error is <em>actually</em> missing in the output.</p>
| 11 | 2009-05-11T19:32:17Z | 849,896 | <p>You need to wait until your Thread finishes its work, so you have to use Thread.join() :</p>
<pre><code>from threading import Thread
def myfunction(mystring,*args):
print mystring
if __name__ == '__main__':
try:
t = Thread(None,myfunction,None,('MyStringHere',1))
t.start()
t.join()
except Exception as errtxt:
print errtxt
</code></pre>
| 14 | 2009-05-11T20:19:04Z | [
"python",
"multithreading",
"python-2.6"
] |
Simple threading in Python 2.6 using thread.start_new_thread() | 849,674 | <p>I'm following a tutorial on simple threading. They give this example and when I try to use it I'm getting unintelligible errors from the interpreter. Can you please tell me why this isn't working? I'm on WinXP SP3 w/ Python 2.6 current</p>
<pre><code>import thread
def myfunction(mystring,*args):
print mystring
if __name__ == '__main__':
try:
thread.start_new_thread(myfunction,('MyStringHere',1))
except Exception as errtxt:
print errtxt
</code></pre>
<p>Executing this results in::</p>
<p>Unhandled exception in thread started by
Error in sys.excepthook:</p>
<p>Original exception was:</p>
<p>The information missing in the error is <em>actually</em> missing in the output.</p>
| 11 | 2009-05-11T19:32:17Z | 20,633,107 | <pre><code>import thread
def myfunction(mystring,*args):
print mystring
if __name__ == '__main__':
try:
thread.start_new_thread(myfunction,('MyStringHere',1))
except Exception as errtxt:
print errtxt
while 1:
pass
</code></pre>
<p>Put while loop at last then it will work for you.</p>
| 0 | 2013-12-17T11:38:56Z | [
"python",
"multithreading",
"python-2.6"
] |
Is there a way to set multiple defaults on a Python dict using another dict? | 849,806 | <p>Suppose I've got two dicts in Python:</p>
<pre><code>mydict = { 'a': 0 }
defaults = {
'a': 5,
'b': 10,
'c': 15
}
</code></pre>
<p>I want to be able to expand <code>mydict</code> using the default values from <code>defaults</code>, such that 'a' remains the same but 'b' and 'c' are filled in. I know about <a href="http://docs.python.org/library/stdtypes.html#dict.setdefault"><code>dict.setdefault()</code></a> and <a href="http://docs.python.org/library/stdtypes.html#dict.update"><code>dict.update()</code></a>, but each only do half of what I want - with <code>dict.setdefault()</code>, I have to loop over each variable in <code>defaults</code>; but with <code>dict.update()</code>, <code>defaults</code> will blow away any pre-existing values in <code>mydict</code>.</p>
<p>Is there some functionality I'm not finding built into Python that can do this? And if not, is there a more Pythonic way of writing a loop to repeatedly call <code>dict.setdefaults()</code> than this:</p>
<pre><code>for key in defaults.keys():
mydict.setdefault(key, defaults[key])
</code></pre>
<p>Context: I'm writing up some data in Python that controls how to parse an XML tree. There's a dict for each node (i.e., how to process each node), and I'd rather the data I write up be sparse, but filled in with defaults. The example code is just an example... real code has many more key/value pairs in the default dict.</p>
<p>(I realize this whole question is but a minor quibble, but it's been bothering me, so I was wondering if there was a better way to do this that I am not aware of.)</p>
| 7 | 2009-05-11T20:01:46Z | 849,831 | <pre><code>defaults.update(mydict)
</code></pre>
| 0 | 2009-05-11T20:05:26Z | [
"python",
"dictionary"
] |
Is there a way to set multiple defaults on a Python dict using another dict? | 849,806 | <p>Suppose I've got two dicts in Python:</p>
<pre><code>mydict = { 'a': 0 }
defaults = {
'a': 5,
'b': 10,
'c': 15
}
</code></pre>
<p>I want to be able to expand <code>mydict</code> using the default values from <code>defaults</code>, such that 'a' remains the same but 'b' and 'c' are filled in. I know about <a href="http://docs.python.org/library/stdtypes.html#dict.setdefault"><code>dict.setdefault()</code></a> and <a href="http://docs.python.org/library/stdtypes.html#dict.update"><code>dict.update()</code></a>, but each only do half of what I want - with <code>dict.setdefault()</code>, I have to loop over each variable in <code>defaults</code>; but with <code>dict.update()</code>, <code>defaults</code> will blow away any pre-existing values in <code>mydict</code>.</p>
<p>Is there some functionality I'm not finding built into Python that can do this? And if not, is there a more Pythonic way of writing a loop to repeatedly call <code>dict.setdefaults()</code> than this:</p>
<pre><code>for key in defaults.keys():
mydict.setdefault(key, defaults[key])
</code></pre>
<p>Context: I'm writing up some data in Python that controls how to parse an XML tree. There's a dict for each node (i.e., how to process each node), and I'd rather the data I write up be sparse, but filled in with defaults. The example code is just an example... real code has many more key/value pairs in the default dict.</p>
<p>(I realize this whole question is but a minor quibble, but it's been bothering me, so I was wondering if there was a better way to do this that I am not aware of.)</p>
| 7 | 2009-05-11T20:01:46Z | 849,849 | <p>Couldnt you make mydict be a copy of default, That way, mydict would have all the correct values to start with?</p>
<pre><code>mydict = default.copy()
</code></pre>
| 7 | 2009-05-11T20:07:05Z | [
"python",
"dictionary"
] |
Is there a way to set multiple defaults on a Python dict using another dict? | 849,806 | <p>Suppose I've got two dicts in Python:</p>
<pre><code>mydict = { 'a': 0 }
defaults = {
'a': 5,
'b': 10,
'c': 15
}
</code></pre>
<p>I want to be able to expand <code>mydict</code> using the default values from <code>defaults</code>, such that 'a' remains the same but 'b' and 'c' are filled in. I know about <a href="http://docs.python.org/library/stdtypes.html#dict.setdefault"><code>dict.setdefault()</code></a> and <a href="http://docs.python.org/library/stdtypes.html#dict.update"><code>dict.update()</code></a>, but each only do half of what I want - with <code>dict.setdefault()</code>, I have to loop over each variable in <code>defaults</code>; but with <code>dict.update()</code>, <code>defaults</code> will blow away any pre-existing values in <code>mydict</code>.</p>
<p>Is there some functionality I'm not finding built into Python that can do this? And if not, is there a more Pythonic way of writing a loop to repeatedly call <code>dict.setdefaults()</code> than this:</p>
<pre><code>for key in defaults.keys():
mydict.setdefault(key, defaults[key])
</code></pre>
<p>Context: I'm writing up some data in Python that controls how to parse an XML tree. There's a dict for each node (i.e., how to process each node), and I'd rather the data I write up be sparse, but filled in with defaults. The example code is just an example... real code has many more key/value pairs in the default dict.</p>
<p>(I realize this whole question is but a minor quibble, but it's been bothering me, so I was wondering if there was a better way to do this that I am not aware of.)</p>
| 7 | 2009-05-11T20:01:46Z | 849,856 | <p>If you don't mind creating a new dictionary in the process, this will do the trick:</p>
<pre><code>newdict = dict(defaults)
newdict.update(mydict)
</code></pre>
<p>Now <code>newdict</code> contains what you need.</p>
| 3 | 2009-05-11T20:08:06Z | [
"python",
"dictionary"
] |
Is there a way to set multiple defaults on a Python dict using another dict? | 849,806 | <p>Suppose I've got two dicts in Python:</p>
<pre><code>mydict = { 'a': 0 }
defaults = {
'a': 5,
'b': 10,
'c': 15
}
</code></pre>
<p>I want to be able to expand <code>mydict</code> using the default values from <code>defaults</code>, such that 'a' remains the same but 'b' and 'c' are filled in. I know about <a href="http://docs.python.org/library/stdtypes.html#dict.setdefault"><code>dict.setdefault()</code></a> and <a href="http://docs.python.org/library/stdtypes.html#dict.update"><code>dict.update()</code></a>, but each only do half of what I want - with <code>dict.setdefault()</code>, I have to loop over each variable in <code>defaults</code>; but with <code>dict.update()</code>, <code>defaults</code> will blow away any pre-existing values in <code>mydict</code>.</p>
<p>Is there some functionality I'm not finding built into Python that can do this? And if not, is there a more Pythonic way of writing a loop to repeatedly call <code>dict.setdefaults()</code> than this:</p>
<pre><code>for key in defaults.keys():
mydict.setdefault(key, defaults[key])
</code></pre>
<p>Context: I'm writing up some data in Python that controls how to parse an XML tree. There's a dict for each node (i.e., how to process each node), and I'd rather the data I write up be sparse, but filled in with defaults. The example code is just an example... real code has many more key/value pairs in the default dict.</p>
<p>(I realize this whole question is but a minor quibble, but it's been bothering me, so I was wondering if there was a better way to do this that I am not aware of.)</p>
| 7 | 2009-05-11T20:01:46Z | 849,877 | <p>You can do this the same way Python's collections.DefaultDict works:</p>
<pre><code>class MultiDefaultDict(dict):
def __init__(self, defaults, **kwargs):
self.defaults = defaults
self.update(kwargs)
def __missing__(self, key):
return self.defaults[key]
>>> mydict2 = MultiDefaultDict(defaults, a=0)
>>> mydict2['a']
0
>>> mydict2['b']
10
>>> mydict2
{'a': 0}
</code></pre>
<p>The other solutions posted so far duplicate all the default values; this one shares them, as requested. You may or may not want to override other dict methods like __contains__(), __iter__(), items(), keys(), values() -- this class as defined here iterates over the non-default items only.</p>
| 5 | 2009-05-11T20:11:44Z | [
"python",
"dictionary"
] |
Is there a way to set multiple defaults on a Python dict using another dict? | 849,806 | <p>Suppose I've got two dicts in Python:</p>
<pre><code>mydict = { 'a': 0 }
defaults = {
'a': 5,
'b': 10,
'c': 15
}
</code></pre>
<p>I want to be able to expand <code>mydict</code> using the default values from <code>defaults</code>, such that 'a' remains the same but 'b' and 'c' are filled in. I know about <a href="http://docs.python.org/library/stdtypes.html#dict.setdefault"><code>dict.setdefault()</code></a> and <a href="http://docs.python.org/library/stdtypes.html#dict.update"><code>dict.update()</code></a>, but each only do half of what I want - with <code>dict.setdefault()</code>, I have to loop over each variable in <code>defaults</code>; but with <code>dict.update()</code>, <code>defaults</code> will blow away any pre-existing values in <code>mydict</code>.</p>
<p>Is there some functionality I'm not finding built into Python that can do this? And if not, is there a more Pythonic way of writing a loop to repeatedly call <code>dict.setdefaults()</code> than this:</p>
<pre><code>for key in defaults.keys():
mydict.setdefault(key, defaults[key])
</code></pre>
<p>Context: I'm writing up some data in Python that controls how to parse an XML tree. There's a dict for each node (i.e., how to process each node), and I'd rather the data I write up be sparse, but filled in with defaults. The example code is just an example... real code has many more key/value pairs in the default dict.</p>
<p>(I realize this whole question is but a minor quibble, but it's been bothering me, so I was wondering if there was a better way to do this that I am not aware of.)</p>
| 7 | 2009-05-11T20:01:46Z | 850,402 | <p>Personally I like to append the dictionary object. It works mostly like a dictionary except that you have to create the object first.</p>
<pre><code>class d_dict(dict):
'Dictionary object with easy defaults.'
def __init__(self,defaults={}):
self.setdefault(defaults)
def setdefault(self,defaults):
for key, value in defaults.iteritems():
if not key in self:
dict.__setitem__(self,key,value)
</code></pre>
<p>This provides the exact same functionality as the dict type except that it overrides the setdefault() method and will take a dictionary containing one or more items. You can set the defaults at creation.</p>
<p>This is just a personal preference. As I understand all that dict.setdefault() does is set the items which haven't been set yet. So probably the simplest in place option is:</p>
<pre><code>new_dict = default_dict.copy()
new_dict.update({'a':0})
</code></pre>
<p>However, if you do this more than once you might make a function out of this. At this point it may just be easier to use a custom dict object, rather than constantly adding defaults to your dictionaries.</p>
| 0 | 2009-05-11T22:36:35Z | [
"python",
"dictionary"
] |
Python -- Regex -- How to find a string between two sets of strings | 849,912 | <p>Consider the following:</p>
<pre><code><div id=hotlinklist>
<a href="foo1.com">Foo1</a>
<div id=hotlink>
<a href="/">Home</a>
</div>
<div id=hotlink>
<a href="/extract">Extract</a>
</div>
<div id=hotlink>
<a href="/sitemap">Sitemap</a>
</div>
</div>
</code></pre>
<p>How would you go about taking out the sitemap line with regex in <strong>python</strong>?</p>
<pre><code><a href="/sitemap">Sitemap</a>
</code></pre>
<p>The following can be used to pull out the anchor tags.</p>
<pre><code>'/<a(.*?)a>/i'
</code></pre>
<p>However, there are multiple anchor tags. Also there are multiple hotlink(s) so we can't really use them either?</p>
| 5 | 2009-05-11T20:23:49Z | 849,950 | <p>Don't use a regex. Use <a href="http://www.crummy.com/software/BeautifulSoup/">BeautfulSoup</a>, an HTML parser.</p>
<pre><code>from BeautifulSoup import BeautifulSoup
html = \
"""
<div id=hotlinklist>
<a href="foo1.com">Foo1</a>
<div id=hotlink>
<a href="/">Home</a>
</div>
<div id=hotlink>
<a href="/extract">Extract</a>
</div>
<div id=hotlink>
<a href="/sitemap">Sitemap</a>
</div>
</div>"""
soup = BeautifulSoup(html)
soup.findAll("div",id="hotlink")[2].a
# <a href="/sitemap">Sitemap</a>
</code></pre>
| 14 | 2009-05-11T20:32:41Z | [
"python",
"regex",
"string",
"tags"
] |
Python -- Regex -- How to find a string between two sets of strings | 849,912 | <p>Consider the following:</p>
<pre><code><div id=hotlinklist>
<a href="foo1.com">Foo1</a>
<div id=hotlink>
<a href="/">Home</a>
</div>
<div id=hotlink>
<a href="/extract">Extract</a>
</div>
<div id=hotlink>
<a href="/sitemap">Sitemap</a>
</div>
</div>
</code></pre>
<p>How would you go about taking out the sitemap line with regex in <strong>python</strong>?</p>
<pre><code><a href="/sitemap">Sitemap</a>
</code></pre>
<p>The following can be used to pull out the anchor tags.</p>
<pre><code>'/<a(.*?)a>/i'
</code></pre>
<p>However, there are multiple anchor tags. Also there are multiple hotlink(s) so we can't really use them either?</p>
| 5 | 2009-05-11T20:23:49Z | 849,971 | <p>Parsing HTML with regular expression is a bad idea!</p>
<p>Think about the following piece of html</p>
<pre><code><a></a > <!-- legal html, but won't pass your regex -->
<a href="/sitemap">Sitemap<!-- proof that a>b iff ab>1 --></a>
</code></pre>
<p>There are many more such examples. Regular expressions are good for many things, but not for parsing HTML.</p>
<p>You should consider using <a href="http://www.crummy.com/software/BeautifulSoup/">Beautiful Soup</a> python HTML parser.</p>
<p>Anyhow, a ad-hoc solution using regex is</p>
<pre><code>import re
data = """
<div id=hotlinklist>
<a href="foo1.com">Foo1</a>
<div id=hotlink>
<a href="/">Home</a>
</div>
<div id=hotlink>
<a href="/extract">Extract</a>
</div>
<div id=hotlink>
<a href="/sitemap">Sitemap</a>
</div>
</div>
"""
e = re.compile('<a *[^>]*>.*</a *>')
print e.findall(data)
</code></pre>
<p>Output:</p>
<pre><code>>>> e.findall(data)
['<a href="foo1.com">Foo1</a>', '<a href="/">Home</a>', '<a href="/extract">Extract</a>', '<a href="/sitemap">Sitemap</a>']
</code></pre>
| 6 | 2009-05-11T20:37:51Z | [
"python",
"regex",
"string",
"tags"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.