title stringlengths 10 172 | question_id int64 469 40.1M | question_body stringlengths 22 48.2k | question_score int64 -44 5.52k | question_date stringlengths 20 20 | answer_id int64 497 40.1M | answer_body stringlengths 18 33.9k | answer_score int64 -38 8.38k | answer_date stringlengths 20 20 | tags listlengths 1 5 |
|---|---|---|---|---|---|---|---|---|---|
Python: Convert those TinyURL (bit.ly, tinyurl, ow.ly) to full URLS | 748,324 | <p>I am just learning python and is interested in how this can be accomplished. During the search for the answer, I came across this service: <a href="http://www.longurlplease.com">http://www.longurlplease.com</a> </p>
<p>For example: </p>
<p><a href="http://bit.ly/rgCbf">http://bit.ly/rgCbf</a> can be converted to:<... | 12 | 2009-04-14T16:14:04Z | 1,552,895 | <p>I've been working on Ruby... Just wanna share the code</p>
<pre><code>require 'net/http'
url = URI.parse('http://bit.ly/4okpb2')
host, port = url.host, url.port if url.host && url.port
req = Net::HTTP::Get.new(url.path)
res = Net::HTTP.start(host, port) {|http| http.request(req) }
fullurl = res.header['l... | 1 | 2009-10-12T05:38:42Z | [
"python",
"bit.ly",
"tinyurl"
] |
Writing text with carriage return to image in Python using PIL | 748,453 | <p>I have a python script that is writing text to images using the PIL. Everything this is working fine except for when I encounter strings with carriage returns in them. I need to preserve the carriage returns in the text. Instead of writing the carriage return to the image, I get a little box character where the retu... | 1 | 2009-04-14T16:53:16Z | 748,484 | <p>Let's think for a moment. What does a "return" signify? It means go to the left some distance, and down some distance and resume displaying characters.</p>
<p>You've got to do something like the following.</p>
<pre><code>y, x = 35, 570
for line in attText.splitlines():
draw.text( (x,y), line, ... )
y = y... | 8 | 2009-04-14T16:58:25Z | [
"python",
"text",
"image",
"python-imaging-library"
] |
Writing text with carriage return to image in Python using PIL | 748,453 | <p>I have a python script that is writing text to images using the PIL. Everything this is working fine except for when I encounter strings with carriage returns in them. I need to preserve the carriage returns in the text. Instead of writing the carriage return to the image, I get a little box character where the retu... | 1 | 2009-04-14T16:53:16Z | 37,846,770 | <p>You could try the the following code which works perfectly good for my needs:</p>
<pre><code># Place Text on background
lineCnt = 0
for line in str(attText):
draw = ImageDraw.Draw(blankTemplate)
draw.text((35 + attSpacing,570 + 80 * lineCnt), line, font=attFont)
lineCnt = lineCnt +1
... | 0 | 2016-06-15T22:19:58Z | [
"python",
"text",
"image",
"python-imaging-library"
] |
How do I create a datetime in Python from milliseconds? | 748,491 | <p>I can create a similar Date object in Java by <a href="http://docs.oracle.com/javase/6/docs/api/java/util/Date.html">java.util.Date(milliseconds)</a>. How do I create the comparable in Python?</p>
<blockquote>
<p>Allocates a Date object and initializes it to represent the specified number of milliseconds since th... | 53 | 2009-04-14T17:01:03Z | 748,534 | <p>Just convert it to timestamp</p>
<pre><code>datetime.datetime.fromtimestamp(ms/1000.0)
</code></pre>
| 87 | 2009-04-14T17:12:51Z | [
"python",
"datetime"
] |
How do I create a datetime in Python from milliseconds? | 748,491 | <p>I can create a similar Date object in Java by <a href="http://docs.oracle.com/javase/6/docs/api/java/util/Date.html">java.util.Date(milliseconds)</a>. How do I create the comparable in Python?</p>
<blockquote>
<p>Allocates a Date object and initializes it to represent the specified number of milliseconds since th... | 53 | 2009-04-14T17:01:03Z | 31,625,298 | <p>What about this? I presume it can be counted on to handle dates before 1970 and after 2038. </p>
<pre><code> target_date_time_ms = 200000 # or whatever
base_datetime = datetime.datetime( 1970, 1, 1 )
delta = datetime.timedelta( 0, 0, 0, target_date_time_ms )
target_date = base_datetime + delta
</... | 3 | 2015-07-25T10:01:32Z | [
"python",
"datetime"
] |
Finding duplicate files and removing them | 748,675 | <p>I am writing a Python program to find and remove duplicate files from a folder.</p>
<p>I have multiple copies of mp3 files, and some other files. I am using the sh1 algorithm.</p>
<p>How can I find these duplicate files and remove them?</p>
| 18 | 2009-04-14T17:48:21Z | 748,687 | <p>I wrote one in Python some time ago -- you're welcome to use it.</p>
<pre><code>import sys
import os
import hashlib
check_path = (lambda filepath, hashes, p = sys.stdout.write:
(lambda hash = hashlib.sha1 (file (filepath).read ()).hexdigest ():
((hash in hashes) and (p ('DUPLICATE FILE\n'
... | 8 | 2009-04-14T17:50:52Z | [
"python",
"file",
"duplicates"
] |
Finding duplicate files and removing them | 748,675 | <p>I am writing a Python program to find and remove duplicate files from a folder.</p>
<p>I have multiple copies of mp3 files, and some other files. I am using the sh1 algorithm.</p>
<p>How can I find these duplicate files and remove them?</p>
| 18 | 2009-04-14T17:48:21Z | 748,879 | <pre><code>def remove_duplicates(dir):
unique = []
for filename in os.listdir(dir):
if os.path.isfile(filename):
filehash = md5.md5(file(filename).read()).hexdigest()
if filehash not in unique:
unique.append(filehash)
else:
os.remove(filename)
</code... | 14 | 2009-04-14T18:51:46Z | [
"python",
"file",
"duplicates"
] |
Finding duplicate files and removing them | 748,675 | <p>I am writing a Python program to find and remove duplicate files from a folder.</p>
<p>I have multiple copies of mp3 files, and some other files. I am using the sh1 algorithm.</p>
<p>How can I find these duplicate files and remove them?</p>
| 18 | 2009-04-14T17:48:21Z | 748,908 | <h1>Recursive folders version:</h1>
<p>This version uses the file size and a hash of the contents to find duplicates.
You can pass it multiple paths, it will scan all paths recursively and report all duplicates found.</p>
<pre><code>import sys
import os
import hashlib
def chunk_reader(fobj, chunk_size=1024):
"""... | 30 | 2009-04-14T19:00:37Z | [
"python",
"file",
"duplicates"
] |
Finding duplicate files and removing them | 748,675 | <p>I am writing a Python program to find and remove duplicate files from a folder.</p>
<p>I have multiple copies of mp3 files, and some other files. I am using the sh1 algorithm.</p>
<p>How can I find these duplicate files and remove them?</p>
| 18 | 2009-04-14T17:48:21Z | 13,046,184 | <h2>Faster algorithm</h2>
<p>In case many files of 'big size' should be analyzed (images, mp3, pdf documents), it would be interesting/faster to have the following comparison algorithm:</p>
<ol>
<li><p>a first fast hash is performed on the first N bytes of the file (say 1KB). This hash would say if files are differen... | 4 | 2012-10-24T09:14:42Z | [
"python",
"file",
"duplicates"
] |
Finding duplicate files and removing them | 748,675 | <p>I am writing a Python program to find and remove duplicate files from a folder.</p>
<p>I have multiple copies of mp3 files, and some other files. I am using the sh1 algorithm.</p>
<p>How can I find these duplicate files and remove them?</p>
| 18 | 2009-04-14T17:48:21Z | 18,553,076 | <pre><code> import hashlib
import os
import sys
from sets import Set
def read_chunk(fobj, chunk_size = 2048):
""" Files can be huge so read them in chunks of bytes. """
while True:
chunk = fobj.read(chunk_size)
if not chunk:
return
... | 2 | 2013-08-31T21:40:54Z | [
"python",
"file",
"duplicates"
] |
Finding duplicate files and removing them | 748,675 | <p>I am writing a Python program to find and remove duplicate files from a folder.</p>
<p>I have multiple copies of mp3 files, and some other files. I am using the sh1 algorithm.</p>
<p>How can I find these duplicate files and remove them?</p>
| 18 | 2009-04-14T17:48:21Z | 36,113,168 | <h2>Fastest algorithm - 100x performance increase compared to the accepted answer (really :))</h2>
<p>The approaches in the other solutions are very cool, but they forget about an important property of duplicate files - they have the same file size. Calculating the expensive hash only on files with the same size will ... | 4 | 2016-03-20T11:33:09Z | [
"python",
"file",
"duplicates"
] |
Finding duplicate files and removing them | 748,675 | <p>I am writing a Python program to find and remove duplicate files from a folder.</p>
<p>I have multiple copies of mp3 files, and some other files. I am using the sh1 algorithm.</p>
<p>How can I find these duplicate files and remove them?</p>
| 18 | 2009-04-14T17:48:21Z | 36,890,340 | <p>@IanLee1521 has a nice solution <a href="https://github.com/IanLee1521/utilities/blob/master/utilities/find_duplicates.py" rel="nofollow">here</a>. It is very efficient because it checks the duplicate based on the file size first. </p>
<pre><code>#! /usr/bin/env python
# Originally taken from:
# http://www.pythonc... | 0 | 2016-04-27T12:49:29Z | [
"python",
"file",
"duplicates"
] |
What are the steps to convert from using libglade to GtkBuilder? (Python) | 748,872 | <p>I have a small project that uses libglade and use the following to load the xml file: </p>
<pre><code>self.gladefile = "sdm.glade"
self.wTree = gtk.glade.XML(self.gladefile)
self.window = self.wTree.get_widget("MainWindow")
if (self.window):
self.window.connect("destroy", gtk.main_quit)
dic = { "on_button1_cli... | 5 | 2009-04-14T18:47:35Z | 749,518 | <p>You need to use <code>gtk.Builder</code> instead. This class can load any number of UI files, so you need to add them manually, either as files or as strings:</p>
<pre><code>self.uifile = "sdm.ui"
self.wTree = gtk.Builder()
self.wTree.add_from_file(self.uifile)
</code></pre>
<p>Instead of <code>get_widget</code>, ... | 11 | 2009-04-14T21:57:11Z | [
"python",
"pygtk",
"glade",
"gtkbuilder"
] |
What are the steps to convert from using libglade to GtkBuilder? (Python) | 748,872 | <p>I have a small project that uses libglade and use the following to load the xml file: </p>
<pre><code>self.gladefile = "sdm.glade"
self.wTree = gtk.glade.XML(self.gladefile)
self.window = self.wTree.get_widget("MainWindow")
if (self.window):
self.window.connect("destroy", gtk.main_quit)
dic = { "on_button1_cli... | 5 | 2009-04-14T18:47:35Z | 8,318,333 | <p>Torsten's answer is correct, but a little incomplete, so in the spirit of <a href="http://xkcd.com/979/" rel="nofollow">http://xkcd.com/979/</a> here is the procedure I recently settled on after much trial-and-error:</p>
<p>Open yada.glade in Glade interface designer. Go to edit->project and change the project typ... | 5 | 2011-11-29T22:01:27Z | [
"python",
"pygtk",
"glade",
"gtkbuilder"
] |
How to create a bulleted list in ReportLab | 748,881 | <p>How can I create a bulleted list in ReportLab? The documentation is frustratingly vague. I am trying:</p>
<pre><code>text = ur '''
<para bulletText="&bull;">
item 1
</para>
<para bulletText="&bull;">
item 2
</para>
'''
Story.append(Paragraph(text,TEXT_STYLE))
</code></pre>
<p>But I ... | 4 | 2009-04-14T18:53:07Z | 749,382 | <p>The bulletText argument is actually a constructor to the <code>Paragraph</code> object, not the <code><para></code> tag :-) Try this:</p>
<pre><code>story.append(Paragraph(text, TEXT_STYLE, bulletText='-'))
</code></pre>
<p>Have a look at the examples on page 68 (page 74 now, in 2012) of the <a href="http://... | 5 | 2009-04-14T21:10:23Z | [
"python",
"pdf",
"reportlab"
] |
How to create a bulleted list in ReportLab | 748,881 | <p>How can I create a bulleted list in ReportLab? The documentation is frustratingly vague. I am trying:</p>
<pre><code>text = ur '''
<para bulletText="&bull;">
item 1
</para>
<para bulletText="&bull;">
item 2
</para>
'''
Story.append(Paragraph(text,TEXT_STYLE))
</code></pre>
<p>But I ... | 4 | 2009-04-14T18:53:07Z | 5,153,366 | <p>The very recent versions of ReportLab have ListFlowable and ListItem objects (check Chapter 9 of the current user guide).</p>
| 4 | 2011-03-01T10:40:16Z | [
"python",
"pdf",
"reportlab"
] |
How do I get all the entities of a type with a required property in Google App Engine? | 748,952 | <p>I have a model which has a required string property like the following:</p>
<pre><code>class Jean(db.Model):
sex = db.StringProperty(required=True, choices=set(["male", "female"]))
</code></pre>
<p>When I try calling Jean.all(), python complains about not having a required property.</p>
<p>Surely there must b... | 0 | 2009-04-14T19:14:12Z | 749,012 | <p>Maybe you have old data in the datastore with no sex property (added before you specified the required property), then the system complain that there is an entry without sex property.</p>
<p>Try adding a default value:</p>
<pre><code>class Jean(db.Model):
sex = db.StringProperty(required=True, choices=set(["ma... | 2 | 2009-04-14T19:27:43Z | [
"python",
"google-app-engine",
"data-modeling",
"entity"
] |
Django: How to use stored model instances as form choices? | 749,000 | <p>I have a model which is essentially just a string (django.db.models.CharField). There will only be several instances of this model stored. How could I use those values as choices in a form?</p>
<p>To illustrate, the model could be <code>BlogTopic</code>. I'd like to offer users the ability to choose one or several ... | 5 | 2009-04-14T19:24:39Z | 749,019 | <pre><code>topics = forms.ModelMultipleChoiceField(queryset=BlogTopic.objects.all())
</code></pre>
| 12 | 2009-04-14T19:28:43Z | [
"python",
"django",
"django-forms"
] |
Passing a multi-line string as an argument to a script in Windows | 749,049 | <p>I have a simple python script like so:</p>
<pre><code>import sys
lines = sys.argv[1]
for line in lines.splitlines():
print line
</code></pre>
<p>I want to call it from the command line (or a .bat file) but the first argument may (and probably will) be a string with multiple lines in it. How does one do this?... | 4 | 2009-04-14T19:37:10Z | 749,069 | <p>Just enclose the argument in quotes:</p>
<pre><code>$ python args.py "This is a string
> It has multiple lines
> there are three total"
This is a string
It has multiple lines
there are three total
</code></pre>
| 2 | 2009-04-14T19:44:13Z | [
"python",
"windows",
"string",
"dos",
"batch-file"
] |
Passing a multi-line string as an argument to a script in Windows | 749,049 | <p>I have a simple python script like so:</p>
<pre><code>import sys
lines = sys.argv[1]
for line in lines.splitlines():
print line
</code></pre>
<p>I want to call it from the command line (or a .bat file) but the first argument may (and probably will) be a string with multiple lines in it. How does one do this?... | 4 | 2009-04-14T19:37:10Z | 749,319 | <p>Not sure about the Windows command-line, but would the following work?</p>
<pre><code>> python myscript.py "This is a string\nIt has multiple lines\there are three total"
</code></pre>
<p>..or..</p>
<pre><code>> python myscript.py "This is a string\
It has [...]\
there are [...]"
</code></pre>
<p>If not, I... | 0 | 2009-04-14T20:46:04Z | [
"python",
"windows",
"string",
"dos",
"batch-file"
] |
Passing a multi-line string as an argument to a script in Windows | 749,049 | <p>I have a simple python script like so:</p>
<pre><code>import sys
lines = sys.argv[1]
for line in lines.splitlines():
print line
</code></pre>
<p>I want to call it from the command line (or a .bat file) but the first argument may (and probably will) be a string with multiple lines in it. How does one do this?... | 4 | 2009-04-14T19:37:10Z | 749,323 | <p>The following might work:</p>
<pre><code>C:\> python something.py "This is a string^
More?
More? It has multiple lines^
More?
More? There are three total"
</code></pre>
| 1 | 2009-04-14T20:47:10Z | [
"python",
"windows",
"string",
"dos",
"batch-file"
] |
Passing a multi-line string as an argument to a script in Windows | 749,049 | <p>I have a simple python script like so:</p>
<pre><code>import sys
lines = sys.argv[1]
for line in lines.splitlines():
print line
</code></pre>
<p>I want to call it from the command line (or a .bat file) but the first argument may (and probably will) be a string with multiple lines in it. How does one do this?... | 4 | 2009-04-14T19:37:10Z | 749,329 | <p>Have you tried setting you multiline text as a variable and then passing the expansion of that into your script. For example:</p>
<pre><code>set Text="This is a string
It has multiple lines
there are three total"
python args.py %Text%
</code></pre>
<p>Alternatively, instead of reading an argument you could read fr... | 0 | 2009-04-14T20:49:39Z | [
"python",
"windows",
"string",
"dos",
"batch-file"
] |
Passing a multi-line string as an argument to a script in Windows | 749,049 | <p>I have a simple python script like so:</p>
<pre><code>import sys
lines = sys.argv[1]
for line in lines.splitlines():
print line
</code></pre>
<p>I want to call it from the command line (or a .bat file) but the first argument may (and probably will) be a string with multiple lines in it. How does one do this?... | 4 | 2009-04-14T19:37:10Z | 757,277 | <p>This is the only thing which worked for me:</p>
<pre><code>C:\> python a.py This" "is" "a" "string^
More?
More? It" "has" "multiple" "lines^
More?
More? There" "are" "three" "total
</code></pre>
<p>For me <a href="http://stackoverflow.com/questions/749049/passing-a-multi-line-string-as-an-argument-to-a-script-i... | 1 | 2009-04-16T17:47:40Z | [
"python",
"windows",
"string",
"dos",
"batch-file"
] |
Passing a multi-line string as an argument to a script in Windows | 749,049 | <p>I have a simple python script like so:</p>
<pre><code>import sys
lines = sys.argv[1]
for line in lines.splitlines():
print line
</code></pre>
<p>I want to call it from the command line (or a .bat file) but the first argument may (and probably will) be a string with multiple lines in it. How does one do this?... | 4 | 2009-04-14T19:37:10Z | 2,795,170 | <p>I know this thread is pretty old, but I came across it while trying to solve a similar problem, and others might as well, so let me show you how I solved it.</p>
<p>This works at least on Windows XP Pro, with Zack's code in a file called<br>
"C:\Scratch\test.py":</p>
<pre><code>C:\Scratch>test.py "This is a str... | 2 | 2010-05-08T18:26:32Z | [
"python",
"windows",
"string",
"dos",
"batch-file"
] |
Partial list unpack in Python | 749,070 | <p>In Python, the assignment operator can unpack list or tuple into variables, like this:</p>
<pre><code>l = (1, 2)
a, b = l # Here goes auto unpack
</code></pre>
<p>But I need to specify exactly the same amount of names to the left as an items count in the list to the right. But sometimes I don't know a size of the ... | 30 | 2009-04-14T19:44:54Z | 749,087 | <p>Have you tried this?</p>
<pre><code>values = aString.split("=")
if len(values) == 1:
a = values[0]
else:
a, b = values
</code></pre>
| -2 | 2009-04-14T19:48:51Z | [
"python"
] |
Partial list unpack in Python | 749,070 | <p>In Python, the assignment operator can unpack list or tuple into variables, like this:</p>
<pre><code>l = (1, 2)
a, b = l # Here goes auto unpack
</code></pre>
<p>But I need to specify exactly the same amount of names to the left as an items count in the list to the right. But sometimes I don't know a size of the ... | 30 | 2009-04-14T19:44:54Z | 749,096 | <p>This is slightly better than your solution but still not very elegant; it wouldn't surprise me if there's a better way to do it.</p>
<pre><code>a, b = (string.split("=") + [None])[:2]
</code></pre>
| 4 | 2009-04-14T19:49:59Z | [
"python"
] |
Partial list unpack in Python | 749,070 | <p>In Python, the assignment operator can unpack list or tuple into variables, like this:</p>
<pre><code>l = (1, 2)
a, b = l # Here goes auto unpack
</code></pre>
<p>But I need to specify exactly the same amount of names to the left as an items count in the list to the right. But sometimes I don't know a size of the ... | 30 | 2009-04-14T19:44:54Z | 749,101 | <pre><code># this will result in a="length" and b="25"
a, b = "length=25".partition("=")[::2]
# this will result in a="DEFAULT_LENGTH" and b=""
a, b = "DEFAULT_LENGTH".partition("=")[::2]
</code></pre>
| 40 | 2009-04-14T19:51:25Z | [
"python"
] |
Partial list unpack in Python | 749,070 | <p>In Python, the assignment operator can unpack list or tuple into variables, like this:</p>
<pre><code>l = (1, 2)
a, b = l # Here goes auto unpack
</code></pre>
<p>But I need to specify exactly the same amount of names to the left as an items count in the list to the right. But sometimes I don't know a size of the ... | 30 | 2009-04-14T19:44:54Z | 749,107 | <p>You could write a helper function to do it.</p>
<pre><code>>>> def pack(values, size):
... if len(values) >= size:
... return values[:size]
... return values + [None] * (size - len(values))
...
>>> a, b = pack('a:b:c'.split(':'), 2)
>>> a, b
('a', 'b')
>>> a, b... | 4 | 2009-04-14T19:52:19Z | [
"python"
] |
Partial list unpack in Python | 749,070 | <p>In Python, the assignment operator can unpack list or tuple into variables, like this:</p>
<pre><code>l = (1, 2)
a, b = l # Here goes auto unpack
</code></pre>
<p>But I need to specify exactly the same amount of names to the left as an items count in the list to the right. But sometimes I don't know a size of the ... | 30 | 2009-04-14T19:44:54Z | 749,120 | <p>Don't use this code, it is meant as a joke, but it does what you want: </p>
<pre><code>a = b = None
try: a, b = [a for a in 'DEFAULT_LENGTH'.split('=')]
except: pass
</code></pre>
| 0 | 2009-04-14T19:55:38Z | [
"python"
] |
Partial list unpack in Python | 749,070 | <p>In Python, the assignment operator can unpack list or tuple into variables, like this:</p>
<pre><code>l = (1, 2)
a, b = l # Here goes auto unpack
</code></pre>
<p>But I need to specify exactly the same amount of names to the left as an items count in the list to the right. But sometimes I don't know a size of the ... | 30 | 2009-04-14T19:44:54Z | 749,208 | <p>The nicest way is using the <a href="http://docs.python.org/library/stdtypes.html?highlight=partition#str.partition" rel="nofollow">partition string method</a>:</p>
<blockquote>
<p>Split the string at the first occurrence of sep, and return a 3-tuple containing the part before the separator, the separator itself,... | 6 | 2009-04-14T20:21:43Z | [
"python"
] |
Partial list unpack in Python | 749,070 | <p>In Python, the assignment operator can unpack list or tuple into variables, like this:</p>
<pre><code>l = (1, 2)
a, b = l # Here goes auto unpack
</code></pre>
<p>But I need to specify exactly the same amount of names to the left as an items count in the list to the right. But sometimes I don't know a size of the ... | 30 | 2009-04-14T19:44:54Z | 749,340 | <p>This may be of no use to you unless you're using Python 3. However, for completeness, it's worth noting that the <a href="http://www.python.org/dev/peps/pep-3132/" rel="nofollow">extended tuple unpacking</a> introduced there allows you to do things like:</p>
<pre><code>>>> a, *b = "length=25".split("=")
&g... | 41 | 2009-04-14T20:54:55Z | [
"python"
] |
Partial list unpack in Python | 749,070 | <p>In Python, the assignment operator can unpack list or tuple into variables, like this:</p>
<pre><code>l = (1, 2)
a, b = l # Here goes auto unpack
</code></pre>
<p>But I need to specify exactly the same amount of names to the left as an items count in the list to the right. But sometimes I don't know a size of the ... | 30 | 2009-04-14T19:44:54Z | 749,409 | <blockquote>
<p>But sometimes I don't know a size of the list to the right, for example if I use split().</p>
</blockquote>
<p>Yeah, when I've got cases with limit>1 (so I can't use partition) I usually plump for:</p>
<pre><code>def paddedsplit(s, find, limit):
parts= s.split(find, limit)
return parts+[part... | 1 | 2009-04-14T21:21:05Z | [
"python"
] |
Partial list unpack in Python | 749,070 | <p>In Python, the assignment operator can unpack list or tuple into variables, like this:</p>
<pre><code>l = (1, 2)
a, b = l # Here goes auto unpack
</code></pre>
<p>But I need to specify exactly the same amount of names to the left as an items count in the list to the right. But sometimes I don't know a size of the ... | 30 | 2009-04-14T19:44:54Z | 749,864 | <p>Many other solutions have been proposed, but I have to say the most straightforward to me is still</p>
<pre><code>a, b = string.split("=") if "=" in string else (string, None)
</code></pre>
| 0 | 2009-04-15T00:29:26Z | [
"python"
] |
Partial list unpack in Python | 749,070 | <p>In Python, the assignment operator can unpack list or tuple into variables, like this:</p>
<pre><code>l = (1, 2)
a, b = l # Here goes auto unpack
</code></pre>
<p>But I need to specify exactly the same amount of names to the left as an items count in the list to the right. But sometimes I don't know a size of the ... | 30 | 2009-04-14T19:44:54Z | 750,359 | <p>As an alternative, perhaps use a regular expression?</p>
<pre><code>>>> import re
>>> unpack_re = re.compile("(\w*)(?:=(\w*))?")
>>> x = "DEFAULT_LENGTH"
>>> unpack_re.match(x).groups()
('DEFAULT_LENGTH', None)
>>> y = "length=107"
>>> unpack_re.match(y).group... | 0 | 2009-04-15T04:56:05Z | [
"python"
] |
Partial list unpack in Python | 749,070 | <p>In Python, the assignment operator can unpack list or tuple into variables, like this:</p>
<pre><code>l = (1, 2)
a, b = l # Here goes auto unpack
</code></pre>
<p>But I need to specify exactly the same amount of names to the left as an items count in the list to the right. But sometimes I don't know a size of the ... | 30 | 2009-04-14T19:44:54Z | 20,385,193 | <p>I don't recommend using this, but just for fun here's some code that actually does what you want. When you call <code>unpack(<sequence>)</code>, the <code>unpack</code> function uses the <code>inspect</code> module to find the actual line of source where the function was called, then uses the <code>ast</code> ... | 0 | 2013-12-04T20:25:48Z | [
"python"
] |
How to generate examples of a gettext plural forms expression? In Python? | 749,170 | <p>Given a gettext Plural-Forms line, general a few example values for each <code>n</code>. I'd like this feature for the web interface for my site's translators, so that they know which plural form to put where. For example, given:</p>
<p><code>"Plural-Forms: nplurals=3; plural=n%10==1 && n%100!=11 ? 0 : n%10... | 1 | 2009-04-14T20:11:06Z | 754,246 | <p>Given that it's late, I'll bite.</p>
<p>The following solution is hacky, and relies on converting your plural form to python code that can be evaluated (basically converting the x ? y : z statements to the python x and y or z equivalent, and changing &&/|| to and/or)</p>
<p>I'm not sure if your plural form... | 1 | 2009-04-16T00:01:35Z | [
"python",
"internationalization",
"gettext"
] |
Search a list of strings for any sub-string from another list | 749,342 | <p>Given these 3 lists of data and a list of keywords:</p>
<pre><code>good_data1 = ['hello, world', 'hey, world']
good_data2 = ['hey, man', 'whats up']
bad_data = ['hi, earth', 'sup, planet']
keywords = ['world', 'he']
</code></pre>
<p>I'm trying to write a simple function to check if any of the keywords exist as a s... | 17 | 2009-04-14T20:56:08Z | 749,371 | <p>Are you looking for</p>
<pre><code>any( k in s for k in keywords )
</code></pre>
<p>It's more compact, but might be less efficient.</p>
| 34 | 2009-04-14T21:05:58Z | [
"python"
] |
Search a list of strings for any sub-string from another list | 749,342 | <p>Given these 3 lists of data and a list of keywords:</p>
<pre><code>good_data1 = ['hello, world', 'hey, world']
good_data2 = ['hey, man', 'whats up']
bad_data = ['hi, earth', 'sup, planet']
keywords = ['world', 'he']
</code></pre>
<p>I'm trying to write a simple function to check if any of the keywords exist as a s... | 17 | 2009-04-14T20:56:08Z | 749,375 | <p>I think this is pretty efficient and clear, though you could use map() to avoid the many nests. I agree with ross on the dictionary idea for larger lists.</p>
| 0 | 2009-04-14T21:07:32Z | [
"python"
] |
Search a list of strings for any sub-string from another list | 749,342 | <p>Given these 3 lists of data and a list of keywords:</p>
<pre><code>good_data1 = ['hello, world', 'hey, world']
good_data2 = ['hey, man', 'whats up']
bad_data = ['hi, earth', 'sup, planet']
keywords = ['world', 'he']
</code></pre>
<p>I'm trying to write a simple function to check if any of the keywords exist as a s... | 17 | 2009-04-14T20:56:08Z | 749,388 | <p>You may be able to improve matters by building your list of keywords as a regular expression. </p>
<p>This may allow them to be tested in parallel, but will very much depend on what the keywords are (eg. some work may be reused testing for "hello" and "hell", rather than searching every phrase from the start for e... | 2 | 2009-04-14T21:13:10Z | [
"python"
] |
Search a list of strings for any sub-string from another list | 749,342 | <p>Given these 3 lists of data and a list of keywords:</p>
<pre><code>good_data1 = ['hello, world', 'hey, world']
good_data2 = ['hey, man', 'whats up']
bad_data = ['hi, earth', 'sup, planet']
keywords = ['world', 'he']
</code></pre>
<p>I'm trying to write a simple function to check if any of the keywords exist as a s... | 17 | 2009-04-14T20:56:08Z | 749,418 | <p>In your example, with so few items, it doesn't really matter. But if you have a list of several thousand items, this might help.</p>
<p>Since you don't care which element in the list contains the keyword, you can scan the whole list once (as one string) instead of one item at the time. For that you need a join char... | 16 | 2009-04-14T21:23:41Z | [
"python"
] |
Search a list of strings for any sub-string from another list | 749,342 | <p>Given these 3 lists of data and a list of keywords:</p>
<pre><code>good_data1 = ['hello, world', 'hey, world']
good_data2 = ['hey, man', 'whats up']
bad_data = ['hi, earth', 'sup, planet']
keywords = ['world', 'he']
</code></pre>
<p>I'm trying to write a simple function to check if any of the keywords exist as a s... | 17 | 2009-04-14T20:56:08Z | 749,480 | <p>If you have many keywords, you might want to try a suffix tree [1]. Insert all the words from the three data lists, storing which list each word comes from in it's terminating node. Then you can perform queries on the tree for each keyword really, really fast.</p>
<p>Warning: suffix trees are very complicated to im... | 3 | 2009-04-14T21:40:37Z | [
"python"
] |
How to read and process binary (base-2) logical representations from file | 749,359 | <p>I have a file containing 800 lines like:</p>
<pre><code>id binary-coded-info
---------------------------
4657 001001101
4789 110111111
etc.
</code></pre>
<p>where each 0 or 1 stands for the presence of some feature.
I want to read this file and do several bitwise logical operations on the
binary-code... | 0 | 2009-04-14T21:02:33Z | 749,369 | <p>In C, you can use "strtol(str, NULL, 2)" to do the conversion, if you're already doing this in C.</p>
<p>Something like the following would work:</p>
<pre><code>FILE* f = fopen("myfile.txt", "r");
char line[1024];
while ((line = fgets(line, sizeof(line), f))
{
char* p;
long column1 = strtol(line, &p, 10);
... | 0 | 2009-04-14T21:05:30Z | [
"python",
"shell",
"binary",
"awk",
"decimal"
] |
How to read and process binary (base-2) logical representations from file | 749,359 | <p>I have a file containing 800 lines like:</p>
<pre><code>id binary-coded-info
---------------------------
4657 001001101
4789 110111111
etc.
</code></pre>
<p>where each 0 or 1 stands for the presence of some feature.
I want to read this file and do several bitwise logical operations on the
binary-code... | 0 | 2009-04-14T21:02:33Z | 749,381 | <p>Why convert them and use bit operations?</p>
<p>In Python, you can do all of this as a string.</p>
<pre><code>for line in myFile:
key, value = line.split()
bits = list(value)
# bits will be a list of 1-char strings ['1','0','1',...]
# ... do stuff to bits ...
print key, "".join( value )
</code>... | 3 | 2009-04-14T21:10:10Z | [
"python",
"shell",
"binary",
"awk",
"decimal"
] |
How to read and process binary (base-2) logical representations from file | 749,359 | <p>I have a file containing 800 lines like:</p>
<pre><code>id binary-coded-info
---------------------------
4657 001001101
4789 110111111
etc.
</code></pre>
<p>where each 0 or 1 stands for the presence of some feature.
I want to read this file and do several bitwise logical operations on the
binary-code... | 0 | 2009-04-14T21:02:33Z | 749,603 | <p>In python, you can convert to binary using int, specifying base 2. ie:</p>
<pre><code>>>> int('110111111',2)
447
</code></pre>
<p>To convert back, there is a <code>bin</code> function in python2.6 or 3, but not in python2.5, so you'd need to implement it yourself (or use something like the below):</p>
<... | 1 | 2009-04-14T22:33:40Z | [
"python",
"shell",
"binary",
"awk",
"decimal"
] |
How to read and process binary (base-2) logical representations from file | 749,359 | <p>I have a file containing 800 lines like:</p>
<pre><code>id binary-coded-info
---------------------------
4657 001001101
4789 110111111
etc.
</code></pre>
<p>where each 0 or 1 stands for the presence of some feature.
I want to read this file and do several bitwise logical operations on the
binary-code... | 0 | 2009-04-14T21:02:33Z | 749,611 | <p>"Simple" Perl one liner (replace foo bar baz quux with your flags</p>
<pre><code>perl -le '@f=qw/foo bar baz quux/;$_&&print($f[$i]),$i++for split//, shift' 1011
</code></pre>
<p>Here is a readable Perl version:</p>
<pre><code>#!/usr/bin/perl
use strict;
use warnings;
#flags that can be turned on and of... | 0 | 2009-04-14T22:34:54Z | [
"python",
"shell",
"binary",
"awk",
"decimal"
] |
How to read and process binary (base-2) logical representations from file | 749,359 | <p>I have a file containing 800 lines like:</p>
<pre><code>id binary-coded-info
---------------------------
4657 001001101
4789 110111111
etc.
</code></pre>
<p>where each 0 or 1 stands for the presence of some feature.
I want to read this file and do several bitwise logical operations on the
binary-code... | 0 | 2009-04-14T21:02:33Z | 749,727 | <p>Expanding on Brian's answer:</p>
<pre><code># Get rid of the '----' line for simplicity
data_file = '''id binary-coded-info
4657 001001101
4789 110111111
'''
import cStringIO
import csv, sys
data = [] # A list for the row dictionaries (we could just as easily have used the regular reader method)
# Rea... | 0 | 2009-04-14T23:34:27Z | [
"python",
"shell",
"binary",
"awk",
"decimal"
] |
How to read and process binary (base-2) logical representations from file | 749,359 | <p>I have a file containing 800 lines like:</p>
<pre><code>id binary-coded-info
---------------------------
4657 001001101
4789 110111111
etc.
</code></pre>
<p>where each 0 or 1 stands for the presence of some feature.
I want to read this file and do several bitwise logical operations on the
binary-code... | 0 | 2009-04-14T21:02:33Z | 12,026,896 | <p>And following a long tradition, here is a awk version :-)<br>
Last checked on gawk 4.0.1<br>
Should work for other awk as well.</p>
<pre><code>{
var = _int("00010101",2);
print _bin( or( var , _int("00101001",2) ) , 8 )
print _bin( and( var , _int("10110111",2) ) , 8 )
print _bin( xor( va... | 0 | 2012-08-19T13:36:10Z | [
"python",
"shell",
"binary",
"awk",
"decimal"
] |
Python: How to estimate / calculate memory footprint of data structures? | 749,625 | <p>What's a good way to estimate the memory footprint of an object?</p>
<p>Conversely, what's a good way to measure the footprint?</p>
<p>For example, say I have a dictionary whose values are lists of integer,float tuples:</p>
<pre><code>d['key'] = [ (1131, 3.11e18), (9813, 2.48e19), (4991, 9.11e18) ]
</code></pre>
... | 11 | 2009-04-14T22:40:05Z | 749,637 | <p>You can do this with a memory profiler, of which there are a couple I'm aware of:</p>
<ol>
<li><p><a href="http://pysizer.8325.org/" rel="nofollow">PySizer</a> - poissibly obsolete, as the homepage now recommends:</p></li>
<li><p><a href="http://guppy-pe.sourceforge.net/#Heapy" rel="nofollow">Heapy</a>.</p></li>
</... | 4 | 2009-04-14T22:46:55Z | [
"python",
"memory-management"
] |
Python: How to estimate / calculate memory footprint of data structures? | 749,625 | <p>What's a good way to estimate the memory footprint of an object?</p>
<p>Conversely, what's a good way to measure the footprint?</p>
<p>For example, say I have a dictionary whose values are lists of integer,float tuples:</p>
<pre><code>d['key'] = [ (1131, 3.11e18), (9813, 2.48e19), (4991, 9.11e18) ]
</code></pre>
... | 11 | 2009-04-14T22:40:05Z | 749,648 | <p><a href="http://guppy-pe.sourceforge.net/">Guppy</a> has a nice memory profiler (Heapy):</p>
<pre><code>>>> from guppy import hpy
>>> hp = hpy()
>>> hp.setrelheap() # ignore all existing objects
>>> d = {}
>>> d['key'] = [ (1131, 3.11e18), (9813, 2.48e19), (4991, 9.11e18... | 9 | 2009-04-14T22:53:08Z | [
"python",
"memory-management"
] |
What is the format in which Django passwords are stored in the database? | 749,682 | <p>You know how django passwords are stored like this: </p>
<pre><code>sha1$a1976$a36cc8cbf81742a8fb52e221aaeab48ed7f58ab4
</code></pre>
<p>and that is the "hashtype $salt $hash". My question is, how do they get the $hash? Is it the password and salt combined and then hashed or is something else entirely?</p>
| 23 | 2009-04-14T23:11:07Z | 749,686 | <p><a href="http://docs.djangoproject.com/en/dev/topics/auth/#passwords">According to the docs</a>:</p>
<blockquote>
<p>Hashtype is either sha1 (default), md5 or crypt -- the algorithm used to perform a one-way hash of the password. Salt is a random string used to salt the raw password to create the hash.</p>
</bloc... | 13 | 2009-04-14T23:14:00Z | [
"python",
"django"
] |
What is the format in which Django passwords are stored in the database? | 749,682 | <p>You know how django passwords are stored like this: </p>
<pre><code>sha1$a1976$a36cc8cbf81742a8fb52e221aaeab48ed7f58ab4
</code></pre>
<p>and that is the "hashtype $salt $hash". My question is, how do they get the $hash? Is it the password and salt combined and then hashed or is something else entirely?</p>
| 23 | 2009-04-14T23:11:07Z | 749,703 | <p>As always, use the source:</p>
<pre><code># root/django/trunk/django/contrib/auth/models.py
# snip
def get_hexdigest(algorithm, salt, raw_password):
"""
Returns a string of the hexdigest of the given plaintext password and salt
using the given algorithm ('md5', 'sha1' or 'crypt').
"""
raw_passwo... | 37 | 2009-04-14T23:25:06Z | [
"python",
"django"
] |
What is the format in which Django passwords are stored in the database? | 749,682 | <p>You know how django passwords are stored like this: </p>
<pre><code>sha1$a1976$a36cc8cbf81742a8fb52e221aaeab48ed7f58ab4
</code></pre>
<p>and that is the "hashtype $salt $hash". My question is, how do they get the $hash? Is it the password and salt combined and then hashed or is something else entirely?</p>
| 23 | 2009-04-14T23:11:07Z | 25,954,542 | <p>For a long time, until version 1.3, Django indeed followed the irresponsible practice of using a plain single iteration of SHA1, with a salt that was too short, to store password information. That approach has been <a href="http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.52.4704" rel="nofollow">out of date ... | 2 | 2014-09-21T00:21:21Z | [
"python",
"django"
] |
Pretty printing XML in Python | 749,796 | <p>What is the best way (or even the various ways) to pretty print xml in Python?</p>
| 262 | 2009-04-15T00:05:41Z | 749,801 | <p><a href="http://www.codeplex.com/xmlpp" rel="nofollow">XML pretty print for python</a> looks pretty good for this task. (Appropriately named, too.)</p>
<p>An alternative is to use <a href="http://pyxml.sourceforge.net/topics/" rel="nofollow">pyXML</a>, which has a <a href="http://guillaume.segu.in/blog/home/119/py... | 3 | 2009-04-15T00:07:19Z | [
"python",
"xml",
"pretty-print"
] |
Pretty printing XML in Python | 749,796 | <p>What is the best way (or even the various ways) to pretty print xml in Python?</p>
| 262 | 2009-04-15T00:05:41Z | 749,839 | <p>lxml is recent, updated, and includes a pretty print function</p>
<pre><code>import lxml.etree as etree
x = etree.parse("filename")
print etree.tostring(x, pretty_print = True)
</code></pre>
<p>Check out the lxml tutorial:
<a href="http://lxml.de/tutorial.html">http://lxml.de/tutorial.html</a></p>
| 81 | 2009-04-15T00:21:19Z | [
"python",
"xml",
"pretty-print"
] |
Pretty printing XML in Python | 749,796 | <p>What is the best way (or even the various ways) to pretty print xml in Python?</p>
| 262 | 2009-04-15T00:05:41Z | 749,913 | <p>If you're using a DOM implementation, each has their own form of pretty-printing built-in:</p>
<pre><code># minidom
#
document.toprettyxml()
# 4DOM
#
xml.dom.ext.PrettyPrint(document, stream)
# pxdom (or other DOM Level 3 LS-compliant imp)
#
serializer.domConfig.setParameter('format-pretty-print', True)
serialize... | 8 | 2009-04-15T00:48:22Z | [
"python",
"xml",
"pretty-print"
] |
Pretty printing XML in Python | 749,796 | <p>What is the best way (or even the various ways) to pretty print xml in Python?</p>
| 262 | 2009-04-15T00:05:41Z | 751,763 | <p>I had some problems with minidom's pretty print. I'd get a UnicodeError whenever I tried pretty-printing a document with characters outside the given encoding, eg if I had a β in a document and I tried <code>doc.toprettyxml(encoding='latin-1')</code>. Here's my workaround for it:</p>
<pre><code>def toprettyxml(d... | 4 | 2009-04-15T13:46:01Z | [
"python",
"xml",
"pretty-print"
] |
Pretty printing XML in Python | 749,796 | <p>What is the best way (or even the various ways) to pretty print xml in Python?</p>
| 262 | 2009-04-15T00:05:41Z | 1,206,856 | <pre><code>import xml.dom.minidom
xml = xml.dom.minidom.parse(xml_fname) # or xml.dom.minidom.parseString(xml_string)
pretty_xml_as_string = xml.toprettyxml()
</code></pre>
| 223 | 2009-07-30T14:12:29Z | [
"python",
"xml",
"pretty-print"
] |
Pretty printing XML in Python | 749,796 | <p>What is the best way (or even the various ways) to pretty print xml in Python?</p>
| 262 | 2009-04-15T00:05:41Z | 3,367,423 | <p>Here's my (hacky?) solution to get around the ugly text node problem.</p>
<pre><code>uglyXml = doc.toprettyxml(indent=' ')
text_re = re.compile('>\n\s+([^<>\s].*?)\n\s+</', re.DOTALL)
prettyXml = text_re.sub('>\g<1></', uglyXml)
print prettyXml
</code></pre>
<p>The above code will pr... | 44 | 2010-07-29T22:18:57Z | [
"python",
"xml",
"pretty-print"
] |
Pretty printing XML in Python | 749,796 | <p>What is the best way (or even the various ways) to pretty print xml in Python?</p>
| 262 | 2009-04-15T00:05:41Z | 4,590,052 | <p>Another solution is to borrow <a href="http://effbot.org/zone/element-lib.htm#prettyprint" rel="nofollow">this <code>indent</code> function</a>, for use with the ElementTree library that's built in to Python since 2.5.
Here's what that would look like:</p>
<pre class="lang-py prettyprint-override"><code>from xml.et... | 69 | 2011-01-04T01:57:31Z | [
"python",
"xml",
"pretty-print"
] |
Pretty printing XML in Python | 749,796 | <p>What is the best way (or even the various ways) to pretty print xml in Python?</p>
| 262 | 2009-04-15T00:05:41Z | 5,649,263 | <p>As others pointed out, lxml has a pretty printer built in.</p>
<p>Be aware though that by default it changes CDATA sections to normal text, which can have nasty results.</p>
<p>Here's a Python function that preserves the input file and only changes the indentation (notice the <code>strip_cdata=False</code>). Furth... | 16 | 2011-04-13T12:33:29Z | [
"python",
"xml",
"pretty-print"
] |
Pretty printing XML in Python | 749,796 | <p>What is the best way (or even the various ways) to pretty print xml in Python?</p>
| 262 | 2009-04-15T00:05:41Z | 10,133,365 | <p>If you have <code>xmllint</code> you can spawn a subprocess and use it. <code>xmllint --format <file></code> pretty-prints its input XML to standard output.</p>
<p>Note that this method uses an program external to python, which makes it sort of a hack.</p>
<pre><code>def pretty_print_xml(xml):
proc = sub... | 9 | 2012-04-12T23:40:33Z | [
"python",
"xml",
"pretty-print"
] |
Pretty printing XML in Python | 749,796 | <p>What is the best way (or even the various ways) to pretty print xml in Python?</p>
| 262 | 2009-04-15T00:05:41Z | 12,940,014 | <p>I tried to edit "ade"s answer above, but Stack Overflow wouldn't let me edit after I had initially provided feedback anonymously. This is a less buggy version of the function to pretty-print an ElementTree.</p>
<pre><code>def indent(elem, level=0, more_sibs=False):
i = "\n"
if level:
i += (level-1)... | 6 | 2012-10-17T17:32:01Z | [
"python",
"xml",
"pretty-print"
] |
Pretty printing XML in Python | 749,796 | <p>What is the best way (or even the various ways) to pretty print xml in Python?</p>
| 262 | 2009-04-15T00:05:41Z | 17,613,446 | <p>I solved this with some lines of code, opening the file, going trough it and adding indentation, then saving it again. I was working with small xml files, and did not want to add dependencies, or more libraries to install for the user. Anyway, here is what I ended up with:</p>
<pre><code> f = open(file_name,'r')... | 0 | 2013-07-12T11:01:36Z | [
"python",
"xml",
"pretty-print"
] |
Pretty printing XML in Python | 749,796 | <p>What is the best way (or even the various ways) to pretty print xml in Python?</p>
| 262 | 2009-04-15T00:05:41Z | 23,634,596 | <pre><code>from yattag import indent
pretty_string = indent(ugly_string)
</code></pre>
<p>It won't add spaces or newlines inside text nodes, unless you ask for it with:</p>
<pre><code>indent(mystring, indent_text = True)
</code></pre>
<p>You can specify what the indentation unit should be and what the newline shoul... | 3 | 2014-05-13T14:49:14Z | [
"python",
"xml",
"pretty-print"
] |
Pretty printing XML in Python | 749,796 | <p>What is the best way (or even the various ways) to pretty print xml in Python?</p>
| 262 | 2009-04-15T00:05:41Z | 31,664,793 | <p>I had this problem and solved it like this:</p>
<pre><code>def write_xml_file (self, file, xml_root_element, xml_declaration=False, pretty_print=False, encoding='unicode', indent='\t'):
pretty_printed_xml = etree.tostring(xml_root_element, xml_declaration=xml_declaration, pretty_print=pretty_print, encoding=enc... | 0 | 2015-07-27T23:06:29Z | [
"python",
"xml",
"pretty-print"
] |
Pretty printing XML in Python | 749,796 | <p>What is the best way (or even the various ways) to pretty print xml in Python?</p>
| 262 | 2009-04-15T00:05:41Z | 38,573,964 | <p>I wrote a solution to walk through an existing ElementTree and use text/tail to indent it as one typically expects.</p>
<pre><code>def prettify(element, indent=' '):
queue = [(0, element)] # (level, element)
while queue:
level, element = queue.pop(0)
children = [(level + 1, child) for chil... | 0 | 2016-07-25T17:25:06Z | [
"python",
"xml",
"pretty-print"
] |
Pretty printing XML in Python | 749,796 | <p>What is the best way (or even the various ways) to pretty print xml in Python?</p>
| 262 | 2009-04-15T00:05:41Z | 39,375,635 | <p>You can use popular external library <a href="https://github.com/martinblech/xmltodict" rel="nofollow">xmltodict</a>, with <code>unparse</code> and <code>pretty=True</code> you will get best result:</p>
<pre><code>xmltodict.unparse(
xmltodict.parse(my_xml), full_document=False, pretty=True)
</code></pre>
<p><c... | 0 | 2016-09-07T17:02:38Z | [
"python",
"xml",
"pretty-print"
] |
Pretty printing XML in Python | 749,796 | <p>What is the best way (or even the various ways) to pretty print xml in Python?</p>
| 262 | 2009-04-15T00:05:41Z | 39,482,716 | <p>BeautifulSoup has a easy to use <code>prettify()</code> function. </p>
<p>It indents one space per indentation level. It works much better than lxml's pretty_print and is short and sweet. </p>
<pre><code>from bs4 import BeautifulSoup
bs = BeautifulSoup(open(xml_file), 'xml')
print bs.prettify()
</code></pre>
| 0 | 2016-09-14T04:54:09Z | [
"python",
"xml",
"pretty-print"
] |
How to visualize IP addresses as they change in python? | 749,937 | <p>I've written a little script that collects my external IP address every time I open a new terminal window and appends it, at well as the current time, to a text file. I'm looking for ideas on a way to visualize when/how often my IP address changes. I bounce between home and campus and could separate them using the s... | 1 | 2009-04-15T01:05:26Z | 749,951 | <p>There's a section in the matplotlib user guide about drawing bars on a chart to represent ranges. I've never done that myself but it seems appropriate for what you're looking for.</p>
| 0 | 2009-04-15T01:15:15Z | [
"python",
"matplotlib",
"ip-address",
"visualization"
] |
How to visualize IP addresses as they change in python? | 749,937 | <p>I've written a little script that collects my external IP address every time I open a new terminal window and appends it, at well as the current time, to a text file. I'm looking for ideas on a way to visualize when/how often my IP address changes. I bounce between home and campus and could separate them using the s... | 1 | 2009-04-15T01:05:26Z | 749,955 | <p>Assuming you specified terminal, i'll assume you are on a UNIX variant system. Using the -f switch along with the command line utility tail can allow you to constantly monitor the end of a file. You could also use something like IBM's <a href="http://www.ibm.com/developerworks/linux/library/l-inotify.html" rel="nofo... | 0 | 2009-04-15T01:17:25Z | [
"python",
"matplotlib",
"ip-address",
"visualization"
] |
How to visualize IP addresses as they change in python? | 749,937 | <p>I've written a little script that collects my external IP address every time I open a new terminal window and appends it, at well as the current time, to a text file. I'm looking for ideas on a way to visualize when/how often my IP address changes. I bounce between home and campus and could separate them using the s... | 1 | 2009-04-15T01:05:26Z | 749,972 | <p>"When" is one dimensional temporal data, which is well shown by a timeline. At larger timescales, you'd probably lose the details, but most any plot of "when" would have this defect.</p>
<p>For "How often", a standard 2d (bar) plot of time vs frequency, divided into buckets for each day/week/month, would be a stan... | 1 | 2009-04-15T01:30:42Z | [
"python",
"matplotlib",
"ip-address",
"visualization"
] |
How to visualize IP addresses as they change in python? | 749,937 | <p>I've written a little script that collects my external IP address every time I open a new terminal window and appends it, at well as the current time, to a text file. I'm looking for ideas on a way to visualize when/how often my IP address changes. I bounce between home and campus and could separate them using the s... | 1 | 2009-04-15T01:05:26Z | 749,994 | <p>Plot your IP as a point on <a href="http://xkcd.com/195/" rel="nofollow">the xkcd internet map</a> (or some zoomed in subset of the map, to better show different but closely neighboring IPs). </p>
<p>Plot each point "stacked" proportional to how often you've had that IP, and color the IPs to make more recent points... | 4 | 2009-04-15T01:48:54Z | [
"python",
"matplotlib",
"ip-address",
"visualization"
] |
find missing numeric from ALPHANUMERIC - Python | 750,093 | <p>How would I write a function in Python to determine if a list of filenames matches a given pattern and which files are missing from that pattern? For example:</p>
<p>Input -></p>
<pre><code>KUMAR.3.txt
KUMAR.4.txt
KUMAR.6.txt
KUMAR.7.txt
KUMAR.9.txt
KUMAR.10.txt
KUMAR.11.txt
KUMAR.13.txt
KUMAR.15.txt
KUMAR.16.txt
... | 1 | 2009-04-15T02:36:48Z | 750,111 | <p>Assuming the patterns are relatively static, this is easy enough with a regex:</p>
<pre><code>import re
inlist = "KUMAR.3.txt KUMAR.4.txt KUMAR.6.txt KUMAR.7.txt KUMAR.9.txt KUMAR.10.txt KUMAR.11.txt KUMAR.13.txt KUMAR.15.txt KUMAR.16.txt".split()
def get_count(s):
return int(re.match('.*\.(\d+)\..*', s).grou... | 1 | 2009-04-15T02:46:38Z | [
"python",
"list",
"filenames",
"alphanumeric"
] |
find missing numeric from ALPHANUMERIC - Python | 750,093 | <p>How would I write a function in Python to determine if a list of filenames matches a given pattern and which files are missing from that pattern? For example:</p>
<p>Input -></p>
<pre><code>KUMAR.3.txt
KUMAR.4.txt
KUMAR.6.txt
KUMAR.7.txt
KUMAR.9.txt
KUMAR.10.txt
KUMAR.11.txt
KUMAR.13.txt
KUMAR.15.txt
KUMAR.16.txt
... | 1 | 2009-04-15T02:36:48Z | 750,150 | <p>You can approach this as:</p>
<ol>
<li>Convert the filenames to appropriate integers.</li>
<li>Find the missing numbers.</li>
<li>Combine the missing numbers with the filename template as output.</li>
</ol>
<p>For (1), if the file structure is predictable, then this is easy.</p>
<pre><code>def to_num(s, start=6):... | 2 | 2009-04-15T02:59:26Z | [
"python",
"list",
"filenames",
"alphanumeric"
] |
How is returning the output of a function different than printing it? | 750,136 | <p>In my previous <a href="http://stackoverflow.com/questions/746774/basic-python-quick-question-regarding-calling-a-function">question</a>, Andrew Jaffe writes: </p>
<blockquote>
<p>In addition to all of the other hints and tips, I think you're missing something crucial: your functions actually need to return somet... | 18 | 2009-04-15T02:53:39Z | 750,146 | <p>you just add a return statement...</p>
<pre><code>def autoparts():
parts_dict={}
list_of_parts = open('list_of_parts.txt', 'r')
for line in list_of_parts:
k, v = line.split()
parts_dict[k] = v
return parts_dict
</code></pre>
<p>printing out only prints out to the standard output (screen) of... | 2 | 2009-04-15T02:58:33Z | [
"python",
"return"
] |
How is returning the output of a function different than printing it? | 750,136 | <p>In my previous <a href="http://stackoverflow.com/questions/746774/basic-python-quick-question-regarding-calling-a-function">question</a>, Andrew Jaffe writes: </p>
<blockquote>
<p>In addition to all of the other hints and tips, I think you're missing something crucial: your functions actually need to return somet... | 18 | 2009-04-15T02:53:39Z | 750,148 | <p>Print simply prints out the structure to your output device (normally the console). Nothing more. To return it from your function, you would do:</p>
<pre><code>def autoparts():
parts_dict={}
list_of_parts = open('list_of_parts.txt', 'r')
for line in list_of_parts:
k, v = line.split()
parts_dic... | 47 | 2009-04-15T02:59:11Z | [
"python",
"return"
] |
How is returning the output of a function different than printing it? | 750,136 | <p>In my previous <a href="http://stackoverflow.com/questions/746774/basic-python-quick-question-regarding-calling-a-function">question</a>, Andrew Jaffe writes: </p>
<blockquote>
<p>In addition to all of the other hints and tips, I think you're missing something crucial: your functions actually need to return somet... | 18 | 2009-04-15T02:53:39Z | 750,154 | <p>The print statement will output an object to the user. A return statement will allow assigning the dictionary to a variable <em>once the function is finished</em>.</p>
<pre><code>>>> def foo():
... print "Hello, world!"
...
>>> a = foo()
Hello, world!
>>> a
>>> def foo():
.... | 6 | 2009-04-15T03:01:10Z | [
"python",
"return"
] |
How is returning the output of a function different than printing it? | 750,136 | <p>In my previous <a href="http://stackoverflow.com/questions/746774/basic-python-quick-question-regarding-calling-a-function">question</a>, Andrew Jaffe writes: </p>
<blockquote>
<p>In addition to all of the other hints and tips, I think you're missing something crucial: your functions actually need to return somet... | 18 | 2009-04-15T02:53:39Z | 750,155 | <p>I think you're confused because you're running from the REPL, which automatically prints out the value returned when you call a function. In that case, you do get identical output whether you have a function that creates a value, prints it, and throws it away, or you have a function that creates a value and returns ... | 1 | 2009-04-15T03:01:37Z | [
"python",
"return"
] |
Emacs - tab-completion of local Python variables | 750,267 | <p>Is there a good emacs mode that will allow tab-completion of local python variables? I set up ipython.el but it will only tab-complete things in the scope of the interpreter. I'm looking for something that will let me tab-complete tokens in the local namespace of a function or file.</p>
| 27 | 2009-04-15T04:04:18Z | 750,280 | <p>I think that you may be looking for <a href="http://www.rwdev.eu/articles/emacspyeng" rel="nofollow">something like this</a>. It uses <a href="http://pymacs.progiciels-bpi.ca/" rel="nofollow">Pymacs</a> and <a href="http://sourceforge.net/projects/python-mode/" rel="nofollow">python-mode</a> to do just what you are ... | 4 | 2009-04-15T04:09:23Z | [
"python",
"emacs",
"autocomplete"
] |
Emacs - tab-completion of local Python variables | 750,267 | <p>Is there a good emacs mode that will allow tab-completion of local python variables? I set up ipython.el but it will only tab-complete things in the scope of the interpreter. I'm looking for something that will let me tab-complete tokens in the local namespace of a function or file.</p>
| 27 | 2009-04-15T04:04:18Z | 750,721 | <p>M-/ runs the command dabbrev-expand . This will complete local names in any mode.
Also I bind meta f1 to hippie expand from all open buffers. This is very useful for me.</p>
<pre><code>;; Bind hippie-expand
(global-set-key [(meta f1)] (make-hippie-expand-function
'(try-expand-dabbrev-... | 16 | 2009-04-15T08:02:33Z | [
"python",
"emacs",
"autocomplete"
] |
Emacs - tab-completion of local Python variables | 750,267 | <p>Is there a good emacs mode that will allow tab-completion of local python variables? I set up ipython.el but it will only tab-complete things in the scope of the interpreter. I'm looking for something that will let me tab-complete tokens in the local namespace of a function or file.</p>
| 27 | 2009-04-15T04:04:18Z | 750,912 | <p>The blog post describing kind of tab completion you want can be found at
<a href="http://www.enigmacurry.com/2009/01/21/autocompleteel-python-code-completion-in-emacs/">Python code completion in Emacs</a>.
There is a bit of installing packages, pymacs, <a href="http://www.emacswiki.org/emacs/AutoComplete">AutoCompl... | 10 | 2009-04-15T09:24:11Z | [
"python",
"emacs",
"autocomplete"
] |
Emacs - tab-completion of local Python variables | 750,267 | <p>Is there a good emacs mode that will allow tab-completion of local python variables? I set up ipython.el but it will only tab-complete things in the scope of the interpreter. I'm looking for something that will let me tab-complete tokens in the local namespace of a function or file.</p>
| 27 | 2009-04-15T04:04:18Z | 765,390 | <p>I use emacs-autocomplete.el (version 0.2.0) together with yasnippet. Works ok for me, although it isn't a complete auto-completion environment like eclipse+java is. But enough for a common emacs hacker like me :)</p>
<p>1) Download autocomplete from <a href="http://www.emacswiki.org/emacs/AutoComplete">here</a> (fi... | 13 | 2009-04-19T13:09:35Z | [
"python",
"emacs",
"autocomplete"
] |
Emacs - tab-completion of local Python variables | 750,267 | <p>Is there a good emacs mode that will allow tab-completion of local python variables? I set up ipython.el but it will only tab-complete things in the scope of the interpreter. I'm looking for something that will let me tab-complete tokens in the local namespace of a function or file.</p>
| 27 | 2009-04-15T04:04:18Z | 6,281,004 | <p>If you just want to get it up and running with minimal fuss, try the <a href="http://gabrielelanaro.github.com/emacs-for-python/" rel="nofollow">emacs-for-python</a> package.</p>
<p>Happy coding!</p>
| 3 | 2011-06-08T15:05:47Z | [
"python",
"emacs",
"autocomplete"
] |
Emacs - tab-completion of local Python variables | 750,267 | <p>Is there a good emacs mode that will allow tab-completion of local python variables? I set up ipython.el but it will only tab-complete things in the scope of the interpreter. I'm looking for something that will let me tab-complete tokens in the local namespace of a function or file.</p>
| 27 | 2009-04-15T04:04:18Z | 14,253,624 | <p>Use <a href="https://github.com/tkf/emacs-jedi" rel="nofollow">Jedi</a>!</p>
<p>It really understands Python better than any other autocompletion library:</p>
<ul>
<li>builtins</li>
<li>multiple returns or yields</li>
<li>tuple assignments / array indexing / dictionary indexing</li>
<li>with-statement / exception ... | 4 | 2013-01-10T08:31:32Z | [
"python",
"emacs",
"autocomplete"
] |
Retrieving/Printing execution context | 750,702 | <p>EDIT: This question has been solved with help from apphacker and ConcernedOfTunbridgeWells. I have updated the code to reflect the solution I will be using.</p>
<p>I am currently writing a swarm intelligence simulator and looking to give the user an easy way to debug their algorithms. Among other outputs, I feel it... | 3 | 2009-04-15T07:55:08Z | 750,728 | <p>try:</p>
<pre><code>class TheClass(object):
def __init__(self,val):
self.val=val
def thefunction(self,a,b):
c=a+b
print locals()
C=TheClass(2)
C.thefunction(1,2)
</code></pre>
| 1 | 2009-04-15T08:04:10Z | [
"python"
] |
Retrieving/Printing execution context | 750,702 | <p>EDIT: This question has been solved with help from apphacker and ConcernedOfTunbridgeWells. I have updated the code to reflect the solution I will be using.</p>
<p>I am currently writing a swarm intelligence simulator and looking to give the user an easy way to debug their algorithms. Among other outputs, I feel it... | 3 | 2009-04-15T07:55:08Z | 750,729 | <p>You can use <code>__locals__</code> to get the local execution context. See <a href="http://stackoverflow.com/questions/541329/is-it-possible-to-programmatically-construct-a-python-stack-frame-and-start-execu">this stackoverflow posting</a> for some discussion that may also be pertinent.</p>
| 1 | 2009-04-15T08:04:29Z | [
"python"
] |
How can I use Perl libraries from Python? | 750,872 | <p>I have written a bunch of Perl libraries (actually Perl classes) and I want to use some of them in my Python application. Is there a natural way to do this without using SWIG or writing Perl API for Python. I am asking for a similar way of PHP's Perl <a href="http://devzone.zend.com/node/view/id/1712" rel="nofollow"... | 4 | 2009-04-15T09:09:59Z | 750,885 | <p>Check out <a href="http://wiki.python.org/moin/PyPerl" rel="nofollow">PyPerl</a>.</p>
<p>WARNING: PyPerl is currently unmaintained, so don't use it if you require stability.</p>
| 1 | 2009-04-15T09:12:20Z | [
"python",
"perl",
"api"
] |
How can I use Perl libraries from Python? | 750,872 | <p>I have written a bunch of Perl libraries (actually Perl classes) and I want to use some of them in my Python application. Is there a natural way to do this without using SWIG or writing Perl API for Python. I am asking for a similar way of PHP's Perl <a href="http://devzone.zend.com/node/view/id/1712" rel="nofollow"... | 4 | 2009-04-15T09:09:59Z | 750,928 | <p>You've just missed a chance for having <code>Python</code> running on the <a href="http://www.parrot.org/" rel="nofollow">Parrot VM</a> together with Perl. On <strong>April 1st</strong>, 2009 <a href="http://www.python.org/dev/peps/pep-0401/" rel="nofollow">PEP 401</a> was published, and one of the <em>Official Acts... | 2 | 2009-04-15T09:31:32Z | [
"python",
"perl",
"api"
] |
How can I use Perl libraries from Python? | 750,872 | <p>I have written a bunch of Perl libraries (actually Perl classes) and I want to use some of them in my Python application. Is there a natural way to do this without using SWIG or writing Perl API for Python. I am asking for a similar way of PHP's Perl <a href="http://devzone.zend.com/node/view/id/1712" rel="nofollow"... | 4 | 2009-04-15T09:09:59Z | 751,012 | <p><strong>"What is the easiest way to use Perl classes in python?"</strong></p>
<p>Easiest. Rewrite the Perl into Python and be done with it. Seriously. Just pick one language—that's easiest. Leaving Perl behind is no great loss. Rewriting classes into Python may give you an opportunity to improve them in ... | 3 | 2009-04-15T10:07:05Z | [
"python",
"perl",
"api"
] |
How can I use Perl libraries from Python? | 750,872 | <p>I have written a bunch of Perl libraries (actually Perl classes) and I want to use some of them in my Python application. Is there a natural way to do this without using SWIG or writing Perl API for Python. I am asking for a similar way of PHP's Perl <a href="http://devzone.zend.com/node/view/id/1712" rel="nofollow"... | 4 | 2009-04-15T09:09:59Z | 752,483 | <p>Personally, I would expose the Perl libs as services via XML/RPC or some other such mechanism. That way you can call them from your Python application in a very natural manner.</p>
| 8 | 2009-04-15T16:14:35Z | [
"python",
"perl",
"api"
] |
How can I use Perl libraries from Python? | 750,872 | <p>I have written a bunch of Perl libraries (actually Perl classes) and I want to use some of them in my Python application. Is there a natural way to do this without using SWIG or writing Perl API for Python. I am asking for a similar way of PHP's Perl <a href="http://devzone.zend.com/node/view/id/1712" rel="nofollow"... | 4 | 2009-04-15T09:09:59Z | 752,617 | <p>I haven't tried it, but <a href="http://search.cpan.org/dist/Inline-Python/Python.pod" rel="nofollow">Inline::Python</a> lets you call Python from Perl. </p>
<p>You should be able to use a thin bit of perl to load your python app and then use the <code>perl</code> python package that comes with I::P to access your... | 4 | 2009-04-15T16:42:56Z | [
"python",
"perl",
"api"
] |
Auto __repr__ method | 750,908 | <p>I want to have simple representation of any class, like <code>{ property = value }</code>, is there auto <code>__repr__</code>?</p>
| 5 | 2009-04-15T09:21:58Z | 750,918 | <p>Do you mean</p>
<pre><code>__dict__
</code></pre>
<p>?</p>
| 4 | 2009-04-15T09:26:01Z | [
"python"
] |
Auto __repr__ method | 750,908 | <p>I want to have simple representation of any class, like <code>{ property = value }</code>, is there auto <code>__repr__</code>?</p>
| 5 | 2009-04-15T09:21:58Z | 750,938 | <p>Yes, you can make a class "AutoRepr" and let all other classes extend it:</p>
<pre><code>>>> class AutoRepr(object):
... def __repr__(self):
... items = ("%s = %r" % (k, v) for k, v in self.__dict__.items())
... return "<%s: {%s}>" % (self.__class__.__name__, ', '.join(items))
...... | 6 | 2009-04-15T09:36:03Z | [
"python"
] |
Auto __repr__ method | 750,908 | <p>I want to have simple representation of any class, like <code>{ property = value }</code>, is there auto <code>__repr__</code>?</p>
| 5 | 2009-04-15T09:21:58Z | 27,799,004 | <p>Well, I played a little bit with other answers and got a very pretty solution:</p>
<pre><code>class data:
@staticmethod
def repr(obj):
items = []
for prop, value in obj.__dict__.items():
try:
item = "%s = %r" % (prop, value)
assert len(item) < 2... | 1 | 2015-01-06T12:47:38Z | [
"python"
] |
Auto __repr__ method | 750,908 | <p>I want to have simple representation of any class, like <code>{ property = value }</code>, is there auto <code>__repr__</code>?</p>
| 5 | 2009-04-15T09:21:58Z | 38,540,861 | <p>Simplest way:</p>
<pre><code>def __repr__(self):
return str(self.__dict__)
</code></pre>
| 0 | 2016-07-23T10:43:09Z | [
"python"
] |
Efficient way of Solving Cryptarithms | 750,984 | <p>Hi i came across this puzzle which is a subset of famous kind of word and numbers based puzzles called <a href="http://en.wikipedia.org/wiki/Verbal%5Farithmetic" rel="nofollow">Cryptarithms</a>. Say you have an expression as</p>
<p>S E N D + M O R E = M O N E Y </p>
<p>Now the interesting part there is that, each... | 4 | 2009-04-15T09:54:09Z | 751,005 | <p><a href="http://wiki.tcl.tk/3304" rel="nofollow">this</a> may be of some help</p>
<p>Edit: the answer on the wiki link you posted is also useful!</p>
| 0 | 2009-04-15T10:04:18Z | [
"c#",
"python",
"solver",
"cryptarithmetic-puzzle"
] |
Efficient way of Solving Cryptarithms | 750,984 | <p>Hi i came across this puzzle which is a subset of famous kind of word and numbers based puzzles called <a href="http://en.wikipedia.org/wiki/Verbal%5Farithmetic" rel="nofollow">Cryptarithms</a>. Say you have an expression as</p>
<p>S E N D + M O R E = M O N E Y </p>
<p>Now the interesting part there is that, each... | 4 | 2009-04-15T09:54:09Z | 751,095 | <p>This is such a small problem that a brute-force solution is not a bad method. Assuming that each letter must represent a unique digit (i.e. we won't allow the solution S = 9, M = 1, * = 0) we see that number of combinations to try is <i>n!</i>, where <i>n</i> is the number of unique letters in the cryptarithm. The t... | 2 | 2009-04-15T10:37:17Z | [
"c#",
"python",
"solver",
"cryptarithmetic-puzzle"
] |
Efficient way of Solving Cryptarithms | 750,984 | <p>Hi i came across this puzzle which is a subset of famous kind of word and numbers based puzzles called <a href="http://en.wikipedia.org/wiki/Verbal%5Farithmetic" rel="nofollow">Cryptarithms</a>. Say you have an expression as</p>
<p>S E N D + M O R E = M O N E Y </p>
<p>Now the interesting part there is that, each... | 4 | 2009-04-15T09:54:09Z | 751,121 | <p>On this year's PyCon Raymond Hettinger talked about AI programing in Python, and has covered Cryptarithms. </p>
<p>The video of entire talk can be seen <a href="http://blip.tv/file/1947373/" rel="nofollow">here</a>, and cookbook with solution can be found on <a href="http://code.activestate.com/recipes/576615/" rel... | 6 | 2009-04-15T10:48:01Z | [
"c#",
"python",
"solver",
"cryptarithmetic-puzzle"
] |
Efficient way of Solving Cryptarithms | 750,984 | <p>Hi i came across this puzzle which is a subset of famous kind of word and numbers based puzzles called <a href="http://en.wikipedia.org/wiki/Verbal%5Farithmetic" rel="nofollow">Cryptarithms</a>. Say you have an expression as</p>
<p>S E N D + M O R E = M O N E Y </p>
<p>Now the interesting part there is that, each... | 4 | 2009-04-15T09:54:09Z | 751,133 | <p>Well, try writing it as a list of functions:</p>
<pre><code> SEND
MORE
----+
MONEY
</code></pre>
<p>If I remember my lower school math, this should be:</p>
<pre><code>Y = (D+E) mod 10
E = ((N+R) + (D+E)/10) mod 10
...
</code></pre>
| 1 | 2009-04-15T10:54:12Z | [
"c#",
"python",
"solver",
"cryptarithmetic-puzzle"
] |
Efficient way of Solving Cryptarithms | 750,984 | <p>Hi i came across this puzzle which is a subset of famous kind of word and numbers based puzzles called <a href="http://en.wikipedia.org/wiki/Verbal%5Farithmetic" rel="nofollow">Cryptarithms</a>. Say you have an expression as</p>
<p>S E N D + M O R E = M O N E Y </p>
<p>Now the interesting part there is that, each... | 4 | 2009-04-15T09:54:09Z | 9,647,700 | <p>Here is an efficient brute force method that cycles through all of the possibilities recursively but also takes note of the structure of the particular problem to shortcut the problem.</p>
<p>The first few arguments to each method represent trial values for each branch, the arguments v1, v2 etc are the values yet t... | 1 | 2012-03-10T15:40:27Z | [
"c#",
"python",
"solver",
"cryptarithmetic-puzzle"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.