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 |
---|---|---|---|---|---|---|---|---|---|
How do I parse a listing of files to get just the filenames in python? | 237,699 | <p>So lets say I'm using Python's <a href="http://www.python.org/doc/2.5.2/lib/module-ftplib.html" rel="nofollow">ftplib</a> to retrieve a list of log files from an FTP server. How would I parse that list of files to get just the file names (the last column) inside a list? See the link above for example output.</p>
| 2 | 2008-10-26T07:42:17Z | 237,709 | <p>Since every filename in the output starts at the same column, all you have to do is get the position of the dot on the first line:</p>
<blockquote>
<p><code>drwxrwsr-x 5 ftp-usr pdmaint 1536 Mar 20 09:48 .</code></p>
</blockquote>
<p>Then slice the filename out of the other lines using the position of that dot as the starting index.</p>
<p>Since the dot is the last character on the line, you can use the length of the line minus 1 as the index. So the final code is something like this:</p>
<pre><code>lines = ftp.retrlines('LIST')
lines = lines.split("\n") # This should split the string into an array of lines
filename_index = len(lines[0]) - 1
files = []
for line in lines:
files.append(line[filename_index:])
</code></pre>
| 1 | 2008-10-26T08:00:33Z | [
"python",
"parsing",
"scripting"
] |
How do I parse a listing of files to get just the filenames in python? | 237,699 | <p>So lets say I'm using Python's <a href="http://www.python.org/doc/2.5.2/lib/module-ftplib.html" rel="nofollow">ftplib</a> to retrieve a list of log files from an FTP server. How would I parse that list of files to get just the file names (the last column) inside a list? See the link above for example output.</p>
| 2 | 2008-10-26T07:42:17Z | 237,721 | <p>Is there any reason why <strong>ftplib.FTP.nlst()</strong> won't work for you? I just checked and it returns only names of the files in a given directory.</p>
| 1 | 2008-10-26T08:15:24Z | [
"python",
"parsing",
"scripting"
] |
How do I parse a listing of files to get just the filenames in python? | 237,699 | <p>So lets say I'm using Python's <a href="http://www.python.org/doc/2.5.2/lib/module-ftplib.html" rel="nofollow">ftplib</a> to retrieve a list of log files from an FTP server. How would I parse that list of files to get just the file names (the last column) inside a list? See the link above for example output.</p>
| 2 | 2008-10-26T07:42:17Z | 237,769 | <h2>This best answer</h2>
<p>You may want to use ftp.nlst() instead of ftp.retrlines(). It will give you exactly what you want.</p>
<p>If you cant, read the following :</p>
<h2>Generators for sysadmin processes</h2>
<p>In his now famous review, <a href="http://www.dabeaz.com/generators/Generators.pdf" rel="nofollow">Generator Tricks For Systems Programmers An Introduction</a>, David M. Beazley gives a lot of receipes to answer to this kind of data problem with wuick and reusable code.</p>
<p>E.G :</p>
<pre><code># empty list that will receive all the log entry
log = []
# we pass a callback function bypass the print_line that would be called by retrlines
# we do that only because we cannot use something better than retrlines
ftp.retrlines('LIST', callback=log.append)
# we use rsplit because it more efficient in our case if we have a big file
files = (line.rsplit(None, 1)[1] for line in log)
# get you file list
files_list = list(files)
</code></pre>
<p>Why don't we generate immediately the list ?</p>
<p>Well, it's because doing it this way offer you much flexibility : you can apply any intermediate generator to filter files before turning it into files_list : it's just like pipe, add a line, you add a process without overheat (since it's generators). And if you get rid off retrlines, it still work be it's even better because you don't store the liste even one time.</p>
<p>EDIT : well, I read the comment to the other answer and it says that this won't work if there is any space in the name.</p>
<p>Cool, this will illustrate why this method is handy. If you want to change something in the process, you just change a line. Swap :</p>
<pre><code>files = (line.rsplit(None, 1)[1] for line in log)
</code></pre>
<p>and</p>
<pre><code># join split the line, get all the item from the field 8 then join them
files = (' '.join(line.split()[8:]) for line in log)
</code></pre>
<p>Ok, this may no be obvious here, but for huge batch process scripts, it's nice :-)</p>
| 3 | 2008-10-26T09:09:11Z | [
"python",
"parsing",
"scripting"
] |
How do I parse a listing of files to get just the filenames in python? | 237,699 | <p>So lets say I'm using Python's <a href="http://www.python.org/doc/2.5.2/lib/module-ftplib.html" rel="nofollow">ftplib</a> to retrieve a list of log files from an FTP server. How would I parse that list of files to get just the file names (the last column) inside a list? See the link above for example output.</p>
| 2 | 2008-10-26T07:42:17Z | 3,114,591 | <p>If the FTP server supports the <code>MLSD</code> command, then please see section âsingle directory caseâ from <a href="http://stackoverflow.com/questions/2867217/how-to-delete-files-with-a-python-script-from-a-ftp-server-which-are-older-than-7/3114477#3114477">that</a> answer.</p>
<p>Use an instance (say <code>ftpd</code>) of the <code>FTPDirectory</code> class, call its <code>.getdata</code> method with connected <code>ftplib.FTP</code> instance in the correct folder, then you can:</p>
<pre><code>directory_filenames= [ftpfile.name for ftpfile in ftpd.files]
</code></pre>
| 1 | 2010-06-24T23:17:14Z | [
"python",
"parsing",
"scripting"
] |
Daylight savings time change affecting the outcome of saving and loading an icalendar file? | 237,731 | <p>I have some unit tests that started failing today after a switch in daylight savings time.</p>
<p>We're using the <a href="http://codespeak.net/icalendar/" rel="nofollow">iCalendar python module</a> to load and save ics files.</p>
<p>The following script is a simplified version of our test. The script works fine in 'summer' and fails in 'winter', as of this morning. The failure can be reproduced by setting the clock back manually. Here's the output of the script:</p>
<pre><code>[root@ana icalendar]# date 10250855
Sat Oct 25 08:55:00 CEST 2008
[root@ana icalendar]# python dst.py
DTSTART should represent datetime.datetime(2015, 4, 4, 8, 0, tzinfo=tzfile('/usr/share/zoneinfo/Europe/Brussels')) Brussels time
DTSTART should represent datetime.datetime(2015, 4, 4, 6, 0, tzinfo=<icalendar.prop.UTC object at 0x956b5cc>) UTC
DTSTART represents datetime.datetime(2015, 4, 4, 6, 0, tzinfo=<icalendar.prop.UTC object at 0x956b5cc>) Brussels time
[root@ana icalendar]# date 10260855
Sun Oct 26 08:55:00 CET 2008
[root@ana icalendar]# python dst.py
DTSTART should represent datetime.datetime(2015, 4, 4, 8, 0, tzinfo=tzfile('/usr/share/zoneinfo/Europe/Brussels')) Brussels time
DTSTART should represent datetime.datetime(2015, 4, 4, 6, 0, tzinfo=<icalendar.prop.UTC object at 0x96615cc>) UTC
DTSTART represents datetime.datetime(2015, 4, 4, 7, 0, tzinfo=<icalendar.prop.UTC object at 0x96615cc>) Brussels time
Traceback (most recent call last):
File "dst.py", line 58, in <module>
start.dt, startUTCExpected)
AssertionError: calendar's datetime.datetime(2015, 4, 4, 7, 0, tzinfo=<icalendar.prop.UTC object at 0x96615cc>) != expected datetime.datetime(2015, 4, 4, 6, 0, tzinfo=<icalendar.prop.UTC object at 0x96615cc>)
</code></pre>
<p>And here is the <a href="https://thomas.apestaart.org/thomas/trac/browser/tests/icalendar/dst.py" rel="nofollow">whole script</a>.</p>
<p>So, questions:
- why would my current time (and which part of DST I'm in) affect the loading/saving/parsing of timestamps ? I would expect it not to.
- how would you unit test this kind of bug, if it is a bug ? Obviously, I don't want my unit tests to reset the clock on my computer.</p>
| 1 | 2008-10-26T08:26:31Z | 237,785 | <p>Without looking at your code (and the quoted test-run-script my brain fails to understand right now)
I notice that you try to get a time that is in a different timezone than the one you are at.
(Think of DST as a another TIMEZONE instead of +-1 hour from current timezone).
This could (depending on how you do it) lead to a gain or loss of hours.
(Like when your flying, you start at one time and getting to your location before you started, all in local time)</p>
| 1 | 2008-10-26T09:31:08Z | [
"python",
"unit-testing",
"icalendar"
] |
Formatting dict.items() for wxPython | 237,859 | <p>I have a text box in wxPython that takes the output of dictionary.items() and displays it to the user as items are added to the dictionary. However, the raw data is very ugly, looking like </p>
<pre><code>[(u'BC',45)
(u'CHM',25)
(u'CPM',30)]
</code></pre>
<p>I know dictionary.items() is a list of tuples, but I can't seem to figure out how to make a nice format that is also compatible with the SetValue() method of wxPython.</p>
<p>I've tried iterating through the list and tuples. If I use a <em>print</em> statement, the output is fine. But when I replace the <em>print</em> statement with SetValue(), it only seems to get the last value of each tuple, rather than both items in the tuple.</p>
<p>I've also tried creating a string and passing that string to SetValue() but, again, I can only get one item in the tuple or the other, not both.</p>
<p>Any suggestions?</p>
<p><hr /></p>
<p><strong>Edit:</strong> Yes, I am passing the results of the dictionary.items() to a text field in a wxPython application. Rather than having the results like above, I'm simply looking for something like:</p>
<pre><code>BC 45
CHM 25
CMP 30
</code></pre>
<p>Nothing special, just simply pulling each value from each tuple and making a visual list.</p>
<p>I have tried making a string format and passing that to SetValue() but it gets hung up on the two values in the tuple. It will either double print each string and add the integers together or it simply returns the integer, depending on how I format it.</p>
| 2 | 2008-10-26T10:50:34Z | 237,872 | <p>Maybe the <a href="http://www.python.org/doc/2.5.2/lib/module-pprint.html" rel="nofollow">pretty print</a> module will help:</p>
<pre><code>>>> import pprint
>>> pprint.pformat({ "my key": "my value"})
"{'my key': 'my value'}"
>>>
</code></pre>
| 0 | 2008-10-26T11:02:06Z | [
"python",
"dictionary",
"wxpython"
] |
Formatting dict.items() for wxPython | 237,859 | <p>I have a text box in wxPython that takes the output of dictionary.items() and displays it to the user as items are added to the dictionary. However, the raw data is very ugly, looking like </p>
<pre><code>[(u'BC',45)
(u'CHM',25)
(u'CPM',30)]
</code></pre>
<p>I know dictionary.items() is a list of tuples, but I can't seem to figure out how to make a nice format that is also compatible with the SetValue() method of wxPython.</p>
<p>I've tried iterating through the list and tuples. If I use a <em>print</em> statement, the output is fine. But when I replace the <em>print</em> statement with SetValue(), it only seems to get the last value of each tuple, rather than both items in the tuple.</p>
<p>I've also tried creating a string and passing that string to SetValue() but, again, I can only get one item in the tuple or the other, not both.</p>
<p>Any suggestions?</p>
<p><hr /></p>
<p><strong>Edit:</strong> Yes, I am passing the results of the dictionary.items() to a text field in a wxPython application. Rather than having the results like above, I'm simply looking for something like:</p>
<pre><code>BC 45
CHM 25
CMP 30
</code></pre>
<p>Nothing special, just simply pulling each value from each tuple and making a visual list.</p>
<p>I have tried making a string format and passing that to SetValue() but it gets hung up on the two values in the tuple. It will either double print each string and add the integers together or it simply returns the integer, depending on how I format it.</p>
| 2 | 2008-10-26T10:50:34Z | 237,937 | <pre><code>text_for_display = '\n'.join(item + u' ' + unicode(value) for item, value in my_dictionary.items())
</code></pre>
| 0 | 2008-10-26T12:10:39Z | [
"python",
"dictionary",
"wxpython"
] |
Formatting dict.items() for wxPython | 237,859 | <p>I have a text box in wxPython that takes the output of dictionary.items() and displays it to the user as items are added to the dictionary. However, the raw data is very ugly, looking like </p>
<pre><code>[(u'BC',45)
(u'CHM',25)
(u'CPM',30)]
</code></pre>
<p>I know dictionary.items() is a list of tuples, but I can't seem to figure out how to make a nice format that is also compatible with the SetValue() method of wxPython.</p>
<p>I've tried iterating through the list and tuples. If I use a <em>print</em> statement, the output is fine. But when I replace the <em>print</em> statement with SetValue(), it only seems to get the last value of each tuple, rather than both items in the tuple.</p>
<p>I've also tried creating a string and passing that string to SetValue() but, again, I can only get one item in the tuple or the other, not both.</p>
<p>Any suggestions?</p>
<p><hr /></p>
<p><strong>Edit:</strong> Yes, I am passing the results of the dictionary.items() to a text field in a wxPython application. Rather than having the results like above, I'm simply looking for something like:</p>
<pre><code>BC 45
CHM 25
CMP 30
</code></pre>
<p>Nothing special, just simply pulling each value from each tuple and making a visual list.</p>
<p>I have tried making a string format and passing that to SetValue() but it gets hung up on the two values in the tuple. It will either double print each string and add the integers together or it simply returns the integer, depending on how I format it.</p>
| 2 | 2008-10-26T10:50:34Z | 237,941 | <p>use % formatting (known in C as sprintf), e.g:</p>
<pre><code>"%10s - %d" % dict.items()[0]
</code></pre>
<p>Number of <em>% conversion specifications</em> in the format string should match tuple length, in the dict.items() case, 2. The result of the string formatting operator is a string, so that using it as an argument to SetValue() is no problem. To translate the whole dict to a string:</p>
<pre><code>'\n'.join(("%10s - %d" % t) for t in dict.items())
</code></pre>
<p>The format conversion types are specified in the <a href="http://www.python.org/doc/2.5.2/lib/typesseq-strings.html" rel="nofollow">doc</a>.</p>
| 0 | 2008-10-26T12:17:42Z | [
"python",
"dictionary",
"wxpython"
] |
Formatting dict.items() for wxPython | 237,859 | <p>I have a text box in wxPython that takes the output of dictionary.items() and displays it to the user as items are added to the dictionary. However, the raw data is very ugly, looking like </p>
<pre><code>[(u'BC',45)
(u'CHM',25)
(u'CPM',30)]
</code></pre>
<p>I know dictionary.items() is a list of tuples, but I can't seem to figure out how to make a nice format that is also compatible with the SetValue() method of wxPython.</p>
<p>I've tried iterating through the list and tuples. If I use a <em>print</em> statement, the output is fine. But when I replace the <em>print</em> statement with SetValue(), it only seems to get the last value of each tuple, rather than both items in the tuple.</p>
<p>I've also tried creating a string and passing that string to SetValue() but, again, I can only get one item in the tuple or the other, not both.</p>
<p>Any suggestions?</p>
<p><hr /></p>
<p><strong>Edit:</strong> Yes, I am passing the results of the dictionary.items() to a text field in a wxPython application. Rather than having the results like above, I'm simply looking for something like:</p>
<pre><code>BC 45
CHM 25
CMP 30
</code></pre>
<p>Nothing special, just simply pulling each value from each tuple and making a visual list.</p>
<p>I have tried making a string format and passing that to SetValue() but it gets hung up on the two values in the tuple. It will either double print each string and add the integers together or it simply returns the integer, depending on how I format it.</p>
| 2 | 2008-10-26T10:50:34Z | 237,998 | <p>That data seems much better displayed as a Table/Grid.</p>
| 0 | 2008-10-26T13:16:30Z | [
"python",
"dictionary",
"wxpython"
] |
Formatting dict.items() for wxPython | 237,859 | <p>I have a text box in wxPython that takes the output of dictionary.items() and displays it to the user as items are added to the dictionary. However, the raw data is very ugly, looking like </p>
<pre><code>[(u'BC',45)
(u'CHM',25)
(u'CPM',30)]
</code></pre>
<p>I know dictionary.items() is a list of tuples, but I can't seem to figure out how to make a nice format that is also compatible with the SetValue() method of wxPython.</p>
<p>I've tried iterating through the list and tuples. If I use a <em>print</em> statement, the output is fine. But when I replace the <em>print</em> statement with SetValue(), it only seems to get the last value of each tuple, rather than both items in the tuple.</p>
<p>I've also tried creating a string and passing that string to SetValue() but, again, I can only get one item in the tuple or the other, not both.</p>
<p>Any suggestions?</p>
<p><hr /></p>
<p><strong>Edit:</strong> Yes, I am passing the results of the dictionary.items() to a text field in a wxPython application. Rather than having the results like above, I'm simply looking for something like:</p>
<pre><code>BC 45
CHM 25
CMP 30
</code></pre>
<p>Nothing special, just simply pulling each value from each tuple and making a visual list.</p>
<p>I have tried making a string format and passing that to SetValue() but it gets hung up on the two values in the tuple. It will either double print each string and add the integers together or it simply returns the integer, depending on how I format it.</p>
| 2 | 2008-10-26T10:50:34Z | 238,453 | <p>There is no built-in dictionary method that would return your desired result.</p>
<p>You can, however, achieve your goal by creating a helper function that will format the dictionary, e.g.:</p>
<pre><code>def getNiceDictRepr(aDict):
return '\n'.join('%s %s' % t for t in aDict.iteritems())
</code></pre>
<p>This will produce your exact desired output:</p>
<pre><code>>>> myDict = dict([(u'BC',45), (u'CHM',25), (u'CPM',30)])
>>> print getNiceDictRepr(myDict)
BC 45
CHM 25
CPM 30
</code></pre>
<p>Then, in your application code, you can use it by passing it to <code>SetValue</code>:</p>
<pre><code>self.textCtrl.SetValue(getNiceDictRepr(myDict))
</code></pre>
| 4 | 2008-10-26T18:59:14Z | [
"python",
"dictionary",
"wxpython"
] |
Formatting dict.items() for wxPython | 237,859 | <p>I have a text box in wxPython that takes the output of dictionary.items() and displays it to the user as items are added to the dictionary. However, the raw data is very ugly, looking like </p>
<pre><code>[(u'BC',45)
(u'CHM',25)
(u'CPM',30)]
</code></pre>
<p>I know dictionary.items() is a list of tuples, but I can't seem to figure out how to make a nice format that is also compatible with the SetValue() method of wxPython.</p>
<p>I've tried iterating through the list and tuples. If I use a <em>print</em> statement, the output is fine. But when I replace the <em>print</em> statement with SetValue(), it only seems to get the last value of each tuple, rather than both items in the tuple.</p>
<p>I've also tried creating a string and passing that string to SetValue() but, again, I can only get one item in the tuple or the other, not both.</p>
<p>Any suggestions?</p>
<p><hr /></p>
<p><strong>Edit:</strong> Yes, I am passing the results of the dictionary.items() to a text field in a wxPython application. Rather than having the results like above, I'm simply looking for something like:</p>
<pre><code>BC 45
CHM 25
CMP 30
</code></pre>
<p>Nothing special, just simply pulling each value from each tuple and making a visual list.</p>
<p>I have tried making a string format and passing that to SetValue() but it gets hung up on the two values in the tuple. It will either double print each string and add the integers together or it simply returns the integer, depending on how I format it.</p>
| 2 | 2008-10-26T10:50:34Z | 297,811 | <p>I figured out a "better" way of formatting the output. As usual, I was trying to nuke it out when a more elegant method will do.</p>
<pre><code>for key, value in sorted(self.dict.items()):
self.current_list.WriteText(key + " " + str(self.dict[key]) + "\n")
</code></pre>
<p>This way also sorts the dictionary alphabetically, which is a big help when identifying items that have already been selected or used.</p>
| 0 | 2008-11-18T03:57:39Z | [
"python",
"dictionary",
"wxpython"
] |
Refactoring "to hit" values for a game | 237,876 | <p>I'm making a game and one of the methods calculates a character's base hit numbers based on skill values. The method currently calculates each value individually, since each skill can be used at short, medium, and long range.</p>
<p>I originally thought I could combine the skills into a tuple and iterate over it, dynamically creating each hit number. But I don't know if it's actually possible, since I currently have each hit number assigned to it's own variable.</p>
<p>I also thought about creating a method for each range, and passing the tuple as an argument. I could create a new tuple or list with the resulting values and then assign them to the individual variables, but I don't see how it would be any better than do it this way, except that it won't look so copy & pasted.</p>
<p>Here's what I currently have:</p>
<pre><code> def calcBaseHitNumbers(self, dict):
"""Calculate character's base hit numbers depending on skill level."""
self.skill_dict = dict
self.rifle = self.skill_dict.get('CRM', 0)
self.pistol = self.skill_dict.get('PST', 0)
self.big_gun = self.skill_dict.get('LCG', 0)
self.heavy_weapon = self.skill_dict.get('HW', 0)
self.bow = self.skill_dict.get('LB', 0)
#self.skill_tuple = (self.rifle, self.pistol, self.big_gun, self.heavy_weapon,
# self.bow)
#---Short range
## for skill in self.skill_tuple:
## self.base_hit_short = skill * 0.6
self.charAttribs.bhCRM_short = self.rifle * 0.6
self.charAttribs.bhPST_short = self.pistol * 0.6
self.charAttribs.bhHW_short = self.heavy_weapon * 0.6
self.charAttribs.bhLCG_short = self.big_gun * 0.6
self.charAttribs.bhLB_short = self.bow * 0.6
#---Med range
self.charAttribs.bhCRM_med = self.rifle * 0.3
self.charAttribs.bhPST_med = self.pistol * 0.3
self.charAttribs.bhHW_med = self.heavy_weapon * 0.3
self.charAttribs.bhLCG_med = self.big_gun * 0.3
self.charAttribs.bhLB_med = self.bow * 0.3
#---Long range
self.charAttribs.bhCRM_long = self.rifle * 0.1
self.charAttribs.bhPST_long = self.pistol * 0.1
self.charAttribs.bhHW_long = self.heavy_weapon * 0.1
self.charAttribs.bhLCG_long = self.big_gun * 0.1
self.charAttribs.bhLB_long = self.bow * 0.1
</code></pre>
<p>How would you refactor this so it's more dynamic?</p>
<p><hr /></p>
<p><strong>Edit:</strong> I guess what I want to do is something like this:
Have a tuple (like the one I commented out) and iterate over it 3 times, each time making a new value (for each skill) based on the modifier for each particular range. The resulting value is then automatically assigned to it's respective variable.</p>
<p>In my head, it makes sense. But when I actually try to code it, I get lost. The problem, I think, is that this is the first "real" program I've written; all I've done before are small scripts.</p>
<p>This is only the 0.1 version of my program, so it's not critical to refactor it now. However, it seems very un-Pythonic to do this manually and I also want to "future-proof" this in case things change down the road.</p>
| 1 | 2008-10-26T11:08:32Z | 237,901 | <p>@Vinko: perhaps make calcBaseHitNumbers, do the "if not self.calculatedBase:" check internally, and just no-op if it's been done before. That said, I can't see the pressing need for precalculating this information. But I'm no Python performance expert.</p>
| 0 | 2008-10-26T11:35:07Z | [
"python",
"refactoring"
] |
Refactoring "to hit" values for a game | 237,876 | <p>I'm making a game and one of the methods calculates a character's base hit numbers based on skill values. The method currently calculates each value individually, since each skill can be used at short, medium, and long range.</p>
<p>I originally thought I could combine the skills into a tuple and iterate over it, dynamically creating each hit number. But I don't know if it's actually possible, since I currently have each hit number assigned to it's own variable.</p>
<p>I also thought about creating a method for each range, and passing the tuple as an argument. I could create a new tuple or list with the resulting values and then assign them to the individual variables, but I don't see how it would be any better than do it this way, except that it won't look so copy & pasted.</p>
<p>Here's what I currently have:</p>
<pre><code> def calcBaseHitNumbers(self, dict):
"""Calculate character's base hit numbers depending on skill level."""
self.skill_dict = dict
self.rifle = self.skill_dict.get('CRM', 0)
self.pistol = self.skill_dict.get('PST', 0)
self.big_gun = self.skill_dict.get('LCG', 0)
self.heavy_weapon = self.skill_dict.get('HW', 0)
self.bow = self.skill_dict.get('LB', 0)
#self.skill_tuple = (self.rifle, self.pistol, self.big_gun, self.heavy_weapon,
# self.bow)
#---Short range
## for skill in self.skill_tuple:
## self.base_hit_short = skill * 0.6
self.charAttribs.bhCRM_short = self.rifle * 0.6
self.charAttribs.bhPST_short = self.pistol * 0.6
self.charAttribs.bhHW_short = self.heavy_weapon * 0.6
self.charAttribs.bhLCG_short = self.big_gun * 0.6
self.charAttribs.bhLB_short = self.bow * 0.6
#---Med range
self.charAttribs.bhCRM_med = self.rifle * 0.3
self.charAttribs.bhPST_med = self.pistol * 0.3
self.charAttribs.bhHW_med = self.heavy_weapon * 0.3
self.charAttribs.bhLCG_med = self.big_gun * 0.3
self.charAttribs.bhLB_med = self.bow * 0.3
#---Long range
self.charAttribs.bhCRM_long = self.rifle * 0.1
self.charAttribs.bhPST_long = self.pistol * 0.1
self.charAttribs.bhHW_long = self.heavy_weapon * 0.1
self.charAttribs.bhLCG_long = self.big_gun * 0.1
self.charAttribs.bhLB_long = self.bow * 0.1
</code></pre>
<p>How would you refactor this so it's more dynamic?</p>
<p><hr /></p>
<p><strong>Edit:</strong> I guess what I want to do is something like this:
Have a tuple (like the one I commented out) and iterate over it 3 times, each time making a new value (for each skill) based on the modifier for each particular range. The resulting value is then automatically assigned to it's respective variable.</p>
<p>In my head, it makes sense. But when I actually try to code it, I get lost. The problem, I think, is that this is the first "real" program I've written; all I've done before are small scripts.</p>
<p>This is only the 0.1 version of my program, so it's not critical to refactor it now. However, it seems very un-Pythonic to do this manually and I also want to "future-proof" this in case things change down the road.</p>
| 1 | 2008-10-26T11:08:32Z | 237,905 | <p>Lets see if I understand you scenario: each weapon has its own distinct hit point so a rifle may have 1, a heavy weapon may have 2 etc. Then each character has a short, medium and long value to be multiplied by the hit point of the weapon.</p>
<p>You should consider using a Strategy design. That is create a weapon superclass with a hit point property. Create sub class weapons for rifle, pistol, bow etc. I am sure that the differences between the weapons are more than just the hit points.</p>
<p>Then the Character has one or more weapons depending on your gameplay. To calculate the hit point for a particular weapon is as simple as</p>
<pre><code>current_weapon * self.medium
</code></pre>
<p>If you decide to add more weapons later on then you do not have to edit your Character code because your character can handle any weapon.</p>
<p>In Pseudo Python</p>
<pre><code>class Weapon
hit = 1
#other properties of weapon
class Rifle(Weapon)
#other properties of Rifle
class Pistol(Weapon)
#other properties of Pistol
class Character
weapon = Rifle()
long=0.6
def calcHit()
return self.long*weapon.hit
john = Character()
john.weapon= Rifle()
john.calcHit
</code></pre>
| 1 | 2008-10-26T11:39:29Z | [
"python",
"refactoring"
] |
Refactoring "to hit" values for a game | 237,876 | <p>I'm making a game and one of the methods calculates a character's base hit numbers based on skill values. The method currently calculates each value individually, since each skill can be used at short, medium, and long range.</p>
<p>I originally thought I could combine the skills into a tuple and iterate over it, dynamically creating each hit number. But I don't know if it's actually possible, since I currently have each hit number assigned to it's own variable.</p>
<p>I also thought about creating a method for each range, and passing the tuple as an argument. I could create a new tuple or list with the resulting values and then assign them to the individual variables, but I don't see how it would be any better than do it this way, except that it won't look so copy & pasted.</p>
<p>Here's what I currently have:</p>
<pre><code> def calcBaseHitNumbers(self, dict):
"""Calculate character's base hit numbers depending on skill level."""
self.skill_dict = dict
self.rifle = self.skill_dict.get('CRM', 0)
self.pistol = self.skill_dict.get('PST', 0)
self.big_gun = self.skill_dict.get('LCG', 0)
self.heavy_weapon = self.skill_dict.get('HW', 0)
self.bow = self.skill_dict.get('LB', 0)
#self.skill_tuple = (self.rifle, self.pistol, self.big_gun, self.heavy_weapon,
# self.bow)
#---Short range
## for skill in self.skill_tuple:
## self.base_hit_short = skill * 0.6
self.charAttribs.bhCRM_short = self.rifle * 0.6
self.charAttribs.bhPST_short = self.pistol * 0.6
self.charAttribs.bhHW_short = self.heavy_weapon * 0.6
self.charAttribs.bhLCG_short = self.big_gun * 0.6
self.charAttribs.bhLB_short = self.bow * 0.6
#---Med range
self.charAttribs.bhCRM_med = self.rifle * 0.3
self.charAttribs.bhPST_med = self.pistol * 0.3
self.charAttribs.bhHW_med = self.heavy_weapon * 0.3
self.charAttribs.bhLCG_med = self.big_gun * 0.3
self.charAttribs.bhLB_med = self.bow * 0.3
#---Long range
self.charAttribs.bhCRM_long = self.rifle * 0.1
self.charAttribs.bhPST_long = self.pistol * 0.1
self.charAttribs.bhHW_long = self.heavy_weapon * 0.1
self.charAttribs.bhLCG_long = self.big_gun * 0.1
self.charAttribs.bhLB_long = self.bow * 0.1
</code></pre>
<p>How would you refactor this so it's more dynamic?</p>
<p><hr /></p>
<p><strong>Edit:</strong> I guess what I want to do is something like this:
Have a tuple (like the one I commented out) and iterate over it 3 times, each time making a new value (for each skill) based on the modifier for each particular range. The resulting value is then automatically assigned to it's respective variable.</p>
<p>In my head, it makes sense. But when I actually try to code it, I get lost. The problem, I think, is that this is the first "real" program I've written; all I've done before are small scripts.</p>
<p>This is only the 0.1 version of my program, so it's not critical to refactor it now. However, it seems very un-Pythonic to do this manually and I also want to "future-proof" this in case things change down the road.</p>
| 1 | 2008-10-26T11:08:32Z | 237,906 | <p>What sense of dynamic do you mean? What is likely to vary - the number of skills, or the weighting factors, the number of ranges (short, med, long) or all of these?</p>
<p>What happens to the (e.g.) bhPST_* values afterwards - do they get combined into one number?</p>
<p>One thing that leaps out is that the list of skills is hardwired in the code - I would be inclined to replace the bh variables with a method</p>
<p>So (please take into account I don't know the first thing about Python :) )</p>
<pre><code>def bh_short(self, key)
skill = self.skill_dict.get(key, 0)
return skill * 0.6
</code></pre>
<p>Now you can keep a list of skills that contribute to hit points and iterate over that calling bh_short etc.</p>
<p>Possibly also pass the range (long med short) unto the function, or return all three values - this all depends on what you're going to do next with the calculated hitpoints.</p>
<p>Basically, we need more information about the context this is to be used in</p>
| 0 | 2008-10-26T11:39:38Z | [
"python",
"refactoring"
] |
Refactoring "to hit" values for a game | 237,876 | <p>I'm making a game and one of the methods calculates a character's base hit numbers based on skill values. The method currently calculates each value individually, since each skill can be used at short, medium, and long range.</p>
<p>I originally thought I could combine the skills into a tuple and iterate over it, dynamically creating each hit number. But I don't know if it's actually possible, since I currently have each hit number assigned to it's own variable.</p>
<p>I also thought about creating a method for each range, and passing the tuple as an argument. I could create a new tuple or list with the resulting values and then assign them to the individual variables, but I don't see how it would be any better than do it this way, except that it won't look so copy & pasted.</p>
<p>Here's what I currently have:</p>
<pre><code> def calcBaseHitNumbers(self, dict):
"""Calculate character's base hit numbers depending on skill level."""
self.skill_dict = dict
self.rifle = self.skill_dict.get('CRM', 0)
self.pistol = self.skill_dict.get('PST', 0)
self.big_gun = self.skill_dict.get('LCG', 0)
self.heavy_weapon = self.skill_dict.get('HW', 0)
self.bow = self.skill_dict.get('LB', 0)
#self.skill_tuple = (self.rifle, self.pistol, self.big_gun, self.heavy_weapon,
# self.bow)
#---Short range
## for skill in self.skill_tuple:
## self.base_hit_short = skill * 0.6
self.charAttribs.bhCRM_short = self.rifle * 0.6
self.charAttribs.bhPST_short = self.pistol * 0.6
self.charAttribs.bhHW_short = self.heavy_weapon * 0.6
self.charAttribs.bhLCG_short = self.big_gun * 0.6
self.charAttribs.bhLB_short = self.bow * 0.6
#---Med range
self.charAttribs.bhCRM_med = self.rifle * 0.3
self.charAttribs.bhPST_med = self.pistol * 0.3
self.charAttribs.bhHW_med = self.heavy_weapon * 0.3
self.charAttribs.bhLCG_med = self.big_gun * 0.3
self.charAttribs.bhLB_med = self.bow * 0.3
#---Long range
self.charAttribs.bhCRM_long = self.rifle * 0.1
self.charAttribs.bhPST_long = self.pistol * 0.1
self.charAttribs.bhHW_long = self.heavy_weapon * 0.1
self.charAttribs.bhLCG_long = self.big_gun * 0.1
self.charAttribs.bhLB_long = self.bow * 0.1
</code></pre>
<p>How would you refactor this so it's more dynamic?</p>
<p><hr /></p>
<p><strong>Edit:</strong> I guess what I want to do is something like this:
Have a tuple (like the one I commented out) and iterate over it 3 times, each time making a new value (for each skill) based on the modifier for each particular range. The resulting value is then automatically assigned to it's respective variable.</p>
<p>In my head, it makes sense. But when I actually try to code it, I get lost. The problem, I think, is that this is the first "real" program I've written; all I've done before are small scripts.</p>
<p>This is only the 0.1 version of my program, so it's not critical to refactor it now. However, it seems very un-Pythonic to do this manually and I also want to "future-proof" this in case things change down the road.</p>
| 1 | 2008-10-26T11:08:32Z | 237,907 | <p>It feels like what you really want is a class representing the weapon, with attributes to handle the base values and calculate hit values with various modifiers. Here's a simple example:</p>
<pre><code>SHORT_RANGE = 'S'
MEDIUM_RANGE = 'M'
LONG_RANGE = 'L'
SHORT_RANGE_MODIFIER = 0.6
MEDIUM_RANGE_MODIFIER = 0.3
LONG_RANGE_MODIFIER = 0.1
class Weapon(object):
def __init__(self, code_name, full_name, base_hit_value,
short_range_modifier=None, medium_range_modifier=None,
long_range_modifier=None):
self.code_name, self.full_name = code_name, full_name
self.base_hit_value = base_hit_value
self.range_modifiers = {
SHORT_RANGE: short_range_modifier or SHORT_RANGE_MODIFIER,
MEDIUM_RANGE: medium_range_modifier or MEDIUM_RANGE_MODIFIER,
LONG_RANGE: long_range_modifier or LONG_RANGE_MODIFIER,
}
def hit_value(self, range, modifier=1):
return self.base_hit_value * self.range_modifiers[range] * modifier
</code></pre>
<p>From there, you might create instances of Weapon inside your Character object like so:</p>
<pre><code> self.rifle = Weapon('CRM', 'rifle', 5)
self.pistol = Weapon('PST', 'pistol', 10)
</code></pre>
<p>And then if, say, the character fires the pistol at short range:</p>
<pre><code> hit_value = self.pistol.hit_value(SHORT_RANGE)
</code></pre>
<p>The extra argument to the hit_value() method can be used to pass in character- or situation-specific modifications.</p>
<p>Of course, the next step beyond this would be to directly model the weapons as subclasses of Weapon (perhaps breaking down into specific types of weapons, like guns, bows, grenades, etc., each with their own base values) and add an Inventory class to represent the weapons a character is carrying.</p>
<p>All of this is pretty standard, boring object-oriented design procedure, but for plenty of situations this type of thinking will get you off the ground quickly and provide at least a little bit of basic flexibility.</p>
| 6 | 2008-10-26T11:42:26Z | [
"python",
"refactoring"
] |
Refactoring "to hit" values for a game | 237,876 | <p>I'm making a game and one of the methods calculates a character's base hit numbers based on skill values. The method currently calculates each value individually, since each skill can be used at short, medium, and long range.</p>
<p>I originally thought I could combine the skills into a tuple and iterate over it, dynamically creating each hit number. But I don't know if it's actually possible, since I currently have each hit number assigned to it's own variable.</p>
<p>I also thought about creating a method for each range, and passing the tuple as an argument. I could create a new tuple or list with the resulting values and then assign them to the individual variables, but I don't see how it would be any better than do it this way, except that it won't look so copy & pasted.</p>
<p>Here's what I currently have:</p>
<pre><code> def calcBaseHitNumbers(self, dict):
"""Calculate character's base hit numbers depending on skill level."""
self.skill_dict = dict
self.rifle = self.skill_dict.get('CRM', 0)
self.pistol = self.skill_dict.get('PST', 0)
self.big_gun = self.skill_dict.get('LCG', 0)
self.heavy_weapon = self.skill_dict.get('HW', 0)
self.bow = self.skill_dict.get('LB', 0)
#self.skill_tuple = (self.rifle, self.pistol, self.big_gun, self.heavy_weapon,
# self.bow)
#---Short range
## for skill in self.skill_tuple:
## self.base_hit_short = skill * 0.6
self.charAttribs.bhCRM_short = self.rifle * 0.6
self.charAttribs.bhPST_short = self.pistol * 0.6
self.charAttribs.bhHW_short = self.heavy_weapon * 0.6
self.charAttribs.bhLCG_short = self.big_gun * 0.6
self.charAttribs.bhLB_short = self.bow * 0.6
#---Med range
self.charAttribs.bhCRM_med = self.rifle * 0.3
self.charAttribs.bhPST_med = self.pistol * 0.3
self.charAttribs.bhHW_med = self.heavy_weapon * 0.3
self.charAttribs.bhLCG_med = self.big_gun * 0.3
self.charAttribs.bhLB_med = self.bow * 0.3
#---Long range
self.charAttribs.bhCRM_long = self.rifle * 0.1
self.charAttribs.bhPST_long = self.pistol * 0.1
self.charAttribs.bhHW_long = self.heavy_weapon * 0.1
self.charAttribs.bhLCG_long = self.big_gun * 0.1
self.charAttribs.bhLB_long = self.bow * 0.1
</code></pre>
<p>How would you refactor this so it's more dynamic?</p>
<p><hr /></p>
<p><strong>Edit:</strong> I guess what I want to do is something like this:
Have a tuple (like the one I commented out) and iterate over it 3 times, each time making a new value (for each skill) based on the modifier for each particular range. The resulting value is then automatically assigned to it's respective variable.</p>
<p>In my head, it makes sense. But when I actually try to code it, I get lost. The problem, I think, is that this is the first "real" program I've written; all I've done before are small scripts.</p>
<p>This is only the 0.1 version of my program, so it's not critical to refactor it now. However, it seems very un-Pythonic to do this manually and I also want to "future-proof" this in case things change down the road.</p>
| 1 | 2008-10-26T11:08:32Z | 239,131 | <p>I would have a class for the character's attributes (so you don't have heaps of things in the character class) and a class for a weapon's attributes:</p>
<pre><code>class WeaponAttribute(object):
short_mod = 0.6
med_mod = 0.3
long_mod = 0.1
def __init__(self, base):
self.base = base
@property
def short(self):
return self.base * self.short_mod
@property
def med(self):
return self.base * self.med_mod
@property
def long(self):
return self.base * self.long_mod
class CharacterAttributes(object):
def __init__(self, attributes):
for weapon, base in attributes.items():
setattr(self, weapon, WeaponAttribute(base))
</code></pre>
<p>Have a <code>CharacterAttributes</code> object in the character class and use it like this:</p>
<pre><code># Initialise
self.charAttribs = CharacterAttributes(self.skill_dict)
# Get some values
print self.charAttribs.CRM.short
print self.charAttribs.PST.med
print self.charAttribs.LCG.long
</code></pre>
| 0 | 2008-10-27T05:14:52Z | [
"python",
"refactoring"
] |
How do you log server errors on django sites | 238,081 | <p>So, when playing with the development I can just set <code>settings.DEBUG</code> to <code>True</code> and if an error occures I can see it nicely formatted, with good stack trace and request information.</p>
<p>But on kind of production site I'd rather use <code>DEBUG=False</code> and show visitors some standard error 500 page with information that I'm working on fixing this bug at this moment ;)<br />
At the same time I'd like to have some way of logging all those information (stack trace and request info) to a file on my server - so I can just output it to my console and watch errors scroll, email the log to me every hour or something like this.</p>
<p>What logging solutions would you recomend for a django-site, that would meet those simple requirements? I have the application running as <code>fcgi</code> server and I'm using apache web server as frontend (although thinking of going to lighttpd).</p>
| 139 | 2008-10-26T14:37:42Z | 238,111 | <p>Well, when <code>DEBUG = False</code>, Django will automatically mail a full traceback of any error to each person listed in the <code>ADMINS</code> setting, which gets you notifications pretty much for free. If you'd like more fine-grained control, you can write and add to your settings a middleware class which defines a method named <code>process_exception()</code>, which will have access to the exception that was raised:</p>
<p><a href="http://docs.djangoproject.com/en/dev/topics/http/middleware/#process-exception">http://docs.djangoproject.com/en/dev/topics/http/middleware/#process-exception</a></p>
<p>Your <code>process_exception()</code> method can then perform whatever type of logging you'd like: writing to console, writing to a file, etc., etc.</p>
<p>Edit: though it's a bit less useful, you can also listen for the <code>got_request_exception</code> signal, which will be sent whenever an exception is encountered during request processing:</p>
<p><a href="http://docs.djangoproject.com/en/dev/ref/signals/#got-request-exception">http://docs.djangoproject.com/en/dev/ref/signals/#got-request-exception</a></p>
<p>This does <em>not</em> give you access to the exception object, however, so the middleware method is much easier to work with.</p>
| 74 | 2008-10-26T14:53:31Z | [
"python",
"django",
"error-logging"
] |
How do you log server errors on django sites | 238,081 | <p>So, when playing with the development I can just set <code>settings.DEBUG</code> to <code>True</code> and if an error occures I can see it nicely formatted, with good stack trace and request information.</p>
<p>But on kind of production site I'd rather use <code>DEBUG=False</code> and show visitors some standard error 500 page with information that I'm working on fixing this bug at this moment ;)<br />
At the same time I'd like to have some way of logging all those information (stack trace and request info) to a file on my server - so I can just output it to my console and watch errors scroll, email the log to me every hour or something like this.</p>
<p>What logging solutions would you recomend for a django-site, that would meet those simple requirements? I have the application running as <code>fcgi</code> server and I'm using apache web server as frontend (although thinking of going to lighttpd).</p>
| 139 | 2008-10-26T14:37:42Z | 239,882 | <p>Obviously James is correct, but if you wanted to log exceptions in a datastore there are a few opensource solutions already available:</p>
<p>1) CrashLog is a good choice: <a href="http://code.google.com/p/django-crashlog/">http://code.google.com/p/django-crashlog/</a></p>
<p>2) Db-Log is a good choice as well: <a href="http://code.google.com/p/django-db-log/">http://code.google.com/p/django-db-log/</a></p>
<p>What is the difference between the two? Almost nothing that I can see, so either one will suffice.</p>
<p>I've used both and the work well.</p>
| 27 | 2008-10-27T13:33:44Z | [
"python",
"django",
"error-logging"
] |
How do you log server errors on django sites | 238,081 | <p>So, when playing with the development I can just set <code>settings.DEBUG</code> to <code>True</code> and if an error occures I can see it nicely formatted, with good stack trace and request information.</p>
<p>But on kind of production site I'd rather use <code>DEBUG=False</code> and show visitors some standard error 500 page with information that I'm working on fixing this bug at this moment ;)<br />
At the same time I'd like to have some way of logging all those information (stack trace and request info) to a file on my server - so I can just output it to my console and watch errors scroll, email the log to me every hour or something like this.</p>
<p>What logging solutions would you recomend for a django-site, that would meet those simple requirements? I have the application running as <code>fcgi</code> server and I'm using apache web server as frontend (although thinking of going to lighttpd).</p>
| 139 | 2008-10-26T14:37:42Z | 4,198,664 | <p>django-db-log, mentioned in another answer, has been replaced with:</p>
<p><a href="https://github.com/dcramer/django-sentry">https://github.com/dcramer/django-sentry</a></p>
| 39 | 2010-11-16T20:34:56Z | [
"python",
"django",
"error-logging"
] |
How do you log server errors on django sites | 238,081 | <p>So, when playing with the development I can just set <code>settings.DEBUG</code> to <code>True</code> and if an error occures I can see it nicely formatted, with good stack trace and request information.</p>
<p>But on kind of production site I'd rather use <code>DEBUG=False</code> and show visitors some standard error 500 page with information that I'm working on fixing this bug at this moment ;)<br />
At the same time I'd like to have some way of logging all those information (stack trace and request info) to a file on my server - so I can just output it to my console and watch errors scroll, email the log to me every hour or something like this.</p>
<p>What logging solutions would you recomend for a django-site, that would meet those simple requirements? I have the application running as <code>fcgi</code> server and I'm using apache web server as frontend (although thinking of going to lighttpd).</p>
| 139 | 2008-10-26T14:37:42Z | 6,395,837 | <p>Django Sentry is a good way to go, as already mentioned, but there is a bit of work involved in setting it up properly (as a separate website). If you just want to log everything to a simple text file here's the logging configuration to put in your <code>settings.py</code></p>
<pre><code>LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
# Include the default Django email handler for errors
# This is what you'd get without configuring logging at all.
'mail_admins': {
'class': 'django.utils.log.AdminEmailHandler',
'level': 'ERROR',
# But the emails are plain text by default - HTML is nicer
'include_html': True,
},
# Log to a text file that can be rotated by logrotate
'logfile': {
'class': 'logging.handlers.WatchedFileHandler',
'filename': '/var/log/django/myapp.log'
},
},
'loggers': {
# Again, default Django configuration to email unhandled exceptions
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True,
},
# Might as well log any errors anywhere else in Django
'django': {
'handlers': ['logfile'],
'level': 'ERROR',
'propagate': False,
},
# Your own app - this assumes all your logger names start with "myapp."
'myapp': {
'handlers': ['logfile'],
'level': 'WARNING', # Or maybe INFO or DEBUG
'propagate': False
},
},
}
</code></pre>
| 64 | 2011-06-18T11:58:01Z | [
"python",
"django",
"error-logging"
] |
How do you log server errors on django sites | 238,081 | <p>So, when playing with the development I can just set <code>settings.DEBUG</code> to <code>True</code> and if an error occures I can see it nicely formatted, with good stack trace and request information.</p>
<p>But on kind of production site I'd rather use <code>DEBUG=False</code> and show visitors some standard error 500 page with information that I'm working on fixing this bug at this moment ;)<br />
At the same time I'd like to have some way of logging all those information (stack trace and request info) to a file on my server - so I can just output it to my console and watch errors scroll, email the log to me every hour or something like this.</p>
<p>What logging solutions would you recomend for a django-site, that would meet those simple requirements? I have the application running as <code>fcgi</code> server and I'm using apache web server as frontend (although thinking of going to lighttpd).</p>
| 139 | 2008-10-26T14:37:42Z | 19,267,228 | <p>Some time has passed since EMP's most helpful code submission. I just now implemented it, and while thrashing around with some manage.py option, to try to chase down a bug, I got a deprecation warning to the effect that with my current version of Django (1.5.?) a require_debug_false filter is now needed for the mail_admins handler.</p>
<p>Here is the revised code:</p>
<pre><code>LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'filters': {
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse'
}
},
'handlers': {
# Include the default Django email handler for errors
# This is what you'd get without configuring logging at all.
'mail_admins': {
'class': 'django.utils.log.AdminEmailHandler',
'level': 'ERROR',
'filters': ['require_debug_false'],
# But the emails are plain text by default - HTML is nicer
'include_html': True,
},
# Log to a text file that can be rotated by logrotate
'logfile': {
'class': 'logging.handlers.WatchedFileHandler',
'filename': '/home/username/public_html/djangoprojectname/logfilename.log'
},
},
'loggers': {
# Again, default Django configuration to email unhandled exceptions
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True,
},
# Might as well log any errors anywhere else in Django
'django': {
'handlers': ['logfile'],
'level': 'ERROR',
'propagate': False,
},
# Your own app - this assumes all your logger names start with "myapp."
'myapp': {
'handlers': ['logfile'],
'level': 'DEBUG', # Or maybe INFO or WARNING
'propagate': False
},
},
}
</code></pre>
| 10 | 2013-10-09T08:51:51Z | [
"python",
"django",
"error-logging"
] |
How do you log server errors on django sites | 238,081 | <p>So, when playing with the development I can just set <code>settings.DEBUG</code> to <code>True</code> and if an error occures I can see it nicely formatted, with good stack trace and request information.</p>
<p>But on kind of production site I'd rather use <code>DEBUG=False</code> and show visitors some standard error 500 page with information that I'm working on fixing this bug at this moment ;)<br />
At the same time I'd like to have some way of logging all those information (stack trace and request info) to a file on my server - so I can just output it to my console and watch errors scroll, email the log to me every hour or something like this.</p>
<p>What logging solutions would you recomend for a django-site, that would meet those simple requirements? I have the application running as <code>fcgi</code> server and I'm using apache web server as frontend (although thinking of going to lighttpd).</p>
| 139 | 2008-10-26T14:37:42Z | 39,106,487 | <p>I just had an annoying problem with my <code>fcgi</code> script. It occurred before django even started. The lack of logging is sooo painful. Anyway, redirecting stderr to a file as the very first thing helped a lot:</p>
<pre><code>#!/home/user/env/bin/python
sys.stderr = open('/home/user/fcgi_errors', 'a')
</code></pre>
| 1 | 2016-08-23T16:33:50Z | [
"python",
"django",
"error-logging"
] |
Pattern matching of lists in Python | 238,102 | <p>I want to do some pattern matching on lists in Python. For example, in Haskell, I can do something like the following:</p>
<pre><code>fun (head : rest) = ...
</code></pre>
<p>So when I pass in a list, <code>head</code> will be the first element, and <code>rest</code> will be the trailing elements.</p>
<p>Likewise, in Python, I can automatically unpack tuples:</p>
<pre><code>(var1, var2) = func_that_returns_a_tuple()
</code></pre>
<p>I want to do something similar with lists in Python. Right now, I have a function that returns a list, and a chunk of code that does the following:</p>
<pre><code>ls = my_func()
(head, rest) = (ls[0], ls[1:])
</code></pre>
<p>I wondered if I could somehow do that in one line in Python, instead of two.</p>
| 31 | 2008-10-26T14:50:40Z | 238,123 | <p>That's a very much a 'pure functional' approach and as such is a sensible idiom in Haskell but it's probably not so appropriate to Python. Python only has a very limited concept of <a href="http://www.haskell.org/tutorial/patterns.html" rel="nofollow">patterns</a> in this way - and I suspect you might need a somewhat more rigid type system to implement that sort of construct (<a href="http://www.erlang.org/" rel="nofollow">erlang</a> buffs invited to disagree here).</p>
<p>What you have is probably as close as you would get to that idiom, but you are probably better off using a list comprehension or imperative approach rather than recursively calling a function with the tail of the list. </p>
<p>As has been <a href="http://www.oreillynet.com/onlamp/blog/2005/10/pythons_weak_functional_progra.html" rel="nofollow">stated</a> <a href="http://www.artima.com/weblogs/viewpost.jsp?thread=4550" rel="nofollow">on a few occasions</a> <a href="http://blog.ianbicking.org/functional-python.html" rel="nofollow">before</a>, Python is not actually a functional language. It just borrows ideas from the FP world. It is not inherently <a href="http://en.wikipedia.org/wiki/Tail_recursion" rel="nofollow">Tail Recursive</a> in the way you would expect to see embedded in the architecture of a functional language, so you would have some difficulty doing this sort of recursive operation on a large data set without using a lot of stack space.</p>
| 4 | 2008-10-26T15:00:29Z | [
"python",
"functional-programming",
"pattern-matching"
] |
Pattern matching of lists in Python | 238,102 | <p>I want to do some pattern matching on lists in Python. For example, in Haskell, I can do something like the following:</p>
<pre><code>fun (head : rest) = ...
</code></pre>
<p>So when I pass in a list, <code>head</code> will be the first element, and <code>rest</code> will be the trailing elements.</p>
<p>Likewise, in Python, I can automatically unpack tuples:</p>
<pre><code>(var1, var2) = func_that_returns_a_tuple()
</code></pre>
<p>I want to do something similar with lists in Python. Right now, I have a function that returns a list, and a chunk of code that does the following:</p>
<pre><code>ls = my_func()
(head, rest) = (ls[0], ls[1:])
</code></pre>
<p>I wondered if I could somehow do that in one line in Python, instead of two.</p>
| 31 | 2008-10-26T14:50:40Z | 238,124 | <p>So far as I know there's no way to make it a one-liner in current Python without introducing another function, e.g.:</p>
<pre><code>split_list = lambda lst: (lst[0], lst[1:])
head, rest = split_list(my_func())
</code></pre>
<p>However, in Python 3.0 the specialized syntax used for variadic argument signatures and argument unpacking will become available for this type of general sequence unpacking as well, so in 3.0 you'll be able to write:</p>
<pre><code>head, *rest = my_func()
</code></pre>
<p>See <a href="https://www.python.org/dev/peps/pep-3132/">PEP 3132</a> for details.</p>
| 48 | 2008-10-26T15:01:12Z | [
"python",
"functional-programming",
"pattern-matching"
] |
Pattern matching of lists in Python | 238,102 | <p>I want to do some pattern matching on lists in Python. For example, in Haskell, I can do something like the following:</p>
<pre><code>fun (head : rest) = ...
</code></pre>
<p>So when I pass in a list, <code>head</code> will be the first element, and <code>rest</code> will be the trailing elements.</p>
<p>Likewise, in Python, I can automatically unpack tuples:</p>
<pre><code>(var1, var2) = func_that_returns_a_tuple()
</code></pre>
<p>I want to do something similar with lists in Python. Right now, I have a function that returns a list, and a chunk of code that does the following:</p>
<pre><code>ls = my_func()
(head, rest) = (ls[0], ls[1:])
</code></pre>
<p>I wondered if I could somehow do that in one line in Python, instead of two.</p>
| 31 | 2008-10-26T14:50:40Z | 238,126 | <p>Well, why you want it in 1-line in the first place? </p>
<p>If you really want to, you can always do a trick like this:</p>
<pre><code>def x(func):
y = func()
return y[0], y[1:]
# then, instead of calling my_func() call x(my_func)
(head, rest) = x(my_func) # that's one line :)
</code></pre>
| 2 | 2008-10-26T15:03:08Z | [
"python",
"functional-programming",
"pattern-matching"
] |
Pattern matching of lists in Python | 238,102 | <p>I want to do some pattern matching on lists in Python. For example, in Haskell, I can do something like the following:</p>
<pre><code>fun (head : rest) = ...
</code></pre>
<p>So when I pass in a list, <code>head</code> will be the first element, and <code>rest</code> will be the trailing elements.</p>
<p>Likewise, in Python, I can automatically unpack tuples:</p>
<pre><code>(var1, var2) = func_that_returns_a_tuple()
</code></pre>
<p>I want to do something similar with lists in Python. Right now, I have a function that returns a list, and a chunk of code that does the following:</p>
<pre><code>ls = my_func()
(head, rest) = (ls[0], ls[1:])
</code></pre>
<p>I wondered if I could somehow do that in one line in Python, instead of two.</p>
| 31 | 2008-10-26T14:50:40Z | 238,153 | <p>extended unpacking was introduced in 3.0
<a href="http://www.python.org/dev/peps/pep-3132/" rel="nofollow">http://www.python.org/dev/peps/pep-3132/</a></p>
| 2 | 2008-10-26T15:40:59Z | [
"python",
"functional-programming",
"pattern-matching"
] |
Pattern matching of lists in Python | 238,102 | <p>I want to do some pattern matching on lists in Python. For example, in Haskell, I can do something like the following:</p>
<pre><code>fun (head : rest) = ...
</code></pre>
<p>So when I pass in a list, <code>head</code> will be the first element, and <code>rest</code> will be the trailing elements.</p>
<p>Likewise, in Python, I can automatically unpack tuples:</p>
<pre><code>(var1, var2) = func_that_returns_a_tuple()
</code></pre>
<p>I want to do something similar with lists in Python. Right now, I have a function that returns a list, and a chunk of code that does the following:</p>
<pre><code>ls = my_func()
(head, rest) = (ls[0], ls[1:])
</code></pre>
<p>I wondered if I could somehow do that in one line in Python, instead of two.</p>
| 31 | 2008-10-26T14:50:40Z | 238,170 | <p>First of all, please note that the "pattern matching" of functional languages and the assignment to tuples you mention are not really that similar. In functional languages the patterns are used to give partial definitions of a function. So <code>f (x : s) = e</code> does not mean take the head and tail of the argument of <code>f</code> and return <code>e</code> using them, but it means that <em>if</em> the argument of <code>f</code> is of the form <code>x : s</code> (for some <code>x</code> and <code>s</code>), <em>then</em> <code>f (x : s)</code> is equal to <code>e</code>.</p>
<p>The assignment of python is more like a multiple assignment (I suspect that was its original intention). So you write, for example, <code>x, y = y, x</code> to swap the values in <code>x</code> and <code>y</code> without needing a temporary variable (as you would with a simple assignment statement). This has little to do with pattern matching as it is basically a shorthand for the "simultaneous" execution of <code>x = y</code> and <code>y = x</code>. Although python allows arbitrary sequences instead of comma-separated lists, I would not suggest calling this pattern matching. With pattern matching you check whether or not something matches a pattern; in the python assignment you should ensure that the sequences on both sides are the same.</p>
<p>To do what you seem to want you would usually (also in functional languages) use either a auxiliary function (as mentioned by others) or something similar to <code>let</code> or <code>where</code> constructs (which you can regard as using anonymous functions). For example:</p>
<pre><code>(head, tail) = (x[0], x[1:]) where x = my_func()
</code></pre>
<p>Or, in actual python:</p>
<pre><code>(head, tail) = (lambda x: (x[0], x[1:]))(my_func())
</code></pre>
<p>Note that this is essentially the same as the solutions given by others with an auxiliary function except that this is the one-liner you wanted. It is, however, not necessarily better than a separate function.</p>
<p>(Sorry if my answer is a bit over the top. I just think it's important to make the distinction clear.)</p>
| 28 | 2008-10-26T16:05:12Z | [
"python",
"functional-programming",
"pattern-matching"
] |
Pattern matching of lists in Python | 238,102 | <p>I want to do some pattern matching on lists in Python. For example, in Haskell, I can do something like the following:</p>
<pre><code>fun (head : rest) = ...
</code></pre>
<p>So when I pass in a list, <code>head</code> will be the first element, and <code>rest</code> will be the trailing elements.</p>
<p>Likewise, in Python, I can automatically unpack tuples:</p>
<pre><code>(var1, var2) = func_that_returns_a_tuple()
</code></pre>
<p>I want to do something similar with lists in Python. Right now, I have a function that returns a list, and a chunk of code that does the following:</p>
<pre><code>ls = my_func()
(head, rest) = (ls[0], ls[1:])
</code></pre>
<p>I wondered if I could somehow do that in one line in Python, instead of two.</p>
| 31 | 2008-10-26T14:50:40Z | 238,185 | <p>there was a reciepe in the python cookbook to do this. i cant seem to find it now but here is the code (i modified it slightly)</p>
<pre><code>
def peel(iterable,result=tuple):
'''Removes the requested items from the iterable and stores the remaining in a tuple
>>> x,y,z=peel('test')
>>> print repr(x),repr(y),z
't' 'e' ('s', 't')
'''
def how_many_unpacked():
import inspect,opcode
f = inspect.currentframe().f_back.f_back
if ord(f.f_code.co_code[f.f_lasti])==opcode.opmap['UNPACK_SEQUENCE']:
return ord(f.f_code.co_code[f.f_lasti+1])
raise ValueError("Must be a generator on RHS of a multiple assignment!!")
iterator=iter(iterable)
hasItems=True
amountToUnpack=how_many_unpacked()-1
next=None
for num in xrange(amountToUnpack):
if hasItems:
try:
next = iterator.next()
except StopIteration:
next = None
hasItems = False
yield next
if hasItems:
yield result(iterator)
else:
yield None
</code></pre>
<p>however you should note that that only works when using an assignment unpack because of the way it inespects the previous frame... still its quite useful.</p>
| 1 | 2008-10-26T16:15:17Z | [
"python",
"functional-programming",
"pattern-matching"
] |
Pattern matching of lists in Python | 238,102 | <p>I want to do some pattern matching on lists in Python. For example, in Haskell, I can do something like the following:</p>
<pre><code>fun (head : rest) = ...
</code></pre>
<p>So when I pass in a list, <code>head</code> will be the first element, and <code>rest</code> will be the trailing elements.</p>
<p>Likewise, in Python, I can automatically unpack tuples:</p>
<pre><code>(var1, var2) = func_that_returns_a_tuple()
</code></pre>
<p>I want to do something similar with lists in Python. Right now, I have a function that returns a list, and a chunk of code that does the following:</p>
<pre><code>ls = my_func()
(head, rest) = (ls[0], ls[1:])
</code></pre>
<p>I wondered if I could somehow do that in one line in Python, instead of two.</p>
| 31 | 2008-10-26T14:50:40Z | 239,676 | <p>Further to the other answers, note that the equivalent head / tail operation in Python, including python3's extension of the * syntax is generally going to be less efficient than Haskell's pattern matching.</p>
<p>Python lists are implemented as vectors, so obtaining the tail will need to take a copy of the list. This is O(n) wrt the size of the list, whereas an implementaion using linked lists like Haskell can merely use the tail pointer, an O(1) operation.</p>
<p>The only exception may be iterator based approaches, where the list isn't actually returned, but an iterator is. However this may not be applicable all places where a list is desired (eg. iterating multiple times).</p>
<p>For instance, <a href="http://stackoverflow.com/questions/238102/pattern-matching-of-lists-in-python#238185">Cipher's</a> approach, if modified to return the iterator rather than converting it to a tuple will have this behaviour. Alternatively a simpler 2-item only method not relying on the bytecode would be:</p>
<pre><code>def head_tail(lst):
it = iter(list)
yield it.next()
yield it
>>> a, tail = head_tail([1,2,3,4,5])
>>> b, tail = head_tail(tail)
>>> a,b,tail
(1, 2, <listiterator object at 0x2b1c810>)
>>> list(tail)
[3, 4]
</code></pre>
<p>Obviously though you still have to wrap in a utility function rather than there being nice syntactic sugar for it.</p>
| 2 | 2008-10-27T12:08:14Z | [
"python",
"functional-programming",
"pattern-matching"
] |
Pattern matching of lists in Python | 238,102 | <p>I want to do some pattern matching on lists in Python. For example, in Haskell, I can do something like the following:</p>
<pre><code>fun (head : rest) = ...
</code></pre>
<p>So when I pass in a list, <code>head</code> will be the first element, and <code>rest</code> will be the trailing elements.</p>
<p>Likewise, in Python, I can automatically unpack tuples:</p>
<pre><code>(var1, var2) = func_that_returns_a_tuple()
</code></pre>
<p>I want to do something similar with lists in Python. Right now, I have a function that returns a list, and a chunk of code that does the following:</p>
<pre><code>ls = my_func()
(head, rest) = (ls[0], ls[1:])
</code></pre>
<p>I wondered if I could somehow do that in one line in Python, instead of two.</p>
| 31 | 2008-10-26T14:50:40Z | 240,018 | <p>Unlike Haskell or ML, Python doesn't have built-in pattern-matching of structures. The most Pythonic way of doing pattern-matching is with a try-except block:</p>
<pre><code>def recursive_sum(x):
try:
head, tail = x[0], x[1:]
return head + recursive-sum(tail)
except IndexError: # empty list: [][0] raises IndexError
return 0
</code></pre>
<p>Note that this only works with objects with slice indexing. Also, if the function gets complicated, something in the body <em>after</em> the <code>head, tail</code> line might raise IndexError, which will lead to subtle bugs. However, this does allow you to do things like:</p>
<pre><code>for frob in eggs.frob_list:
try:
frob.spam += 1
except AttributeError:
eggs.no_spam_count += 1
</code></pre>
<p>In Python, tail recursion is generally better implemented as a loop with an accumulator, i.e.:</p>
<pre><code>def iterative_sum(x):
ret_val = 0
for i in x:
ret_val += i
return ret_val
</code></pre>
<p>This is the one obvious, right way to do it 99% of the time. Not only is it clearer to read, it's faster and it will work on things other than lists (sets, for instance). If there's an exception waiting to happen in there, the function will happily fail and deliver it up the chain.</p>
| 1 | 2008-10-27T14:15:34Z | [
"python",
"functional-programming",
"pattern-matching"
] |
Pattern matching of lists in Python | 238,102 | <p>I want to do some pattern matching on lists in Python. For example, in Haskell, I can do something like the following:</p>
<pre><code>fun (head : rest) = ...
</code></pre>
<p>So when I pass in a list, <code>head</code> will be the first element, and <code>rest</code> will be the trailing elements.</p>
<p>Likewise, in Python, I can automatically unpack tuples:</p>
<pre><code>(var1, var2) = func_that_returns_a_tuple()
</code></pre>
<p>I want to do something similar with lists in Python. Right now, I have a function that returns a list, and a chunk of code that does the following:</p>
<pre><code>ls = my_func()
(head, rest) = (ls[0], ls[1:])
</code></pre>
<p>I wondered if I could somehow do that in one line in Python, instead of two.</p>
| 31 | 2008-10-26T14:50:40Z | 11,588,095 | <p>I'm working on <a href="https://github.com/martinblech/pyfpm" rel="nofollow">pyfpm</a>, a library for pattern matching in Python with a Scala-like syntax. You can use it to unpack objects like this:</p>
<pre><code>from pyfpm import Unpacker
unpacker = Unpacker()
unpacker('head :: tail') << (1, 2, 3)
unpacker.head # 1
unpacker.tail # (2, 3)
</code></pre>
<p>Or in a function's arglist:</p>
<pre><code>from pyfpm import match_args
@match_args('head :: tail')
def f(head, tail):
return (head, tail)
f(1) # (1, ())
f(1, 2, 3, 4) # (1, (2, 3, 4))
</code></pre>
| 2 | 2012-07-20T23:18:17Z | [
"python",
"functional-programming",
"pattern-matching"
] |
Is there a windows implementation to python libsvn? | 238,151 | <p>Because windows is case-insensitive and because SVN is case-sensitive and because VS2005 tends to rename files giving them the lower-case form which messes my repositories' history, I've tried to add the pre-commit hook script from <a href="http://svn.collab.net/repos/svn/trunk/contrib/hook-scripts/case-insensitive.py" rel="nofollow">http://svn.collab.net/repos/svn/trunk/contrib/hook-scripts/case-insensitive.py</a>.
Sure enough, the script uses classes from python's libsvn ("from svn import repos, fs") which I fail to find compiled for Windows.
Is there an alternative? To libsvn or to the hook script?</p>
| 1 | 2008-10-26T15:39:36Z | 238,263 | <p>There are two alternative Python bindings for libsvn:</p>
<ul>
<li><a href="http://pysvn.tigris.org/" rel="nofollow">pysvn</a>.</li>
<li><a href="https://launchpad.net/subvertpy" rel="nofollow">subvertpy</a>. </li>
</ul>
<p>Subvertpy is quite new and is written by the author of <a href="http://bazaar-vcs.org/BzrForeignBranches/Subversion" rel="nofollow">bzr-svn</a>: the transparent <a href="http://subversion.apache.org/" rel="nofollow">svn</a> inter-operation bridge for <a href="http://bazaar-vcs.org/" rel="nofollow">bzr</a>.</p>
<p>For a while, bzr-svn used the upstream <a href="http://www.swig.org/" rel="nofollow">SWIG</a> Python bindings, and the author contributed a lot of bug fixes. It helped move the upstream python support for "horribly broken" to "painfully aggravating and unpythonic". So after wasting too many hours of his life to SWIG, the author decided to make his own bindings.</p>
| 4 | 2008-10-26T17:02:43Z | [
"python",
"svn",
"hook",
"pre-commit"
] |
Is there a windows implementation to python libsvn? | 238,151 | <p>Because windows is case-insensitive and because SVN is case-sensitive and because VS2005 tends to rename files giving them the lower-case form which messes my repositories' history, I've tried to add the pre-commit hook script from <a href="http://svn.collab.net/repos/svn/trunk/contrib/hook-scripts/case-insensitive.py" rel="nofollow">http://svn.collab.net/repos/svn/trunk/contrib/hook-scripts/case-insensitive.py</a>.
Sure enough, the script uses classes from python's libsvn ("from svn import repos, fs") which I fail to find compiled for Windows.
Is there an alternative? To libsvn or to the hook script?</p>
| 1 | 2008-10-26T15:39:36Z | 238,479 | <p>The Tigris.org's pre-complied python bindings for libsvn are a separate download. The latest as of Oct 27 could be found <a href="http://subversion.tigris.org/files/documents/15/44104/svn-win32-1.5.4_py25.zip" rel="nofollow">here</a>.</p>
<p>There are other binary SVN distributions listed <a href="http://subversion.tigris.org/getting.html#windows" rel="nofollow">here</a>, and they probably have different policy for bundling the python bindings.</p>
| 3 | 2008-10-26T19:20:27Z | [
"python",
"svn",
"hook",
"pre-commit"
] |
Match unicode in ply's regexes | 238,223 | <p>I'm matching identifiers, but now I have a problem: my identifiers are allowed to contain unicode characters. Therefore the old way to do things is not enough:</p>
<pre><code>t_IDENTIFIER = r"[A-Za-z](\\.|[A-Za-z_0-9])*"
</code></pre>
<p>In <a href="http://freehg.org/u/cheery/aml/" rel="nofollow">my markup language</a> parser I match unicode characters by allowing all the characters except those I explicitly use, because my markup language only has two or three of characters I need to escape that way.</p>
<p>How do I match all unicode characters with python regexs and ply? Also is this a good idea at all?</p>
<p>I'd want to let people use identifiers like Ω » « ° foo² väli Ï as an identifiers (variable names and such) in their programs. Heck! I want that people could write programs in their own language if it's practical! Anyway unicode is supported nowadays in wide variety of places, and it should spread.</p>
<p>Edit: POSIX character classes doesnt seem to be recognised by python regexes.</p>
<pre><code>>>> import re
>>> item = re.compile(r'[[:word:]]')
>>> print item.match('e')
None
</code></pre>
<p>Edit: To explain better what I need. I'd need a regex -thing that matches all the unicode printable characters but not ASCII characters at all.</p>
<p>Edit: r"\w" does a bit stuff what I want, but it does not match « », and I also need a regex that does not match numbers.</p>
| 4 | 2008-10-26T16:35:07Z | 238,227 | <p>Probably <a href="http://www.regular-expressions.info/posixbrackets.html" rel="nofollow">POSIX character classes</a> are right for you?</p>
| 0 | 2008-10-26T16:37:58Z | [
"python",
"regex",
"unicode",
"ply",
"character-properties"
] |
Match unicode in ply's regexes | 238,223 | <p>I'm matching identifiers, but now I have a problem: my identifiers are allowed to contain unicode characters. Therefore the old way to do things is not enough:</p>
<pre><code>t_IDENTIFIER = r"[A-Za-z](\\.|[A-Za-z_0-9])*"
</code></pre>
<p>In <a href="http://freehg.org/u/cheery/aml/" rel="nofollow">my markup language</a> parser I match unicode characters by allowing all the characters except those I explicitly use, because my markup language only has two or three of characters I need to escape that way.</p>
<p>How do I match all unicode characters with python regexs and ply? Also is this a good idea at all?</p>
<p>I'd want to let people use identifiers like Ω » « ° foo² väli Ï as an identifiers (variable names and such) in their programs. Heck! I want that people could write programs in their own language if it's practical! Anyway unicode is supported nowadays in wide variety of places, and it should spread.</p>
<p>Edit: POSIX character classes doesnt seem to be recognised by python regexes.</p>
<pre><code>>>> import re
>>> item = re.compile(r'[[:word:]]')
>>> print item.match('e')
None
</code></pre>
<p>Edit: To explain better what I need. I'd need a regex -thing that matches all the unicode printable characters but not ASCII characters at all.</p>
<p>Edit: r"\w" does a bit stuff what I want, but it does not match « », and I also need a regex that does not match numbers.</p>
| 4 | 2008-10-26T16:35:07Z | 238,257 | <p>Check the answers to this question</p>
<p><a href="http://stackoverflow.com/questions/92438/stripping-non-printable-characters-from-a-string-in-python">http://stackoverflow.com/questions/92438/stripping-non-printable-characters-from-a-string-in-python</a></p>
<p>you'd just need to use the other unicode character categories instead</p>
| 1 | 2008-10-26T16:58:56Z | [
"python",
"regex",
"unicode",
"ply",
"character-properties"
] |
Match unicode in ply's regexes | 238,223 | <p>I'm matching identifiers, but now I have a problem: my identifiers are allowed to contain unicode characters. Therefore the old way to do things is not enough:</p>
<pre><code>t_IDENTIFIER = r"[A-Za-z](\\.|[A-Za-z_0-9])*"
</code></pre>
<p>In <a href="http://freehg.org/u/cheery/aml/" rel="nofollow">my markup language</a> parser I match unicode characters by allowing all the characters except those I explicitly use, because my markup language only has two or three of characters I need to escape that way.</p>
<p>How do I match all unicode characters with python regexs and ply? Also is this a good idea at all?</p>
<p>I'd want to let people use identifiers like Ω » « ° foo² väli Ï as an identifiers (variable names and such) in their programs. Heck! I want that people could write programs in their own language if it's practical! Anyway unicode is supported nowadays in wide variety of places, and it should spread.</p>
<p>Edit: POSIX character classes doesnt seem to be recognised by python regexes.</p>
<pre><code>>>> import re
>>> item = re.compile(r'[[:word:]]')
>>> print item.match('e')
None
</code></pre>
<p>Edit: To explain better what I need. I'd need a regex -thing that matches all the unicode printable characters but not ASCII characters at all.</p>
<p>Edit: r"\w" does a bit stuff what I want, but it does not match « », and I also need a regex that does not match numbers.</p>
| 4 | 2008-10-26T16:35:07Z | 238,293 | <p>Solved it with the help of Vinko.</p>
<p>I realised that getting unicode range is plain dumb. So I'll do this:</p>
<pre><code>symbols = re.escape(''.join([chr(i) for i in xrange(33, 127) if not chr(i).isalnum()]))
symnums = re.escape(''.join([chr(i) for i in xrange(33, 127) if not chr(i).isalnum()]))
t_IDENTIFIER = "[^%s](\\.|[^%s])*" % (symnums, symbols)
</code></pre>
<p>I don't know about unicode character classses. If this unicode stuff starts getting too complicated, I can just put the original one in place. UTF-8 support still ensures the support is on at the STRING tokens, which is more important.</p>
<p>Edit: On other hand, I start understanding why there's not much unicode support in programming languages.. This is an ugly hack, not a satisfying solution.</p>
| 1 | 2008-10-26T17:19:46Z | [
"python",
"regex",
"unicode",
"ply",
"character-properties"
] |
Match unicode in ply's regexes | 238,223 | <p>I'm matching identifiers, but now I have a problem: my identifiers are allowed to contain unicode characters. Therefore the old way to do things is not enough:</p>
<pre><code>t_IDENTIFIER = r"[A-Za-z](\\.|[A-Za-z_0-9])*"
</code></pre>
<p>In <a href="http://freehg.org/u/cheery/aml/" rel="nofollow">my markup language</a> parser I match unicode characters by allowing all the characters except those I explicitly use, because my markup language only has two or three of characters I need to escape that way.</p>
<p>How do I match all unicode characters with python regexs and ply? Also is this a good idea at all?</p>
<p>I'd want to let people use identifiers like Ω » « ° foo² väli Ï as an identifiers (variable names and such) in their programs. Heck! I want that people could write programs in their own language if it's practical! Anyway unicode is supported nowadays in wide variety of places, and it should spread.</p>
<p>Edit: POSIX character classes doesnt seem to be recognised by python regexes.</p>
<pre><code>>>> import re
>>> item = re.compile(r'[[:word:]]')
>>> print item.match('e')
None
</code></pre>
<p>Edit: To explain better what I need. I'd need a regex -thing that matches all the unicode printable characters but not ASCII characters at all.</p>
<p>Edit: r"\w" does a bit stuff what I want, but it does not match « », and I also need a regex that does not match numbers.</p>
| 4 | 2008-10-26T16:35:07Z | 238,646 | <p>the <a href="http://docs.python.org/library/re#regular-expression-syntax">re</a> module supports the \w syntax which:</p>
<blockquote>
<p>If UNICODE is set, this will match the
characters [0-9_] plus whatever is
classified as alphanumeric in the
Unicode character properties database.</p>
</blockquote>
<p>therefore the following examples shows how to match unicode identifiers:</p>
<pre><code>>>> import re
>>> m = re.compile('(?u)[^\W0-9]\w*')
>>> m.match('a')
<_sre.SRE_Match object at 0xb7d75410>
>>> m.match('9')
>>> m.match('ab')
<_sre.SRE_Match object at 0xb7c258e0>
>>> m.match('a9')
<_sre.SRE_Match object at 0xb7d75410>
>>> m.match('unicöde')
<_sre.SRE_Match object at 0xb7c258e0>
>>> m.match('ödipus')
<_sre.SRE_Match object at 0xb7d75410>
</code></pre>
<p>So the expression you look for is: (?u)[^\W0-9]\w*</p>
| 5 | 2008-10-26T21:18:53Z | [
"python",
"regex",
"unicode",
"ply",
"character-properties"
] |
Match unicode in ply's regexes | 238,223 | <p>I'm matching identifiers, but now I have a problem: my identifiers are allowed to contain unicode characters. Therefore the old way to do things is not enough:</p>
<pre><code>t_IDENTIFIER = r"[A-Za-z](\\.|[A-Za-z_0-9])*"
</code></pre>
<p>In <a href="http://freehg.org/u/cheery/aml/" rel="nofollow">my markup language</a> parser I match unicode characters by allowing all the characters except those I explicitly use, because my markup language only has two or three of characters I need to escape that way.</p>
<p>How do I match all unicode characters with python regexs and ply? Also is this a good idea at all?</p>
<p>I'd want to let people use identifiers like Ω » « ° foo² väli Ï as an identifiers (variable names and such) in their programs. Heck! I want that people could write programs in their own language if it's practical! Anyway unicode is supported nowadays in wide variety of places, and it should spread.</p>
<p>Edit: POSIX character classes doesnt seem to be recognised by python regexes.</p>
<pre><code>>>> import re
>>> item = re.compile(r'[[:word:]]')
>>> print item.match('e')
None
</code></pre>
<p>Edit: To explain better what I need. I'd need a regex -thing that matches all the unicode printable characters but not ASCII characters at all.</p>
<p>Edit: r"\w" does a bit stuff what I want, but it does not match « », and I also need a regex that does not match numbers.</p>
| 4 | 2008-10-26T16:35:07Z | 8,502,908 | <p>You need pass pass parameter reflags in lex.lex:</p>
<pre><code>lex.lex(reflags=re.UNICODE)
</code></pre>
| 3 | 2011-12-14T10:26:38Z | [
"python",
"regex",
"unicode",
"ply",
"character-properties"
] |
How can I support wildcards in user-defined search strings in Python? | 238,600 | <p>Is there a simple way to support wildcards ("*") when searching strings - without using RegEx?</p>
<p>Users are supposed to enter search terms using wildcards, but should not have to deal with the complexity of RegEx:</p>
<pre><code>"foo*" => str.startswith("foo")
"*foo" => str.endswith("foo")
"*foo*" => "foo" in str
</code></pre>
<p>(it gets more complicated when there are multiple search terms though, e.g. "foo*bar*baz")</p>
<p>This seems like a common issue, so I wonder whether there's a ready-made solution for it.</p>
<p>Any help would be greatly appreciated!</p>
| 8 | 2008-10-26T20:52:35Z | 238,602 | <p>You could try the <a href="http://www.python.org/doc/2.5.2/lib/module-fnmatch.html"><code>fnmatch</code></a> module, it's got a shell-like wildcard syntax.</p>
| 14 | 2008-10-26T20:54:30Z | [
"python",
"search",
"parsing",
"string",
"wildcard"
] |
XPath search with ElementTree | 238,697 | <p>New to xml. Looking for XPath to search a xml file with python ElementTree format</p>
<pre><code><root>
<child>One</child>
<child>Two</child>
<child>Three</child>
</root>
</code></pre>
<p>to do search for child with "Two" and return true/false</p>
<p>if it was started off like </p>
<pre><code>from elementtree import ElementTree
root = ElementTree.parse(open(PathFile)).getroot()
</code></pre>
<p>how can this be achieved</p>
| 4 | 2008-10-26T22:00:16Z | 239,422 | <p>I've been playing with ElementTree lately, lets see..</p>
<pre><code>>>> from xml.etree import ElementTree
>>> help(ElementTree.ElementPath)
>>> root = ElementTree.fromstring("""
<root><child>One</child><child>Two</child><child>Three</child></root>
""")
>>> ElementTree.ElementPath.findall(root, "child")
[<Element child at 2ac98c0>, <Element child at 2ac9638>, <Element child at 2ac9518>]
>>> elements = ElementTree.ElementPath.findall(root, "child")
>>> two = [x for x in elements if x.text == "Two"]
>>> two[0].text
'Two'
</code></pre>
<p>This is what you look for right? It says ElementPath has just limited xpath support though, but it does not say not support at all.</p>
| 1 | 2008-10-27T09:32:36Z | [
"python",
"xml",
"xpath"
] |
XPath search with ElementTree | 238,697 | <p>New to xml. Looking for XPath to search a xml file with python ElementTree format</p>
<pre><code><root>
<child>One</child>
<child>Two</child>
<child>Three</child>
</root>
</code></pre>
<p>to do search for child with "Two" and return true/false</p>
<p>if it was started off like </p>
<pre><code>from elementtree import ElementTree
root = ElementTree.parse(open(PathFile)).getroot()
</code></pre>
<p>how can this be achieved</p>
| 4 | 2008-10-26T22:00:16Z | 285,719 | <p>When the following XPath expression is evaluated:</p>
<p> <code>boolean(/*/*[.='Two'])</code></p>
<p>the result is <strong>true</strong>, if such an element (a child of the top element such that its string value is equal to "Two") exists,</p>
<p>and <strong>false</strong> otherwise.</p>
<p>Hope this helped.</p>
<p>Cheers,</p>
<p>Dimitre Novatchev</p>
| 1 | 2008-11-12T23:00:26Z | [
"python",
"xml",
"xpath"
] |
How do I install plpython on MacOs X 10.5? | 238,882 | <p>I have just installed PostgreSQL 8.3.4 on Mac OS X 10.5 (using ports), but I cannot figure out how to enable PL/Python. When I run the <code>CREATE LANGUAGE plpythonu</code> I get the following errors:</p>
<pre><code>ERROR: could not access file "$libdir/plpython": No such file or directory
STATEMENT: CREATE LANGUAGE plpythonu;
psql:<stdin>:18: ERROR: could not access file "$libdir/plpython": No such file or directory
</code></pre>
<p>How can I fix it? Ideally I would prefer to avoid compiling Postgres without <code>port</code> or something like that.</p>
<p>Thia the output of running pg_config:</p>
<pre><code>BINDIR = /opt/local/lib/postgresql83/bin
DOCDIR =
INCLUDEDIR = /opt/local/include/postgresql83
PKGINCLUDEDIR = /opt/local/include/postgresql83
INCLUDEDIR-SERVER = /opt/local/include/postgresql83/server
LIBDIR = /opt/local/lib/postgresql83
PKGLIBDIR = /opt/local/lib/postgresql83
LOCALEDIR =
MANDIR = /opt/local/share/man
SHAREDIR = /opt/local/share/postgresql83
SYSCONFDIR = /opt/local/etc/postgresql83
PGXS = /opt/local/lib/postgresql83/pgxs/src/makefiles/pgxs.mk
CONFIGURE = '--prefix=/opt/local' '--sysconfdir=/opt/local/etc/postgresql83' '--bindir=/opt/local/lib/postgresql83/bin' '--libdir=/opt/local/lib/postgresql83' '--includedir=/opt/local/include/postgresql83' '--datadir=/opt/local/share/postgresql83' '--mandir=/opt/local/share/man' '--without-docdir' '--with-includes=/opt/local/include' '--with-libraries=/opt/local/lib' '--with-openssl' '--with-bonjour' '--with-readline' '--with-zlib' '--with-libxml' '--with-libxslt' '--enable-thread-safety' '--enable-integer-datetimes' '--with-ossp-uuid' 'CC=/usr/bin/gcc-4.0' 'CFLAGS=-O2' 'CPPFLAGS=-I/opt/local/include -I/opt/local/include/ossp' 'CPP=/usr/bin/cpp-4.0' 'LDFLAGS=-L/opt/local/lib'
CC = /usr/bin/gcc-4.0 -no-cpp-precomp
CPPFLAGS = -I/opt/local/include -I/opt/local/include/ossp -I/opt/local/include/libxml2 -I/opt/local/include
CFLAGS = -O2 -Wall -Wmissing-prototypes -Wpointer-arith -Winline -Wdeclaration-after-statement -Wendif-labels -fno-strict-aliasing -fwrapv
CFLAGS_SL =
LDFLAGS = -L/opt/local/lib -L/opt/local/lib -L/opt/local/lib
LDFLAGS_SL =
LIBS = -lpgport -lxslt -lxml2 -lssl -lcrypto -lz -lreadline -lm
VERSION = PostgreSQL 8.3.4
</code></pre>
<p>(I've just switched from Linux to Mac a couple of days ago... In Ubuntu stuff like that used to <em>just work</em>, so I am pretty lost.)</p>
| 1 | 2008-10-27T01:03:40Z | 238,906 | <p>Silly me:</p>
<pre><code>[lib/postgresql83] > variants postgresql83
postgresql83 has the variants:
universal
python: add support for python
krb5: add support for Kerberos 5 authentication
perl: add Perl support
</code></pre>
<p>(I'd had <code>universal</code>.)</p>
<p>This means that you have to install the right variant of PostgreSQL to make your python functions fly.</p>
<pre><code>$ sudo port install postgresql83 +python postgresql-server +python
</code></pre>
| 3 | 2008-10-27T01:20:29Z | [
"python",
"osx",
"postgresql"
] |
getting pywin32 to work inside open office 2.4 built in python 2.3 interpreter | 239,009 | <p>I need to update data to a mssql 2005 database so I have decided to use adodbapi, which is supposed to come built into the standard installation of python 2.1.1 and greater.</p>
<p>It needs pywin32 to work correctly and the open office python 2.3 installation does not have pywin32 built into it. It also seems like this built int python installation does not have adodbapi, as I get an error when I go import adodbapi. </p>
<p>Any suggestions on how to get both pywin32 and adodbapi installed into this open office 2.4 python installation?</p>
<p>thanks </p>
<p><hr /></p>
<p>oh yeah I tried those ways. annoyingly nothing. So i have reverted to jython, that way I can access Open Office for its conversion capabilities along with decent database access.</p>
<p>Thanks for the help.</p>
| 0 | 2008-10-27T03:32:24Z | 239,014 | <p><a href="http://www.time-travellers.org/shane/howtos/MS-SQL-Express-Python-HOWTO.html" rel="nofollow">http://www.time-travellers.org/shane/howtos/MS-SQL-Express-Python-HOWTO.html</a></p>
<p>use an alternative?</p>
| 0 | 2008-10-27T03:34:37Z | [
"python",
"openoffice.org",
"pywin32",
"adodbapi"
] |
getting pywin32 to work inside open office 2.4 built in python 2.3 interpreter | 239,009 | <p>I need to update data to a mssql 2005 database so I have decided to use adodbapi, which is supposed to come built into the standard installation of python 2.1.1 and greater.</p>
<p>It needs pywin32 to work correctly and the open office python 2.3 installation does not have pywin32 built into it. It also seems like this built int python installation does not have adodbapi, as I get an error when I go import adodbapi. </p>
<p>Any suggestions on how to get both pywin32 and adodbapi installed into this open office 2.4 python installation?</p>
<p>thanks </p>
<p><hr /></p>
<p>oh yeah I tried those ways. annoyingly nothing. So i have reverted to jython, that way I can access Open Office for its conversion capabilities along with decent database access.</p>
<p>Thanks for the help.</p>
| 0 | 2008-10-27T03:32:24Z | 239,179 | <p>I don't know about open office python.
I suggest trying the standard <a href="http://www.python.org/download/" rel="nofollow">windows python installation</a> followed by <a href="http://sourceforge.net/projects/pywin32/" rel="nofollow">Pywin32</a>. Alternatively, there is a single installer containing both at <a href="http://www.activestate.com/Products/activepython/feature_list.mhtml" rel="nofollow">activestate</a>. In the <em>pythonwin IDE</em>, select menu item <code>tools / COM Makepy utility</code>. The libraries you need to build with <code>makepy</code> are (or similar versions):</p>
<pre><code>Microsoft ActiveX Data Objects 2.8 Library (2.8)
Microsoft ActiveX Data Objects Recordset 2.8 Library (2.8)
</code></pre>
<p>After <code>makepy</code> is done, you can use the <code>COM</code> object to access <code>ADODB</code>:</p>
<pre><code>from win32com import client
conn=client.Dispatch('adodb.connection')
conn.Open(connection_string)
resultset,x=e.Execute('select * from mytable')
resultset.MoveFirst()
record_fields=resultset.Fields
(etc.)
</code></pre>
| 0 | 2008-10-27T05:56:42Z | [
"python",
"openoffice.org",
"pywin32",
"adodbapi"
] |
getting pywin32 to work inside open office 2.4 built in python 2.3 interpreter | 239,009 | <p>I need to update data to a mssql 2005 database so I have decided to use adodbapi, which is supposed to come built into the standard installation of python 2.1.1 and greater.</p>
<p>It needs pywin32 to work correctly and the open office python 2.3 installation does not have pywin32 built into it. It also seems like this built int python installation does not have adodbapi, as I get an error when I go import adodbapi. </p>
<p>Any suggestions on how to get both pywin32 and adodbapi installed into this open office 2.4 python installation?</p>
<p>thanks </p>
<p><hr /></p>
<p>oh yeah I tried those ways. annoyingly nothing. So i have reverted to jython, that way I can access Open Office for its conversion capabilities along with decent database access.</p>
<p>Thanks for the help.</p>
| 0 | 2008-10-27T03:32:24Z | 239,487 | <p>maybe the best way to install pywin32 is to place it in </p>
<p>(openofficedir)\program\python-core-2.3.4\lib\site-packages</p>
<p>it is easy if you have a python 2.3 installation (with pywin installed) under </p>
<p>C:\python2.3 </p>
<p>move the C:\python2.3\Lib\site-packages\ to your</p>
<p>(openofficedir)\program\python-core-2.3.4\lib\site-packages</p>
| 1 | 2008-10-27T10:13:39Z | [
"python",
"openoffice.org",
"pywin32",
"adodbapi"
] |
How can I call a DLL from a scripting language? | 239,020 | <p>I have a third-party product, a terminal emulator, which provides a DLL that can be linked to a C program to basically automate the driving of this product (send keystrokes, detect what's on the screen and so forth).</p>
<p>I want to drive it from a scripting language (I'm comfortable with Python and slightly less so with Perl) so that we don't have to compile and send out executables to our customers whenever there's a problem found.</p>
<p>We also want the customers to be able to write their own scripts using ours as baselines and they won't entertain the idea of writing and compiling C code.</p>
<p>What's a good way of getting Python/Perl to interface to a Windows DLL. My first thought was to write a server program and have a Python script communicate with it via TCP but there's got to be an easier solution.</p>
| 9 | 2008-10-27T03:42:07Z | 239,041 | <p>One way to call C libraries from Python is to use <a href="https://docs.python.org/library/ctypes.html" rel="nofollow">ctypes</a>:</p>
<pre><code>>>> from ctypes import *
>>> windll.user32.MessageBoxA(None, "Hello world", "ctypes", 0);
</code></pre>
| 15 | 2008-10-27T03:57:11Z | [
"python",
"perl",
"dll"
] |
How can I call a DLL from a scripting language? | 239,020 | <p>I have a third-party product, a terminal emulator, which provides a DLL that can be linked to a C program to basically automate the driving of this product (send keystrokes, detect what's on the screen and so forth).</p>
<p>I want to drive it from a scripting language (I'm comfortable with Python and slightly less so with Perl) so that we don't have to compile and send out executables to our customers whenever there's a problem found.</p>
<p>We also want the customers to be able to write their own scripts using ours as baselines and they won't entertain the idea of writing and compiling C code.</p>
<p>What's a good way of getting Python/Perl to interface to a Windows DLL. My first thought was to write a server program and have a Python script communicate with it via TCP but there's got to be an easier solution.</p>
| 9 | 2008-10-27T03:42:07Z | 239,043 | <p>In Perl, <a href="http://search.cpan.org/perldoc?Win32::API" rel="nofollow">Win32::API</a> is an easy way to some interfacing to DLLs. There is also <a href="http://search.cpan.org/perldoc?Inline::C" rel="nofollow">Inline::C</a>, if you have access to a compiler and the windows headers.</p>
<p>Perl <a href="http://search.cpan.org/perldoc?perlxs" rel="nofollow">XSUB</a>s can also create an interface between Perl and C. </p>
| 12 | 2008-10-27T03:58:05Z | [
"python",
"perl",
"dll"
] |
How can I call a DLL from a scripting language? | 239,020 | <p>I have a third-party product, a terminal emulator, which provides a DLL that can be linked to a C program to basically automate the driving of this product (send keystrokes, detect what's on the screen and so forth).</p>
<p>I want to drive it from a scripting language (I'm comfortable with Python and slightly less so with Perl) so that we don't have to compile and send out executables to our customers whenever there's a problem found.</p>
<p>We also want the customers to be able to write their own scripts using ours as baselines and they won't entertain the idea of writing and compiling C code.</p>
<p>What's a good way of getting Python/Perl to interface to a Windows DLL. My first thought was to write a server program and have a Python script communicate with it via TCP but there's got to be an easier solution.</p>
| 9 | 2008-10-27T03:42:07Z | 239,064 | <p>In Perl, <a href="http://search.cpan.org/perldoc/P5NCI" rel="nofollow">P5NCI</a> will also do that, at least in some cases. But it seems to me that anything you use that directly manages interfacing with the dll is going to be user-unfriendly, and if you are going to have a user (scriptor?) friendly wrapper, it might as well be an XS module.</p>
<p>I guess I don't see a meaningful distinction between "compile and send out executables" and "compile and send out scripts".</p>
| 5 | 2008-10-27T04:13:34Z | [
"python",
"perl",
"dll"
] |
How can I call a DLL from a scripting language? | 239,020 | <p>I have a third-party product, a terminal emulator, which provides a DLL that can be linked to a C program to basically automate the driving of this product (send keystrokes, detect what's on the screen and so forth).</p>
<p>I want to drive it from a scripting language (I'm comfortable with Python and slightly less so with Perl) so that we don't have to compile and send out executables to our customers whenever there's a problem found.</p>
<p>We also want the customers to be able to write their own scripts using ours as baselines and they won't entertain the idea of writing and compiling C code.</p>
<p>What's a good way of getting Python/Perl to interface to a Windows DLL. My first thought was to write a server program and have a Python script communicate with it via TCP but there's got to be an easier solution.</p>
| 9 | 2008-10-27T03:42:07Z | 239,098 | <p>For Python, you could compile an extension which links to the DLL, so that in Python you could just import it like a normal module. You could do this by hand, by using a library like Boost.Python, or by using a tool such as SWIG (which also supports Perl and other scripting languages) to generate a wrapper automatically.</p>
| 4 | 2008-10-27T04:46:03Z | [
"python",
"perl",
"dll"
] |
How can I call a DLL from a scripting language? | 239,020 | <p>I have a third-party product, a terminal emulator, which provides a DLL that can be linked to a C program to basically automate the driving of this product (send keystrokes, detect what's on the screen and so forth).</p>
<p>I want to drive it from a scripting language (I'm comfortable with Python and slightly less so with Perl) so that we don't have to compile and send out executables to our customers whenever there's a problem found.</p>
<p>We also want the customers to be able to write their own scripts using ours as baselines and they won't entertain the idea of writing and compiling C code.</p>
<p>What's a good way of getting Python/Perl to interface to a Windows DLL. My first thought was to write a server program and have a Python script communicate with it via TCP but there's got to be an easier solution.</p>
| 9 | 2008-10-27T03:42:07Z | 241,652 | <p>The Python <strong>Py_InitModule</strong> API function allows you to create a module from c/c++ functions which can then be call from Python. </p>
<p>It takes about a dozen or so lines of c/c++ code to achieve but it is pretty easy code to write:</p>
<p><a href="https://python.readthedocs.org/en/v2.7.2/extending/extending.html#the-module-s-method-table-and-initialization-function" rel="nofollow">https://python.readthedocs.org/en/v2.7.2/extending/extending.html#the-module-s-method-table-and-initialization-function</a></p>
<p>The <a href="http://www.zeusedit.com" rel="nofollow">Zeus</a> editor that I wrote, uses this appoach to allow <a href="http://www.zeusedit.com" rel="nofollow">Zeus</a> macros to be written in Python and it works very well.</p>
| 3 | 2008-10-27T22:56:18Z | [
"python",
"perl",
"dll"
] |
Python: DISTINCT on GQuery result set (GQL, GAE) | 239,258 | <p>Imagine you got an entity in the Google App Engine datastore, storing links for anonymous users.
You would like to perform the following SQL query, which is not supported:</p>
<pre><code>SELECT DISTINCT user_hash FROM links
</code></pre>
<p>Instead you could use:</p>
<pre><code>user = db.GqlQuery("SELECT user_hash FROM links")
</code></pre>
<p>How to use Python <strong>most efficiently</strong> to filter the result, so it returns a DISTINCT result set?
How to count the DISTINCT result set?</p>
| 7 | 2008-10-27T07:13:11Z | 239,305 | <p>One option would be to put the results into a set object:</p>
<p><a href="http://www.python.org/doc/2.6/library/sets.html#sets.Set" rel="nofollow">http://www.python.org/doc/2.6/library/sets.html#sets.Set</a></p>
<p>The resulting set will consist only of the distinct values passed into it.</p>
<p>Failing that, building up a new list containing only the unique objects would work. Something like:</p>
<pre><code>unique_results = []
for obj in user:
if obj not in unique_results:
unique_results.append(obj)
</code></pre>
<p>That <code>for</code> loop can be condensed into a list comprehension as well.</p>
| 1 | 2008-10-27T08:01:47Z | [
"python",
"sql",
"google-app-engine",
"distinct",
"gql"
] |
Python: DISTINCT on GQuery result set (GQL, GAE) | 239,258 | <p>Imagine you got an entity in the Google App Engine datastore, storing links for anonymous users.
You would like to perform the following SQL query, which is not supported:</p>
<pre><code>SELECT DISTINCT user_hash FROM links
</code></pre>
<p>Instead you could use:</p>
<pre><code>user = db.GqlQuery("SELECT user_hash FROM links")
</code></pre>
<p>How to use Python <strong>most efficiently</strong> to filter the result, so it returns a DISTINCT result set?
How to count the DISTINCT result set?</p>
| 7 | 2008-10-27T07:13:11Z | 239,326 | <p>A set is good way to deal with that:</p>
<pre><code>>>> a = ['google.com', 'livejournal.com', 'livejournal.com', 'google.com', 'stackoverflow.com']
>>> b = set(a)
>>> b
set(['livejournal.com', 'google.com', 'stackoverflow.com'])
>>>
</code></pre>
<p>One suggestion w/r/t the first answer, is that sets and dicts are better at retrieving unique results quickly, membership in lists is O(n) versus O(1) for the other types, so if you want to store additional data, or do something like create the mentioned <code>unique_results</code> list, it may be better to do something like:</p>
<pre><code>unique_results = {}
>>> for item in a:
unique_results[item] = ''
>>> unique_results
{'livejournal.com': '', 'google.com': '', 'stackoverflow.com': ''}
</code></pre>
| 3 | 2008-10-27T08:25:57Z | [
"python",
"sql",
"google-app-engine",
"distinct",
"gql"
] |
Python: DISTINCT on GQuery result set (GQL, GAE) | 239,258 | <p>Imagine you got an entity in the Google App Engine datastore, storing links for anonymous users.
You would like to perform the following SQL query, which is not supported:</p>
<pre><code>SELECT DISTINCT user_hash FROM links
</code></pre>
<p>Instead you could use:</p>
<pre><code>user = db.GqlQuery("SELECT user_hash FROM links")
</code></pre>
<p>How to use Python <strong>most efficiently</strong> to filter the result, so it returns a DISTINCT result set?
How to count the DISTINCT result set?</p>
| 7 | 2008-10-27T07:13:11Z | 5,340,901 | <p>Sorry to dig this question up but in GAE I cannot compare objects like that, I must use .key() for comparison like that:</p>
<p>Beware, this is very inefficient :</p>
<pre><code>def unique_result(array):
urk={} #unique results with key
for c in array:
if c.key() not in urwk:
urk[str(c.key())]=c
return urk.values()
</code></pre>
<p>If anyone has a better solution, please share.</p>
| 0 | 2011-03-17T15:04:24Z | [
"python",
"sql",
"google-app-engine",
"distinct",
"gql"
] |
Python: DISTINCT on GQuery result set (GQL, GAE) | 239,258 | <p>Imagine you got an entity in the Google App Engine datastore, storing links for anonymous users.
You would like to perform the following SQL query, which is not supported:</p>
<pre><code>SELECT DISTINCT user_hash FROM links
</code></pre>
<p>Instead you could use:</p>
<pre><code>user = db.GqlQuery("SELECT user_hash FROM links")
</code></pre>
<p>How to use Python <strong>most efficiently</strong> to filter the result, so it returns a DISTINCT result set?
How to count the DISTINCT result set?</p>
| 7 | 2008-10-27T07:13:11Z | 14,169,747 | <p>Reviving this question for completion:</p>
<p>The DISTINCT keyword has been introduced in <a href="http://googleappengine.blogspot.com/2012/12/app-engine-174-released.html" rel="nofollow">release 1.7.4</a>.</p>
<p>You can find the updated GQL reference (for example for Python) <a href="https://developers.google.com/appengine/docs/python/datastore/gqlreference" rel="nofollow">here</a>.</p>
| 4 | 2013-01-05T07:38:24Z | [
"python",
"sql",
"google-app-engine",
"distinct",
"gql"
] |
WindowsError: priveledged instruction when saving a FreeImagePy Image in script, works in IDLE | 240,031 | <p>I'm working on a program to do some image wrangling in Python for work. I'm using FreeImagePy because PIL doesn't support multi-page TIFFs. Whenever I try to save a file with it from my program I get this error message (or something similar depending on which way I try to save):</p>
<pre><code>Error returned. TIFF FreeImage_Save: failed to open file C:/OCRtmp/ocr page0
Traceback (most recent call last):
File "C:\Python25\Projects\OCRPageUnzipper\PageUnzipper.py", line 102, in <mod
ule> OCRBox.convertToPages("C:/OCRtmp/ocr page",FIPY.FIF_TIFF)
File "C:\Python25\lib\site-packages\FreeImagePy\FreeImagePy\FreeImagePy.py", l
ine 2080, in convertToPages self.Save(FIF, dib, fileNameOut, flags)
File "C:\Python25\lib\site-packages\FreeImagePy\FreeImagePy\FreeImagePy.py", l
ine 187, in Save return self.__lib.Save(typ, bitmap, fileName, flags)
WindowsError: exception: priviledged instruction
</code></pre>
<p>When I try and do the same things from IDLE, it works fine.</p>
| 1 | 2008-10-27T14:18:54Z | 242,366 | <p>Looks like a permission issues, make sure you don't have the file open in another application, and that you have write permissions to the file location your trying to write to.</p>
| 1 | 2008-10-28T06:04:56Z | [
"python",
"exception",
"windowserror"
] |
WindowsError: priveledged instruction when saving a FreeImagePy Image in script, works in IDLE | 240,031 | <p>I'm working on a program to do some image wrangling in Python for work. I'm using FreeImagePy because PIL doesn't support multi-page TIFFs. Whenever I try to save a file with it from my program I get this error message (or something similar depending on which way I try to save):</p>
<pre><code>Error returned. TIFF FreeImage_Save: failed to open file C:/OCRtmp/ocr page0
Traceback (most recent call last):
File "C:\Python25\Projects\OCRPageUnzipper\PageUnzipper.py", line 102, in <mod
ule> OCRBox.convertToPages("C:/OCRtmp/ocr page",FIPY.FIF_TIFF)
File "C:\Python25\lib\site-packages\FreeImagePy\FreeImagePy\FreeImagePy.py", l
ine 2080, in convertToPages self.Save(FIF, dib, fileNameOut, flags)
File "C:\Python25\lib\site-packages\FreeImagePy\FreeImagePy\FreeImagePy.py", l
ine 187, in Save return self.__lib.Save(typ, bitmap, fileName, flags)
WindowsError: exception: priviledged instruction
</code></pre>
<p>When I try and do the same things from IDLE, it works fine.</p>
| 1 | 2008-10-27T14:18:54Z | 244,526 | <p>That's what I thought too, but I figured it out a couple hours ago. Apparently if the directory/file I'm trying to write to doesn't exist, FreeImagePy isn't smart enough to create it (most of the time. Creating a new multipage image seems to work fine) but i guess running it within IDLE, IDLE figures it out and takes care of it or something. I managed to work around it by using os.mkdir to explicitly make sure things that I need exist.</p>
| 0 | 2008-10-28T19:29:43Z | [
"python",
"exception",
"windowserror"
] |
Python list of lists, changes reflected across sublists unexpectedly | 240,178 | <p>I needed to create a list of lists in Python, so I typed the following: </p>
<pre><code>myList = [[1] * 4] * 3
</code></pre>
<p>The list looked like this: </p>
<pre><code>[[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]
</code></pre>
<p>Then I changed one of the innermost values: </p>
<pre><code>myList[0][0] = 5
</code></pre>
<p>Now my list looks like this: </p>
<pre><code>[[5, 1, 1, 1], [5, 1, 1, 1], [5, 1, 1, 1]]
</code></pre>
<p>which is not what I wanted or expected. Can someone please explain what's going on, and how to get around it?</p>
| 227 | 2008-10-27T14:57:22Z | 240,202 | <pre><code> [[1] * 4] * 3
</code></pre>
<p>or even</p>
<pre><code> [[1, 1, 1, 1]] * 3
</code></pre>
<p>Creates a list that references the internal <code>[1,1,1,1]</code> 3 times - not three copies of the inner list, so any time you modify the list (in any position), you'll see the change three times.</p>
<p>It's the same as this example:</p>
<pre><code>>>> inner = [1,1,1,1]
>>> outer = [inner]*3
>>> outer
[[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]
>>> inner[0] = 5
>>> outer
[[5, 1, 1, 1], [5, 1, 1, 1], [5, 1, 1, 1]]
</code></pre>
<p>where it's probably a little less surprising.</p>
| 19 | 2008-10-27T15:02:54Z | [
"python",
"list",
"nested-lists",
"mutable"
] |
Python list of lists, changes reflected across sublists unexpectedly | 240,178 | <p>I needed to create a list of lists in Python, so I typed the following: </p>
<pre><code>myList = [[1] * 4] * 3
</code></pre>
<p>The list looked like this: </p>
<pre><code>[[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]
</code></pre>
<p>Then I changed one of the innermost values: </p>
<pre><code>myList[0][0] = 5
</code></pre>
<p>Now my list looks like this: </p>
<pre><code>[[5, 1, 1, 1], [5, 1, 1, 1], [5, 1, 1, 1]]
</code></pre>
<p>which is not what I wanted or expected. Can someone please explain what's going on, and how to get around it?</p>
| 227 | 2008-10-27T14:57:22Z | 240,205 | <p>When you write <code>[x]*3</code> you get, essentially, the list <code>[x, x, x]</code>. That is, a list with 3 references to the same <code>x</code>. When you then modify this single <code>x</code> it is visible via all three references to it.</p>
<p>To fix it, you need to make sure that you create a new list at each position. One way to do it is</p>
<pre><code>[[1]*4 for n in range(3)]
</code></pre>
| 186 | 2008-10-27T15:03:30Z | [
"python",
"list",
"nested-lists",
"mutable"
] |
Python list of lists, changes reflected across sublists unexpectedly | 240,178 | <p>I needed to create a list of lists in Python, so I typed the following: </p>
<pre><code>myList = [[1] * 4] * 3
</code></pre>
<p>The list looked like this: </p>
<pre><code>[[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]
</code></pre>
<p>Then I changed one of the innermost values: </p>
<pre><code>myList[0][0] = 5
</code></pre>
<p>Now my list looks like this: </p>
<pre><code>[[5, 1, 1, 1], [5, 1, 1, 1], [5, 1, 1, 1]]
</code></pre>
<p>which is not what I wanted or expected. Can someone please explain what's going on, and how to get around it?</p>
| 227 | 2008-10-27T14:57:22Z | 240,215 | <p>Actually, this is exactly what you would expect. Let's decompose what is happening here:</p>
<p>You write</p>
<pre><code>lst = [[1] * 4] * 3
</code></pre>
<p>This is equivalent to:</p>
<pre><code>lst1 = [1]*4
lst = [lst1]*3
</code></pre>
<p>This means <code>lst</code> is a list with 3 elements all pointing to <code>lst1</code>. This means the two following lines are equivalent:</p>
<pre><code>lst[0][0] = 5
lst1[0] = 5
</code></pre>
<p>As <code>lst[0]</code> is nothing but <code>lst1</code>.</p>
<p>To obtain the desired behavior, you can use list comprehension:</p>
<pre><code>lst = [ [1]*4 for n in xrange(3) ]
</code></pre>
<p>In this case, the expression is re-evaluated for each n, leading to a different list.</p>
| 26 | 2008-10-27T15:07:02Z | [
"python",
"list",
"nested-lists",
"mutable"
] |
Python list of lists, changes reflected across sublists unexpectedly | 240,178 | <p>I needed to create a list of lists in Python, so I typed the following: </p>
<pre><code>myList = [[1] * 4] * 3
</code></pre>
<p>The list looked like this: </p>
<pre><code>[[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]
</code></pre>
<p>Then I changed one of the innermost values: </p>
<pre><code>myList[0][0] = 5
</code></pre>
<p>Now my list looks like this: </p>
<pre><code>[[5, 1, 1, 1], [5, 1, 1, 1], [5, 1, 1, 1]]
</code></pre>
<p>which is not what I wanted or expected. Can someone please explain what's going on, and how to get around it?</p>
| 227 | 2008-10-27T14:57:22Z | 18,454,568 | <pre><code>size = 3
matrix_surprise = [[0] * size] * size
matrix = [[0]*size for i in range(size)]
</code></pre>
<p><img src="https://i.stack.imgur.com/uHuck.png" alt="Frames and Objects"></p>
<p><a href="http://pythontutor.com/visualize.html#code=size+%3D+3%0Amatrix_surprise+%3D+%5B%5B0%5D+*+size%5D+*+size%0Amatrix+%3D+%5B%5B0%5D*size+for+i+in+range(size)%5D&mode=display&cumulative=false&heapPrimitives=false&drawParentPointers=false&textReferences=false&showOnlyOutputs=false&py=2&curInstr=6">Live Python Tutor Visualize</a></p>
| 56 | 2013-08-26T23:17:52Z | [
"python",
"list",
"nested-lists",
"mutable"
] |
Python list of lists, changes reflected across sublists unexpectedly | 240,178 | <p>I needed to create a list of lists in Python, so I typed the following: </p>
<pre><code>myList = [[1] * 4] * 3
</code></pre>
<p>The list looked like this: </p>
<pre><code>[[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]
</code></pre>
<p>Then I changed one of the innermost values: </p>
<pre><code>myList[0][0] = 5
</code></pre>
<p>Now my list looks like this: </p>
<pre><code>[[5, 1, 1, 1], [5, 1, 1, 1], [5, 1, 1, 1]]
</code></pre>
<p>which is not what I wanted or expected. Can someone please explain what's going on, and how to get around it?</p>
| 227 | 2008-10-27T14:57:22Z | 28,146,989 | <p>Actually, think it in another case. Assume that if your list is this;</p>
<pre><code>[[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]
</code></pre>
<p>and if you write <code>myList[0][0] = 5</code> output will be;</p>
<pre><code>>>>
[[5, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]
>>>
</code></pre>
<p>As you expected. But since you define your list variable like this;</p>
<pre><code>[[1] * 4] * 3
</code></pre>
<p>Python will process your codes on this pattern. So if you write <code>myList[0][0]</code> and your list defined like above, Python will process it like <code>[1]*3</code>. That's why all of the lists first elements are changed.</p>
| -1 | 2015-01-26T08:50:32Z | [
"python",
"list",
"nested-lists",
"mutable"
] |
Python list of lists, changes reflected across sublists unexpectedly | 240,178 | <p>I needed to create a list of lists in Python, so I typed the following: </p>
<pre><code>myList = [[1] * 4] * 3
</code></pre>
<p>The list looked like this: </p>
<pre><code>[[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]
</code></pre>
<p>Then I changed one of the innermost values: </p>
<pre><code>myList[0][0] = 5
</code></pre>
<p>Now my list looks like this: </p>
<pre><code>[[5, 1, 1, 1], [5, 1, 1, 1], [5, 1, 1, 1]]
</code></pre>
<p>which is not what I wanted or expected. Can someone please explain what's going on, and how to get around it?</p>
| 227 | 2008-10-27T14:57:22Z | 30,759,580 | <p>Let us rewrite your code in the following way:</p>
<pre><code>x = 1
y = [x]
z = y * 4
myList = [z] * 3
</code></pre>
<p>Then having this, run the following code to make everything more clear. What the code does is basically print the <a href="https://docs.python.org/2/library/functions.html#id" rel="nofollow"><code>id</code></a>s of the obtained objects, which</p>
<blockquote>
<p>Return the âidentityâ of an object</p>
</blockquote>
<p>and will help us identify them and analyse what happens:</p>
<pre><code>print("myList:")
for i, subList in enumerate(myList):
print("\t[{}]: {}".format(i, id(subList)))
for j, elem in enumerate(subList):
print("\t\t[{}]: {}".format(j, id(elem)))
</code></pre>
<p>And you will get the following output:</p>
<pre><code>x: 1
y: [1]
z: [1, 1, 1, 1]
myList:
[0]: 4300763792
[0]: 4298171528
[1]: 4298171528
[2]: 4298171528
[3]: 4298171528
[1]: 4300763792
[0]: 4298171528
[1]: 4298171528
[2]: 4298171528
[3]: 4298171528
[2]: 4300763792
[0]: 4298171528
[1]: 4298171528
[2]: 4298171528
[3]: 4298171528
</code></pre>
<hr>
<p>So now let us go step-by-step. You have <code>x</code> which is <code>1</code>, and a single element list <code>y</code> containing <code>x</code>. Your first step is <code>y * 4</code> which will get you a new list <code>z</code>, which is basically <code>[x, x, x, x]</code>, i.e. it creates a new list which will have 4 elements, which are references to the initial <code>x</code> object. The net step is pretty similar. You basically do <code>z * 3</code>, which is <code>[[x, x, x, x]] * 3</code> and returns <code>[[x, x, x, x], [x, x, x, x], [x, x, x, x]]</code>, for the same reason as for the first step.</p>
| 0 | 2015-06-10T14:38:24Z | [
"python",
"list",
"nested-lists",
"mutable"
] |
Python list of lists, changes reflected across sublists unexpectedly | 240,178 | <p>I needed to create a list of lists in Python, so I typed the following: </p>
<pre><code>myList = [[1] * 4] * 3
</code></pre>
<p>The list looked like this: </p>
<pre><code>[[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]
</code></pre>
<p>Then I changed one of the innermost values: </p>
<pre><code>myList[0][0] = 5
</code></pre>
<p>Now my list looks like this: </p>
<pre><code>[[5, 1, 1, 1], [5, 1, 1, 1], [5, 1, 1, 1]]
</code></pre>
<p>which is not what I wanted or expected. Can someone please explain what's going on, and how to get around it?</p>
| 227 | 2008-10-27T14:57:22Z | 30,898,048 | <p>Alongside the accepted answer that explained the problem correctly instead of creating a list with duplicated elements using following code :</p>
<pre><code>[[1]*4 for n in range(3)]
</code></pre>
<p>That use the throwaway variable <code>n</code> and the <code>range()</code> function, if You are in python 2 use <code>xrange()</code> that returns a generator which is more efficient (<code>range()</code> in python 3 does the same job) and use <code>_</code> instead of <code>n</code>: </p>
<pre><code>[[1]*4 for _ in xrange(3)] # and in python3 [[1]*4 for _ in range(3)]
</code></pre>
<p>Also you can use <a href="https://docs.python.org/2/library/itertools.html#itertools.repeat" rel="nofollow"><code>itertools.repeat()</code></a> that returns a generator of repeated elements :</p>
<pre><code>>>> a=list(repeat(1,4))
[1, 1, 1, 1]
>>> a[0]=5
>>> a
[5, 1, 1, 1]
</code></pre>
| 3 | 2015-06-17T17:08:52Z | [
"python",
"list",
"nested-lists",
"mutable"
] |
Python list of lists, changes reflected across sublists unexpectedly | 240,178 | <p>I needed to create a list of lists in Python, so I typed the following: </p>
<pre><code>myList = [[1] * 4] * 3
</code></pre>
<p>The list looked like this: </p>
<pre><code>[[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]
</code></pre>
<p>Then I changed one of the innermost values: </p>
<pre><code>myList[0][0] = 5
</code></pre>
<p>Now my list looks like this: </p>
<pre><code>[[5, 1, 1, 1], [5, 1, 1, 1], [5, 1, 1, 1]]
</code></pre>
<p>which is not what I wanted or expected. Can someone please explain what's going on, and how to get around it?</p>
| 227 | 2008-10-27T14:57:22Z | 36,452,923 | <p>Python containers contain references to other objects. See this example:</p>
<pre><code>>>> a = []
>>> b = [a]
>>> b
[[]]
>>> a.append(1)
>>> b
[[1]]
</code></pre>
<p>In this <code>b</code> is a list that contains one item that is a reference to list <code>a</code>. The list <code>a</code> is mutable.</p>
<p>The multiplication of a list by an integer is equivalent to adding the list to itself multiple times (see <a href="https://docs.python.org/3/library/stdtypes.html#typesseq-common" rel="nofollow">common sequence operations</a>). So continuing with the example:</p>
<pre><code>>>> c = b + b
>>> c
[[1], [1]]
>>>
>>> a[0] = 2
>>> c
[[2], [2]]
</code></pre>
<p>We can see that the list <code>c</code> now contains two references to list <code>a</code> which is equivalent to <code>c = b * 2</code>.</p>
<p>Python FAQ also contains explanation of this behavior: <a href="https://docs.python.org/3/faq/programming.html#faq-multidimensional-list" rel="nofollow">How do I create a multidimensional list?</a></p>
| 0 | 2016-04-06T13:40:43Z | [
"python",
"list",
"nested-lists",
"mutable"
] |
Python list of lists, changes reflected across sublists unexpectedly | 240,178 | <p>I needed to create a list of lists in Python, so I typed the following: </p>
<pre><code>myList = [[1] * 4] * 3
</code></pre>
<p>The list looked like this: </p>
<pre><code>[[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]
</code></pre>
<p>Then I changed one of the innermost values: </p>
<pre><code>myList[0][0] = 5
</code></pre>
<p>Now my list looks like this: </p>
<pre><code>[[5, 1, 1, 1], [5, 1, 1, 1], [5, 1, 1, 1]]
</code></pre>
<p>which is not what I wanted or expected. Can someone please explain what's going on, and how to get around it?</p>
| 227 | 2008-10-27T14:57:22Z | 36,823,796 | <p>I guess everybody explain what is happening.
I suggest one way to solve it:</p>
<p><code>myList = [[1 for i in range(4)] for j in range(3)]</code></p>
<pre><code>myList[0][0] = 5
</code></pre>
<p><code>print myList</code></p>
<p>And then you have:</p>
<pre><code>[[5, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]
</code></pre>
| 0 | 2016-04-24T13:31:04Z | [
"python",
"list",
"nested-lists",
"mutable"
] |
Python list of lists, changes reflected across sublists unexpectedly | 240,178 | <p>I needed to create a list of lists in Python, so I typed the following: </p>
<pre><code>myList = [[1] * 4] * 3
</code></pre>
<p>The list looked like this: </p>
<pre><code>[[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]
</code></pre>
<p>Then I changed one of the innermost values: </p>
<pre><code>myList[0][0] = 5
</code></pre>
<p>Now my list looks like this: </p>
<pre><code>[[5, 1, 1, 1], [5, 1, 1, 1], [5, 1, 1, 1]]
</code></pre>
<p>which is not what I wanted or expected. Can someone please explain what's going on, and how to get around it?</p>
| 227 | 2008-10-27T14:57:22Z | 37,804,636 | <p>In simple words this is happening because in python everything works <strong>by reference</strong>, so when you create a list of list that way you basically end up with such problems.</p>
<p>To solve your issue you can do either one of them:
1. Use numpy array <a href="http://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.empty.html" rel="nofollow">documentation for numpy.empty</a>
2. Append the list as you get to a list.
3. You can also use dictionary if you want </p>
| 1 | 2016-06-14T06:36:52Z | [
"python",
"list",
"nested-lists",
"mutable"
] |
Python list of lists, changes reflected across sublists unexpectedly | 240,178 | <p>I needed to create a list of lists in Python, so I typed the following: </p>
<pre><code>myList = [[1] * 4] * 3
</code></pre>
<p>The list looked like this: </p>
<pre><code>[[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]
</code></pre>
<p>Then I changed one of the innermost values: </p>
<pre><code>myList[0][0] = 5
</code></pre>
<p>Now my list looks like this: </p>
<pre><code>[[5, 1, 1, 1], [5, 1, 1, 1], [5, 1, 1, 1]]
</code></pre>
<p>which is not what I wanted or expected. Can someone please explain what's going on, and how to get around it?</p>
| 227 | 2008-10-27T14:57:22Z | 38,397,772 | <p>By using the inbuilt list function you can do like this</p>
<pre><code>a
out:[[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]
#Displaying the list
a.remove(a[0])
out:[[1, 1, 1, 1], [1, 1, 1, 1]]
# Removed the first element of the list in which you want altered number
a.append([5,1,1,1])
out:[[1, 1, 1, 1], [1, 1, 1, 1], [5, 1, 1, 1]]
# append the element in the list but the appended element as you can see is appended in last but you want that in starting
a.reverse()
out:[[5, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]
#So at last reverse the whole list to get the desired list
</code></pre>
| 0 | 2016-07-15T13:48:36Z | [
"python",
"list",
"nested-lists",
"mutable"
] |
Python list of lists, changes reflected across sublists unexpectedly | 240,178 | <p>I needed to create a list of lists in Python, so I typed the following: </p>
<pre><code>myList = [[1] * 4] * 3
</code></pre>
<p>The list looked like this: </p>
<pre><code>[[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]
</code></pre>
<p>Then I changed one of the innermost values: </p>
<pre><code>myList[0][0] = 5
</code></pre>
<p>Now my list looks like this: </p>
<pre><code>[[5, 1, 1, 1], [5, 1, 1, 1], [5, 1, 1, 1]]
</code></pre>
<p>which is not what I wanted or expected. Can someone please explain what's going on, and how to get around it?</p>
| 227 | 2008-10-27T14:57:22Z | 38,866,487 | <p>Trying to explain it more descriptively,</p>
<p>Operation 1:</p>
<pre><code>x = [[0, 0], [0, 0]]
print(type(x)) # <class 'list'>
print(x) # [[0, 0], [0, 0]]
x[0][0] = 1
print(x) # [[1, 0], [0, 0]]
</code></pre>
<p>Operation 2:</p>
<pre><code>y = [[0] * 2] * 2
print(type(y)) # <class 'list'>
print(y) # [[0, 0], [0, 0]]
y[0][0] = 1
print(y) # [[1, 0], [1, 0]]
</code></pre>
<p>Noticed why doesn't modifying the first element of the first list didn't modify the second element of each list? That's because <code>[0] * 2</code> really is a list of two numbers, and a reference to 0 cannot be modified.</p>
<p>If you want to create clone copies, try Operation 3:</p>
<pre><code>import copy
y = [0] * 2
print(y) # [0, 0]
y = [y, copy.deepcopy(y)]
print(y) # [[0, 0], [0, 0]]
y[0][0] = 1
print(y) # [[1, 0], [0, 0]]
</code></pre>
<p>another interesting way to create clone copies, Operation 4:</p>
<pre><code>import copy
y = [0] * 2
print(y) # [0, 0]
y = [copy.deepcopy(y) for num in range(1,5)]
print(y) # [[0, 0], [0, 0], [0, 0], [0, 0]]
y[0][0] = 5
print(y) # [[5, 0], [0, 0], [0, 0], [0, 0]]
</code></pre>
| 0 | 2016-08-10T07:09:51Z | [
"python",
"list",
"nested-lists",
"mutable"
] |
post_save signal on m2m field | 240,659 | <p>I have a pretty generic Article model, with m2m relation to Tag model. I want to keep count of each tag usage, i think the best way would be to denormalise count field on Tag model and update it each time Article being saved. How can i accomplish this, or maybe there's a better way?</p>
| 5 | 2008-10-27T17:09:41Z | 241,430 | <p>You can do this by creating an <a href="http://docs.djangoproject.com/en/dev/topics/db/models/#extra-fields-on-many-to-many-relationships" rel="nofollow">intermediate model</a> for the M2M relationship and use it as your hook for the <code>post_save</code> and <code>post_delete</code> signals to update the denormalised column in the <code>Article</code> table.</p>
<p>For example, I do this for favourited <code>Question</code> counts in <a href="http://code.google.com/p/soclone/" rel="nofollow">soclone</a>, where <code>User</code>s have a M2M relationship with <code>Question</code>s:</p>
<pre><code>from django.contrib.auth.models import User
from django.db import connection, models, transaction
from django.db.models.signals import post_delete, post_save
class Question(models.Model):
# ...
favourite_count = models.PositiveIntegerField(default=0)
class FavouriteQuestion(models.Model):
question = models.ForeignKey(Question)
user = models.ForeignKey(User)
def update_question_favourite_count(instance, **kwargs):
"""
Updates the favourite count for the Question related to the given
FavouriteQuestion.
"""
if kwargs.get('raw', False):
return
cursor = connection.cursor()
cursor.execute(
'UPDATE soclone_question SET favourite_count = ('
'SELECT COUNT(*) from soclone_favouritequestion '
'WHERE soclone_favouritequestion.question_id = soclone_question.id'
') '
'WHERE id = %s', [instance.question_id])
transaction.commit_unless_managed()
post_save.connect(update_question_favourite_count, sender=FavouriteQuestion)
post_delete.connect(update_question_favourite_count, sender=FavouriteQuestion)
# Very, very naughty
User.add_to_class('favourite_questions',
models.ManyToManyField(Question, through=FavouriteQuestion,
related_name='favourited_by'))
</code></pre>
<p>There's been a bit of discussion on the django-developers mailing list about implementing a means of declaratively declaring denormalisations to avoid having to write code like the above:</p>
<ul>
<li><a href="http://groups.google.com/group/django-developers/browse_thread/thread/9a672d5bbbe67562" rel="nofollow">Denormalisation, magic, and is it really that useful?</a></li>
<li><a href="http://groups.google.com/group/django-developers/browse_thread/thread/6630273ab1869c19" rel="nofollow">Denormalisation Magic, Round Two</a> </li>
</ul>
| 2 | 2008-10-27T21:17:58Z | [
"python",
"django",
"django-signals"
] |
post_save signal on m2m field | 240,659 | <p>I have a pretty generic Article model, with m2m relation to Tag model. I want to keep count of each tag usage, i think the best way would be to denormalise count field on Tag model and update it each time Article being saved. How can i accomplish this, or maybe there's a better way?</p>
| 5 | 2008-10-27T17:09:41Z | 2,732,790 | <p>This is a new feature in Django 1.2:
<a href="http://docs.djangoproject.com/en/dev/ref/signals/#m2m-changed" rel="nofollow">http://docs.djangoproject.com/en/dev/ref/signals/#m2m-changed</a></p>
| 3 | 2010-04-28T20:10:44Z | [
"python",
"django",
"django-signals"
] |
Possible to integrate Google AppEngine and Google Code for continuous integration? | 241,007 | <p>Anyone have any thoughts on how/if it is possible to integrate Google Code commits to cause a Google AppEngine deployment of the most recent code?</p>
<p>I have a simple Google AppEngine project's source hosted on Google Code and would love if everytime I committed to Subversion, that AppEngine would reflect the latest commit. I don't mind if things are broken on the live site since the project is for personal use mainly and for learning.</p>
<p>Anyone have any thoughts on how to tie into the subversion commit for the Code repository and/or how to kickoff the deployment to AppEngine? Ideally the solution would not require anything manual from me nor any type of server/listener software on my machine.</p>
| 18 | 2008-10-27T18:43:41Z | 241,126 | <p>Very interesting, but not yet possible, AFAIK. I have been looking for that option in Google Code with no success.</p>
<p>The only solution I can figure out is to install something in your machine that checks for changes in your SVN repository.</p>
<p>I'll be happy to hear about other approaches.</p>
| 1 | 2008-10-27T19:26:59Z | [
"python",
"svn",
"google-app-engine",
"continuous-integration",
"google-code"
] |
Possible to integrate Google AppEngine and Google Code for continuous integration? | 241,007 | <p>Anyone have any thoughts on how/if it is possible to integrate Google Code commits to cause a Google AppEngine deployment of the most recent code?</p>
<p>I have a simple Google AppEngine project's source hosted on Google Code and would love if everytime I committed to Subversion, that AppEngine would reflect the latest commit. I don't mind if things are broken on the live site since the project is for personal use mainly and for learning.</p>
<p>Anyone have any thoughts on how to tie into the subversion commit for the Code repository and/or how to kickoff the deployment to AppEngine? Ideally the solution would not require anything manual from me nor any type of server/listener software on my machine.</p>
| 18 | 2008-10-27T18:43:41Z | 241,672 | <p>For those of us who are using Github, this feature from the GAE team would make us all seriously consider switching to Google Code...</p>
| 1 | 2008-10-27T23:02:16Z | [
"python",
"svn",
"google-app-engine",
"continuous-integration",
"google-code"
] |
Possible to integrate Google AppEngine and Google Code for continuous integration? | 241,007 | <p>Anyone have any thoughts on how/if it is possible to integrate Google Code commits to cause a Google AppEngine deployment of the most recent code?</p>
<p>I have a simple Google AppEngine project's source hosted on Google Code and would love if everytime I committed to Subversion, that AppEngine would reflect the latest commit. I don't mind if things are broken on the live site since the project is for personal use mainly and for learning.</p>
<p>Anyone have any thoughts on how to tie into the subversion commit for the Code repository and/or how to kickoff the deployment to AppEngine? Ideally the solution would not require anything manual from me nor any type of server/listener software on my machine.</p>
| 18 | 2008-10-27T18:43:41Z | 242,262 | <p>You'd probably have to have some glue on another computer which monitored SVN commits and deployed a new version for you. Google Code has yet to develop and release an API (which they need to do soon if they're serious about this whole development thing), but GAE can be deployed to with relative automated ease, so I wouldn't have thought it should be that difficult. The deployment process, however, will vary with each project, so that's something you need to sort out yourself (you might wanna take a look at the <a href="http://www.nongnu.org/fab/" rel="nofollow">fabric</a> deployment system). Then, just set a cron job going which updates a local SVN checkout on the middle machine, and you're done.</p>
| 2 | 2008-10-28T04:31:13Z | [
"python",
"svn",
"google-app-engine",
"continuous-integration",
"google-code"
] |
Possible to integrate Google AppEngine and Google Code for continuous integration? | 241,007 | <p>Anyone have any thoughts on how/if it is possible to integrate Google Code commits to cause a Google AppEngine deployment of the most recent code?</p>
<p>I have a simple Google AppEngine project's source hosted on Google Code and would love if everytime I committed to Subversion, that AppEngine would reflect the latest commit. I don't mind if things are broken on the live site since the project is for personal use mainly and for learning.</p>
<p>Anyone have any thoughts on how to tie into the subversion commit for the Code repository and/or how to kickoff the deployment to AppEngine? Ideally the solution would not require anything manual from me nor any type of server/listener software on my machine.</p>
| 18 | 2008-10-27T18:43:41Z | 342,168 | <p><a href="http://www.madebysofa.com" rel="nofollow">Made By Sofa</a> had a <a href="http://www.madebysofa.com/#blog/appengine_hosting" rel="nofollow">blog post</a> about their workflow with Google App Engine. In the second last paragraph they have <a href="http://www.madebysofa.com/media/downloads/appengine_deploy.sh" rel="nofollow">attached a subversion hook</a> that when when someone commits code it will automatically deploy to Google App Engine. It would take a little bit of tweaking (because it works on the server side not the client) but you could do the same.</p>
| 5 | 2008-12-04T21:37:02Z | [
"python",
"svn",
"google-app-engine",
"continuous-integration",
"google-code"
] |
Possible to integrate Google AppEngine and Google Code for continuous integration? | 241,007 | <p>Anyone have any thoughts on how/if it is possible to integrate Google Code commits to cause a Google AppEngine deployment of the most recent code?</p>
<p>I have a simple Google AppEngine project's source hosted on Google Code and would love if everytime I committed to Subversion, that AppEngine would reflect the latest commit. I don't mind if things are broken on the live site since the project is for personal use mainly and for learning.</p>
<p>Anyone have any thoughts on how to tie into the subversion commit for the Code repository and/or how to kickoff the deployment to AppEngine? Ideally the solution would not require anything manual from me nor any type of server/listener software on my machine.</p>
| 18 | 2008-10-27T18:43:41Z | 466,252 | <p>Google Code Project Hosting now supports <a href="http://code.google.com/p/support/wiki/PostCommitWebHooks" rel="nofollow">Post-Commit Web Hooks</a>, which ping a project-owner-specified URL after every commit. This would eliminate the need to regularly poll your Google Code repository.</p>
| 5 | 2009-01-21T17:34:57Z | [
"python",
"svn",
"google-app-engine",
"continuous-integration",
"google-code"
] |
Python lazy list | 241,141 | <p>I would like create my own collection that has all the attributes of python list and also knows how to save/load itself into/from a database. Also I want to make the load implicit and lazy, as in it doesn't happen at the point of creation of the list, but waits until its first used.</p>
<p>Is there a single<code>__xxx__</code>method I can override to load the list on first usage of any list property (such as<code>len</code>,<code>getitem</code>,<code>iter</code>...etc) without having to override them all?</p>
| 14 | 2008-10-27T19:32:52Z | 241,169 | <p><a href="http://www.python.org/doc/2.5.2/ref/new-style-attribute-access.html" rel="nofollow"><code>__getattribute__</code></a></p>
| 3 | 2008-10-27T19:42:08Z | [
"python",
"lazylist"
] |
Python lazy list | 241,141 | <p>I would like create my own collection that has all the attributes of python list and also knows how to save/load itself into/from a database. Also I want to make the load implicit and lazy, as in it doesn't happen at the point of creation of the list, but waits until its first used.</p>
<p>Is there a single<code>__xxx__</code>method I can override to load the list on first usage of any list property (such as<code>len</code>,<code>getitem</code>,<code>iter</code>...etc) without having to override them all?</p>
| 14 | 2008-10-27T19:32:52Z | 241,519 | <p>No, there isn't.</p>
| 1 | 2008-10-27T21:56:35Z | [
"python",
"lazylist"
] |
Python lazy list | 241,141 | <p>I would like create my own collection that has all the attributes of python list and also knows how to save/load itself into/from a database. Also I want to make the load implicit and lazy, as in it doesn't happen at the point of creation of the list, but waits until its first used.</p>
<p>Is there a single<code>__xxx__</code>method I can override to load the list on first usage of any list property (such as<code>len</code>,<code>getitem</code>,<code>iter</code>...etc) without having to override them all?</p>
| 14 | 2008-10-27T19:32:52Z | 242,111 | <p>Not exactly. For emulating things <em>other</em> than lists, there's <code>__getattribute__</code>, but unfortunately Python doesn't consider operators like <code>x[y]</code> or <code>x(y)</code> to be <em>exactly</em> the same as <code>x.__getitem__(y)</code> or <code>x.__call__(y)</code>. Operators like that are attributes of the class, not attributes of the instance, as you can see here:</p>
<pre><code>>>> class x(object):
... def __getattribute__(self, o):
... print o
...
>>> x()[3]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'x' object does not support indexing
</code></pre>
<p>However, you can take advantage of Python's dynamic nature to effectively eliminate that distinction. If your main concern is to save yourself typing, and to produce less code that needs maintaining, you can do something like this:</p>
<pre><code>class override(object):
def __init__(self, methodName):
self.methodName = methodName
def __get__(self, oself, cls):
oself._load(self.methodName)
return getattr(super(oself.__class__, oself), self.methodName)
class LazyList(list):
def _load(self, name):
print 'Loading data for %s...' % (name,)
for methodName in set(dir(list)) - set(dir(object)):
locals()[methodName] = override(methodName)
</code></pre>
<p>You probably don't want to use <code>dir()</code> in real life, but a suitable fixed list of strings could work as a substitute.</p>
| 7 | 2008-10-28T02:59:18Z | [
"python",
"lazylist"
] |
Python lazy list | 241,141 | <p>I would like create my own collection that has all the attributes of python list and also knows how to save/load itself into/from a database. Also I want to make the load implicit and lazy, as in it doesn't happen at the point of creation of the list, but waits until its first used.</p>
<p>Is there a single<code>__xxx__</code>method I can override to load the list on first usage of any list property (such as<code>len</code>,<code>getitem</code>,<code>iter</code>...etc) without having to override them all?</p>
| 14 | 2008-10-27T19:32:52Z | 5,104,787 | <p>Not a <em>single</em>, but 5 is enough:</p>
<pre><code>from collections import MutableSequence
class Monitored(MutableSequence):
  def __init__(self):
    super(Monitored, self).__init__()
    self._list = []
  def __len__(self):
    r = len(self._list)
    print "len: {0:d}".format(r)
    return r
  def __getitem__(self, index):
    r = self._list[index]
    print "getitem: {0!s}".format(index)
    return r
  def __setitem__(self, index, value):
    print "setitem {0!s}: {1:s}".format(index, repr(value))
    self._list[index] = value
  def __delitem__(self, index):
    print "delitem: {0!s}".format(index)
    del self._list[index]
  def insert(self, index, value):
    print "insert at {0:d}: {1:s}".format(index, repr(value))
    self._list.insert(index, value)
</code></pre>
<p>The correct way of checking if something implements the whole list interface is to check if it is a subclass of <code>MutableSequence</code>. The ABCs found in the <code>collections</code> module, of which <code>MutableSequence</code> is one, are there for two reasons: </p>
<ol>
<li><p>to allow you to make your own classes emulating internal container types so that they are usable everywhere a normal built-in is. </p></li>
<li><p>to use as argument for <code>isinstance</code> and <code>issubclass</code> to verify that an object implements the necessary functionality:</p></li>
</ol>
<p><p></p>
<pre><code>>>> isinstance([], MutableSequence)
True
>>> issubclass(list, MutableSequence)
True
</code></pre>
<p>Our <code>Monitored</code> class works like this:</p>
<pre>
>>> m = Monitored()
>>> m.append(3)
len: 0
insert at 0: 3
>>> m.extend((1, 4))
len: 1
insert at 1: 1
len: 2
insert at 2: 4
>>> m.l
[3, 1, 4]
>>> m.remove(4)
getitem: 0
getitem: 1
getitem: 2
delitem: 2
>>> m.pop(0) # after this, m.l == [1]
getitem: 0
delitem: 0
3
>>> m.insert(0, 4)
insert at 0: 4
>>> m.reverse() # After reversing, m.l == [1, 4]
len: 2
getitem: 1
getitem: 0
setitem 0: 1
setitem 1: 4
>>> m.index(4)
getitem: 0
getitem: 1
1
</pre>
| 7 | 2011-02-24T12:39:42Z | [
"python",
"lazylist"
] |
Python lazy list | 241,141 | <p>I would like create my own collection that has all the attributes of python list and also knows how to save/load itself into/from a database. Also I want to make the load implicit and lazy, as in it doesn't happen at the point of creation of the list, but waits until its first used.</p>
<p>Is there a single<code>__xxx__</code>method I can override to load the list on first usage of any list property (such as<code>len</code>,<code>getitem</code>,<code>iter</code>...etc) without having to override them all?</p>
| 14 | 2008-10-27T19:32:52Z | 18,638,351 | <p>There isn't a single method. You have to redefine quite a lot of them. MutableSequence seems to be the modern way of doing it. Here is a version that works with Python 2.4+::</p>
<pre><code>class LazyList(list):
"""List populated on first use."""
def __new__(cls, fill_iter):
class LazyList(list):
_fill_iter = None
_props = (
'__str__', '__repr__', '__unicode__',
'__hash__', '__sizeof__', '__cmp__', '__nonzero__',
'__lt__', '__le__', '__eq__', '__ne__', '__gt__', '__ge__',
'append', 'count', 'index', 'extend', 'insert', 'pop', 'remove',
'reverse', 'sort', '__add__', '__radd__', '__iadd__', '__mul__',
'__rmul__', '__imul__', '__contains__', '__len__', '__nonzero__',
'__getitem__', '__setitem__', '__delitem__', '__iter__',
'__reversed__', '__getslice__', '__setslice__', '__delslice__')
def lazy(name):
def _lazy(self, *args, **kw):
if self._fill_iter is not None:
_fill_lock.acquire()
try:
if self._fill_iter is not None:
list.extend(self, self._fill_iter)
self._fill_iter = None
finally:
_fill_lock.release()
real = getattr(list, name)
setattr(self.__class__, name, real)
return real(self, *args, **kw)
return _lazy
for name in _props:
setattr(LazyList, name, lazy(name))
new_list = LazyList()
new_list._fill_iter = fill_iter
return new_list
</code></pre>
| 1 | 2013-09-05T13:57:11Z | [
"python",
"lazylist"
] |
Single Table Inheritance in Django | 241,250 | <p>Is there explicit support for Single Table Inheritance in Django? Last I heard, the feature was still under development and debate. </p>
<p>Are there libraries/hacks I can use in the meantime to capture the basic behavior? I have a hierarchy that mixes different objects. The canonical example of a corporation structure with an Employee class, subclasses for types of employees, and a manager_id (parent_id) would be a good approximation of the problem I am solving. </p>
<p>In my case, I would like to represent the idea that an employee can manage other employees while being managed by a different employee. There are not separate classes for Manager and Worker, which makes this hard to spread across tables. Sub-classes would represent types of employees-programmers, accountants, sales, etc and would be independent of who supervises who (OK, I guess it's no longer a typical corporation in some respect). </p>
| 15 | 2008-10-27T20:18:08Z | 243,543 | <p>There are currently two forms of inheritance in Django - MTI (model table inheritance) and ABC (abstract base classes).</p>
<p>I wrote a <a href="http://web.archive.org/web/20090227074910/http://thisweekindjango.com/articles/2008/jun/17/abstract-base-classes-vs-model-tab/" rel="nofollow">tutorial</a> on what's going on under the hood.</p>
<p>You can also reference the official docs on <a href="http://docs.djangoproject.com/en/dev/topics/db/models/#model-inheritance" rel="nofollow">model inheritance</a>.</p>
| 15 | 2008-10-28T14:29:20Z | [
"python",
"django",
"django-models",
"single-table-inheritance"
] |
Single Table Inheritance in Django | 241,250 | <p>Is there explicit support for Single Table Inheritance in Django? Last I heard, the feature was still under development and debate. </p>
<p>Are there libraries/hacks I can use in the meantime to capture the basic behavior? I have a hierarchy that mixes different objects. The canonical example of a corporation structure with an Employee class, subclasses for types of employees, and a manager_id (parent_id) would be a good approximation of the problem I am solving. </p>
<p>In my case, I would like to represent the idea that an employee can manage other employees while being managed by a different employee. There are not separate classes for Manager and Worker, which makes this hard to spread across tables. Sub-classes would represent types of employees-programmers, accountants, sales, etc and would be independent of who supervises who (OK, I guess it's no longer a typical corporation in some respect). </p>
| 15 | 2008-10-27T20:18:08Z | 1,720,733 | <p>I think the OP is asking about Single-Table Inheritance as <a href="http://www.martinfowler.com/eaaCatalog/singleTableInheritance.html" rel="nofollow">defined here</a>:</p>
<blockquote>
<p>Relational databases don't support inheritance, so when mapping from objects to databases we have to consider how to represent our nice inheritance structures in relational tables. When mapping to a relational database, we try to minimize the joins that can quickly mount up when processing an inheritance structure in multiple tables. Single Table Inheritance maps all fields of all classes of an inheritance structure into a single table.</p>
</blockquote>
<p>That is, a single database table for a whole hierarchy of entity classes. Django does not support that kind of inheritance.</p>
| 14 | 2009-11-12T08:25:21Z | [
"python",
"django",
"django-models",
"single-table-inheritance"
] |
Single Table Inheritance in Django | 241,250 | <p>Is there explicit support for Single Table Inheritance in Django? Last I heard, the feature was still under development and debate. </p>
<p>Are there libraries/hacks I can use in the meantime to capture the basic behavior? I have a hierarchy that mixes different objects. The canonical example of a corporation structure with an Employee class, subclasses for types of employees, and a manager_id (parent_id) would be a good approximation of the problem I am solving. </p>
<p>In my case, I would like to represent the idea that an employee can manage other employees while being managed by a different employee. There are not separate classes for Manager and Worker, which makes this hard to spread across tables. Sub-classes would represent types of employees-programmers, accountants, sales, etc and would be independent of who supervises who (OK, I guess it's no longer a typical corporation in some respect). </p>
| 15 | 2008-10-27T20:18:08Z | 2,383,744 | <p>I think you can do something akin to this. </p>
<p>I have to implement a solution for this problem myself, and here was how I solved it:</p>
<pre><code>class Citrus(models.Model)
how_acidic = models.PositiveIntegerField(max_value=100)
skin_color = models.CharField()
type = models.CharField()
class TangeloManager(models.Manager)
def get_query_set(self):
return super(TangeloManager, self).get_query_set().filter(type='Tangelo')
class Tangelo(models.Model)
how_acidic = models.PositiveIntegerField(max_value=100)
skin_color = models.CharField()
type = models.CharField()
objects = TangeloManager()
class Meta:
# 'appname' below is going to vary with the name of your app
db_table = u'appname_citrus'
</code></pre>
<p>This may have some locking issues... I'm not really sure how django handles that off the top of my head. Also, I didn't really test the above code, it's strictly for entertainment purposes, to hopefully put you on the right track.</p>
| 1 | 2010-03-05T00:28:58Z | [
"python",
"django",
"django-models",
"single-table-inheritance"
] |
Single Table Inheritance in Django | 241,250 | <p>Is there explicit support for Single Table Inheritance in Django? Last I heard, the feature was still under development and debate. </p>
<p>Are there libraries/hacks I can use in the meantime to capture the basic behavior? I have a hierarchy that mixes different objects. The canonical example of a corporation structure with an Employee class, subclasses for types of employees, and a manager_id (parent_id) would be a good approximation of the problem I am solving. </p>
<p>In my case, I would like to represent the idea that an employee can manage other employees while being managed by a different employee. There are not separate classes for Manager and Worker, which makes this hard to spread across tables. Sub-classes would represent types of employees-programmers, accountants, sales, etc and would be independent of who supervises who (OK, I guess it's no longer a typical corporation in some respect). </p>
| 15 | 2008-10-27T20:18:08Z | 5,615,845 | <p>See my attempt:</p>
<p><a href="http://djangosnippets.org/snippets/2408/" rel="nofollow">http://djangosnippets.org/snippets/2408/</a></p>
<blockquote>
<p>An emulation of "table per hierarchy" a.k.a. "single table inheritance" in Django. The base class must hold all the fields. It's subclasses are not allowed to contain any additional fields and optimally they should be proxies.</p>
</blockquote>
<p>Not exactly "single table inheritance", but close enough for many situations.</p>
| 3 | 2011-04-11T01:00:01Z | [
"python",
"django",
"django-models",
"single-table-inheritance"
] |
Single Table Inheritance in Django | 241,250 | <p>Is there explicit support for Single Table Inheritance in Django? Last I heard, the feature was still under development and debate. </p>
<p>Are there libraries/hacks I can use in the meantime to capture the basic behavior? I have a hierarchy that mixes different objects. The canonical example of a corporation structure with an Employee class, subclasses for types of employees, and a manager_id (parent_id) would be a good approximation of the problem I am solving. </p>
<p>In my case, I would like to represent the idea that an employee can manage other employees while being managed by a different employee. There are not separate classes for Manager and Worker, which makes this hard to spread across tables. Sub-classes would represent types of employees-programmers, accountants, sales, etc and would be independent of who supervises who (OK, I guess it's no longer a typical corporation in some respect). </p>
| 15 | 2008-10-27T20:18:08Z | 14,661,921 | <p>this might be of use: <a href="https://github.com/craigds/django-typed-models" rel="nofollow">https://github.com/craigds/django-typed-models</a>
It looks to be somewhat of an implementation of Single Table Inheritance but it has the limitation that subclasses can't have any extra fields.</p>
<p>there is also a fork that addresses the problem of not being able to create extra fields:
<a href="https://github.com/KrzysiekJ/django-typed-models" rel="nofollow">https://github.com/KrzysiekJ/django-typed-models</a></p>
<p>update: I believe the fork may have been merged back in</p>
<p>here is a recent discussion on the django developer mailing list about STI:
<a href="https://groups.google.com/forum/#!msg/django-developers/-UOM8HNUnxg/6k34kopzerEJ" rel="nofollow">https://groups.google.com/forum/#!msg/django-developers/-UOM8HNUnxg/6k34kopzerEJ</a></p>
| 1 | 2013-02-02T12:31:11Z | [
"python",
"django",
"django-models",
"single-table-inheritance"
] |
Python snippet to remove C and C++ comments | 241,327 | <p>I'm looking for Python code that removes C and C++ comments from a string. (Assume the string contains an entire C source file.)</p>
<p>I realize that I could .match() substrings with a Regex, but that doesn't solve nesting <code>/*</code>, or having a <code>//</code> inside a <code>/* */</code>.</p>
<p>Ideally, I would prefer a non-naive implementation that properly handles awkward cases.</p>
| 32 | 2008-10-27T20:47:24Z | 241,329 | <p>C (and C++) comments cannot be nested. Regular expressions work well:</p>
<pre><code>//.*?\n|/\*.*?\*/
</code></pre>
<p>This requires the âSingle lineâ flag (<code>Re.S</code>) because a C comment can span multiple lines.</p>
<pre><code>def stripcomments(text):
return re.sub('//.*?\n|/\*.*?\*/', '', text, re.S)
</code></pre>
<p>This code should work.</p>
<p>/EDIT: Notice that my above code actually makes an assumption about line endings! This code won't work on a Mac text file. However, this can be amended relatively easily:</p>
<pre><code>//.*?(\r\n?|\n)|/\*.*?\*/
</code></pre>
<p>This regular expression should work on all text files, regardless of their line endings (covers Windows, Unix and Mac line endings).</p>
<p>/EDIT: MizardX and Brian (in the comments) made a valid remark about the handling of strings. I completely forgot about that because the above regex is plucked from a parsing module that has additional handling for strings. MizardX's solution should work very well but it only handles double-quoted strings.</p>
| 19 | 2008-10-27T20:48:57Z | [
"c++",
"python",
"c",
"regex",
"comments"
] |
Python snippet to remove C and C++ comments | 241,327 | <p>I'm looking for Python code that removes C and C++ comments from a string. (Assume the string contains an entire C source file.)</p>
<p>I realize that I could .match() substrings with a Regex, but that doesn't solve nesting <code>/*</code>, or having a <code>//</code> inside a <code>/* */</code>.</p>
<p>Ideally, I would prefer a non-naive implementation that properly handles awkward cases.</p>
| 32 | 2008-10-27T20:47:24Z | 241,333 | <p>you may be able to leverage <a href="http://www.language-binding.net/pyplusplus/pyplusplus.html" rel="nofollow">py++</a> to parse the C++ source with GCC.</p>
<blockquote>
<p>Py++ does not reinvent the wheel. It
uses GCC C++ compiler to parse C++
source files. To be more precise, the
tool chain looks like this:</p>
<p>source code is passed to GCC-XML
GCC-XML passes it to GCC C++ compiler
GCC-XML generates an XML description
of a C++ program from GCC's internal
representation. Py++ uses pygccxml
package to read GCC-XML generated
file. The bottom line - you can be
sure, that all your declarations are
read correctly.</p>
</blockquote>
<p>or, maybe not. regardless, this is not a trivial parse.</p>
<p>@ RE based solutions - you are unlikely to find a RE that handles all possible 'awkward' cases correctly, unless you constrain input (e.g. no macros). for a bulletproof solution, you really have no choice than leveraging the real grammar.</p>
| 3 | 2008-10-27T20:50:45Z | [
"c++",
"python",
"c",
"regex",
"comments"
] |
Python snippet to remove C and C++ comments | 241,327 | <p>I'm looking for Python code that removes C and C++ comments from a string. (Assume the string contains an entire C source file.)</p>
<p>I realize that I could .match() substrings with a Regex, but that doesn't solve nesting <code>/*</code>, or having a <code>//</code> inside a <code>/* */</code>.</p>
<p>Ideally, I would prefer a non-naive implementation that properly handles awkward cases.</p>
| 32 | 2008-10-27T20:47:24Z | 241,506 | <p>This handles C++-style comments, C-style comments, strings and simple nesting thereof.</p>
<pre><code>def comment_remover(text):
def replacer(match):
s = match.group(0)
if s.startswith('/'):
return " " # note: a space and not an empty string
else:
return s
pattern = re.compile(
r'//.*?$|/\*.*?\*/|\'(?:\\.|[^\\\'])*\'|"(?:\\.|[^\\"])*"',
re.DOTALL | re.MULTILINE
)
return re.sub(pattern, replacer, text)
</code></pre>
<p>Strings needs to be included, because comment-markers inside them does not start a comment.</p>
<p><strong>Edit:</strong> re.sub didn't take any flags, so had to compile the pattern first.</p>
<p><strong>Edit2:</strong> Added character literals, since they could contain quotes that would otherwise be recognized as string delimiters.</p>
<p><strong>Edit3:</strong> Fixed the case where a legal expression <code>int/**/x=5;</code> would become <code>intx=5;</code> which would not compile, by replacing the comment with a space rather then an empty string.</p>
| 54 | 2008-10-27T21:48:07Z | [
"c++",
"python",
"c",
"regex",
"comments"
] |
Python snippet to remove C and C++ comments | 241,327 | <p>I'm looking for Python code that removes C and C++ comments from a string. (Assume the string contains an entire C source file.)</p>
<p>I realize that I could .match() substrings with a Regex, but that doesn't solve nesting <code>/*</code>, or having a <code>//</code> inside a <code>/* */</code>.</p>
<p>Ideally, I would prefer a non-naive implementation that properly handles awkward cases.</p>
| 32 | 2008-10-27T20:47:24Z | 242,107 | <p>Don't forget that in C, backslash-newline is eliminated before comments are processed, and trigraphs are processed before that (because ??/ is the trigraph for backslash). I have a C program called SCC (strip C/C++ comments), and here is part of the test code...</p>
<pre><code>" */ /* SCC has been trained to know about strings /* */ */"!
"\"Double quotes embedded in strings, \\\" too\'!"
"And \
newlines in them"
"And escaped double quotes at the end of a string\""
aa '\\
n' OK
aa "\""
aa "\
\n"
This is followed by C++/C99 comment number 1.
// C++/C99 comment with \
continuation character \
on three source lines (this should not be seen with the -C fla
The C++/C99 comment number 1 has finished.
This is followed by C++/C99 comment number 2.
/\
/\
C++/C99 comment (this should not be seen with the -C flag)
The C++/C99 comment number 2 has finished.
This is followed by regular C comment number 1.
/\
*\
Regular
comment
*\
/
The regular C comment number 1 has finished.
/\
\/ This is not a C++/C99 comment!
This is followed by C++/C99 comment number 3.
/\
\
\
/ But this is a C++/C99 comment!
The C++/C99 comment number 3 has finished.
/\
\* This is not a C or C++ comment!
This is followed by regular C comment number 2.
/\
*/ This is a regular C comment *\
but this is just a routine continuation *\
and that was not the end either - but this is *\
\
/
The regular C comment number 2 has finished.
This is followed by regular C comment number 3.
/\
\
\
\
* C comment */
</code></pre>
<p>This does not illustrate trigraphs. Note that you can have multiple backslashes at the end of a line, but the line splicing doesn't care about how many there are, but the subsequent processing might. Etc. Writing a single regex to handle all these cases will be non-trivial (but that is different from impossible).</p>
| 6 | 2008-10-28T02:57:06Z | [
"c++",
"python",
"c",
"regex",
"comments"
] |
Python snippet to remove C and C++ comments | 241,327 | <p>I'm looking for Python code that removes C and C++ comments from a string. (Assume the string contains an entire C source file.)</p>
<p>I realize that I could .match() substrings with a Regex, but that doesn't solve nesting <code>/*</code>, or having a <code>//</code> inside a <code>/* */</code>.</p>
<p>Ideally, I would prefer a non-naive implementation that properly handles awkward cases.</p>
| 32 | 2008-10-27T20:47:24Z | 242,110 | <p>The regular expression cases will fall down in some situations, like where a string literal contains a subsequence which matches the comment syntax. You really need a parse tree to deal with this.</p>
| 4 | 2008-10-28T02:58:24Z | [
"c++",
"python",
"c",
"regex",
"comments"
] |
Python snippet to remove C and C++ comments | 241,327 | <p>I'm looking for Python code that removes C and C++ comments from a string. (Assume the string contains an entire C source file.)</p>
<p>I realize that I could .match() substrings with a Regex, but that doesn't solve nesting <code>/*</code>, or having a <code>//</code> inside a <code>/* */</code>.</p>
<p>Ideally, I would prefer a non-naive implementation that properly handles awkward cases.</p>
| 32 | 2008-10-27T20:47:24Z | 242,226 | <p>I don't know if you're familiar with <code>sed</code>, the UNIX-based (but Windows-available) text parsing program, but I've found a sed script <a href="http://sed.sourceforge.net/grabbag/scripts/remccoms3.sed">here</a> which will remove C/C++ comments from a file. It's very smart; for example, it will ignore '//' and '/*' if found in a string declaration, etc. From within Python, it can be used using the following code:</p>
<pre><code>import subprocess
from cStringIO import StringIO
input = StringIO(source_code) # source_code is a string with the source code.
output = StringIO()
process = subprocess.Popen(['sed', '/path/to/remccoms3.sed'],
input=input, output=output)
return_code = process.wait()
stripped_code = output.getvalue()
</code></pre>
<p>In this program, <code>source_code</code> is the variable holding the C/C++ source code, and eventually <code>stripped_code</code> will hold C/C++ code with the comments removed. Of course, if you have the file on disk, you could have the <code>input</code> and <code>output</code> variables be file handles pointing to those files (<code>input</code> in read-mode, <code>output</code> in write-mode). <code>remccoms3.sed</code> is the file from the above link, and it should be saved in a readable location on disk. <code>sed</code> is also available on Windows, and comes installed by default on most GNU/Linux distros and Mac OS X.</p>
<p>This will probably be better than a pure Python solution; no need to reinvent the wheel.</p>
| 9 | 2008-10-28T04:03:20Z | [
"c++",
"python",
"c",
"regex",
"comments"
] |
Python snippet to remove C and C++ comments | 241,327 | <p>I'm looking for Python code that removes C and C++ comments from a string. (Assume the string contains an entire C source file.)</p>
<p>I realize that I could .match() substrings with a Regex, but that doesn't solve nesting <code>/*</code>, or having a <code>//</code> inside a <code>/* */</code>.</p>
<p>Ideally, I would prefer a non-naive implementation that properly handles awkward cases.</p>
| 32 | 2008-10-27T20:47:24Z | 1,078,406 | <p>You don't really need a parse tree to do this perfectly, but you do in effect need the token stream equivalent to what is produced by the compiler's front end. Such a token stream must necessarilyy take care of all the weirdness such as line-continued comment start, comment start in string, trigraph normalization, etc. If you have the token stream, deleting the comments is easy. (I have a tool that produces exactly such token streams, as, guess what, the front end of a real parser that produces a real parse tree :). </p>
<p>The fact that the tokens are individually recognized by regular expressions suggests that you can, in principle, write a regular expression that will pick out the comment lexemes. The real complexity of the set regular expressions for the tokenizer (at least the one we wrote) suggests you can't do this in practice; writing them individually was hard enough. If you don't want to do it perfectly, well, then, most of the RE solutions above are just fine.</p>
<p>Now, <em>why</em> you would want strip comments is beyond me, unless you are building a code obfuscator. In this case, you have to have it perfectly right.</p>
| 0 | 2009-07-03T08:38:46Z | [
"c++",
"python",
"c",
"regex",
"comments"
] |
Python snippet to remove C and C++ comments | 241,327 | <p>I'm looking for Python code that removes C and C++ comments from a string. (Assume the string contains an entire C source file.)</p>
<p>I realize that I could .match() substrings with a Regex, but that doesn't solve nesting <code>/*</code>, or having a <code>//</code> inside a <code>/* */</code>.</p>
<p>Ideally, I would prefer a non-naive implementation that properly handles awkward cases.</p>
| 32 | 2008-10-27T20:47:24Z | 1,078,484 | <p>I'm sorry this not a Python solution, but you could also use a tool that understands how to remove comments, like your C/C++ preprocessor. Here's how GNU CPP <a href="http://gcc.gnu.org/onlinedocs/cpp/Invocation.html#index-fpreprocessed-171" rel="nofollow">does it</a>.</p>
<pre><code>cpp -fpreprocessed foo.c
</code></pre>
| 0 | 2009-07-03T09:08:24Z | [
"c++",
"python",
"c",
"regex",
"comments"
] |
Python snippet to remove C and C++ comments | 241,327 | <p>I'm looking for Python code that removes C and C++ comments from a string. (Assume the string contains an entire C source file.)</p>
<p>I realize that I could .match() substrings with a Regex, but that doesn't solve nesting <code>/*</code>, or having a <code>//</code> inside a <code>/* */</code>.</p>
<p>Ideally, I would prefer a non-naive implementation that properly handles awkward cases.</p>
| 32 | 2008-10-27T20:47:24Z | 1,294,188 | <p>There is also a non-python answer: use the program <a href="http://www.bdc.cx/software/stripcmt/" rel="nofollow">stripcmt</a>:</p>
<blockquote>
<p>StripCmt is a simple utility written
in C to remove comments from C, C++,
and Java source files. In the grand
tradition of Unix text processing
programs, it can function either as a
FIFO (First In - First Out) filter or
accept arguments on the commandline.</p>
</blockquote>
| 1 | 2009-08-18T14:18:07Z | [
"c++",
"python",
"c",
"regex",
"comments"
] |
Python snippet to remove C and C++ comments | 241,327 | <p>I'm looking for Python code that removes C and C++ comments from a string. (Assume the string contains an entire C source file.)</p>
<p>I realize that I could .match() substrings with a Regex, but that doesn't solve nesting <code>/*</code>, or having a <code>//</code> inside a <code>/* */</code>.</p>
<p>Ideally, I would prefer a non-naive implementation that properly handles awkward cases.</p>
| 32 | 2008-10-27T20:47:24Z | 5,221,953 | <p>I ran across this problem recently when I took a class where the professor required us to strip javadoc from our source code before submitting it to him for a code review. We had to do this several times, but we couldn't just remove the javadoc permanently because we were required to generate javadoc html files as well. Here is a little python script I made to do the trick. Since javadoc starts with /** and ends with */, the script looks for these tokens, but the script can be modified to suite your needs. It also handles single line block comments and cases where a block comment ends but there is still non-commented code on the same line as the block comment ending. I hope this helps!</p>
<p><em>WARNING: This scripts modifies the contents of files passed in and saves them to the original files. It would be wise to have a backup somewhere else</em></p>
<pre><code>#!/usr/bin/python
"""
A simple script to remove block comments of the form /** */ from files
Use example: ./strip_comments.py *.java
Author: holdtotherod
Created: 3/6/11
"""
import sys
import fileinput
for file in sys.argv[1:]:
inBlockComment = False
for line in fileinput.input(file, inplace = 1):
if "/**" in line:
inBlockComment = True
if inBlockComment and "*/" in line:
inBlockComment = False
# If the */ isn't last, remove through the */
if line.find("*/") != len(line) - 3:
line = line[line.find("*/")+2:]
else:
continue
if inBlockComment:
continue
sys.stdout.write(line)
</code></pre>
| -1 | 2011-03-07T16:10:54Z | [
"c++",
"python",
"c",
"regex",
"comments"
] |
Python snippet to remove C and C++ comments | 241,327 | <p>I'm looking for Python code that removes C and C++ comments from a string. (Assume the string contains an entire C source file.)</p>
<p>I realize that I could .match() substrings with a Regex, but that doesn't solve nesting <code>/*</code>, or having a <code>//</code> inside a <code>/* */</code>.</p>
<p>Ideally, I would prefer a non-naive implementation that properly handles awkward cases.</p>
| 32 | 2008-10-27T20:47:24Z | 18,234,680 | <p>This posting provides a coded-out version of the improvement to Markus Jarderot's code that was described by atikat, in a comment to Markus Jarderot's posting. (Thanks to both for providing the original code, which saved me a lot of work.)</p>
<p>To describe the improvement somewhat more fully: The improvement keeps the line numbering intact. (This is done by keeping the newline characters intact in the strings by which the C/C++ comments are replaced.)</p>
<p>This version of the C/C++ comment removal function is suitable when you want to generate error messages to your users (e.g. parsing errors) that contain line numbers (i.e. line numbers valid for the original text).</p>
<pre><code>import re
def removeCCppComment( text ) :
def blotOutNonNewlines( strIn ) : # Return a string containing only the newline chars contained in strIn
return "" + ("\n" * strIn.count('\n'))
def replacer( match ) :
s = match.group(0)
if s.startswith('/'): # Matched string is //...EOL or /*...*/ ==> Blot out all non-newline chars
return blotOutNonNewlines(s)
else: # Matched string is '...' or "..." ==> Keep unchanged
return s
pattern = re.compile(
r'//.*?$|/\*.*?\*/|\'(?:\\.|[^\\\'])*\'|"(?:\\.|[^\\"])*"',
re.DOTALL | re.MULTILINE
)
return re.sub(pattern, replacer, text)
</code></pre>
| 5 | 2013-08-14T14:36:25Z | [
"c++",
"python",
"c",
"regex",
"comments"
] |
Python snippet to remove C and C++ comments | 241,327 | <p>I'm looking for Python code that removes C and C++ comments from a string. (Assume the string contains an entire C source file.)</p>
<p>I realize that I could .match() substrings with a Regex, but that doesn't solve nesting <code>/*</code>, or having a <code>//</code> inside a <code>/* */</code>.</p>
<p>Ideally, I would prefer a non-naive implementation that properly handles awkward cases.</p>
| 32 | 2008-10-27T20:47:24Z | 18,996,903 | <p>The following worked for me: </p>
<pre><code>from subprocess import check_output
class Util:
def strip_comments(self,source_code):
process = check_output(['cpp', '-fpreprocessed', source_code],shell=False)
return process
if __name__ == "__main__":
util = Util()
print util.strip_comments("somefile.ext")
</code></pre>
<p>This is a combination of the subprocess and the cpp preprocessor. For my project I have a utility class called "Util" that I keep various tools I use/need.</p>
| 0 | 2013-09-25T05:27:45Z | [
"c++",
"python",
"c",
"regex",
"comments"
] |
Reading collections of extended elements in an RSS feed with Universal Feed Parser | 241,503 | <p>Is there any way to read a collection of extension elements with <a href="http://www.feedparser.org/" rel="nofollow">Universal Feed Parser</a>?</p>
<p>This is just a short snippet from Kuler RSS feed:</p>
<pre><code><channel>
<item>
<!-- snip: regular RSS elements -->
<kuler:themeItem>
<kuler:themeID>123456</kuler:themeID>
<!-- snip -->
<kuler:themeSwatches>
<kuler:swatch>
<kuler:swatchHexColor>FFFFFF</kuler:swatchHexColor>
<!-- snip -->
</kuler:swatch>
<kuler:swatch>
<kuler:swatchHexColor>000000</kuler:swatchHexColor>
<!-- snip -->
</kuler:swatch>
</kuler:themeSwatches>
</kuler:themeItem>
</item>
</channel>
</code></pre>
<p>I tried the following:</p>
<pre><code>>>> feed = feedparser.parse(url)
>>> feed.channel.title
u'kuler highest rated themes'
>>> feed.entries[0].title
u'Foobar'
>>> feed.entries[0].kuler_themeid
u'123456'
>>> feed.entries[0].kuler_swatch
u''
</code></pre>
<p><code>feed.entries[0].kuler_swatchhexcolor</code> returns only last <code>kuler:swatchHexColor</code>. Is there any way to retrieve all elements with <code>feedparser</code>?</p>
<p>I have already worked around the issue by using minidom, but I would like to use Universal Feed Parser if possible (due to very simple API). Can it be extended? I haven't found anything about that in the documentation, so if someone has more experience with the library, please, advise me.</p>
| 4 | 2008-10-27T21:46:19Z | 242,254 | <p>Universal Feed Parser is really nice for most feeds, but for extended feeds, you might wanna try something called <a href="http://crummy.com/software/BeautifulSoup" rel="nofollow">BeautifulSoup</a>. It's an XML/HTML/XHTML parsing library which is originally designed for screenscraping; turns out it's also brilliant for this sort of thing. The documentation is pretty good, and it's got a self-explanatory API, so if you're thinking of using anything else, that's what I'd recommend.</p>
<p>I'd probably use it like this:</p>
<pre><code>>>> import BeautifulSoup
>>> import urllib2
# Fetch HTML data from url
>>> connection = urllib2.urlopen('http://kuler.adobe.com/path/to/rss.xml')
>>> html_data = connection.read()
>>> connection.close()
# Create and search the soup
>>> soup = BeautifulSoup.BeautifulSoup(html_data)
>>> themes = soup.findAll('kuler:themeitem') # Note: all lower-case element names
# Get the ID of the first theme
>>> themes[0].find('kuler:themeid').contents[0]
u'123456'
# Get an ordered list of the hex colors for the first theme
>>> themeswatches = themes[0].find('kuler:themeswatches')
>>> colors = [color.contents[0] for color in
... themeswatches.findAll('kuler:swatchhexcolor')]
>>> colors
[u'FFFFFF', u'000000']
</code></pre>
<p>So you can probably get the idea that this is a very cool library. It wouldn't be too good if you were parsing any old RSS feed, but because the data is from Adobe Kuler, you can be pretty sure that it's not going to vary enough to break your app (i.e. it's a trusted enough source).</p>
<p>Even worse is trying to parse Adobe's goddamn .ASE format. I tried writing a parser for it and it got really horrible, really quickly. Ug. So, yeah, the RSS feeds are probably the easiest way of interfacing with Kuler.</p>
| 3 | 2008-10-28T04:23:48Z | [
"python",
"rss",
"adobe",
"feeds"
] |
I want a program that writes every possible combination to a different line of a text file | 241,533 | <p>I want to write a program that would print every combination of a set of variables to a text file, creating a word list. Each answer should be written on a separate line and write all of the results for 1 digit, 2 digits, and 3 digits to a single text file.</p>
<p>Is there a simple way I can write a python program that can accomplish this? Here is an example of the output I am expecting when printing all the binary number combinations possible for 1, 2, and 3 digits:</p>
<pre><code>Output:
0
1
00
01
10
11
000
001
010
011
100
101
110
111
</code></pre>
| 4 | 2008-10-27T22:03:06Z | 241,542 | <p>It shouldn't be too hard in most languages. Does the following pseudo-code help?</p>
<pre><code>for(int i=0; i < 2^digits; i++)
{
WriteLine(ToBinaryString(i));
}
</code></pre>
| 2 | 2008-10-27T22:06:54Z | [
"python",
"recursion"
] |
I want a program that writes every possible combination to a different line of a text file | 241,533 | <p>I want to write a program that would print every combination of a set of variables to a text file, creating a word list. Each answer should be written on a separate line and write all of the results for 1 digit, 2 digits, and 3 digits to a single text file.</p>
<p>Is there a simple way I can write a python program that can accomplish this? Here is an example of the output I am expecting when printing all the binary number combinations possible for 1, 2, and 3 digits:</p>
<pre><code>Output:
0
1
00
01
10
11
000
001
010
011
100
101
110
111
</code></pre>
| 4 | 2008-10-27T22:03:06Z | 241,557 | <pre><code># Given two lists of strings, return a list of all ways to concatenate
# one from each.
def combos(xs, ys):
return [x + y for x in xs for y in ys]
digits = ['0', '1']
for c in combos(digits, combos(digits, digits)):
print c
#. 000
#. 001
#. 010
#. 011
#. 100
#. 101
#. 110
#. 111
</code></pre>
| 3 | 2008-10-27T22:12:51Z | [
"python",
"recursion"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.