title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
Python: 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:</p> <p><a href="http://webdesignledger.com/freebies/the-best-social-media-icons-all-in-one-place">http://webdesignledger.com/freebies/the-best-social-media-icons-all-in-one-place</a></p> <p>I did some inspecting with Firefox and see that the original url is not in the header.</p>
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 &amp;&amp; url.port req = Net::HTTP::Get.new(url.path) res = Net::HTTP.start(host, port) {|http| http.request(req) } fullurl = res.header['location'] puts fullurl </code></pre>
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 return should be. Here is the code that is writing the text:</p> <pre><code>&lt;code&gt; draw = ImageDraw.Draw(blankTemplate) draw.text((35 + attSpacing, 570),str(attText),fill=0,font=attFont) &lt;/code&gt; </code></pre> <p>attText is the variable that I am having trouble with. I'm casting it to a string before writing it because in some cases it is a number. </p> <p>Thanks for you help.</p>
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 + attSpacing </code></pre>
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 return should be. Here is the code that is writing the text:</p> <pre><code>&lt;code&gt; draw = ImageDraw.Draw(blankTemplate) draw.text((35 + attSpacing, 570),str(attText),fill=0,font=attFont) &lt;/code&gt; </code></pre> <p>attText is the variable that I am having trouble with. I'm casting it to a string before writing it because in some cases it is a number. </p> <p>Thanks for you help.</p>
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 </code></pre> <p>The expression "y+80*lineCnt" moves the text down y position depending on the line no. (the factor "80" for the shift must be adapted according the font).</p>
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 the standard base time known as "the epoch", namely January 1, 1970, 00:00:00 GMT.</p> </blockquote>
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 the standard base time known as "the epoch", namely January 1, 1970, 00:00:00 GMT.</p> </blockquote>
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 </code></pre> <p>as mentioned in the Python standard lib:</p> <blockquote> <p>fromtimestamp() may raise ValueError, if the timestamp is out of the range of values supported by the platform C localtime() or gmtime() functions. It’s common for this to be restricted to years in 1970 through 2038.</p> </blockquote>
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' ' %s\n' 'of %s\n' % (filepath, hashes[hash]))) or hashes.setdefault (hash, filepath)))()) scan = (lambda dirpath, hashes = {}: map (lambda (root, dirs, files): map (lambda filename: check_path (os.path.join (root, filename), hashes), files), os.walk (dirpath))) ((len (sys.argv) &gt; 1) and scan (sys.argv[1])) </code></pre>
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></pre> <p>//edit:</p> <p>for mp3 you may be also interested in this topic <a href="http://stackoverflow.com/questions/476227/detect-duplicate-mp3-files-with-different-bitrates-and-or-different-id3-tags">Detect duplicate MP3 files with different bitrates and/or different ID3 tags?</a></p>
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): """Generator that reads a file in chunks of bytes""" while True: chunk = fobj.read(chunk_size) if not chunk: return yield chunk def check_for_duplicates(paths, hash=hashlib.sha1): hashes = {} for path in paths: for dirpath, dirnames, filenames in os.walk(path): for filename in filenames: full_path = os.path.join(dirpath, filename) hashobj = hash() for chunk in chunk_reader(open(full_path, 'rb')): hashobj.update(chunk) file_id = (hashobj.digest(), os.path.getsize(full_path)) duplicate = hashes.get(file_id, None) if duplicate: print "Duplicate found: %s and %s" % (full_path, duplicate) else: hashes[file_id] = full_path if sys.argv[1:]: check_for_duplicates(sys.argv[1:]) else: print "Please pass the paths to check as parameters to the script" </code></pre>
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 different without doubt, but will not say if two files are exactly the same (accuracy of the hash, limited data read from disk)</p></li> <li><p>a second, slower, hash, which is more accurate and performed on the whole content of the file, if a collision occurs in the first stage</p></li> </ol> <p>Here is an implementation of this algorithm:</p> <pre><code>import hashlib def Checksum(current_file_name, check_type = 'sha512', first_block = False): """Computes the hash for the given file. If first_block is True, only the first block of size size_block is hashed.""" size_block = 1024 * 1024 # The first N bytes (1KB) d = {'sha1' : hashlib.sha1, 'md5': hashlib.md5, 'sha512': hashlib.sha512} if(not d.has_key(check_type)): raise Exception("Unknown checksum method") file_size = os.stat(current_file_name)[stat.ST_SIZE] with file(current_file_name, 'rb') as f: key = d[check_type].__call__() while True: s = f.read(size_block) key.update(s) file_size -= size_block if(len(s) &lt; size_block or first_block): break return key.hexdigest().upper() def find_duplicates(files): """Find duplicates among a set of files. The implementation uses two types of hashes: - A small and fast one one the first block of the file (first 1KB), - and in case of collision a complete hash on the file. The complete hash is not computed twice. It flushes the files that seems to have the same content (according to the hash method) at the end. """ print 'Analyzing', len(files), 'files' # this dictionary will receive small hashes d = {} # this dictionary will receive full hashes. It is filled # only in case of collision on the small hash (contains at least two # elements) duplicates = {} for f in files: # small hash to be fast check = Checksum(f, first_block = True, check_type = 'sha1') if(not d.has_key(check)): # d[check] is a list of files that have the same small hash d[check] = [(f, None)] else: l = d[check] l.append((f, None)) for index, (ff, checkfull) in enumerate(l): if(checkfull is None): # computes the full hash in case of collision checkfull = Checksum(ff, first_block = False) l[index] = (ff, checkfull) # for each new full hash computed, check if their is # a collision in the duplicate dictionary. if(not duplicates.has_key(checkfull)): duplicates[checkfull] = [ff] else: duplicates[checkfull].append(ff) # prints the detected duplicates if(len(duplicates) != 0): print print "The following files have the same sha512 hash" for h, lf in duplicates.items(): if(len(lf)==1): continue print 'Hash value', h for f in lf: print '\t', f.encode('unicode_escape') if \ type(f) is types.UnicodeType else f return duplicates </code></pre> <p>The <code>find_duplicates</code> function takes a list of files. This way, it is also possible to compare two directories (for instance, to better synchronize their content.) An example of function creating a list of files, with specified extension, and avoiding entering in some directories, is below:</p> <pre><code>def getFiles(_path, extensions = ['.png'], subdirs = False, avoid_directories = None): """Returns the list of files in the path :'_path', of extension in 'extensions'. 'subdir' indicates if the search should also be performed in the subdirectories. If extensions = [] or None, all files are returned. avoid_directories: if set, do not parse subdirectories that match any element of avoid_directories.""" l = [] extensions = [p.lower() for p in extensions] if not extensions is None \ else None for root, dirs, files in os.walk(_path, topdown=True): for name in files: if(extensions is None or len(extensions) == 0 or \ os.path.splitext(name)[1].lower() in extensions): l.append(os.path.join(root, name)) if(not subdirs): while(len(dirs) &gt; 0): dirs.pop() elif(not avoid_directories is None): for d in avoid_directories: if(d in dirs): dirs.remove(d) return l </code></pre> <p>This method is convenient for not parsing <code>.svn</code> paths for instance, which surely will trigger colliding files in <code>find_duplicates</code>. </p> <p>Feedbacks are welcome.</p>
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 yield chunk def remove_duplicates(dir, hashfun = hashlib.sha512): unique = Set() for filename in os.listdir(dir): filepath = os.path.join(dir, filename) if os.path.isfile(filepath): hashobj = hashfun() for chunk in read_chunk(open(filepath,'rb')): hashobj.update(chunk) # the size of the hashobj is constant # print "hashfun: ", hashfun.__sizeof__() hashfile = hashobj.hexdigest() if hashfile not in unique: unique.add(hashfile) else: os.remove(filepath) try: hashfun = hashlib.sha256 remove_duplicates(sys.argv[1], hashfun) except IndexError: print """Please pass a path to a directory with duplicate files as a parameter to the script.""" </code></pre>
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 save tremendous amount of CPU; performance comparisons at the end, here's the explanation.</p> <p>Iterating on the solid answers given by @nosklo and borrowing the idea of @Raffi to have a fast hash of just the beginning of each file, and calculating the full one only on collisions in the fast hash, here are the steps:</p> <ol> <li>Buildup a hash table of the files, where the filesize is the key.</li> <li>For files with the same size, create a hash table with the hash of their first 1024 bytes; non-colliding elements are unique</li> <li>For files with the same hash on the first 1k bytes, calculate the hash on the full contents - files with matching ones are unique.</li> </ol> <p>The code:</p> <pre><code>#!/usr/bin/env python import sys import os import hashlib def chunk_reader(fobj, chunk_size=1024): """Generator that reads a file in chunks of bytes""" while True: chunk = fobj.read(chunk_size) if not chunk: return yield chunk def get_hash(filename, first_chunk_only=False, hash=hashlib.sha1): hashobj = hash() file_object = open(filename, 'rb') if first_chunk_only: hashobj.update(file_object.read(1024)) else: for chunk in chunk_reader(file_object): hashobj.update(chunk) hashed = hashobj.digest() file_object.close() return hashed def check_for_duplicates(paths, hash=hashlib.sha1): hashes_by_size = {} hashes_on_1k = {} hashes_full = {} for path in paths: for dirpath, dirnames, filenames in os.walk(path): for filename in filenames: full_path = os.path.join(dirpath, filename) try: file_size = os.path.getsize(full_path) except (OSError,): # not accessible (permissions, etc) - pass on pass duplicate = hashes_by_size.get(file_size) if duplicate: hashes_by_size[file_size].append(full_path) else: hashes_by_size[file_size] = [] # create the list for this file size hashes_by_size[file_size].append(full_path) # For all files with the same file size, get their hash on the 1st 1024 bytes for __, files in hashes_by_size.items(): if len(files) &lt; 2: continue # this file size is unique, no need to spend cpy cycles on it for filename in files: small_hash = get_hash(filename, first_chunk_only=True) duplicate = hashes_on_1k.get(small_hash) if duplicate: hashes_on_1k[small_hash].append(filename) else: hashes_on_1k[small_hash] = [] # create the list for this 1k hash hashes_on_1k[small_hash].append(filename) # For all files with the hash on the 1st 1024 bytes, get their hash on the full file - collisions will be duplicates for __, files in hashes_on_1k.items(): if len(files) &lt; 2: continue # this hash of fist 1k file bytes is unique, no need to spend cpy cycles on it for filename in files: full_hash = get_hash(filename, first_chunk_only=False) duplicate = hashes_full.get(full_hash) if duplicate: print "Duplicate found: %s and %s" % (filename, duplicate) else: hashes_full[full_hash] = filename if sys.argv[1:]: check_for_duplicates(sys.argv[1:]) else: print "Please pass the paths to check as parameters to the script" </code></pre> <hr> <p>And, here's the fun part - performance comparisons.</p> <p>Baseline - </p> <ul> <li>a directory with 1047 files, 32 mp4, 1015 - jpg, total size - 5445.998 GiB - i.e. my phone's camera auto upload directory :)</li> <li>small (but fully functional processor) - 1600 BogoMIPS, 1.2 GHz 32L1 + 256L2 Kbs cache, /proc/cpuinfo: <blockquote> <p>Processor : Feroceon 88FR131 rev 1 (v5l) BogoMIPS : 1599.07</p> </blockquote></li> </ul> <p>(i.e. my low-end NAS :), running Python 2.7.11)</p> <p>So, the output of @nosklo's very handy solution:</p> <pre><code>root@NAS:InstantUpload# time ~/scripts/checkDuplicates.py Duplicate found: ./IMG_20151231_143053 (2).jpg and ./IMG_20151231_143053.jpg Duplicate found: ./IMG_20151125_233019 (2).jpg and ./IMG_20151125_233019.jpg Duplicate found: ./IMG_20160204_150311.jpg and ./IMG_20160204_150311 (2).jpg Duplicate found: ./IMG_20160216_074620 (2).jpg and ./IMG_20160216_074620.jpg real 5m44.198s user 4m44.550s sys 0m33.530s </code></pre> <p>And, here's the version with filter on size check, then small hashes, and finally full hash if collisions are found:</p> <pre><code>root@NAS:InstantUpload# time ~/scripts/checkDuplicatesSmallHash.py . "/i-data/51608399/photo/Todor phone" Duplicate found: ./IMG_20160216_074620 (2).jpg and ./IMG_20160216_074620.jpg Duplicate found: ./IMG_20160204_150311.jpg and ./IMG_20160204_150311 (2).jpg Duplicate found: ./IMG_20151231_143053 (2).jpg and ./IMG_20151231_143053.jpg Duplicate found: ./IMG_20151125_233019 (2).jpg and ./IMG_20151125_233019.jpg real 0m1.398s user 0m1.200s sys 0m0.080s </code></pre> <p>Both versions were ran 3 times each, to get the avg of the time needed.</p> <p>So v1 is (user+sys) <strong>284s</strong>, the other - <strong>2s</strong>; quite a diff, huh :) With this increase, one could go to SHA512, or even fancier - the perf penalty will be mitigated by the less calculations needed.</p> <p>Negatives:</p> <ul> <li>More disk access than the other versions - every file is accessed once for size stats (that's cheap, but still is disk IO), and every duplicate is opened twice (for the small first 1k bytes hash, and for the full contents hash)</li> <li>Will consume more memory due to storing the hash tables runtime</li> </ul>
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.pythoncentral.io/finding-duplicate-files-with-python/ # Original Auther: Andres Torres # Adapted to only compute the md5sum of files with the same size import argparse import os import sys import hashlib def find_duplicates(folders): """ Takes in an iterable of folders and prints &amp; returns the duplicate files """ dup_size = {} for i in folders: # Iterate the folders given if os.path.exists(i): # Find the duplicated files and append them to dup_size join_dicts(dup_size, find_duplicate_size(i)) else: print('%s is not a valid path, please verify' % i) return {} print('Comparing files with the same size...') dups = {} for dup_list in dup_size.values(): if len(dup_list) &gt; 1: join_dicts(dups, find_duplicate_hash(dup_list)) print_results(dups) return dups def find_duplicate_size(parent_dir): # Dups in format {hash:[names]} dups = {} for dirName, subdirs, fileList in os.walk(parent_dir): print('Scanning %s...' % dirName) for filename in fileList: # Get the path to the file path = os.path.join(dirName, filename) # Check to make sure the path is valid. if not os.path.exists(path): continue # Calculate sizes file_size = os.path.getsize(path) # Add or append the file path if file_size in dups: dups[file_size].append(path) else: dups[file_size] = [path] return dups def find_duplicate_hash(file_list): print('Comparing: ') for filename in file_list: print(' {}'.format(filename)) dups = {} for path in file_list: file_hash = hashfile(path) if file_hash in dups: dups[file_hash].append(path) else: dups[file_hash] = [path] return dups # Joins two dictionaries def join_dicts(dict1, dict2): for key in dict2.keys(): if key in dict1: dict1[key] = dict1[key] + dict2[key] else: dict1[key] = dict2[key] def hashfile(path, blocksize=65536): afile = open(path, 'rb') hasher = hashlib.md5() buf = afile.read(blocksize) while len(buf) &gt; 0: hasher.update(buf) buf = afile.read(blocksize) afile.close() return hasher.hexdigest() def print_results(dict1): results = list(filter(lambda x: len(x) &gt; 1, dict1.values())) if len(results) &gt; 0: print('Duplicates Found:') print( 'The following files are identical. The name could differ, but the' ' content is identical' ) print('___________________') for result in results: for subresult in result: print('\t\t%s' % subresult) print('___________________') else: print('No duplicate files found.') def main(): parser = argparse.ArgumentParser(description='Find duplicate files') parser.add_argument( 'folders', metavar='dir', type=str, nargs='+', help='A directory to parse for duplicates', ) args = parser.parse_args() find_duplicates(args.folders) if __name__ == '__main__': sys.exit(main()) </code></pre>
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_clicked" : self.button1_clicked, "on_MainWindow_destroy" : gtk.main_quit} self.wTree.signal_autoconnect(dic) </code></pre> <p>After converting my project in glade, what structural changes do I need to make? I'm on Ubuntu 9.04.</p>
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>, just use <code>get_object</code> on the builder class:</p> <pre><code>self.window = self.wTree.get_object("MainWindow") if self.window: self.window.connect("destroy", gtk.main_quit) </code></pre> <p>To connect the signals, just use <code>connect_signals</code>, which also takes a dictionary:</p> <pre><code>dic = { "on_button1_clicked" : self.button1_clicked, "on_MainWindow_destroy" : gtk.main_quit} self.wTree.connect_signals(dic) </code></pre> <p>It used to be the case (at least in GTK+ 2.12, not sure if it's still the same) that you could call <code>connect_signals</code> only once, any signals which are not connected during the first invocation will never be connected. This was different in glade, so be careful if you relied on that feature before.</p>
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_clicked" : self.button1_clicked, "on_MainWindow_destroy" : gtk.main_quit} self.wTree.signal_autoconnect(dic) </code></pre> <p>After converting my project in glade, what structural changes do I need to make? I'm on Ubuntu 9.04.</p>
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 type to GtkBuilder and make sure it targets the latest version (2.24 as of this writing). Save the file, being sure that it saves in GtkBuilder format, and change the name from yada.glade to yada.ui</p> <p>Open yada.py and change the following code: </p> <pre><code>gladefile = relativize_filename(os.path.join("glade", "yada.glade")) self.wTree = gtk.glade.XML(gladefile, self.windowname) </code></pre> <p>to:</p> <pre><code>uifile = relativize_filename(os.path.join("glade", "yada.ui")) self.wTree = gtk.Builder() self.wTree.add_from_file(uifile) </code></pre> <p>Similarly change all instances of <code>self.wTree.get_widget(...)</code> to <code>self.wTree.get_object(...)</code> </p> <p>Change <code>self.wTree.signal_autoconnect(dic)</code> to <code>self.wTree.connect_signals(dic)</code></p> <p>If your code depends on the name assigned the widget in the interface designer, change <code>widget.get_name()</code> to <code>gtk.Buildable.get_name(widget)</code>. <code>widget.get_name()</code> now just returns the widget type. EDIT: You also need to change <code>widget.set_name('my_widget')</code> to <code>gtk.Buildable.set_name(widget, 'my_widget')</code>.</p> <p>Delete <code>import gtk.glade</code></p> <p>I found numerous unused signals defined in the yada.ui xml file, I had to open the xml file and manually delete them to eliminate the warnings they caused.</p>
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 ''' &lt;para bulletText="&amp;bull;"&gt; item 1 &lt;/para&gt; &lt;para bulletText="&amp;bull;"&gt; item 2 &lt;/para&gt; ''' Story.append(Paragraph(text,TEXT_STYLE)) </code></pre> <p>But I keep getting errors like <code>list index out of range</code>. It seems that I can't put more than one <code>&lt;para&gt;&lt;/para&gt;</code> in a single call to <code>Paragraph()</code>? I also tried setting <code>TEXT_STYLE.bulletText="&amp;bull;"</code> but that doesn't work either...</p>
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>&lt;para&gt;</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://www.reportlab.com/docs/reportlab-userguide.pdf" rel="nofollow">ReportLab Documentation</a>, though. The convention in ReportLab seems to be to use the <code>&lt;bullet&gt;</code> tag, and the docs do warn that you can have only one per <code>Paragraph</code> instance. We render our bullets in ReportLab like so:</p> <pre><code>story.append(Paragraph('&lt;bullet&gt;The rain in spain&lt;/bullet&gt;', TEXT_STYLE)) </code></pre>
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 ''' &lt;para bulletText="&amp;bull;"&gt; item 1 &lt;/para&gt; &lt;para bulletText="&amp;bull;"&gt; item 2 &lt;/para&gt; ''' Story.append(Paragraph(text,TEXT_STYLE)) </code></pre> <p>But I keep getting errors like <code>list index out of range</code>. It seems that I can't put more than one <code>&lt;para&gt;&lt;/para&gt;</code> in a single call to <code>Paragraph()</code>? I also tried setting <code>TEXT_STYLE.bulletText="&amp;bull;"</code> but that doesn't work either...</p>
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 be a way to get all of them.</p> <p>If Steve is correct (his answer does make sense). How can I determine if that's actually causing the problem. How do I find out what exactly is in my datastore?</p>
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(["male", "female"]), default="male") </code></pre> <p>I hope it helps.</p> <p>/edit: Go to the local datastore viewer (default is at <a href="http://localhost:8080/_ah/admin/" rel="nofollow">http://localhost:8080/_ah/admin/</a>) and list your entities. You can try fixing the issue manually (if possible) by filling the missing property.</p>
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 topics to subscribe to.</p> <p>I started writing something like:</p> <pre><code>from mysite.blog.models import BlogTopic choices = [(topic.id, topic.name) for topic in BlogTopic.objects.all()] class SubscribeForm(forms.Form): topics = forms.ChoiceField(choices=choices) </code></pre> <p>But I'm not sure when <code>choices</code> would be defined. I assume only when the module is first imported (i.e. when starting Django). Obviously that is not a very good approach.</p> <p>This seems like it would be a common requirement, but I can't seem to find any examples. I suspect I may be missing something obvious here. Anyway, thanks in advance for your answers.</p>
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?</p> <p>Of course, this works:</p> <pre><code>import sys lines = """This is a string It has multiple lines there are three total""" for line in lines.splitlines(): print line </code></pre> <p>But I need to be able to process an argument line-by-line.</p> <p>EDIT: This is probably more of a Windows command-line problem than a Python problem. </p> <p>EDIT 2: Thanks for all of the good suggestions. It doesn't look like it's possible. I can't use another shell because I'm actually trying to invoke the script from another program which seems to use the Windows command-line behind the scenes.</p>
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 &gt; It has multiple lines &gt; 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?</p> <p>Of course, this works:</p> <pre><code>import sys lines = """This is a string It has multiple lines there are three total""" for line in lines.splitlines(): print line </code></pre> <p>But I need to be able to process an argument line-by-line.</p> <p>EDIT: This is probably more of a Windows command-line problem than a Python problem. </p> <p>EDIT 2: Thanks for all of the good suggestions. It doesn't look like it's possible. I can't use another shell because I'm actually trying to invoke the script from another program which seems to use the Windows command-line behind the scenes.</p>
4
2009-04-14T19:37:10Z
749,319
<p>Not sure about the Windows command-line, but would the following work?</p> <pre><code>&gt; python myscript.py "This is a string\nIt has multiple lines\there are three total" </code></pre> <p>..or..</p> <pre><code>&gt; python myscript.py "This is a string\ It has [...]\ there are [...]" </code></pre> <p>If not, I would suggest installing Cygwin and using a sane shell!</p>
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?</p> <p>Of course, this works:</p> <pre><code>import sys lines = """This is a string It has multiple lines there are three total""" for line in lines.splitlines(): print line </code></pre> <p>But I need to be able to process an argument line-by-line.</p> <p>EDIT: This is probably more of a Windows command-line problem than a Python problem. </p> <p>EDIT 2: Thanks for all of the good suggestions. It doesn't look like it's possible. I can't use another shell because I'm actually trying to invoke the script from another program which seems to use the Windows command-line behind the scenes.</p>
4
2009-04-14T19:37:10Z
749,323
<p>The following might work:</p> <pre><code>C:\&gt; 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?</p> <p>Of course, this works:</p> <pre><code>import sys lines = """This is a string It has multiple lines there are three total""" for line in lines.splitlines(): print line </code></pre> <p>But I need to be able to process an argument line-by-line.</p> <p>EDIT: This is probably more of a Windows command-line problem than a Python problem. </p> <p>EDIT 2: Thanks for all of the good suggestions. It doesn't look like it's possible. I can't use another shell because I'm actually trying to invoke the script from another program which seems to use the Windows command-line behind the scenes.</p>
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 from standard in.</p> <pre><code>import sys for line in iter(sys.stdin.readline, ''): print line </code></pre> <p>On Linux you would pipe the multiline text to the standard input of args.py.</p> <p>$ &lt;command-that-produces-text&gt; | python args.py</p>
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?</p> <p>Of course, this works:</p> <pre><code>import sys lines = """This is a string It has multiple lines there are three total""" for line in lines.splitlines(): print line </code></pre> <p>But I need to be able to process an argument line-by-line.</p> <p>EDIT: This is probably more of a Windows command-line problem than a Python problem. </p> <p>EDIT 2: Thanks for all of the good suggestions. It doesn't look like it's possible. I can't use another shell because I'm actually trying to invoke the script from another program which seems to use the Windows command-line behind the scenes.</p>
4
2009-04-14T19:37:10Z
757,277
<p>This is the only thing which worked for me:</p> <pre><code>C:\&gt; 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-in-windows/749323#749323">Johannes' solution</a> invokes the python interpreter at the end of the first line, so I don't have the chance to pass additional lines.</p> <p>But you said you are calling the python script from another process, not from the command line. Then why don't you use <a href="http://stackoverflow.com/questions/749049/passing-a-multi-line-string-as-an-argument-to-a-script-in-windows/749319#749319">dbr' solution</a>? This worked for me as a Ruby script:</p> <pre><code>puts `python a.py "This is a string\nIt has multiple lines\nThere are three total"` </code></pre> <p>And in what language are you writing the program which calls the python script? The issue you have is with <em>argument passing</em>, not with the windows shell, not with Python...</p> <p>Finally, as <a href="http://stackoverflow.com/questions/749049/passing-a-multi-line-string-as-an-argument-to-a-script-in-windows/749329#749329">mattkemp</a> said, I also suggest you use the standard input to read your multi-line argument, avoiding command line magic.</p>
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?</p> <p>Of course, this works:</p> <pre><code>import sys lines = """This is a string It has multiple lines there are three total""" for line in lines.splitlines(): print line </code></pre> <p>But I need to be able to process an argument line-by-line.</p> <p>EDIT: This is probably more of a Windows command-line problem than a Python problem. </p> <p>EDIT 2: Thanks for all of the good suggestions. It doesn't look like it's possible. I can't use another shell because I'm actually trying to invoke the script from another program which seems to use the Windows command-line behind the scenes.</p>
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&gt;test.py "This is a string"^ More? More? "It has multiple lines"^ More? More? "There are three total" This is a string It has multiple lines There are three total C:\Scratch&gt; </code></pre> <p>This is a little more readable than Romulo's solution above.</p>
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 list to the right, for example if I use split(). Example:</p> <pre><code>a, b = "length=25".split("=") # This will result in a="length" and b=25 </code></pre> <p>But the following code will lead to an error:</p> <pre><code>a, b = "DEFAULT_LENGTH".split("=") # Error, list has only one item </code></pre> <p>Is it possible to somehow unpack list in the example above so I get a = "DEFAULT_LENGTH" and b equals to 'None' or not set? A straightforward way looks kind of long:</p> <pre><code>a = b = None if "=" in string : a, b = string.split("=") else : a = string </code></pre>
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 list to the right, for example if I use split(). Example:</p> <pre><code>a, b = "length=25".split("=") # This will result in a="length" and b=25 </code></pre> <p>But the following code will lead to an error:</p> <pre><code>a, b = "DEFAULT_LENGTH".split("=") # Error, list has only one item </code></pre> <p>Is it possible to somehow unpack list in the example above so I get a = "DEFAULT_LENGTH" and b equals to 'None' or not set? A straightforward way looks kind of long:</p> <pre><code>a = b = None if "=" in string : a, b = string.split("=") else : a = string </code></pre>
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 list to the right, for example if I use split(). Example:</p> <pre><code>a, b = "length=25".split("=") # This will result in a="length" and b=25 </code></pre> <p>But the following code will lead to an error:</p> <pre><code>a, b = "DEFAULT_LENGTH".split("=") # Error, list has only one item </code></pre> <p>Is it possible to somehow unpack list in the example above so I get a = "DEFAULT_LENGTH" and b equals to 'None' or not set? A straightforward way looks kind of long:</p> <pre><code>a = b = None if "=" in string : a, b = string.split("=") else : a = string </code></pre>
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 list to the right, for example if I use split(). Example:</p> <pre><code>a, b = "length=25".split("=") # This will result in a="length" and b=25 </code></pre> <p>But the following code will lead to an error:</p> <pre><code>a, b = "DEFAULT_LENGTH".split("=") # Error, list has only one item </code></pre> <p>Is it possible to somehow unpack list in the example above so I get a = "DEFAULT_LENGTH" and b equals to 'None' or not set? A straightforward way looks kind of long:</p> <pre><code>a = b = None if "=" in string : a, b = string.split("=") else : a = string </code></pre>
30
2009-04-14T19:44:54Z
749,107
<p>You could write a helper function to do it.</p> <pre><code>&gt;&gt;&gt; def pack(values, size): ... if len(values) &gt;= size: ... return values[:size] ... return values + [None] * (size - len(values)) ... &gt;&gt;&gt; a, b = pack('a:b:c'.split(':'), 2) &gt;&gt;&gt; a, b ('a', 'b') &gt;&gt;&gt; a, b = pack('a'.split(':'), 2) &gt;&gt;&gt; a, b ('a', None) </code></pre>
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 list to the right, for example if I use split(). Example:</p> <pre><code>a, b = "length=25".split("=") # This will result in a="length" and b=25 </code></pre> <p>But the following code will lead to an error:</p> <pre><code>a, b = "DEFAULT_LENGTH".split("=") # Error, list has only one item </code></pre> <p>Is it possible to somehow unpack list in the example above so I get a = "DEFAULT_LENGTH" and b equals to 'None' or not set? A straightforward way looks kind of long:</p> <pre><code>a = b = None if "=" in string : a, b = string.split("=") else : a = string </code></pre>
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 list to the right, for example if I use split(). Example:</p> <pre><code>a, b = "length=25".split("=") # This will result in a="length" and b=25 </code></pre> <p>But the following code will lead to an error:</p> <pre><code>a, b = "DEFAULT_LENGTH".split("=") # Error, list has only one item </code></pre> <p>Is it possible to somehow unpack list in the example above so I get a = "DEFAULT_LENGTH" and b equals to 'None' or not set? A straightforward way looks kind of long:</p> <pre><code>a = b = None if "=" in string : a, b = string.split("=") else : a = string </code></pre>
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, and the part after the separator. If the separator is not found, return a 3-tuple containing the string itself, followed by two empty strings.</p> <p>New in version 2.5.</p> </blockquote> <pre><code>&gt;&gt;&gt; inputstr = "length=25" &gt;&gt;&gt; inputstr.partition("=") ('length', '=', '25') &gt;&gt;&gt; name, _, value = inputstr.partition("=") &gt;&gt;&gt; print name, value length 25 </code></pre> <p>It also works for strings not containing the <code>=</code>:</p> <pre><code>&gt;&gt;&gt; inputstr = "DEFAULT_VALUE" &gt;&gt;&gt; inputstr.partition("=") ('DEFAULT_VALUE', '', '') </code></pre> <p>If for some reason you are using a version of Python before 2.5, you can use list-slicing to do much the same, if slightly less tidily:</p> <pre><code>&gt;&gt;&gt; x = "DEFAULT_LENGTH" &gt;&gt;&gt; a = x.split("=")[0] &gt;&gt;&gt; b = "=".join(x.split("=")[1:]) &gt;&gt;&gt; print (a, b) ('DEFAULT_LENGTH', '') </code></pre> <p>..and when <code>x = "length=25"</code>:</p> <pre><code>('length', '25') </code></pre> <p>Easily turned into a function or lambda:</p> <pre><code>&gt;&gt;&gt; part = lambda x: (x.split("=")[0], "=".join(x.split("=")[1:])) &gt;&gt;&gt; part("length=25") ('length', '25') &gt;&gt;&gt; part('DEFAULT_LENGTH') ('DEFAULT_LENGTH', '') </code></pre>
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 list to the right, for example if I use split(). Example:</p> <pre><code>a, b = "length=25".split("=") # This will result in a="length" and b=25 </code></pre> <p>But the following code will lead to an error:</p> <pre><code>a, b = "DEFAULT_LENGTH".split("=") # Error, list has only one item </code></pre> <p>Is it possible to somehow unpack list in the example above so I get a = "DEFAULT_LENGTH" and b equals to 'None' or not set? A straightforward way looks kind of long:</p> <pre><code>a = b = None if "=" in string : a, b = string.split("=") else : a = string </code></pre>
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>&gt;&gt;&gt; a, *b = "length=25".split("=") &gt;&gt;&gt; a,b ("length", ['25']) &gt;&gt;&gt; a, *b = "DEFAULT_LENGTH".split("=") &gt;&gt;&gt; a,b ("DEFAULT_LENGTH", []) </code></pre> <p>I.e. tuple unpacking now works similarly to how it does in argument unpacking, so you can denote "the rest of the items" with <code>*</code>, and get them as a (possibly empty) list.</p> <p>Partition is probably the best solution for what you're doing however.</p>
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 list to the right, for example if I use split(). Example:</p> <pre><code>a, b = "length=25".split("=") # This will result in a="length" and b=25 </code></pre> <p>But the following code will lead to an error:</p> <pre><code>a, b = "DEFAULT_LENGTH".split("=") # Error, list has only one item </code></pre> <p>Is it possible to somehow unpack list in the example above so I get a = "DEFAULT_LENGTH" and b equals to 'None' or not set? A straightforward way looks kind of long:</p> <pre><code>a = b = None if "=" in string : a, b = string.split("=") else : a = string </code></pre>
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+[parts[0][:0]]*(limit+1-len(parts)) username, password, hash= paddedsplit(credentials, ':', 2) </code></pre> <p>(<code>parts[0][:0]</code> is there to get an empty ‘str’ or ‘unicode’, matching whichever of those the split produced. You could use None if you prefer.)</p>
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 list to the right, for example if I use split(). Example:</p> <pre><code>a, b = "length=25".split("=") # This will result in a="length" and b=25 </code></pre> <p>But the following code will lead to an error:</p> <pre><code>a, b = "DEFAULT_LENGTH".split("=") # Error, list has only one item </code></pre> <p>Is it possible to somehow unpack list in the example above so I get a = "DEFAULT_LENGTH" and b equals to 'None' or not set? A straightforward way looks kind of long:</p> <pre><code>a = b = None if "=" in string : a, b = string.split("=") else : a = string </code></pre>
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 list to the right, for example if I use split(). Example:</p> <pre><code>a, b = "length=25".split("=") # This will result in a="length" and b=25 </code></pre> <p>But the following code will lead to an error:</p> <pre><code>a, b = "DEFAULT_LENGTH".split("=") # Error, list has only one item </code></pre> <p>Is it possible to somehow unpack list in the example above so I get a = "DEFAULT_LENGTH" and b equals to 'None' or not set? A straightforward way looks kind of long:</p> <pre><code>a = b = None if "=" in string : a, b = string.split("=") else : a = string </code></pre>
30
2009-04-14T19:44:54Z
750,359
<p>As an alternative, perhaps use a regular expression?</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; unpack_re = re.compile("(\w*)(?:=(\w*))?") &gt;&gt;&gt; x = "DEFAULT_LENGTH" &gt;&gt;&gt; unpack_re.match(x).groups() ('DEFAULT_LENGTH', None) &gt;&gt;&gt; y = "length=107" &gt;&gt;&gt; unpack_re.match(y).groups() ('length', '107') </code></pre> <p>If you make sure the re.match() always succeeds, .groups() will always return the right number of elements to unpack into your tuple, so you can safely do</p> <pre><code>a,b = unpack_re.match(x).groups() </code></pre>
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 list to the right, for example if I use split(). Example:</p> <pre><code>a, b = "length=25".split("=") # This will result in a="length" and b=25 </code></pre> <p>But the following code will lead to an error:</p> <pre><code>a, b = "DEFAULT_LENGTH".split("=") # Error, list has only one item </code></pre> <p>Is it possible to somehow unpack list in the example above so I get a = "DEFAULT_LENGTH" and b equals to 'None' or not set? A straightforward way looks kind of long:</p> <pre><code>a = b = None if "=" in string : a, b = string.split("=") else : a = string </code></pre>
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(&lt;sequence&gt;)</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> module to parse that line and count the number of variables being unpacked.</p> <p>Caveats:</p> <ul> <li>For multiple assignment (e.g. <code>(a,b) = c = unpack([1,2,3])</code>), it only uses the first term in the assignment</li> <li>It won't work if it can't find the source code (e.g. because you're calling it from the repl)</li> <li>It won't work if the assignment statement spans multiple lines</li> </ul> <p>Code:</p> <pre class="lang-py prettyprint-override"><code>import inspect, ast from itertools import islice, chain, cycle def iter_n(iterator, n, default=None): return islice(chain(iterator, cycle([default])), n) def unpack(sequence, default=None): stack = inspect.stack() try: frame = stack[1][0] source = inspect.getsource(inspect.getmodule(frame)).splitlines() line = source[frame.f_lineno-1].strip() try: tree = ast.parse(line, 'whatever', 'exec') except SyntaxError: return tuple(sequence) exp = tree.body[0] if not isinstance(exp, ast.Assign): return tuple(sequence) exp = exp.targets[0] if not isinstance(exp, ast.Tuple): return tuple(sequence) n_items = len(exp.elts) return tuple(iter_n(sequence, n_items, default)) finally: del stack # Examples if __name__ == '__main__': # Extra items are discarded x, y = unpack([1,2,3,4,5]) assert (x,y) == (1,2) # Missing items become None x, y, z = unpack([9]) assert (x, y, z) == (9, None, None) # Or the default you provide x, y, z = unpack([1], 'foo') assert (x, y, z) == (1, 'foo', 'foo') # unpack() is equivalent to tuple() if it's not part of an assignment assert unpack('abc') == ('a', 'b', 'c') # Or if it's part of an assignment that isn't sequence-unpacking x = unpack([1,2,3]) assert x == (1,2,3) # Add a comma to force tuple assignment: x, = unpack([1,2,3]) assert x == 1 # unpack only uses the first assignment target # So in this case, unpack('foobar') returns tuple('foo') (x, y, z) = t = unpack('foobar') assert (x, y, z) == t == ('f', 'o', 'o') # But in this case, it returns tuple('foobar') try: t = (x, y, z) = unpack('foobar') except ValueError as e: assert str(e) == 'too many values to unpack' else: raise Exception("That should have failed.") # Also, it won't work if the call spans multiple lines, because it only # inspects the actual line where the call happens: try: (x, y, z) = unpack([ 1, 2, 3, 4]) except ValueError as e: assert str(e) == 'too many values to unpack' else: raise Exception("That should have failed.") </code></pre>
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 &amp;&amp; n%100!=11 ? 0 : n%10&gt;=2 &amp;&amp; n%"</code> <code>"10&lt;=4 &amp;&amp; (n%100&lt;10 || n%100&gt;=20) ? 1 : 2;\n"</code></p> <p>... I want the first text field to be labeled "1, 21..", then "2, 3, 4...", then "5, 6..." (not sure if this is exactly right, but you get the idea.)</p> <p>Right now the best thing I can come up with is to parse the expression somehow, then iterate x from 0 to 100 and see what n it produces. This isn't guaranteed to work (what if the lowest x is over 100 for some language?) but it's probably good enough. Any better ideas or existing Python code?</p>
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 &amp;&amp;/|| to and/or)</p> <p>I'm not sure if your plural form rule is a contrived example, and I don't understand what you mean with your first text field, but I'm sure you'll get where I'm going with my example solution:</p> <pre><code># -*- Mode: Python -*- # vi:si:et:sw=4:sts=4:ts=4 p = "Plural-Forms: nplurals=3; plural=n%10==1 &amp;&amp; n%100!=11 ? 0 : n%10&gt;=2 &amp;&amp; n%10&lt;=4 &amp;&amp; (n%100&lt;10 || n%100&gt;=20) ? 1 : 2;\n" # extract rule import re matcher = re.compile('plural=(.*);') match = matcher.search(p) rule = match.expand("\\1") # convert rule to python syntax oldrule = None while oldrule != rule: oldrule = rule rule = re.sub('(.*)\?(.*):(.*)', r'(\1) and (\2) or (\3)', oldrule) rule = re.sub('&amp;&amp;', 'and', rule) rule = re.sub('\|\|', 'or', rule) for n in range(40): code = "n = %d" % n print n, eval(rule) </code></pre>
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 substring of any word in the data lists. It should return True for the <code>good_data</code> lists and False for <code>bad_data</code>.</p> <p>I know how to do this in what seems to be an inefficient way:</p> <pre><code>def checkData(data): for s in data: for k in keywords: if k in s: return True return False </code></pre>
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 substring of any word in the data lists. It should return True for the <code>good_data</code> lists and False for <code>bad_data</code>.</p> <p>I know how to do this in what seems to be an inefficient way:</p> <pre><code>def checkData(data): for s in data: for k in keywords: if k in s: return True return False </code></pre>
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 substring of any word in the data lists. It should return True for the <code>good_data</code> lists and False for <code>bad_data</code>.</p> <p>I know how to do this in what seems to be an inefficient way:</p> <pre><code>def checkData(data): for s in data: for k in keywords: if k in s: return True return False </code></pre>
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 each word.</p> <p>You could do this by executing:</p> <pre><code>import re keyword_re = re.compile("|".join(map(re.escape, keywords))) </code></pre> <p>Then:</p> <pre><code>&gt;&gt;&gt; bool(keyword_re.search('hello, world')) True &gt;&gt;&gt; bool(keyword_re.search('hi, earth')) False </code></pre> <p>(It will actually return a match object on found, and None if not found - this might be useful if you need to know which keyword matched)</p> <p>However, how much (if anything) this gains you will depend on the keywords. If you only have one or two, keep your current approach. If you have a large list, it may be worth tring and profiling to see which performs better.</p> <p><strong>[Edit]</strong> For reference, here's how the approaches do for your example:</p> <pre><code> good1 good2 good3 bad1 bad2 original : 0.206 0.233 0.229 0.390 63.879 gnud (join) : 0.257 0.347 4.600 0.281 6.706 regex : 0.766 1.018 0.397 0.764 124.351 regex (join) : 0.345 0.337 3.305 0.481 48.666 </code></pre> <p>Obviously for this case, your approach performs far better than the regex one. Whether this will always be the case depends a lot on the number and complexity of keywords, and the input data that will be checked. For large numbers of keywords, and lengthy lists or rarely matching phrases, regexes may work better, but <em>do</em> get timing information, and perhaps try even simpler optimisations (like moving the most common words to the front of your keyword list) first. Sometimes the simplest approach really is the best.</p> <p><strong>[Edit2]</strong> Updated the table with <a href="http://stackoverflow.com/questions/749342/search-a-list-of-strings-for-any-sub-string-from-another-list/749418#749418">gnud's solution</a>, and a similar approach before applying the regexes. I also added 2 new tests:</p> <pre><code>good_data3 = good_data2 * 500 # 1000 items, the first of which matches. bad_data2 = bad_data * 500 # 1000 items, none of which matches. </code></pre> <p>Which show up the various strengths and weaknesses. Joining does do worse when a match would immediately be found (as there is an always paid, up-front cost in joining the list - this is a best possible case for the linear search method), however for non-matching lists, it performs better. <strong>Much</strong> better when there are a large number of items in the list.case).</p>
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 substring of any word in the data lists. It should return True for the <code>good_data</code> lists and False for <code>bad_data</code>.</p> <p>I know how to do this in what seems to be an inefficient way:</p> <pre><code>def checkData(data): for s in data: for k in keywords: if k in s: return True return False </code></pre>
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 character that you know won't occur in the keyword, in order to avoid false positives. I use the newline in this example.</p> <pre><code>def check_data(data): s = "\n".join(data); for k in keywords: if k in s: return True return False </code></pre> <p>In my completely unscientific test, my version checked a list of 5000 items 100000 times in about 30 seconds. I stopped your version after 3 minutes -- got tired of waiting to post =)</p>
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 substring of any word in the data lists. It should return True for the <code>good_data</code> lists and False for <code>bad_data</code>.</p> <p>I know how to do this in what seems to be an inefficient way:</p> <pre><code>def checkData(data): for s in data: for k in keywords: if k in s: return True return False </code></pre>
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 implement!</p> <p>[1] <a href="http://en.wikipedia.org/wiki/Suffix_tree" rel="nofollow">http://en.wikipedia.org/wiki/Suffix_tree</a></p>
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-coded-info (the operations depend on user input and on info from a second file with 3000 lines). Then, these re-calculated binary-coded-info should be written to file (with trailing zeros, e.g. </p> <pre><code>4657 000110011 4789 110110000 etc. </code></pre> <p>How should I do this without writing my own base conversion routine? I am open for anything, also languages I do not know, like python, perl, etc. And it should work without compiling.</p> <p>So far, I tried to script, awk and sed my way. This would mean (I think): batch read as base-2, convert to base-10, do bitwise operations depending on user input and second file, convert to base-2, add leading zeros and print. The usual console hints to use bc do not seem elegant because I have many lines in a file. The same holds for dc.sed. And awk doesnt seem to have an equivalent to flagging input as binary ( as in "echo $((2#101010))" ), and also, the printf trick doesn't work for binary. So, how would I do this most elegantly (or, at all, for that matter) ?</p>
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, &amp;p, 10); long column2 = strtol(p, &amp;p, 2); ... } </code></pre> <p>You'll need to add error-handling, etc.</p>
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-coded-info (the operations depend on user input and on info from a second file with 3000 lines). Then, these re-calculated binary-coded-info should be written to file (with trailing zeros, e.g. </p> <pre><code>4657 000110011 4789 110110000 etc. </code></pre> <p>How should I do this without writing my own base conversion routine? I am open for anything, also languages I do not know, like python, perl, etc. And it should work without compiling.</p> <p>So far, I tried to script, awk and sed my way. This would mean (I think): batch read as base-2, convert to base-10, do bitwise operations depending on user input and second file, convert to base-2, add leading zeros and print. The usual console hints to use bc do not seem elegant because I have many lines in a file. The same holds for dc.sed. And awk doesnt seem to have an equivalent to flagging input as binary ( as in "echo $((2#101010))" ), and also, the printf trick doesn't work for binary. So, how would I do this most elegantly (or, at all, for that matter) ?</p>
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></pre>
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-coded-info (the operations depend on user input and on info from a second file with 3000 lines). Then, these re-calculated binary-coded-info should be written to file (with trailing zeros, e.g. </p> <pre><code>4657 000110011 4789 110110000 etc. </code></pre> <p>How should I do this without writing my own base conversion routine? I am open for anything, also languages I do not know, like python, perl, etc. And it should work without compiling.</p> <p>So far, I tried to script, awk and sed my way. This would mean (I think): batch read as base-2, convert to base-10, do bitwise operations depending on user input and second file, convert to base-2, add leading zeros and print. The usual console hints to use bc do not seem elegant because I have many lines in a file. The same holds for dc.sed. And awk doesnt seem to have an equivalent to flagging input as binary ( as in "echo $((2#101010))" ), and also, the printf trick doesn't work for binary. So, how would I do this most elegantly (or, at all, for that matter) ?</p>
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>&gt;&gt;&gt; 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> <pre><code>def bin(x, width): return ''.join(str((x&gt;&gt;i)&amp;1) for i in xrange(width))[::-1] &gt;&gt;&gt; bin(447, 9) 110111111 </code></pre> <p>(The width is the number of digits to pad to - your examples seem to be using 9-bit numbers.)</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-coded-info (the operations depend on user input and on info from a second file with 3000 lines). Then, these re-calculated binary-coded-info should be written to file (with trailing zeros, e.g. </p> <pre><code>4657 000110011 4789 110110000 etc. </code></pre> <p>How should I do this without writing my own base conversion routine? I am open for anything, also languages I do not know, like python, perl, etc. And it should work without compiling.</p> <p>So far, I tried to script, awk and sed my way. This would mean (I think): batch read as base-2, convert to base-10, do bitwise operations depending on user input and second file, convert to base-2, add leading zeros and print. The usual console hints to use bc do not seem elegant because I have many lines in a file. The same holds for dc.sed. And awk doesnt seem to have an equivalent to flagging input as binary ( as in "echo $((2#101010))" ), and also, the printf trick doesn't work for binary. So, how would I do this most elegantly (or, at all, for that matter) ?</p>
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/;$_&amp;&amp;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 off, the first #flag is turned on/off by the left-most bit my @flags = ( "flag one", "flag two", "flag three", "flag four", "flag five", "flag six", "flag seven", "flag eight", ); #turn the command line argument into individual #ones and zeros my @bits = split //, shift; #loop through the bits printing the flag that #goes with the bit if it is 1 my $i = 0; for my $bit (@bits) { if ($bit) { print "$flags[$i]\n"; } $i++; } </code></pre>
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-coded-info (the operations depend on user input and on info from a second file with 3000 lines). Then, these re-calculated binary-coded-info should be written to file (with trailing zeros, e.g. </p> <pre><code>4657 000110011 4789 110110000 etc. </code></pre> <p>How should I do this without writing my own base conversion routine? I am open for anything, also languages I do not know, like python, perl, etc. And it should work without compiling.</p> <p>So far, I tried to script, awk and sed my way. This would mean (I think): batch read as base-2, convert to base-10, do bitwise operations depending on user input and second file, convert to base-2, add leading zeros and print. The usual console hints to use bc do not seem elegant because I have many lines in a file. The same holds for dc.sed. And awk doesnt seem to have an equivalent to flagging input as binary ( as in "echo $((2#101010))" ), and also, the printf trick doesn't work for binary. So, how would I do this most elegantly (or, at all, for that matter) ?</p>
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) # Read in the file using the csv module # Each row will be a dictionary with keys corresponding to the first row reader = csv.DictReader(cStringIO.StringIO(data_file), delimiter=' ', skipinitialspace = True) try: for row in reader: data.append(row) # Add the row dictionary to the data list except csv.Error, e: sys.exit('file %s, line %d: %s' % (filename, reader.line_num, e)) # Do something with the bits first = int(data[0]['binary-coded-info'],2) # First bit string assert(first &amp; int('00001101',2) == int('1101',2)) # Bitwise AND assert(first | int('00001101',2) == int('1001101',2)) # Bitwise OR assert(first ^ int('00001101',2) == int('1000000',2)) # Bitwise XOR assert(~first == int('110110010',2)) # Binary Ones Complement assert(first &lt;&lt; 2 == int('100110100',2)) # Binary Left Shift assert(first &gt;&gt; 2 == int('000010011',2)) # Binary Right Shift </code></pre> <p>See the python docs on <a href="http://docs.python.org/reference/expressions.html#binary-arithmetic-operations" rel="nofollow">expressions</a> for more information and <a href="http://docs.python.org/library/csv.html#module-csv" rel="nofollow">csv module</a> for more information on the csv module.</p>
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-coded-info (the operations depend on user input and on info from a second file with 3000 lines). Then, these re-calculated binary-coded-info should be written to file (with trailing zeros, e.g. </p> <pre><code>4657 000110011 4789 110110000 etc. </code></pre> <p>How should I do this without writing my own base conversion routine? I am open for anything, also languages I do not know, like python, perl, etc. And it should work without compiling.</p> <p>So far, I tried to script, awk and sed my way. This would mean (I think): batch read as base-2, convert to base-10, do bitwise operations depending on user input and second file, convert to base-2, add leading zeros and print. The usual console hints to use bc do not seem elegant because I have many lines in a file. The same holds for dc.sed. And awk doesnt seem to have an equivalent to flagging input as binary ( as in "echo $((2#101010))" ), and also, the printf trick doesn't work for binary. So, how would I do this most elegantly (or, at all, for that matter) ?</p>
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( var ,var ) , 8 ); } # convert var to d-ht base. Specify 16 for hex, 8 for oct, and such. Up to base 36, for fruther base, provide X. if d&lt;=36, and wish to use custom X, provide 1 for i. function _obase( v , d , X , i, this , r ){ if(d&lt;=9){r="";while(v){r=v%d""r;v=int(v/d)};return r;} if(d&lt;=36&amp;&amp;!i){for(i=0;i&lt;=9;i++)X[i]=""i;for(;i&lt;d;i++)X[i]=sprintf("%c",55+i);} r="";while(v){r=X[v%d]""r;v=int(v/d)};return r; } function _pad(d, p, w, this ,r){ r=""d;while(length(r)&lt;w)r=p""r;return r; } function _bin( v , w , this ){ return _pad(_obase(v,2),"0",w); } # convert string to var, using d as base. for base&gt;36, specify X. if wish to use custom X, provide 1 to i function _int( s , d , X , i , this , k , r ){ r=0;k=length(s);if(d&lt;=9){for(i=1;i&lt;=k;i++){r*=d;r=r+int(substr(s,i,1));}return r;} if(d&lt;=36&amp;&amp;!i){for(i=0;i&lt;=9;i++)X[""i]=i;for(;i&lt;d;i++)X[sprintf("%c",55+i)]=i;} for(i=1;i&lt;=k;i++){r*=d;r=r+X[substr(s,i,1)];}eturn r; } </code></pre> <p>function and(), or(), xor() may be missing on some type of awk. If so, load the bit manipulation libs. There are some for awk floating in the net. Or provide your own.</p>
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> <p>I have 4G of physical memory and would like to figure out approximately how many rows (key:values) I can store in memory before I spill into swap. This is on linux/ubuntu 8.04 and OS X 10.5.6 .</p> <p>Also, what's the best way to figure out the actual in-memory footprint of my program? How do I best figure out when it's exhausting physical memory and spilling?</p>
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> </ol> <p>This is possibly a duplicate of <a href="http://stackoverflow.com/questions/110259/python-memory-profiler">this</a> question.</p>
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> <p>I have 4G of physical memory and would like to figure out approximately how many rows (key:values) I can store in memory before I spill into swap. This is on linux/ubuntu 8.04 and OS X 10.5.6 .</p> <p>Also, what's the best way to figure out the actual in-memory footprint of my program? How do I best figure out when it's exhausting physical memory and spilling?</p>
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>&gt;&gt;&gt; from guppy import hpy &gt;&gt;&gt; hp = hpy() &gt;&gt;&gt; hp.setrelheap() # ignore all existing objects &gt;&gt;&gt; d = {} &gt;&gt;&gt; d['key'] = [ (1131, 3.11e18), (9813, 2.48e19), (4991, 9.11e18) ] &gt;&gt;&gt; hp.heap() Partition of a set of 24 objects. Total size = 1464 bytes. Index Count % Size % Cumulative % Kind (class / dict of class) 0 2 8 676 46 676 46 types.FrameType 1 6 25 220 15 896 61 str 2 6 25 184 13 1080 74 tuple ... </code></pre> <p>Heapy is a little underdocumented, so you might have to dig through the web page or source code a little, but it's very powerful. There are also some <a href="http://www.pkgcore.org/trac/pkgcore/doc/dev-notes/heapy.rst">articles</a> which might be relevant.</p>
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> </blockquote> <p>According to the code of <a href="http://docs.djangoproject.com/en/dev/topics/auth/#django.contrib.auth.models.User.set%5Fpassword"><code>set_password</code></a>:</p> <pre><code>def set_password(self, raw_password): import random algo = 'sha1' salt = get_hexdigest(algo, str(random.random()), str(random.random()))[:5] hsh = get_hexdigest(algo, salt, raw_password) self.password = '%s$%s$%s' % (algo, salt, hsh) </code></pre> <p>As the documentation describes, the hash is the salt, algorithm, and password, hashed.</p>
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_password, salt = smart_str(raw_password), smart_str(salt) if algorithm == 'crypt': try: import crypt except ImportError: raise ValueError('"crypt" password algorithm not supported in this environment') return crypt.crypt(raw_password, salt) if algorithm == 'md5': return md5_constructor(salt + raw_password).hexdigest() elif algorithm == 'sha1': return sha_constructor(salt + raw_password).hexdigest() raise ValueError("Got unknown password algorithm type in password.") </code></pre> <p>As we can see, the password digests are made by concatenating the salt with the password using the selected hashing algorithm. then the algorithm name, the original salt, and password hash are concatenated, separated by "$"s to form the digest. </p> <pre><code># Also from root/django/trunk/django/contrib/auth/models.py def check_password(raw_password, enc_password): """ Returns a boolean of whether the raw_password was correct. Handles encryption formats behind the scenes. """ algo, salt, hsh = enc_password.split('$') return hsh == get_hexdigest(algo, salt, raw_password) </code></pre> <p>To validate passwords django just verifies that the same salt and same password result in the same digest.</p>
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 since 1979</a>. Any passwords still stored that way are highly vulnerable to brute force attack. For reasons why, see <a href="http://security.stackexchange.com/tags/passwords/info">Security Stackexchange on password hashing</a></p> <p>Since version 1.4 in 2012, Django has a default hashing algorithm based on a good, standard key derivation function, PBKDF2, with a configurable number of iterations, whose default increases with each release (20000 in version 1.7). It also provides bcrypt support, and is backwards compatible with earlier releases, automatically upgrading password hashes when users log in. See more at <a href="https://docs.djangoproject.com/en/dev/topics/auth/passwords/" rel="nofollow">Password management in Django | Django documentation</a></p>
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/python-tip-of-the-day-replace-pyxmls-prettyprint/" rel="nofollow">PrettyPrint function</a>.</p>
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) serializer.writeToString(document) </code></pre> <p>If you're using something else without its own pretty-printer — or those pretty-printers don't quite do it the way you want —  you'd probably have to write or subclass your own serialiser.</p>
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(doc, encoding): """Return a pretty-printed XML document in a given encoding.""" unistr = doc.toprettyxml().replace(u'&lt;?xml version="1.0" ?&gt;', u'&lt;?xml version="1.0" encoding="%s"?&gt;' % encoding) return unistr.encode(encoding, 'xmlcharrefreplace') </code></pre>
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('&gt;\n\s+([^&lt;&gt;\s].*?)\n\s+&lt;/', re.DOTALL) prettyXml = text_re.sub('&gt;\g&lt;1&gt;&lt;/', uglyXml) print prettyXml </code></pre> <p>The above code will produce:</p> <pre><code>&lt;?xml version="1.0" ?&gt; &lt;issues&gt; &lt;issue&gt; &lt;id&gt;1&lt;/id&gt; &lt;title&gt;Add Visual Studio 2005 and 2008 solution files&lt;/title&gt; &lt;details&gt;We need Visual Studio 2005/2008 project files for Windows.&lt;/details&gt; &lt;/issue&gt; &lt;/issues&gt; </code></pre> <p>Instead of this:</p> <pre><code>&lt;?xml version="1.0" ?&gt; &lt;issues&gt; &lt;issue&gt; &lt;id&gt; 1 &lt;/id&gt; &lt;title&gt; Add Visual Studio 2005 and 2008 solution files &lt;/title&gt; &lt;details&gt; We need Visual Studio 2005/2008 project files for Windows. &lt;/details&gt; &lt;/issue&gt; &lt;/issues&gt; </code></pre> <p><em>Disclaimer:</em> There are probably some limitations.</p>
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.etree import ElementTree def indent(elem, level=0): i = "\n" + level*" " j = "\n" + (level-1)*" " if len(elem): if not elem.text or not elem.text.strip(): elem.text = i + " " if not elem.tail or not elem.tail.strip(): elem.tail = i for subelem in elem: indent(subelem, level+1) if not elem.tail or not elem.tail.strip(): elem.tail = j else: if level and (not elem.tail or not elem.tail.strip()): elem.tail = j return elem root = ElementTree.parse('/tmp/xmlfile').getroot() indent(root) ElementTree.dump(root) </code></pre>
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>). Furthermore it makes sure the output uses UTF-8 as encoding instead of the default ASCII (notice the <code>encoding='utf-8'</code>):</p> <pre class="lang-py prettyprint-override"><code>from lxml import etree def prettyPrintXml(xmlFilePathToPrettyPrint): assert xmlFilePathToPrettyPrint is not None parser = etree.XMLParser(resolve_entities=False, strip_cdata=False) document = etree.parse(xmlFilePathToPrettyPrint, parser) document.write(xmlFilePathToPrettyPrint, pretty_print=True, encoding='utf-8') </code></pre> <p>Example usage:</p> <pre class="lang-py prettyprint-override"><code>prettyPrintXml('some_folder/some_file.xml') </code></pre>
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 &lt;file&gt;</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 = subprocess.Popen( ['xmllint', '--format', '/dev/stdin'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, ) (output, error_output) = proc.communicate(xml); return output print(pretty_print_xml(data)) </code></pre>
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) * ' ' num_kids = len(elem) if num_kids: if not elem.text or not elem.text.strip(): elem.text = i + " " if level: elem.text += ' ' count = 0 for kid in elem: indent(kid, level+1, count &lt; num_kids - 1) count += 1 if not elem.tail or not elem.tail.strip(): elem.tail = i if more_sibs: elem.tail += ' ' else: if level and (not elem.tail or not elem.tail.strip()): elem.tail = i if more_sibs: elem.tail += ' ' </code></pre>
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') xml = f.read() f.close() #Removing old indendations raw_xml = '' for line in xml: raw_xml += line xml = raw_xml new_xml = '' indent = ' ' deepness = 0 for i in range((len(xml))): new_xml += xml[i] if(i&lt;len(xml)-3): simpleSplit = xml[i:(i+2)] == '&gt;&lt;' advancSplit = xml[i:(i+3)] == '&gt;&lt;/' end = xml[i:(i+2)] == '/&gt;' start = xml[i] == '&lt;' if(advancSplit): deepness += -1 new_xml += '\n' + indent*deepness simpleSplit = False deepness += -1 if(simpleSplit): new_xml += '\n' + indent*deepness if(start): deepness += 1 if(end): deepness += -1 f = open(file_name,'w') f.write(new_xml) f.close() </code></pre> <p>It works for me, perhaps someone will have some use of it :)</p>
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 should look like.</p> <pre><code>pretty_xml_string = indent( ugly_xml_string, indentation = ' ', newline = '\r\n' ) </code></pre> <p>The doc is on <a href="http://www.yattag.org" rel="nofollow">http://www.yattag.org</a> homepage.</p>
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=encoding) if pretty_print: pretty_printed_xml = pretty_printed_xml.replace(' ', indent) file.write(pretty_printed_xml) </code></pre> <p>In my code this method is called like this:</p> <pre><code>try: with open(file_path, 'w') as file: file.write('&lt;?xml version="1.0" encoding="utf-8" ?&gt;') # create some xml content using etree ... xml_parser = XMLParser() xml_parser.write_xml_file(file, xml_root, xml_declaration=False, pretty_print=True, encoding='unicode', indent='\t') except IOError: print("Error while writing in log file!") </code></pre> <p>This works only because etree by default uses <code>two spaces</code> to indent, which I don't find very much emphasizing the indentation and therefore not pretty. I couldn't ind any setting for etree or parameter for any function to change the standard etree indent. I like how easy it is to use etree, but this was really annoying me.</p>
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 child in list(element)] if children: element.text = '\n' + indent * (level+1) # for child open if queue: element.tail = '\n' + indent * queue[0][0] # for sibling open else: element.tail = '\n' + indent * (level-1) # for parent close queue[0:0] = children # prepend so children come before siblings </code></pre>
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><code>full_document=False</code> against <code>&lt;?xml version="1.0" encoding="UTF-8"?&gt;</code> at the top.</p>
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 script, but it would be nice to visualize them separately.</p> <p>I frequently use matplotlib. Any ideas?</p>
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 script, but it would be nice to visualize them separately.</p> <p>I frequently use matplotlib. Any ideas?</p>
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="nofollow">inotify</a>, which can monitor file changes or dnotify (and place the file in it's own directory) which usually comes standard on most distributions (you can then call tail -n 1 to get the last line). Once the line changes, you can grab the current system time since epoch using Python's time.time() and subtract it from the time of the last change, then plot this difference using matplotlib. I assume you could categorize the times into ranges to make the graphing easier on yourself. 1 Bar for less than 1 hour change intervals, another for changes between 1 - 5 hours, and so on.</p> <p>There is a Python implementation of tail -f located <a href="http://code.activestate.com/recipes/157035/" rel="nofollow">here</a> if you don't want to use it directly. Upon a detection of a change in the file, you could perform the above.</p>
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 script, but it would be nice to visualize them separately.</p> <p>I frequently use matplotlib. Any ideas?</p>
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 standard way to go. A moving average might also be informational.</p> <p>You could combine the timeline &amp; bar plot, with the timeline visible when you're zoomed in &amp; the frequency display when zoomed out.</p> <p>How about a bar plot with time on the horizontal axis where the width of each bar is the length of time your computer held a particular IP address and the height of each bar is inversely proportional to the width? That would also give a plot of when vs how often plot.</p> <p>You could also interpret the data as a <a href="http://en.wikipedia.org/wiki/Pulse-density%5Fmodulation" rel="nofollow">pulse density modulated</a> signal, like what you get on a SuperAudio CD. You could graph this or even listen to the data. As there's no obvious time length for an IP change event, the length of a pulse would be a tunable parameter. Along similar lines, you could view the data as a square wave (triangular wave, sawtooth &amp;c), where each IP change event is a level transition. Sounds like a fun <a href="http://puredata.info/" rel="nofollow">Pure Data</a> project.</p>
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 script, but it would be nice to visualize them separately.</p> <p>I frequently use matplotlib. Any ideas?</p>
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 brighter, less recent points proportionally darker. </p>
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 </code></pre> <p>Desired Output--></p> <pre><code>KUMAR.5.txt KUMAR.8.txt KUMAR.12.txt KUMAR.14.txt </code></pre> <hr> <p>Input --></p> <pre><code>KUMAR3.txt KUMAR4.txt KUMAR6.txt KUMAR7.txt KUMAR9.txt KUMAR10.txt KUMAR11.txt KUMAR13.txt KUMAR15.txt KUMAR16.txt </code></pre> <p>Desired Output --></p> <pre><code>KUMAR5.txt KUMAR8.txt KUMAR12.txt KUMAR14.txt </code></pre>
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).groups()[0]) mincount = get_count(inlist[0]) maxcount = get_count(inlist[-1]) values = set(map(get_count, inlist)) for ii in range (mincount, maxcount): if ii not in values: print 'KUMAR.%d.txt' % ii </code></pre>
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 </code></pre> <p>Desired Output--></p> <pre><code>KUMAR.5.txt KUMAR.8.txt KUMAR.12.txt KUMAR.14.txt </code></pre> <hr> <p>Input --></p> <pre><code>KUMAR3.txt KUMAR4.txt KUMAR6.txt KUMAR7.txt KUMAR9.txt KUMAR10.txt KUMAR11.txt KUMAR13.txt KUMAR15.txt KUMAR16.txt </code></pre> <p>Desired Output --></p> <pre><code>KUMAR5.txt KUMAR8.txt KUMAR12.txt KUMAR14.txt </code></pre>
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): return int(s[start:s.index('.txt')]) </code></pre> <p>Given:</p> <pre><code>lst = ['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'] </code></pre> <p>you can get a list of known numbers by: <code>map(to_num, lst)</code>. Of course, to look for gaps, you only really need the minimum and maximum. Combine that with the <code>range</code> function and you get all the numbers that you should see, and then remove the numbers you've got. Sets are helpful here.</p> <pre><code>def find_gaps(int_list): return sorted(set(range(min(int_list), max(int_list))) - set(int_list)) </code></pre> <p>Putting it all together:</p> <pre><code>missing = find_gaps(map(to_num, lst)) for i in missing: print 'KUMAR.%d.txt' % i </code></pre>
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 something. When you create <code>autoparts()</code> or <code>splittext()</code>, the idea is that this will be a function that you can call, and it can (and should) give something back. Once you figure out the output that you want your function to have, you need to put it in a <code>return</code> statement.</p> </blockquote> <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 print(parts_dict) &gt;&gt;&gt; autoparts() {'part A': 1, 'part B': 2, ...} </code></pre> <p>This function creates a dictionary, but it does not return something. However, since I added the <code>print</code>, the output of the function is shown when I run the function. What is the difference between <code>return</code>ing something and <code>print</code>ing it?</p>
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 the application. You can also return multiple things by separating them with commas:</p> <pre><code>return parts_dict, list_of_parts </code></pre> <p>to use it:</p> <pre><code>test_dict = {} test_dict = autoparts() </code></pre>
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 something. When you create <code>autoparts()</code> or <code>splittext()</code>, the idea is that this will be a function that you can call, and it can (and should) give something back. Once you figure out the output that you want your function to have, you need to put it in a <code>return</code> statement.</p> </blockquote> <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 print(parts_dict) &gt;&gt;&gt; autoparts() {'part A': 1, 'part B': 2, ...} </code></pre> <p>This function creates a dictionary, but it does not return something. However, since I added the <code>print</code>, the output of the function is shown when I run the function. What is the difference between <code>return</code>ing something and <code>print</code>ing it?</p>
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_dict[k] = v return parts_dict </code></pre> <p>Why return? Well if you don't, that dictionary dies (gets garbage collected) and is no longer accessible as soon as this function call ends. If you return the value, you can do other stuff with it. Such as:</p> <pre><code>my_auto_parts=autoparts() print my_auto_parts['engine'] </code></pre> <p>See what happened? autoparts() was called and it returned the parts_dict and we stored it into the my_auto_parts variable. Now we can use this variable to access the dictionary object and it continues to live even though the function call is over. We then printed out the object in the dictionary with the key 'engine'.</p> <p>For a good tutorial, check out <a href="http://www.diveintopython.net/">dive into python</a>. It's free and very easy to follow.</p>
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 something. When you create <code>autoparts()</code> or <code>splittext()</code>, the idea is that this will be a function that you can call, and it can (and should) give something back. Once you figure out the output that you want your function to have, you need to put it in a <code>return</code> statement.</p> </blockquote> <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 print(parts_dict) &gt;&gt;&gt; autoparts() {'part A': 1, 'part B': 2, ...} </code></pre> <p>This function creates a dictionary, but it does not return something. However, since I added the <code>print</code>, the output of the function is shown when I run the function. What is the difference between <code>return</code>ing something and <code>print</code>ing it?</p>
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>&gt;&gt;&gt; def foo(): ... print "Hello, world!" ... &gt;&gt;&gt; a = foo() Hello, world! &gt;&gt;&gt; a &gt;&gt;&gt; def foo(): ... return "Hello, world!" ... &gt;&gt;&gt; a = foo() &gt;&gt;&gt; a 'Hello, world!' </code></pre> <p>Or in the context of returning a dictionary:</p> <pre><code>&gt;&gt;&gt; def foo(): ... print {'a' : 1, 'b' : 2} ... &gt;&gt;&gt; a = foo() {'a': 1, 'b': 2} &gt;&gt;&gt; a &gt;&gt;&gt; def foo(): ... return {'a' : 1, 'b' : 2} ... &gt;&gt;&gt; a = foo() &gt;&gt;&gt; a {'a': 1, 'b': 2} </code></pre> <p>(The statements where nothing is printed out after a line is executed means the last statement returned None)</p>
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 something. When you create <code>autoparts()</code> or <code>splittext()</code>, the idea is that this will be a function that you can call, and it can (and should) give something back. Once you figure out the output that you want your function to have, you need to put it in a <code>return</code> statement.</p> </blockquote> <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 print(parts_dict) &gt;&gt;&gt; autoparts() {'part A': 1, 'part B': 2, ...} </code></pre> <p>This function creates a dictionary, but it does not return something. However, since I added the <code>print</code>, the output of the function is shown when I run the function. What is the difference between <code>return</code>ing something and <code>print</code>ing it?</p>
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 it, letting the REPL print it. </p> <p>However, these are very much not the same thing, as you will realize when you call autoparts with another function that wants to do something with the value that autoparts creates.</p>
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 looking for.</p> <p>Let us know how it works out for you?</p>
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-visible try-expand-dabbrev try-expand-dabbrev-all-buffers) t)) </code></pre> <p>Hope this is useful.</p>
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">AutoComplete</a>, rope, ropemacs, rope mode, yasnippet and setting up, but in the end I hope it will pay off.</p>
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> (first link) and put it in your load-path directory. Also download the extensions you want to use (Attention: Ruby and etags extensions need additional stuff). Put them also in yout load-path dir. </p> <p>2) Download <a href="http://www.emacswiki.org/emacs/Yasnippet">yasnippet</a> and install it like the instruction on that page says (including the (require ...) part).</p> <p>3) Put these lines in your .emacs file and edit them for your needs (like all the extensions you want to use):</p> <pre><code>(require 'auto-complete) (global-auto-complete-mode t) (when (require 'auto-complete nil t) (require 'auto-complete-yasnippet) (require 'auto-complete-python) (require 'auto-complete-css) (require 'auto-complete-cpp) (require 'auto-complete-emacs-lisp) (require 'auto-complete-semantic) (require 'auto-complete-gtags) (global-auto-complete-mode t) (setq ac-auto-start 3) (setq ac-dwim t) (set-default 'ac-sources '(ac-source-yasnippet ac-source-abbrev ac-source-words-in-buffer ac-source-files-in-current-dir ac-source-symbols)) </code></pre> <p>For more informations on options see the auto-complete.el file. </p> <p>4) Restart emacs or do a M-x load-file with your .emacs file. Write some code and press TAB for auto completion.</p>
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 handling</li> <li>*args / **kwargs</li> <li>decorators / lambdas / closures</li> <li>generators / iterators</li> <li>some descriptors: property / staticmethod / classmethod</li> <li>some magic methods: <code>__call__</code>, <code>__iter__</code>, <code>__next__</code>, <code>__get__</code>, <code>__getitem__</code>, <code>__init__</code></li> <li>list.append(), set.add(), list.extend(), etc.</li> <li>(nested) list comprehensions / ternary expressions</li> <li>relative imports</li> <li>getattr() / <code>__getattr__</code> / <code>__getattribute__</code></li> <li>simple/usual sys.path modifications</li> <li>isinstance checks for if/while/assert</li> </ul>
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 would be beneficial to give the user a printout of the execution context at the beginning of each step in the algorithm.</p> <p>The following code achieves what I was needing.</p> <pre><code>import inspect def print_current_execution_context(): frame=inspect.currentframe().f_back #get caller frame print frame.f_locals #print locals of caller class TheClass(object): def __init__(self,val): self.val=val def thefunction(self,a,b): c=a+b print_current_execution_context() C=TheClass(2) C.thefunction(1,2) </code></pre> <p>This gives the expected output of:</p> <pre><code>{'a': 1, 'c': 3, 'b': 2, 'self': &lt;__main__.TheClass object at 0xb7d2214c&gt;} </code></pre> <p>Thank you to apphacker and ConcernedOfTunbridgeWells who pointed me towards this answer</p>
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 would be beneficial to give the user a printout of the execution context at the beginning of each step in the algorithm.</p> <p>The following code achieves what I was needing.</p> <pre><code>import inspect def print_current_execution_context(): frame=inspect.currentframe().f_back #get caller frame print frame.f_locals #print locals of caller class TheClass(object): def __init__(self,val): self.val=val def thefunction(self,a,b): c=a+b print_current_execution_context() C=TheClass(2) C.thefunction(1,2) </code></pre> <p>This gives the expected output of:</p> <pre><code>{'a': 1, 'c': 3, 'b': 2, 'self': &lt;__main__.TheClass object at 0xb7d2214c&gt;} </code></pre> <p>Thank you to apphacker and ConcernedOfTunbridgeWells who pointed me towards this answer</p>
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">interface</a>. If there is no such kind of work for Perl in Python. What is the easiest way to use Perl classes in python?</p>
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">interface</a>. If there is no such kind of work for Perl in Python. What is the easiest way to use Perl classes in python?</p>
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 of the FLUFL</em> read:</p> <blockquote> <ul> <li>Recognized that C is a 20th century language with almost universal rejection by programmers under the age of 30, the CPython implementation will terminate with the release of Python 2.6.2 and 3.0.2. Thereafter, <strong>the reference implementation of Python will target the Parrot virtual machine</strong>. Alternative implementations of Python (e.g. Jython, IronPython, and PyPy ) are officially discouraged but tolerated.</li> </ul> </blockquote>
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">interface</a>. If there is no such kind of work for Perl in Python. What is the easiest way to use Perl classes in python?</p>
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&mdash;that's easiest. Leaving Perl behind is no great loss. Rewriting classes into Python may give you an opportunity to improve them in small ways. </p> <p>Not so easy. Run the Perl application using Python's <a href="http://docs.python.org/library/subprocess.html" rel="nofollow">subprocess</a> module. That uses the Perl classes in the Perl application without problems. You can easily create pipelines so the Perl gets input from Python and produces output to Python</p> <pre><code>someApp.py | something.pl | finalStep.py </code></pre> <p>This has the advantage of breaking your application into three concurrent processes, using up lots of processor resources and running (sometimes) in 1/3 the time.</p> <p>Everything else is much less easy.</p>
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">interface</a>. If there is no such kind of work for Perl in Python. What is the easiest way to use Perl classes in python?</p>
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">interface</a>. If there is no such kind of work for Perl in Python. What is the easiest way to use Perl classes in python?</p>
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 Perl objects.</p>
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>&gt;&gt;&gt; class AutoRepr(object): ... def __repr__(self): ... items = ("%s = %r" % (k, v) for k, v in self.__dict__.items()) ... return "&lt;%s: {%s}&gt;" % (self.__class__.__name__, ', '.join(items)) ... &gt;&gt;&gt; class AnyOtherClass(AutoRepr): ... def __init__(self): ... self.foo = 'foo' ... self.bar = 'bar' ... &gt;&gt;&gt; repr(AnyOtherClass()) "&lt;AnyOtherClass: {foo = 'foo', bar = 'bar'}&gt;" </code></pre> <p>Note that the above code will not act nicely on data structures that (either directly or indirectly) reference themselves. As an alternative, you can define a function that works on any type:</p> <pre><code>&gt;&gt;&gt; def autoRepr(obj): ... try: ... items = ("%s = %r" % (k, v) for k, v in obj.__dict__.items()) ... return "&lt;%s: {%s}." % (obj.__class__.__name__, ', '.join(items)) ... except AttributeError: ... return repr(obj) ... &gt;&gt;&gt; class AnyOtherClass(object): ... def __init__(self): ... self.foo = 'foo' ... self.bar = 'bar' ... &gt;&gt;&gt; autoRepr(AnyOtherClass()) "&lt;AnyOtherClass: {foo = 'foo', bar = 'bar'}&gt;" &gt;&gt;&gt; autoRepr(7) '7' &gt;&gt;&gt; autoRepr(None) 'None' </code></pre> <p>Note that the above function is not defined recursively, on purpose, for the reason mentioned earlier.</p>
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) &lt; 20 except: item = "%s: &lt;%s&gt;" % (prop, value.__class__.__name__) items.append(item) return "%s(%s)" % (obj.__class__.__name__, ', '.join(items)) def __init__(self, cls): cls.__repr__ = data.repr self.cls = cls def __call__(self, *args, **kwargs): return self.cls(*args, **kwargs) </code></pre> <p>You use it as a decorator:</p> <pre><code>@data class PythonBean: def __init__(self): self.int = 1 self.list = [5, 6, 7] self.str = "hello" self.obj = SomeOtherClass() </code></pre> <p>and get a smart <code>__repr__</code> out of the box:</p> <pre><code>PythonBean(int = 1, obj: &lt;SomeOtherClass&gt;, list = [5, 6, 7], str = 'hello') </code></pre> <p>This works with any recursive classes, including tree structures. If you try to put a self-reference in the class <code>self.ref = self</code>, the function will try (successfully) to work it out for about a second.</p> <p>Of course, always mind your boss - mine would not like such a syntax sugar ))</p>
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 alphabet is representing a unique digit from 0-9. I wanted to write a generalized solver, but i ended up writing a brute forced solution for it. Any takers as how can i solve it? </p> <p>I think it can be solved using predicate logic or set theory. And i'm particularly interested in finding C# or Python based solutions. Any one.?</p>
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 alphabet is representing a unique digit from 0-9. I wanted to write a generalized solver, but i ended up writing a brute forced solution for it. Any takers as how can i solve it? </p> <p>I think it can be solved using predicate logic or set theory. And i'm particularly interested in finding C# or Python based solutions. Any one.?</p>
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 theoretical max number of combinations to evaluate is <i>10! = 3 628 800</i>, which is really small number for a computer. </p> <p>If we allow several letters to represent the same number, the number of combinations to try will be bounded by <i>10^n</i>, again where <i>n</i> is the number of unique letters. Assuming only capital English letters we have a theoretical max number of combinations of <i>10^26</i>, so for that theoretical worst case we might need some heuristics. Most practical cryptarithms have a lot less than 26 unique letters though, so the normal case will probably be bounded by an <i>n</i> less than 10, which is again pretty reasonable for a computer.</p>
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 alphabet is representing a unique digit from 0-9. I wanted to write a generalized solver, but i ended up writing a brute forced solution for it. Any takers as how can i solve it? </p> <p>I think it can be solved using predicate logic or set theory. And i'm particularly interested in finding C# or Python based solutions. Any one.?</p>
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="nofollow">this link</a>.</p>
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 alphabet is representing a unique digit from 0-9. I wanted to write a generalized solver, but i ended up writing a brute forced solution for it. Any takers as how can i solve it? </p> <p>I think it can be solved using predicate logic or set theory. And i'm particularly interested in finding C# or Python based solutions. Any one.?</p>
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 alphabet is representing a unique digit from 0-9. I wanted to write a generalized solver, but i ended up writing a brute forced solution for it. Any takers as how can i solve it? </p> <p>I think it can be solved using predicate logic or set theory. And i'm particularly interested in finding C# or Python based solutions. Any one.?</p>
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 to be allocated and can be passed in any order. the method is efficient because it has a maximum of 8x7x5 possible trial solutions rather than the 10!/2 possible solutions by brute force</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication1 { class Program { static void MESDYNR(int m, int s, int e, int d, int y, int n, int r, int v1, int v2, int v3) { // Solve for O in hundreds position // "SEND" + "M?RE" = "M?NEY" int carry = (10 * n + d + 10 * r + e) / 100; int o = (10 + n - (e + carry))%10; if ((v1 == o) || (v2 == o) || (v3 == o)) { // check O is valid in thousands position if (o == ((10 + (100 * e + 10 * n + d + 100 * o + 10 * r + e) / 1000 + m + s) % 10)) { // "SEND" + "MORE" = "MONEY" int send = 1000 * s + 100 * e + 10 * n + d; int more = 1000 * m + 100 * o + 10 * r + e; int money = 10000 * m + 1000 * o + 100 * n + 10 * e + y; // Chck this solution if ((send + more) == money) { Console.WriteLine(send + " + " + more + " = " + money); } } } } static void MSEDYN(int m, int s, int e, int d, int y, int n, int v1, int v2, int v3, int v4) { // Solve for R // "SEND" + "M*?E" = "M*NEY" int carry = (d + e) / 10; int r = (10 + e - (n + carry)) % 10; if (v1 == r) MESDYNR(m, s, e, d, y, n, r, v2, v3, v4); else if (v2 == r) MESDYNR(m, s, e, d, y, n, r, v1, v3, v4); else if (v3 == r) MESDYNR(m, s, e, d, y, n, r, v1, v2, v4); else if (v4 == r) MESDYNR(m, s, e, d, y, n, r, v1, v2, v3); } static void MSEDY(int m, int s, int e, int d, int y, int v1, int v2, int v3, int v4, int v5) { // Pick any value for N MSEDYN(m, s, e, d, y, v1, v2, v3, v4, v5); MSEDYN(m, s, e, d, y, v2, v1, v3, v4, v5); MSEDYN(m, s, e, d, y, v3, v1, v2, v4, v5); MSEDYN(m, s, e, d, y, v4, v1, v2, v3, v5); MSEDYN(m, s, e, d, y, v5, v1, v2, v3, v4); } static void MSED(int m, int s, int e, int d, int v1, int v2, int v3, int v4, int v5, int v6) { // Solve for Y // "SE*D" + "M**E" = "M**E?" int y = (e + d) % 10; if (v1 == y) MSEDY(m, s, e, d, y, v2, v3, v4, v5, v6); else if (v2 == y) MSEDY(m, s, e, d, y, v1, v3, v4, v5, v6); else if (v3 == y) MSEDY(m, s, e, d, y, v1, v2, v4, v5, v6); else if (v4 == y) MSEDY(m, s, e, d, y, v1, v2, v3, v5, v6); else if (v5 == y) MSEDY(m, s, e, d, y, v1, v2, v3, v4, v6); else if (v6 == y) MSEDY(m, s, e, d, y, v1, v2, v3, v4, v5); } static void MSE(int m, int s, int e, int v1, int v2, int v3, int v4, int v5, int v6, int v7) { // "SE**" + "M**E" = "M**E*" // Pick any value for D MSED(m, s, e, v1, v2, v3, v4, v5, v6, v7); MSED(m, s, e, v2, v1, v3, v4, v5, v6, v7); MSED(m, s, e, v3, v1, v2, v4, v5, v6, v7); MSED(m, s, e, v4, v1, v2, v3, v5, v6, v7); MSED(m, s, e, v5, v1, v2, v3, v4, v6, v7); MSED(m, s, e, v6, v1, v2, v3, v4, v5, v7); MSED(m, s, e, v7, v1, v2, v3, v4, v5, v6); } static void MS(int m, int s, int v1, int v2, int v3, int v4, int v5, int v6, int v7, int v8) { // "S***" + "M***" = "M****" // Pick any value for E MSE(m, s, v1, v2, v3, v4, v5, v6, v7, v8); MSE(m, s, v2, v1, v3, v4, v5, v6, v7, v8); MSE(m, s, v3, v1, v2, v4, v5, v6, v7, v8); MSE(m, s, v4, v1, v2, v3, v5, v6, v7, v8); MSE(m, s, v5, v1, v2, v3, v4, v6, v7, v8); MSE(m, s, v6, v1, v2, v3, v4, v5, v7, v8); MSE(m, s, v7, v1, v2, v3, v4, v5, v6, v8); MSE(m, s, v8, v1, v2, v3, v4, v5, v6, v7); } static void Main(string[] args) { // M must be 1 // S must be 8 or 9 DateTime Start = DateTime.Now; MS(1, 8, 2, 3, 4, 5, 6, 7, 9, 0); MS(1, 9, 2, 3, 4, 5, 6, 7, 8, 0); Console.WriteLine((DateTime.Now-Start).Milliseconds); return; } } } </code></pre>
1
2012-03-10T15:40:27Z
[ "c#", "python", "solver", "cryptarithmetic-puzzle" ]