content
stringlengths
85
101k
title
stringlengths
0
150
question
stringlengths
15
48k
answers
list
answers_scores
list
non_answers
list
non_answers_scores
list
tags
list
name
stringlengths
35
137
Q: Python - efficient method to remove all non-letters and replace them with underscores def format_title(title): ''.join(map(lambda x: x if (x.isupper() or x.islower()) else '_', title.strip())) Anything faster? A: The faster way to do it is to use str.translate() This is ~50 times faster than your way # You only need to do this once >>> title_trans=''.join(chr(c) if chr(c).isupper() or chr(c).islower() else '_' for c in range(256)) >>> "abcde1234!@%^".translate(title_trans) 'abcde________' # Using map+lambda $ python -m timeit '"".join(map(lambda x: x if (x.isupper() or x.islower()) else "_", "abcd1234!@#$".strip()))' 10000 loops, best of 3: 21.9 usec per loop # Using str.translate $ python -m timeit -s 'titletrans="".join(chr(c) if chr(c).isupper() or chr(c).islower() else "_" for c in range(256))' '"abcd1234!@#$".translate(titletrans)' 1000000 loops, best of 3: 0.422 usec per loop # Here is regex for a comparison $ python -m timeit -s 'import re;transre=re.compile("[\W\d]+")' 'transre.sub("_","abcd1234!@#$")' 100000 loops, best of 3: 3.17 usec per loop Here is a version for unicode # coding: UTF-8 def format_title_unicode_translate(title): return title.translate(title_unicode_trans) class TitleUnicodeTranslate(dict): def __missing__(self,item): uni = unichr(item) res = u"_" if uni.isupper() or uni.islower(): res = uni self[item] = res return res title_unicode_trans=TitleUnicodeTranslate() print format_title_unicode_translate(u"Metallica Μεταλλικα") Note that the Greek letters count as upper and lower, so they are not substituted. If they are to be substituted, simply change the condition to if item<256 and (uni.isupper() or uni.islower()): A: import re title = re.sub("[\W\d]", "_", title.strip()) should be faster. If you want to replace a succession of adjacent non-letters with a single underscore, use title = re.sub("[\W\d]+", "_", title.strip()) instead which is even faster. I just ran a time comparison: C:\>python -m timeit -n 100 -s "data=open('test.txt').read().strip()" "''.join(map(lambda x: x if (x.isupper() or x.islower()) else '_', data))" 100 loops, best of 3: 4.51 msec per loop C:\>python -m timeit -n 100 -s "import re; regex=re.compile('[\W\d]+'); data=open('test.txt').read().strip()" "title=regex.sub('_',data)" 100 loops, best of 3: 2.35 msec per loop This will work on Unicode strings, too (under Python 3, \W matches any character which is not a Unicode word character. Under Python 2, you'd have to additionally set the UNICODE flag for this). A: Instead of (x.isupper() or x.islower()) you should be able to use x.isalpha(). The isalpha() method might return True for '_' (I don't remember if it does or not) but then you'll just end up replacing '_' with '_' so no harm done. (Thanks for pointing that out, KennyTM.) A: Curious about this for my own reasons I wrote a quick script to test the different approaches listed here along with just removing the lambda which I expected (incorrectly) would speed up the original solution. The short version is that the str.translate approach blows the other ones away. As an aside the regex solution, while a close second, is in correct as written above. Here is my test program: import re from time import time def format_title(title): return ''.join(map(lambda x: x if (x.isupper() or x.islower()) else "_", title.strip())) def format_title_list_comp(title): return ''.join([x if x.isupper() or x.islower() else "_" for x in title.strip()]) def format_title_list_comp_is_alpha(title): return ''.join([x if x.isalpha() else "_" for x in title.strip()]) def format_title_is_alpha(title): return ''.join(map(lambda x: x if x.isalpha() else '_', title.strip())) def format_title_no_lambda(title): def trans(c): if c.isupper() or c.islower(): return c return "_" return ''.join(map(trans, title.strip())) def format_title_no_lambda_is_alpha(title): def trans(c): if c.isalpha(): return c return "_" return ''.join(map(trans, title.strip())) def format_title_re(title): return re.sub("[\W\d]+", "_", title.strip()) def format_title_re_corrected(title): return re.sub("[\W\d]", "_", title.strip()) TITLE_TRANS = ''.join(chr(c) if chr(c).isalpha() else '_' for c in range(256)) def format_title_with_translate(title): return title.translate(TITLE_TRANS) ITERATIONS = 200000 EXAMPLE_TITLE = "abc123def_$%^!FOO BAR*bazx-bif" def timetest(f): start = time() for i in xrange(ITERATIONS): result = f(EXAMPLE_TITLE) diff = time() - start return result, diff baseline_result, baseline_time = timetest(format_title) def print_result(f, result, time): if result == baseline_result: msg = "CORRECT" else: msg = "INCORRECT" diff = time - baseline_time if diff < 0: indicator = "" else: indicator = "+" pct = (diff / baseline_time) * 100 print "%s: %0.3fs %s%0.3fs [%s%0.4f%%] (%s - %s)" % ( f.__name__, time, indicator, diff, indicator, pct, result, msg) print_result(format_title, baseline_result, baseline_time) print "----" for f in [format_title_is_alpha, format_title_list_comp, format_title_list_comp_is_alpha, format_title_no_lambda, format_title_no_lambda_is_alpha, format_title_re, format_title_re_corrected, format_title_with_translate]: alt_result, alt_time = timetest(f) print_result(f, alt_result, alt_time) And here are the results: format_title: 3.121s +0.000s [+0.0000%] (abc___def_____FOO_BAR_bazx_bif - CORRECT) ---- format_title_is_alpha: 2.336s -0.785s [-25.1470%] (abc___def_____FOO_BAR_bazx_bif - CORRECT) format_title_list_comp: 2.369s -0.751s [-24.0773%] (abc___def_____FOO_BAR_bazx_bif - CORRECT) format_title_list_comp_is_alpha: 1.735s -1.386s [-44.4021%] (abc___def_____FOO_BAR_bazx_bif - CORRECT) format_title_no_lambda: 2.992s -0.129s [-4.1336%] (abc___def_____FOO_BAR_bazx_bif - CORRECT) format_title_no_lambda_is_alpha: 2.377s -0.744s [-23.8314%] (abc___def_____FOO_BAR_bazx_bif - CORRECT) format_title_re: 1.290s -1.831s [-58.6628%] (abc_def__FOO_BAR_bazx_bif - INCORRECT) format_title_re_corrected: 1.338s -1.782s [-57.1165%] (abc___def_____FOO_BAR_bazx_bif - CORRECT) format_title_with_translate: 0.098s -3.022s [-96.8447%] (abc___def_____FOO_BAR_bazx_bif - CORRECT) EDITED: I added a variation that shows list comprehensions significantly improve the original implementation as well as a correct regex implementation that shows it's still nearly as fast when correct. Of course str.translate still wins hands down. A: import string,sys letters=string.letters mystring = list("abc134#$@e##$%%$*&(()#def") for n,c in enumerate(mystring): if not c in letters: mystring[n]="_" print ''.join(mystring)
Python - efficient method to remove all non-letters and replace them with underscores
def format_title(title): ''.join(map(lambda x: x if (x.isupper() or x.islower()) else '_', title.strip())) Anything faster?
[ "The faster way to do it is to use str.translate()\nThis is ~50 times faster than your way\n# You only need to do this once\n>>> title_trans=''.join(chr(c) if chr(c).isupper() or chr(c).islower() else '_' for c in range(256))\n\n>>> \"abcde1234!@%^\".translate(title_trans)\n'abcde________'\n\n# Using map+lambda\n$ python -m timeit '\"\".join(map(lambda x: x if (x.isupper() or x.islower()) else \"_\", \"abcd1234!@#$\".strip()))'\n10000 loops, best of 3: 21.9 usec per loop\n\n# Using str.translate\n$ python -m timeit -s 'titletrans=\"\".join(chr(c) if chr(c).isupper() or chr(c).islower() else \"_\" for c in range(256))' '\"abcd1234!@#$\".translate(titletrans)'\n1000000 loops, best of 3: 0.422 usec per loop\n\n# Here is regex for a comparison\n$ python -m timeit -s 'import re;transre=re.compile(\"[\\W\\d]+\")' 'transre.sub(\"_\",\"abcd1234!@#$\")'\n100000 loops, best of 3: 3.17 usec per loop\n\nHere is a version for unicode\n# coding: UTF-8\n\ndef format_title_unicode_translate(title):\n return title.translate(title_unicode_trans)\n\nclass TitleUnicodeTranslate(dict):\n def __missing__(self,item):\n uni = unichr(item)\n res = u\"_\"\n if uni.isupper() or uni.islower():\n res = uni\n self[item] = res\n return res\ntitle_unicode_trans=TitleUnicodeTranslate()\n\nprint format_title_unicode_translate(u\"Metallica Μεταλλικα\")\n\nNote that the Greek letters count as upper and lower, so they are not substituted.\nIf they are to be substituted, simply change the condition to\n if item<256 and (uni.isupper() or uni.islower()):\n\n", "import re\ntitle = re.sub(\"[\\W\\d]\", \"_\", title.strip())\n\nshould be faster.\nIf you want to replace a succession of adjacent non-letters with a single underscore, use\ntitle = re.sub(\"[\\W\\d]+\", \"_\", title.strip())\n\ninstead which is even faster.\nI just ran a time comparison:\nC:\\>python -m timeit -n 100 -s \"data=open('test.txt').read().strip()\" \"''.join(map(lambda x: x if (x.isupper() or x.islower()) else '_', data))\"\n100 loops, best of 3: 4.51 msec per loop\n\nC:\\>python -m timeit -n 100 -s \"import re; regex=re.compile('[\\W\\d]+'); data=open('test.txt').read().strip()\" \"title=regex.sub('_',data)\"\n100 loops, best of 3: 2.35 msec per loop\n\nThis will work on Unicode strings, too (under Python 3, \\W matches any character which is not a Unicode word character. Under Python 2, you'd have to additionally set the UNICODE flag for this).\n", "Instead of (x.isupper() or x.islower()) you should be able to use x.isalpha(). The isalpha() method might return True for '_' (I don't remember if it does or not) but then you'll just end up replacing '_' with '_' so no harm done. (Thanks for pointing that out, KennyTM.)\n", "Curious about this for my own reasons I wrote a quick script to test the different approaches listed here along with just removing the lambda which I expected (incorrectly) would speed up the original solution.\nThe short version is that the str.translate approach blows the other ones away. As an aside the regex solution, while a close second, is in correct as written above. \nHere is my test program:\nimport re\nfrom time import time\n\n\ndef format_title(title):\n return ''.join(map(lambda x: x if (x.isupper() or x.islower()) else \"_\",\n title.strip()))\n\n\ndef format_title_list_comp(title):\n return ''.join([x if x.isupper() or x.islower() else \"_\" for x in\n title.strip()])\n\n\ndef format_title_list_comp_is_alpha(title):\n return ''.join([x if x.isalpha() else \"_\" for x in title.strip()])\n\n\ndef format_title_is_alpha(title):\n return ''.join(map(lambda x: x if x.isalpha() else '_', title.strip()))\n\n\ndef format_title_no_lambda(title):\n\n def trans(c):\n if c.isupper() or c.islower():\n return c\n return \"_\"\n\n return ''.join(map(trans, title.strip()))\n\n\ndef format_title_no_lambda_is_alpha(title):\n\n def trans(c):\n if c.isalpha():\n return c\n return \"_\"\n\n return ''.join(map(trans, title.strip()))\n\n\ndef format_title_re(title):\n return re.sub(\"[\\W\\d]+\", \"_\", title.strip())\n\n\ndef format_title_re_corrected(title):\n return re.sub(\"[\\W\\d]\", \"_\", title.strip())\n\n\nTITLE_TRANS = ''.join(chr(c) if chr(c).isalpha() else '_' for c in range(256))\n\n\ndef format_title_with_translate(title):\n return title.translate(TITLE_TRANS)\n\n\nITERATIONS = 200000\nEXAMPLE_TITLE = \"abc123def_$%^!FOO BAR*bazx-bif\"\n\n\ndef timetest(f):\n start = time()\n for i in xrange(ITERATIONS):\n result = f(EXAMPLE_TITLE)\n diff = time() - start\n return result, diff\n\n\nbaseline_result, baseline_time = timetest(format_title)\n\n\ndef print_result(f, result, time):\n if result == baseline_result:\n msg = \"CORRECT\"\n else:\n msg = \"INCORRECT\"\n diff = time - baseline_time\n if diff < 0:\n indicator = \"\"\n else:\n indicator = \"+\"\n pct = (diff / baseline_time) * 100\n print \"%s: %0.3fs %s%0.3fs [%s%0.4f%%] (%s - %s)\" % (\n f.__name__, time, indicator, diff, indicator, pct, result, msg)\n\n\nprint_result(format_title, baseline_result, baseline_time)\n\nprint \"----\"\n\nfor f in [format_title_is_alpha,\n format_title_list_comp,\n format_title_list_comp_is_alpha,\n format_title_no_lambda,\n format_title_no_lambda_is_alpha,\n format_title_re,\n format_title_re_corrected,\n format_title_with_translate]:\n alt_result, alt_time = timetest(f)\n print_result(f, alt_result, alt_time)\n\nAnd here are the results:\nformat_title: 3.121s +0.000s [+0.0000%] (abc___def_____FOO_BAR_bazx_bif - CORRECT)\n----\nformat_title_is_alpha: 2.336s -0.785s [-25.1470%] (abc___def_____FOO_BAR_bazx_bif - CORRECT)\nformat_title_list_comp: 2.369s -0.751s [-24.0773%] (abc___def_____FOO_BAR_bazx_bif - CORRECT)\nformat_title_list_comp_is_alpha: 1.735s -1.386s [-44.4021%] (abc___def_____FOO_BAR_bazx_bif - CORRECT)\nformat_title_no_lambda: 2.992s -0.129s [-4.1336%] (abc___def_____FOO_BAR_bazx_bif - CORRECT)\nformat_title_no_lambda_is_alpha: 2.377s -0.744s [-23.8314%] (abc___def_____FOO_BAR_bazx_bif - CORRECT)\nformat_title_re: 1.290s -1.831s [-58.6628%] (abc_def__FOO_BAR_bazx_bif - INCORRECT)\nformat_title_re_corrected: 1.338s -1.782s [-57.1165%] (abc___def_____FOO_BAR_bazx_bif - CORRECT)\nformat_title_with_translate: 0.098s -3.022s [-96.8447%] (abc___def_____FOO_BAR_bazx_bif - CORRECT)\n\n\nEDITED: I added a variation that shows list comprehensions significantly improve the original implementation as well as a correct regex implementation that shows it's still nearly as fast when correct. Of course str.translate still wins hands down.\n\n", "import string,sys\nletters=string.letters\nmystring = list(\"abc134#$@e##$%%$*&(()#def\")\nfor n,c in enumerate(mystring):\n if not c in letters:\n mystring[n]=\"_\"\nprint ''.join(mystring)\n\n" ]
[ 20, 17, 2, 1, 0 ]
[]
[]
[ "performance", "python", "string" ]
stackoverflow_0002171095_performance_python_string.txt
Q: Can Large Python Scripts Drain DiskSpace? UPDATE: Interestingly, after almost 15min, I seem to have AUTOMATICALLY restored about 500MB. Hows this happening? I'm on Mac OSX 10.5.6(Leopard). I wrote a python script for a Project-Euler problem. My script had a loop which iterated for an enormous count like 600851475143. Used Vi and Python on Mac's Terminal. I didn't get the result even after running for 5min. I left it to run till it gets a result. Then I got error "Your Startup disk is almost full". I was shocked to see my disk having just 38MB free while it used to have atleast 1GB free. I immediately terminated "Terminal". But now I don't know how to get my memory back. :( Can somebody please tell me how to recover the memory used for execution of my script? Here's the script: # Program to Find Largest Prime Factor of 600851475143 def isPrime(n): #Check if Prime or Not i,notFactor=2,False while i<n: if(n%i==0): break notFactor=True i = i+1 return notFactor test = 600851475143 #Number to Test i = test-1 while i>1: #Finds Factors and See if they are Prime print i if test%i==0: if isPrime(i)==True: #Syntax Error Fixed. Thanks, batbrat! print i break i=i-1 A: The only way your script can fill up your disk is if it creates large/many temporary files and doesn't clean up. Just running a Python program cannot itself fill up your disk. To recover the disk space, you need to figure out where the space is spent and remove the temporary files. Not sure how to do that on OSX, though. On Windows and Linux there are several excellent tools for visualizing disk usage. EDIT: Euler-problems are designed to be solved in under a minute, even on modestly powerful computers. If you're spending 5 minutes, you're approaching the problem the wrong way. A: What I first though was that your program used a lot of memory which caused the swap file to grow. However, from the code I can see that it does not consume much memory. Therefore this script is not the cause of the lost space. A: That's not python, that's something else on your system using memory... probably your browser. 1GB is not nearly enough free space on a Mac... you need at least 10GB free, so it's time to clean up.
Can Large Python Scripts Drain DiskSpace?
UPDATE: Interestingly, after almost 15min, I seem to have AUTOMATICALLY restored about 500MB. Hows this happening? I'm on Mac OSX 10.5.6(Leopard). I wrote a python script for a Project-Euler problem. My script had a loop which iterated for an enormous count like 600851475143. Used Vi and Python on Mac's Terminal. I didn't get the result even after running for 5min. I left it to run till it gets a result. Then I got error "Your Startup disk is almost full". I was shocked to see my disk having just 38MB free while it used to have atleast 1GB free. I immediately terminated "Terminal". But now I don't know how to get my memory back. :( Can somebody please tell me how to recover the memory used for execution of my script? Here's the script: # Program to Find Largest Prime Factor of 600851475143 def isPrime(n): #Check if Prime or Not i,notFactor=2,False while i<n: if(n%i==0): break notFactor=True i = i+1 return notFactor test = 600851475143 #Number to Test i = test-1 while i>1: #Finds Factors and See if they are Prime print i if test%i==0: if isPrime(i)==True: #Syntax Error Fixed. Thanks, batbrat! print i break i=i-1
[ "The only way your script can fill up your disk is if it creates large/many temporary files and doesn't clean up. Just running a Python program cannot itself fill up your disk.\nTo recover the disk space, you need to figure out where the space is spent and remove the temporary files. Not sure how to do that on OSX, though. On Windows and Linux there are several excellent tools for visualizing disk usage.\nEDIT: Euler-problems are designed to be solved in under a minute, even on modestly powerful computers. If you're spending 5 minutes, you're approaching the problem the wrong way.\n", "What I first though was that your program used a lot of memory which caused the swap file to grow. However, from the code I can see that it does not consume much memory. Therefore this script is not the cause of the lost space.\n", "That's not python, that's something else on your system using memory... probably your browser.\n1GB is not nearly enough free space on a Mac... you need at least 10GB free, so it's time to clean up.\n" ]
[ 2, 0, 0 ]
[]
[]
[ "caching", "loops", "macos", "memory", "python" ]
stackoverflow_0002171395_caching_loops_macos_memory_python.txt
Q: Redirect calls to a member of a class in python I was trying to 'extend' a closed class collections.defaultdict(lambda: 1) by addint it 2 methods, called 'vocabulary', and 'wordcount' apparently it's impossible to setattr method to builin types, nor can I inherit from defaultdic, so I decided to write a class and redirect calls to it to the type I want to extend. class BagOfWordDoc(): def __init__(self): self.data = collections.defaultdict(lambda: 1) for method in dir(self.data): if hasattr(getattr(self.data, method),'__call__') and method not in ['__class__', '__self__']: l = lambda *args: getattr(self.data, method)(*args) setattr(self, method,l) def vocabulary(self): return self.data.keys() def wordcount(self): return reduce(operator.add, self.data.values(), 0) However it shows upon accessing it doc = BagOfWordDoc() doc[123] = 123 # yields TypeError: values() takes no arguments (1 given) doc.keys() # yields TypeError: values() takes no arguments (1 given) doc.xxx() # yields TypeError: values() takes no arguments (1 given) So it'is as if every lambda was mapped to the 'values' function And 'values' is the last element of the property list Do you know why this happens ? As for the initial problem, I am now thinking of rewriting my own defaultdict. update Based on the suggestion made, hereis the working implementation : class BagOfWordDoc(): def __init__(self): self.data = collections.defaultdict(lambda: 0) def __getattr__(self, *args): return self.data.__getattribute__(*args) def vocabulary(self): return self.data.keys() def wordcount(self): return reduce(operator.add, self.data.values(), 0) A: Either copy from class to class, not instance to instance, or just have .__getattr__() delegate to the encapsulated object. A: What do you mean with "cannot inherit from defaultdict"? It works for me (not a very good example, but I'm not sure what you're trying to accomplish, so...): #!/usr/bin/env python from collections import defaultdict import operator class DD(defaultdict): def vocabulary(self): return self.keys() def wordcount(self): return reduce(operator.add, self.data.itervalues(), 0) if __name__ == '__main__': dd = DD(int) dd[2] += 1 print dd.vocabulary()
Redirect calls to a member of a class in python
I was trying to 'extend' a closed class collections.defaultdict(lambda: 1) by addint it 2 methods, called 'vocabulary', and 'wordcount' apparently it's impossible to setattr method to builin types, nor can I inherit from defaultdic, so I decided to write a class and redirect calls to it to the type I want to extend. class BagOfWordDoc(): def __init__(self): self.data = collections.defaultdict(lambda: 1) for method in dir(self.data): if hasattr(getattr(self.data, method),'__call__') and method not in ['__class__', '__self__']: l = lambda *args: getattr(self.data, method)(*args) setattr(self, method,l) def vocabulary(self): return self.data.keys() def wordcount(self): return reduce(operator.add, self.data.values(), 0) However it shows upon accessing it doc = BagOfWordDoc() doc[123] = 123 # yields TypeError: values() takes no arguments (1 given) doc.keys() # yields TypeError: values() takes no arguments (1 given) doc.xxx() # yields TypeError: values() takes no arguments (1 given) So it'is as if every lambda was mapped to the 'values' function And 'values' is the last element of the property list Do you know why this happens ? As for the initial problem, I am now thinking of rewriting my own defaultdict. update Based on the suggestion made, hereis the working implementation : class BagOfWordDoc(): def __init__(self): self.data = collections.defaultdict(lambda: 0) def __getattr__(self, *args): return self.data.__getattribute__(*args) def vocabulary(self): return self.data.keys() def wordcount(self): return reduce(operator.add, self.data.values(), 0)
[ "Either copy from class to class, not instance to instance, or just have .__getattr__() delegate to the encapsulated object.\n", "What do you mean with \"cannot inherit from defaultdict\"? It works for me (not a very good example, but I'm not sure what you're trying to accomplish, so...):\n#!/usr/bin/env python\n\n\nfrom collections import defaultdict\nimport operator\n\n\nclass DD(defaultdict):\n\n def vocabulary(self):\n return self.keys()\n\n def wordcount(self):\n return reduce(operator.add, self.data.itervalues(), 0)\n\n\nif __name__ == '__main__':\n dd = DD(int)\n\n dd[2] += 1\n print dd.vocabulary()\n\n" ]
[ 4, 1 ]
[]
[]
[ "functional_programming", "metaprogramming", "python" ]
stackoverflow_0002171396_functional_programming_metaprogramming_python.txt
Q: python-tz am I wrong or it's a bug It's a bit weird it seems that when I want to get a timezone for Europe/Paris with pytz it gets me to the PMT timezone instead of GMT+1 when it seems to work for Europe/Berlin. Not clear ? Well look at this snippet : #!/usr/bin/python import os import datetime from pytz.tzfile import build_tzinfo base='/usr/share/zoneinfo/' tz = build_tzinfo('Europe/Paris', open(os.path.join(base,'Europe','Paris'), 'rb')) fmt = '%Y-%m-%d %H:%M:%S %Z%z' print datetime.datetime(2009, 01, 30, 9, 00, tzinfo=tz).strftime(fmt) tz = build_tzinfo('Europe/Berlin', open(os.path.join(base,'Europe','Berlin'), 'rb')) print datetime.datetime(2009, 01, 30, 9, 00, tzinfo=tz).strftime(fmt) the output is : 2009-01-30 09:00:00 PMT+0009 2009-01-30 09:00:00 CET+0100 when really paris should be as well CET+1. Constructing from datetime.datetime.now(tz) would get the thing right no matter what. Anybody have an idea ? A: The docs say you can't use datetime.datetime(..., tzinfo) like you're doing: Unfortunately using the tzinfo argument of the standard datetime constructors does not work with pytz for many timezones. And curiously, despite all signs that the Europe/Paris timezone is wrong, when you actually use with localize as it recommends, it works nonetheless: >>> tz= pytz.timezone('Europe/Paris') # using built-in zoneinfo >>> tz <DstTzInfo 'Europe/Paris' PMT+0:09:00 STD> # what? Pierre et Miquelon Time? >>> datetime.datetime(2010,1,1,12,0,0, tzinfo=tz) datetime.datetime(2010, 1, 1, 12, 0, tzinfo=<DstTzInfo 'Europe/Paris' PMT+0:09:00 STD>) # bad >>> tz.localize(datetime.datetime(2010,1,1,12,0,0)) datetime.datetime(2010, 1, 1, 12, 0, tzinfo=<DstTzInfo 'Europe/Paris' CET+1:00:00 STD>) # OK Note that the tzinfo property of the localized datetime references a completely different object to the tz it was created from, sharing only the name. It's a mystery to me why this is happening. It seems to be a problem with city files that understand multiple timezone names, but why you don't get the default timezone for a city until you call localize, I've no idea. (To be honest I've never trusted Python's datetime and tzinfo stuff. Much prefer working with int UTC timestamps.)
python-tz am I wrong or it's a bug
It's a bit weird it seems that when I want to get a timezone for Europe/Paris with pytz it gets me to the PMT timezone instead of GMT+1 when it seems to work for Europe/Berlin. Not clear ? Well look at this snippet : #!/usr/bin/python import os import datetime from pytz.tzfile import build_tzinfo base='/usr/share/zoneinfo/' tz = build_tzinfo('Europe/Paris', open(os.path.join(base,'Europe','Paris'), 'rb')) fmt = '%Y-%m-%d %H:%M:%S %Z%z' print datetime.datetime(2009, 01, 30, 9, 00, tzinfo=tz).strftime(fmt) tz = build_tzinfo('Europe/Berlin', open(os.path.join(base,'Europe','Berlin'), 'rb')) print datetime.datetime(2009, 01, 30, 9, 00, tzinfo=tz).strftime(fmt) the output is : 2009-01-30 09:00:00 PMT+0009 2009-01-30 09:00:00 CET+0100 when really paris should be as well CET+1. Constructing from datetime.datetime.now(tz) would get the thing right no matter what. Anybody have an idea ?
[ "The docs say you can't use datetime.datetime(..., tzinfo) like you're doing:\n\nUnfortunately using the tzinfo argument of the standard datetime constructors does not work with pytz for many timezones.\n\nAnd curiously, despite all signs that the Europe/Paris timezone is wrong, when you actually use with localize as it recommends, it works nonetheless:\n>>> tz= pytz.timezone('Europe/Paris') # using built-in zoneinfo\n>>> tz\n<DstTzInfo 'Europe/Paris' PMT+0:09:00 STD> # what? Pierre et Miquelon Time?\n>>> datetime.datetime(2010,1,1,12,0,0, tzinfo=tz)\ndatetime.datetime(2010, 1, 1, 12, 0, tzinfo=<DstTzInfo 'Europe/Paris' PMT+0:09:00 STD>) # bad\n>>> tz.localize(datetime.datetime(2010,1,1,12,0,0))\ndatetime.datetime(2010, 1, 1, 12, 0, tzinfo=<DstTzInfo 'Europe/Paris' CET+1:00:00 STD>) # OK\n\nNote that the tzinfo property of the localized datetime references a completely different object to the tz it was created from, sharing only the name.\nIt's a mystery to me why this is happening. It seems to be a problem with city files that understand multiple timezone names, but why you don't get the default timezone for a city until you call localize, I've no idea.\n(To be honest I've never trusted Python's datetime and tzinfo stuff. Much prefer working with int UTC timestamps.)\n" ]
[ 6 ]
[]
[]
[ "python", "timezone" ]
stackoverflow_0002171189_python_timezone.txt
Q: how to wait for a pause in user input in a gtk.TextBuffer? I'm trying to write a simple gui-based application in pygtk which provides 'live' previewing of text-based markup. The markup processing, however, can be quite computationally expensive and slow to run, so updating the preview on every keystroke is not really viable. Instead I'd like to have the update run only when user input lapses. Ideally, I'd have it update a specified interval after the last keystroke in a sequence. I've looked into using threading.Timer, by cancelling and re-starting a timer to invoke the update function each time the "changed" signal is emitted. I've also tried to use gtk.idle_add(), but I can't seem to get it working. Below is a very simple example - could someone suggest the best strategy to achieve what I'm after, preferably with an example? import gtk class example: def __init__(self): window = gtk.Window() window.set_title("example") window.resize(600,400) box = gtk.HBox(homogeneous = True, spacing = 2) buf = gtk.TextBuffer() buf.connect("changed", self.buf_on_change) textInput = gtk.TextView(buf) box.add(textInput) self.lbl = gtk.Label() box.add(self.lbl) window.add(box) window.connect("destroy", gtk.main_quit) window.show_all() def buf_on_change(self, buf): txt = buf.get_text(*buf.get_bounds()) output = self.renderText(txt) self.lbl.set_text(output) def renderText(self, txt): # perform computation-intensive text-manipulation here output = txt return output if __name__ == '__main__': example() gtk.main() A: so I think I found a solution using glib.timeout_add() instead of threading.Timer: import gtk, glib class example: def __init__(self): window = gtk.Window() window.set_title("example") window.resize(600,400) box = gtk.HBox(homogeneous = True, spacing = 2) self.buf = gtk.TextBuffer() self.buf.connect("changed", self.buf_on_change) textInput = gtk.TextView(self.buf) box.add(textInput) self.lbl = gtk.Label() box.add(self.lbl) window.add(box) window.connect("destroy", gtk.main_quit) window.show_all() self.timer = glib.timeout_add(1000, self.renderText) def buf_on_change(self, buf): glib.source_remove(self.timer) self.timer = glib.timeout_add(1000, self.renderText) def renderText(self): txt = self.buf.get_text(*self.buf.get_bounds()) # perform computation-intensive text-manipulation here self.lbl.set_text(txt) return False if __name__ == '__main__': example() gtk.main() this seems to work as desired, but since I'm completely new to gtk (and desktop dui programming in general - in case you couldn't tell ;) ) I'd like to leave this question open in the hope that someone more experience might comment on the best way to achieve this kind of effect. I hope that's okay? A: So i did not have pygtk, so i mimiced your problem using termios and a home made loop for the text input. But the part about the timer should work in gtk too. Please note that the access to the self.timer is not thread safe if you use an object of class example within more than one thread at the time you must lock self.txt and self.timer. import termios, fcntl, sys, os, time, threading fd = sys.stdin.fileno() #just setting up the terminal input oldterm = termios.tcgetattr(fd) newattr = termios.tcgetattr(fd) newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO termios.tcsetattr(fd, termios.TCSANOW, newattr) oldflags = fcntl.fcntl(fd, fcntl.F_GETFL) fcntl.fcntl(fd, fcntl.F_SETFL, oldflags | os.O_NONBLOCK) class example: def __init__(self, timeout): self.timeout = timeout self.timer = threading.Timer(timeout, self.render_text) self.txt = '' self.timer.start() #at the end of __init__ def buf_on_change(self, buf): print "Got buffer:", buf, time.ctime() self.txt = self.txt + buf self.timer.cancel() #won't do no harm if timer already elapsed self.timer = threading.Timer(self.timeout, self.render_text) self.timer.start() def render_text(self): print "starting intensive computation" print "rendering", self.txt time.sleep(3) print "stopping intensive computation" # just my poor mans event loop for the text input obj = example(3) try: while 1: time.sleep(0.001) #just to keep processor cool try: buf = sys.stdin.read(5) obj.buf_on_change(buf) except IOError: pass finally: termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm) fcntl.fcntl(fd, fcntl.F_SETFL, oldflags)
how to wait for a pause in user input in a gtk.TextBuffer?
I'm trying to write a simple gui-based application in pygtk which provides 'live' previewing of text-based markup. The markup processing, however, can be quite computationally expensive and slow to run, so updating the preview on every keystroke is not really viable. Instead I'd like to have the update run only when user input lapses. Ideally, I'd have it update a specified interval after the last keystroke in a sequence. I've looked into using threading.Timer, by cancelling and re-starting a timer to invoke the update function each time the "changed" signal is emitted. I've also tried to use gtk.idle_add(), but I can't seem to get it working. Below is a very simple example - could someone suggest the best strategy to achieve what I'm after, preferably with an example? import gtk class example: def __init__(self): window = gtk.Window() window.set_title("example") window.resize(600,400) box = gtk.HBox(homogeneous = True, spacing = 2) buf = gtk.TextBuffer() buf.connect("changed", self.buf_on_change) textInput = gtk.TextView(buf) box.add(textInput) self.lbl = gtk.Label() box.add(self.lbl) window.add(box) window.connect("destroy", gtk.main_quit) window.show_all() def buf_on_change(self, buf): txt = buf.get_text(*buf.get_bounds()) output = self.renderText(txt) self.lbl.set_text(output) def renderText(self, txt): # perform computation-intensive text-manipulation here output = txt return output if __name__ == '__main__': example() gtk.main()
[ "so I think I found a solution using glib.timeout_add() instead of threading.Timer:\nimport gtk, glib\n\nclass example:\n def __init__(self):\n window = gtk.Window()\n window.set_title(\"example\")\n window.resize(600,400)\n box = gtk.HBox(homogeneous = True, spacing = 2)\n self.buf = gtk.TextBuffer()\n self.buf.connect(\"changed\", self.buf_on_change)\n textInput = gtk.TextView(self.buf)\n box.add(textInput)\n self.lbl = gtk.Label()\n box.add(self.lbl)\n window.add(box)\n window.connect(\"destroy\", gtk.main_quit)\n window.show_all()\n\n self.timer = glib.timeout_add(1000, self.renderText)\n\n def buf_on_change(self, buf):\n glib.source_remove(self.timer)\n self.timer = glib.timeout_add(1000, self.renderText)\n\n\n def renderText(self):\n txt = self.buf.get_text(*self.buf.get_bounds())\n # perform computation-intensive text-manipulation here\n self.lbl.set_text(txt)\n return False\n\nif __name__ == '__main__':\n example()\n gtk.main()\n\nthis seems to work as desired, but since I'm completely new to gtk (and desktop dui programming in general - in case you couldn't tell ;) ) I'd like to leave this question open in the hope that someone more experience might comment on the best way to achieve this kind of effect. I hope that's okay?\n", "So i did not have pygtk, so i mimiced your problem using termios and a home made loop for the text input. But the part about the timer should work in gtk too. Please note that the access to the self.timer is not thread safe if you use an object of class example within more than one thread at the time you must lock self.txt and self.timer.\nimport termios, fcntl, sys, os, time, threading\nfd = sys.stdin.fileno()\n\n#just setting up the terminal input\noldterm = termios.tcgetattr(fd)\nnewattr = termios.tcgetattr(fd)\nnewattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO\ntermios.tcsetattr(fd, termios.TCSANOW, newattr)\noldflags = fcntl.fcntl(fd, fcntl.F_GETFL)\nfcntl.fcntl(fd, fcntl.F_SETFL, oldflags | os.O_NONBLOCK)\n\n\nclass example:\n def __init__(self, timeout):\n self.timeout = timeout\n self.timer = threading.Timer(timeout, self.render_text)\n self.txt = ''\n self.timer.start() #at the end of __init__ \n\n def buf_on_change(self, buf):\n print \"Got buffer:\", buf, time.ctime()\n self.txt = self.txt + buf\n self.timer.cancel() #won't do no harm if timer already elapsed\n self.timer = threading.Timer(self.timeout, self.render_text)\n self.timer.start()\n\n def render_text(self):\n print \"starting intensive computation\"\n print \"rendering\", self.txt\n time.sleep(3)\n print \"stopping intensive computation\"\n\n\n# just my poor mans event loop for the text input\nobj = example(3)\ntry:\n while 1:\n time.sleep(0.001) #just to keep processor cool\n try:\n buf = sys.stdin.read(5)\n obj.buf_on_change(buf)\n except IOError: pass\nfinally:\n termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm)\n fcntl.fcntl(fd, fcntl.F_SETFL, oldflags)\n\n" ]
[ 1, 0 ]
[]
[]
[ "gtk", "pygtk", "python" ]
stackoverflow_0002170851_gtk_pygtk_python.txt
Q: How to implement a client admin in Django? I'm building a simple app, a sort of project/tasks manager where I can have several projects and several tasks that are assigned to one project. I enabled Django admin for all this sort of tasks and it's working like a charm. Also, I have some users that have projects assigned to them. So what I want now is to enable a cut down version of the admin for those users, where: They can only manage/see tasks within their own project. They can only delete their own tasks some other minor restrictions. What would be the best approach to this? Should I create another app with custom views and pages for client editing tasks or should I drop another admin instance and fine-tune it just for them? I hope it was clear and not too subjective. Thanks. A: +1 for custom app, hacking admin can take more time than just putting together your own admin from generic views. A: I think that the best way to do this, either way, would be to somehow implement row-level permissions. At the moment, the best solution for this is probably using the django-granular-permissions. Like Dmitry I'm also for the custom app. Using generic views, modelforms et cetera will probably result in less work than modifying the admin app (which is not really made for hacking). Also, if you keep an eye to the future, should the need for some more complex feature/restriction arise, you'll have less problems.
How to implement a client admin in Django?
I'm building a simple app, a sort of project/tasks manager where I can have several projects and several tasks that are assigned to one project. I enabled Django admin for all this sort of tasks and it's working like a charm. Also, I have some users that have projects assigned to them. So what I want now is to enable a cut down version of the admin for those users, where: They can only manage/see tasks within their own project. They can only delete their own tasks some other minor restrictions. What would be the best approach to this? Should I create another app with custom views and pages for client editing tasks or should I drop another admin instance and fine-tune it just for them? I hope it was clear and not too subjective. Thanks.
[ "+1 for custom app, hacking admin can take more time than just putting together your own admin from generic views.\n", "I think that the best way to do this, either way, would be to somehow implement row-level permissions.\nAt the moment, the best solution for this is probably using the django-granular-permissions.\nLike Dmitry I'm also for the custom app. Using generic views, modelforms et cetera will probably result in less work than modifying the admin app (which is not really made for hacking). \nAlso, if you keep an eye to the future, should the need for some more complex feature/restriction arise, you'll have less problems.\n" ]
[ 3, 2 ]
[]
[]
[ "django", "django_admin", "python" ]
stackoverflow_0002171820_django_django_admin_python.txt
Q: python how to -generate license- using time module I'm searching for a way to generate a (limited time license) .so when a user starts the program . it has to check license date first before the program runs. but the problem is : i tried a couple of solutions . one of them is python's time.ctime , (to check time and see if it's realy during the license time) and it returns the time of the machine, so whenever a user want to use software without license he'll just change time of the machine. i hope the idea is clear enough any better ideas? please inform me if you want more explanation A: Regardless with the question whether or not this hassle is really worth the effort, you can check access times of ubiquitous files (e.g. /etc/passwd in Linux) and compare these to the current date. If you see that the files have been accessed/modified in the future, you know that there is a problem. Again, at least in *nix, a user may substitute system's stat, so that it "massages" the info you are looking at. A: You could get the time from an external source via Internet: Python Getting date online? Of course, this will only work if the user doesn't block your program from accessing the internet. And what should your program do when it can't access the internet? Refuse to run? I doubt that this is a good idea. A: Nearly every standard function will return the machine time that can be adjusted by the user. One possibility is to call a web service that returns the "correct" time. But this is only possible if you can assume internet access. And may be should ask your self the question if that hassle is really worth the effort?
python how to -generate license- using time module
I'm searching for a way to generate a (limited time license) .so when a user starts the program . it has to check license date first before the program runs. but the problem is : i tried a couple of solutions . one of them is python's time.ctime , (to check time and see if it's realy during the license time) and it returns the time of the machine, so whenever a user want to use software without license he'll just change time of the machine. i hope the idea is clear enough any better ideas? please inform me if you want more explanation
[ "Regardless with the question whether or not this hassle is really worth the effort, you can check access times of ubiquitous files (e.g. /etc/passwd in Linux) and compare these to the current date. If you see that the files have been accessed/modified in the future, you know that there is a problem. Again, at least in *nix, a user may substitute system's stat, so that it \"massages\" the info you are looking at. \n", "You could get the time from an external source via Internet: Python Getting date online?\nOf course, this will only work if the user doesn't block your program from accessing the internet. And what should your program do when it can't access the internet? Refuse to run? I doubt that this is a good idea.\n", "Nearly every standard function will return the machine time that can be adjusted by the user.\nOne possibility is to call a web service that returns the \"correct\" time. But this is only possible if you can assume internet access.\nAnd may be should ask your self the question if that hassle is really worth the effort?\n" ]
[ 3, 1, 0 ]
[]
[]
[ "datetime", "licensing", "python", "time" ]
stackoverflow_0002171902_datetime_licensing_python_time.txt
Q: Python regex for matching bb code I'm writing a very simple bbcode parse. If i want to replace hello i'm a [b]bold[/b] text, i have success with replacing this regex r'\[b\](.*)\[\/b\]' with this <strong>\g<1></strong> to get hello, i'm a <strong>bold</strong> text. If I have two or more tags of the same type, it fails. eg: i'm [b]bold[/b] and i'm [b]bold[/b] too gives i'm <strong>bold[/b] and i'm [b]bold</strong> too How to solve the problem? Thanks A: You shouldn't use regular expressions to parse non-regular languages (like matching tags). Look into a parser instead. Edit - a quick Google search takes me here. A: Just change your regular expression from: r'\[b\](.*)\[\/b\]' to r'\[b\](.*?)\[\/b\]' The * qualifier is greedy, appending a ? to it you make it performing as a non-greedy qualifier. Here's a more complete explaination taken from the python re documentation: The '*', '+', and '?' qualifiers are all greedy; they match as much text as possible. Sometimes this behaviour isn’t desired; if the RE <.*> is matched against '<H1>title</H1>', it will match the entire string, and not just '<H1>'. Adding '?' after the qualifier makes it perform the match in non-greedy or minimal fashion; as few characters as possible will be matched. Using .*? in the previous expression will match only '<H1>'. Source: http://docs.python.org/library/re.html
Python regex for matching bb code
I'm writing a very simple bbcode parse. If i want to replace hello i'm a [b]bold[/b] text, i have success with replacing this regex r'\[b\](.*)\[\/b\]' with this <strong>\g<1></strong> to get hello, i'm a <strong>bold</strong> text. If I have two or more tags of the same type, it fails. eg: i'm [b]bold[/b] and i'm [b]bold[/b] too gives i'm <strong>bold[/b] and i'm [b]bold</strong> too How to solve the problem? Thanks
[ "You shouldn't use regular expressions to parse non-regular languages (like matching tags). Look into a parser instead.\nEdit - a quick Google search takes me here.\n", "Just change your regular expression from:\nr'\\[b\\](.*)\\[\\/b\\]'\n\nto\nr'\\[b\\](.*?)\\[\\/b\\]'\n\nThe * qualifier is greedy, appending a ? to it you make it performing as a non-greedy qualifier.\nHere's a more complete explaination taken from the python re documentation:\n\nThe '*', '+', and '?' qualifiers are\n all greedy; they match as much text as\n possible. Sometimes this behaviour\n isn’t desired; if the RE <.*> is\n matched against '<H1>title</H1>', it\n will match the entire string, and not\n just '<H1>'. Adding '?' after the\n qualifier makes it perform the match\n in non-greedy or minimal fashion; as\n few characters as possible will be\n matched. Using .*? in the previous\n expression will match only '<H1>'.\nSource: http://docs.python.org/library/re.html\n\n" ]
[ 7, 5 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0002172046_python_regex.txt
Q: draw hebrew text to an image using Image module (python) I am trying to use Image module in order to make bitmaps with hebrew lettering in it. when printing from the shell (idle) I managed to print hebrew, but when trying to draw text to a bitmap it draws some ascii lettering. this is the code: import Image import ImageDraw a = "אריאל" #or any other hebrew string im=Image.new('RGB',(200,200),(100,100,100)) #type file,size,Background color d=ImageDraw.Draw(im) d.text((0,0),a) #should draw the string im.show() any help will be very appreciated. A: Try a = u"אריאל". Failing that, try PyCairo. It has advanced typography handling that may work better. A: This site mentions that to draw Chinese text, they had to specify that the string was unicode, so you should do the same, e.g. a = u"אריאל" #like this a = unicode("אריאל", "UTF-8") #or like this They also specified a font. Is there an appropriate one for Hebrew? e.g.: font = ImageFont.truetype('simsun.ttc',24) and then specify that font when drawing text, e.g.: d.text( (0,0), a, font=font) I think your code is drawing an ascii string (and Hebrew is faaaaar away from ascii) in the wrong font.
draw hebrew text to an image using Image module (python)
I am trying to use Image module in order to make bitmaps with hebrew lettering in it. when printing from the shell (idle) I managed to print hebrew, but when trying to draw text to a bitmap it draws some ascii lettering. this is the code: import Image import ImageDraw a = "אריאל" #or any other hebrew string im=Image.new('RGB',(200,200),(100,100,100)) #type file,size,Background color d=ImageDraw.Draw(im) d.text((0,0),a) #should draw the string im.show() any help will be very appreciated.
[ "Try a = u\"אריאל\".\nFailing that, try PyCairo. It has advanced typography handling that may work better.\n", "This site mentions that to draw Chinese text, they had to specify that the string was unicode, so you should do the same, e.g.\na = u\"אריאל\" #like this\na = unicode(\"אריאל\", \"UTF-8\") #or like this\n\nThey also specified a font. Is there an appropriate one for Hebrew? e.g.:\nfont = ImageFont.truetype('simsun.ttc',24)\n\nand then specify that font when drawing text, e.g.:\nd.text( (0,0), a, font=font)\n\nI think your code is drawing an ascii string (and Hebrew is faaaaar away from ascii) in the wrong font.\n" ]
[ 1, 1 ]
[]
[]
[ "draw", "image", "python" ]
stackoverflow_0002171910_draw_image_python.txt
Q: problem with breadth first tree generation i have a problem with breadth first algorithm, my script generates curves in maya, position them, rotate and scale them so they give me the tree shape, i have these variables cs=current State, p=parent, nodes=non visited node List lvl=current depth maxlvl= max depth the problem is that i cant determine current depth, and terminate the tree there, it exists without all nodes being visited here is my script import random import math import maya.cmds as mc #----define set----- #--- curve, #children,angle,l-------- #----define rule---- # l=80% ch<=3 angle<=45 l=0.8 ch=6 ang=50 #---list to track---- nodes=[] #--- begin----- #---start curve----- nodes.append(mc.curve(n="a",d=3,p=((0,0,0),(0,1,0),(0,3,0),(0,5,0),(0,6,0)),k=(0,0,0,1,2,2,2))) cs="" #---current state---- p="a" #---paretn of the current state---- maxlvl=6 #--max depth for the tree lvl=1 #-- cuurent level---- while (len(nodes)!=0 and lvl<5): #---generate children number---- chN=random.randint(0,ch) for j in range(chN): #----generate node---- mc.select(p,r=1) cs=mc.duplicate(rr=1)[0] #---append to node lst---- nodes.append(cs) #---adjust pos--- pos=mc.pointPosition(p+".cv[4]") mc.xform(cs,t=(pos[0],pos[1],pos[2]),ws=1) #---adjust rotation--- mc.rotate(0,0,(random.random()*45+5)*math.pow(-1,j%2),cs,r=1) #---adjust scale--- mc.scale(0,math.pow(0.8,lvl),0,cs) j+=1 #--- go to next parent--- nodes.pop(0) if nodes: p=nodes[0] lvl+=1 thank you in advance A: You need to associate the depth with each node. Either put it as a member in the node class, or have your queue entries store both depth and node like this: nodes.append((1, firstNode)) while nodes and lvl<5: lvl, p = nodes.pop(0) For each child: #...create child nodes.append((lvl+1, cs)) Some unrelated notes: Use collections.deque instead of list: It's faster for FIFO queues. The j+=1 statement is unnecessary in the for loop.
problem with breadth first tree generation
i have a problem with breadth first algorithm, my script generates curves in maya, position them, rotate and scale them so they give me the tree shape, i have these variables cs=current State, p=parent, nodes=non visited node List lvl=current depth maxlvl= max depth the problem is that i cant determine current depth, and terminate the tree there, it exists without all nodes being visited here is my script import random import math import maya.cmds as mc #----define set----- #--- curve, #children,angle,l-------- #----define rule---- # l=80% ch<=3 angle<=45 l=0.8 ch=6 ang=50 #---list to track---- nodes=[] #--- begin----- #---start curve----- nodes.append(mc.curve(n="a",d=3,p=((0,0,0),(0,1,0),(0,3,0),(0,5,0),(0,6,0)),k=(0,0,0,1,2,2,2))) cs="" #---current state---- p="a" #---paretn of the current state---- maxlvl=6 #--max depth for the tree lvl=1 #-- cuurent level---- while (len(nodes)!=0 and lvl<5): #---generate children number---- chN=random.randint(0,ch) for j in range(chN): #----generate node---- mc.select(p,r=1) cs=mc.duplicate(rr=1)[0] #---append to node lst---- nodes.append(cs) #---adjust pos--- pos=mc.pointPosition(p+".cv[4]") mc.xform(cs,t=(pos[0],pos[1],pos[2]),ws=1) #---adjust rotation--- mc.rotate(0,0,(random.random()*45+5)*math.pow(-1,j%2),cs,r=1) #---adjust scale--- mc.scale(0,math.pow(0.8,lvl),0,cs) j+=1 #--- go to next parent--- nodes.pop(0) if nodes: p=nodes[0] lvl+=1 thank you in advance
[ "You need to associate the depth with each node. Either put it as a member in the node class, or have your queue entries store both depth and node like this:\nnodes.append((1, firstNode))\nwhile nodes and lvl<5:\n lvl, p = nodes.pop(0)\n\n For each child:\n #...create child\n nodes.append((lvl+1, cs))\n\nSome unrelated notes:\n\nUse collections.deque instead of list: It's faster for FIFO queues.\nThe j+=1 statement is unnecessary in the for loop.\n\n" ]
[ 4 ]
[]
[]
[ "breadth_first_search", "python", "tree" ]
stackoverflow_0002171733_breadth_first_search_python_tree.txt
Q: Parsing forwarded emails I'm writing some code to parse forwarded emails. What I'm not sure is if maybe there is some Python library, some RFC I could stick to or some other resource that would allow me to automate the task. To be precise, I don't know if the "layout" of forwarded emails is covered by some standard or recommendation, or if it has just evolved over the years so now most email clients produce similar output for the text part: Begin forwarded message: > From: Me <me@me.me> > Date: January 30, 2010 18:26:33 PM GMT+02:00 > To: Other Me <other-me@me.me> > Subject: Unwise question -- and go wild for attachments (and whatever other MIME sections can be there). If it's still not precise enough I'll clarify it, it's just that I'm not 100% sure what to ask about (RFC, Python lib, convention or something else). A: Unlike what many other people said, there is a standard on forwarded emails, RFC 2046, "Multipurpose Internet Mail Extensions (MIME) Part Two: Media Types", more than ten years old. See specially its section 5.2, "Message Media Type". The basic idea behind RFC 2046 is to encapsulate one message into the MIME part of another, of type named (unfortunately) message/rfc822 (never forget that MIME is recursive). The MIME library of Python can handle it fine. I did not downvote the other answers because they are right in one respect: the standard is not followed by every mailer. For instance, the mutt mailer can forward a message in RFC 2046 format but also in a adhoc format. So, in practice, a mailer probably cannot handle only RFC 2046, it also has to parse the various others and underspecified syntaxes. A: In my experience just about ever email client forwards/replies differently. Typically you'll have a plain text version and a html encoded version in the mime at the bottom of the mail pack. Mail headers do have a RFC (http://www.faqs.org/rfcs/rfc2822.html "2822"), but unfortunately the content of the message body is out side the scope. Not only do you have to contend with the mail client variance, but the variance of user preferences. As an example: Lotus Notes puts replies at the top and Thunderbird replies at the bottom. So when a Thunderbird user is replying to a Lotus Notes user's reply they might insert their reply at the top and leave their signature at the bottom. Another pitfall maybe contending with word wrapping of replied chains. >>>> The outer reply that goes over the limit and is word wraped by the middle replier's mail client\n >> The message body of a middle reply > Previous reply Newest reply I wouldn't parse the message and leave it to the user to parse in their heads. Or, I'd borrow the code from another project. A: As the other answers already indicate: there is no standard, and your program is not going to be flawless. You could have a look at the headers, in particular the User-Agent header, to see what kind of client was used, and code specifically for the most common clients. To find out what clients you should consider to support, have a look at this popularity study. Various Outlooks, Yahoo!, Hotmail, Mail.app, iPhone mail, Gmail and Lotus Notes rank highly. About 11% of the mail is classified as "undetectable", but using headers from the forwarded e-mail you might be able to do better than that. Note that the statistics were gathered by placing an image inside the e-mail, so results may be skewed. Another problem is HTML mail, which may or may not include a plain-text version. I'm not sure about clients' usual behaviour in this respect. A: Standard for a reply/forward is > prepending each line the number of times the mail is nested including who sent the initial e-mail is up to the client to sort out. So what you need to do in python is simply add > to the start of each line. imap Test <imap@gazler.com> Wrote: > >twice >imap Test wrote: >> nested >> >> imap@gazler.com wrote: >>> test >>> >>> -- >>> Message sent via AHEM. >>> >> > Attachments just simply need to be attached to the message or as you put it 'go wild.' I am not familiar with python, but believe the code would be: string = string.replace("\n","\n>")
Parsing forwarded emails
I'm writing some code to parse forwarded emails. What I'm not sure is if maybe there is some Python library, some RFC I could stick to or some other resource that would allow me to automate the task. To be precise, I don't know if the "layout" of forwarded emails is covered by some standard or recommendation, or if it has just evolved over the years so now most email clients produce similar output for the text part: Begin forwarded message: > From: Me <me@me.me> > Date: January 30, 2010 18:26:33 PM GMT+02:00 > To: Other Me <other-me@me.me> > Subject: Unwise question -- and go wild for attachments (and whatever other MIME sections can be there). If it's still not precise enough I'll clarify it, it's just that I'm not 100% sure what to ask about (RFC, Python lib, convention or something else).
[ "Unlike what many other people said, there is a standard on forwarded emails, RFC 2046, \"Multipurpose Internet Mail Extensions (MIME) Part Two: Media Types\", more than ten years old. See specially its section 5.2, \"Message Media Type\".\nThe basic idea behind RFC 2046 is to encapsulate one message into the MIME part of another, of type named (unfortunately) message/rfc822 (never forget that MIME is recursive). The MIME library of Python can handle it fine.\nI did not downvote the other answers because they are right in one respect: the standard is not followed by every mailer. For instance, the mutt mailer can forward a message in RFC 2046 format but also in a adhoc format. So, in practice, a mailer probably cannot handle only RFC 2046, it also has to parse the various others and underspecified syntaxes.\n", "In my experience just about ever email client forwards/replies differently. Typically you'll have a plain text version and a html encoded version in the mime at the bottom of the mail pack. Mail headers do have a RFC (http://www.faqs.org/rfcs/rfc2822.html \"2822\"), but unfortunately the content of the message body is out side the scope.\nNot only do you have to contend with the mail client variance, but the variance of user preferences. As an example: Lotus Notes puts replies at the top and Thunderbird replies at the bottom. So when a Thunderbird user is replying to a Lotus Notes user's reply they might insert their reply at the top and leave their signature at the bottom.\nAnother pitfall maybe contending with word wrapping of replied chains.\n>>>> The outer reply that goes over the limit and is word wraped by\nthe middle replier's mail client\\n\n>> The message body of a middle reply\n> Previous reply\nNewest reply\nI wouldn't parse the message and leave it to the user to parse in their heads. Or, I'd borrow the code from another project.\n", "As the other answers already indicate: there is no standard, and your program is not going to be flawless.\nYou could have a look at the headers, in particular the User-Agent header, to see what kind of client was used, and code specifically for the most common clients.\nTo find out what clients you should consider to support, have a look at this popularity study. Various Outlooks, Yahoo!, Hotmail, Mail.app, iPhone mail, Gmail and Lotus Notes rank highly. About 11% of the mail is classified as \"undetectable\", but using headers from the forwarded e-mail you might be able to do better than that. Note that the statistics were gathered by placing an image inside the e-mail, so results may be skewed.\nAnother problem is HTML mail, which may or may not include a plain-text version. I'm not sure about clients' usual behaviour in this respect.\n", "Standard for a reply/forward is > prepending each line the number of times the mail is nested including who sent the initial e-mail is up to the client to sort out. So what you need to do in python is simply add > to the start of each line.\nimap Test <imap@gazler.com> Wrote:\n>\n>twice\n>imap Test wrote:\n>> nested\n>>\n>> imap@gazler.com wrote:\n>>> test\n>>>\n>>> -- \n>>> Message sent via AHEM.\n>>> \n>>\n>\n\nAttachments just simply need to be attached to the message or as you put it 'go wild.'\nI am not familiar with python, but believe the code would be:\nstring = string.replace(\"\\n\",\"\\n>\")\n\n" ]
[ 5, 2, 2, 1 ]
[]
[]
[ "python", "rfc" ]
stackoverflow_0002168719_python_rfc.txt
Q: How does len work? How does len work on Python? Look at this example: class INT(int): pass class STR(str): def __len__(self): return INT(42) q = STR('how').__len__() print q, type(q) q = len(STR('how')) print q, type(q) The output is: 42 <class '__main__.INT'> 42 <type 'int'> How can I handle it so len returns an INT instance? Answers suggest that the only solution is overriding len This is my alternative implementation. It doesn't seem very harmful. original_len = len def len(o): l = o.__len__() if isinstance(l, int): return l original_len(o) A: Do not do this. You need to learn when the best answer really is not to do what you are trying to do at all. This is one of those times. A: I don't think you can, unless you write your own len. The builtin len always return an int. A: You won't be able to. At least if you want it to work with the rest of python. See the definition of len Called to implement the built-in function len(). Should return the length of the object, an integer >= 0. Also, an object that doesn’t define a nonzero() method and whose len() method returns zero is considered to be false in a Boolean context. Italics emphasis mine. A: As others say, don't do this. Consider how usage of this class would look: length = len(s) # the reader assumes `q` is an int. length.in_yards() # the reader is going WTF?! Instead of violating the reader's expectations, why don't you just add a different method: s.length_in_yards() P.S. Doesn't solve this question, but if you have a good reason to write custom integer-like objects, you might be interested in the __index__ special method that allows such object to be directly usable for indexing built-in sequences.
How does len work?
How does len work on Python? Look at this example: class INT(int): pass class STR(str): def __len__(self): return INT(42) q = STR('how').__len__() print q, type(q) q = len(STR('how')) print q, type(q) The output is: 42 <class '__main__.INT'> 42 <type 'int'> How can I handle it so len returns an INT instance? Answers suggest that the only solution is overriding len This is my alternative implementation. It doesn't seem very harmful. original_len = len def len(o): l = o.__len__() if isinstance(l, int): return l original_len(o)
[ "Do not do this. You need to learn when the best answer really is not to do what you are trying to do at all. This is one of those times.\n", "I don't think you can, unless you write your own len.\nThe builtin len always return an int.\n", "You won't be able to. At least if you want it to work with the rest of python. See the definition of len\n\nCalled to implement the built-in\n function len(). Should return the\n length of the object, an integer >= 0.\n Also, an object that doesn’t define a\n nonzero() method and whose len() method returns zero is considered to be false in a Boolean\n context.\n\nItalics emphasis mine.\n", "As others say, don't do this. Consider how usage of this class would look:\nlength = len(s) # the reader assumes `q` is an int.\nlength.in_yards() # the reader is going WTF?!\n\nInstead of violating the reader's expectations, why don't you just add a different method:\ns.length_in_yards()\n\n\nP.S. Doesn't solve this question, but if you have a good reason to write custom integer-like objects, you might be interested in the __index__ special method that allows such object to be directly usable for indexing built-in sequences.\n" ]
[ 4, 3, 3, 3 ]
[]
[]
[ "python" ]
stackoverflow_0002171960_python.txt
Q: Best python UI package for simple graph simulations (TSP simulation, etc...) I've never done any UI programming in python before. What is the best (read most intuitive, easy to use, functional) UI package for python for doing simulations? I'll be doing a simulation of TSP right now. So I'll have a graph (nodes and edges) where the edges are rapidly changing, along with some selection boxes to choose different styles of the algorithm, choose the number of nodes, etc.. I've already written this code with a command line interface and I'm hoping for something pretty seamless to port in a gui :) A: I am not sure what you mean by "simulations" since the type of UI you want to do depends on what you simulate. But if you want to visualize graphs, networkx is pretty cool. A: Such a simulation could be easily coded using: networkx - for the graph data structures and algorithms matplotlib - which is used by networkx to visualize graphs Some GUI framework - PyQt, for instance, for the display and interaction with the user What's cool is that these can be learned and tried separately. networkx is very powerful and can provide anything you need graph-vise. It works well with matplotlib, and you can show the steps of TSP by different colorings of edges/nodes. matplotlib can also be easily integrated with PyQt to put it all into a single interactive program. A: Colleagues of mine are working on a similar-sounding setup to you - they use http://matplotlib.sourceforge.net/ and PyQt - PyQt can add a matplotlib object easily as a widget so the two integrate very well. A tutorial for PyQt is available here: http://www.zetcode.com/tutorials/pyqt4/ A: If you have graphs, you should definitely check out PyGraphviz (the interface is pretty similar to the aforementioned networkx)
Best python UI package for simple graph simulations (TSP simulation, etc...)
I've never done any UI programming in python before. What is the best (read most intuitive, easy to use, functional) UI package for python for doing simulations? I'll be doing a simulation of TSP right now. So I'll have a graph (nodes and edges) where the edges are rapidly changing, along with some selection boxes to choose different styles of the algorithm, choose the number of nodes, etc.. I've already written this code with a command line interface and I'm hoping for something pretty seamless to port in a gui :)
[ "I am not sure what you mean by \"simulations\" since the type of UI you want to do depends on what you simulate. But if you want to visualize graphs, networkx is pretty cool.\n", "Such a simulation could be easily coded using:\n\nnetworkx - for the graph data structures and algorithms\nmatplotlib - which is used by networkx to visualize graphs\nSome GUI framework - PyQt, for instance, for the display and interaction with the user\n\nWhat's cool is that these can be learned and tried separately. networkx is very powerful and can provide anything you need graph-vise. It works well with matplotlib, and you can show the steps of TSP by different colorings of edges/nodes. matplotlib can also be easily integrated with PyQt to put it all into a single interactive program.\n", "Colleagues of mine are working on a similar-sounding setup to you - they use http://matplotlib.sourceforge.net/ and PyQt - PyQt can add a matplotlib object easily as a widget so the two integrate very well. A tutorial for PyQt is available here: http://www.zetcode.com/tutorials/pyqt4/\n", "If you have graphs, you should definitely check out PyGraphviz (the interface is pretty similar to the aforementioned networkx)\n" ]
[ 3, 2, 1, 0 ]
[]
[]
[ "python", "user_interface" ]
stackoverflow_0002172302_python_user_interface.txt
Q: Why I can't extend bool in Python? >>> class BOOL(bool): ... print "why?" ... why? Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: Error when calling the metaclass bases type 'bool' is not an acceptable base type I thought Python trusted the programmer. A: Guido's take on it: I thought about this last night, and realized that you shouldn't be allowed to subclass bool at all! A subclass would only be useful when it has instances, but the mere existance of an instance of a subclass of bool would break the invariant that True and False are the only instances of bool! (An instance of a subclass of C is also an instance of C.) I think it's important not to provide a backdoor to create additional bool instances, so I think bool should not be subclassable. Reference: http://mail.python.org/pipermail/python-dev/2002-March/020822.html A: If you are using Python 3, and you want to have a class that can be evaluated as a boolean, but also contain other functionality, implement __bool__ in your class. In Python 2 the same effect can be achieved by implementing __nonzero__ or __len__ (if your class is a container). A: Since the OP mentions in a comment: I want 1 and 2 to return an instance of my class. I think it's important to point out that this is entirely impossible: Python does not let you alter built-in types (and, in particular, their special methods). Literal 1 will always be an instance of built-in type int, and in any case the basic semantics of the and operator are not overridable anyway -- a and b is always identical to b if a else a for any a and b (no bool coercion involved, even though the OP appears to mistakenly believe one is happening). Restating this crucial point: the value of a and b is always, unchangeably either a or b -- there is no way to break this semantic constraint (even if a and b were instances of your own peculiar classes -- even less so of course when they're constrained to be instances of Python's built-in int!-). A: Here is a post that explains the reasoning behind the decision: http://mail.python.org/pipermail/python-dev/2004-February/042537.html The idea is that bool has a specific purpose - to be True or to be False, and adding to that would only serve to complicate your code elsewhere. A: Because bool is supposed to only have two values -- True and False. If you were able to subclass bool, you could define arbitrary numbers of values for it, and that's definitely not what you want to happen. A better question is: why do you want to extend bool?
Why I can't extend bool in Python?
>>> class BOOL(bool): ... print "why?" ... why? Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: Error when calling the metaclass bases type 'bool' is not an acceptable base type I thought Python trusted the programmer.
[ "Guido's take on it:\n\nI thought about this last\n night, and realized that you shouldn't\n be allowed to subclass bool at all! A\n subclass would only be useful when it\n has instances, but the mere existance\n of an instance of a subclass of bool\n would break the invariant that True\n and False are the only instances of\n bool! (An instance of a subclass of C\n is also an instance of C.) I think\n it's important not to provide a\n backdoor to create additional bool\n instances, so I think bool should not\n be subclassable.\n\nReference: http://mail.python.org/pipermail/python-dev/2002-March/020822.html\n", "If you are using Python 3, and you want to have a class that can be evaluated as a boolean, but also contain other functionality, implement __bool__ in your class.\nIn Python 2 the same effect can be achieved by implementing __nonzero__ or __len__ (if your class is a container).\n", "Since the OP mentions in a comment:\n\nI want 1 and 2 to return an instance\n of my class.\n\nI think it's important to point out that this is entirely impossible: Python does not let you alter built-in types (and, in particular, their special methods). Literal 1 will always be an instance of built-in type int, and in any case the basic semantics of the and operator are not overridable anyway -- a and b is always identical to b if a else a for any a and b (no bool coercion involved, even though the OP appears to mistakenly believe one is happening).\nRestating this crucial point: the value of a and b is always, unchangeably either a or b -- there is no way to break this semantic constraint (even if a and b were instances of your own peculiar classes -- even less so of course when they're constrained to be instances of Python's built-in int!-).\n", "Here is a post that explains the reasoning behind the decision: http://mail.python.org/pipermail/python-dev/2004-February/042537.html\nThe idea is that bool has a specific purpose - to be True or to be False, and adding to that would only serve to complicate your code elsewhere.\n", "Because bool is supposed to only have two values -- True and False. If you were able to subclass bool, you could define arbitrary numbers of values for it, and that's definitely not what you want to happen.\nA better question is: why do you want to extend bool?\n" ]
[ 58, 12, 12, 9, 3 ]
[]
[]
[ "boolean", "python", "restriction" ]
stackoverflow_0002172189_boolean_python_restriction.txt
Q: Where is gsl_cdf_beta_Pinv() in PyGSL? I'm trying to use the distribution functions in a Python program (the random functions I've got figured out; I'm looking specifically for gsl_cdf_beta_Pinv()) and I can't find it. Can someone tell me how I can use these or a fast alternative in a program? Thanks, Mark Ch. A: It's defined in this Cython source file (for module probability_distribution) as being mediated by the method cum_distribution_function_inv of an instance of class RealDistribution when its self.distribution_type==beta. So you should import the module, instantiate the class, and then call the method -- e.g. from gsl import probability_distribution thebeta = probability_distribution.RealDistribution(type='beta', parameters=[alpha, beta]) print thebeta.cum_distribution_function_inv(0.1) I don't have a GSL installation at hand to test this code (so there might be some minor detail wrong here!) but I do hope this points you in the right direction.
Where is gsl_cdf_beta_Pinv() in PyGSL?
I'm trying to use the distribution functions in a Python program (the random functions I've got figured out; I'm looking specifically for gsl_cdf_beta_Pinv()) and I can't find it. Can someone tell me how I can use these or a fast alternative in a program? Thanks, Mark Ch.
[ "It's defined in this Cython source file (for module probability_distribution) as being mediated by the method cum_distribution_function_inv of an instance of class RealDistribution when its self.distribution_type==beta. So you should import the module, instantiate the class, and then call the method -- e.g.\nfrom gsl import probability_distribution\nthebeta = probability_distribution.RealDistribution(type='beta',\n parameters=[alpha, beta])\nprint thebeta.cum_distribution_function_inv(0.1)\n\nI don't have a GSL installation at hand to test this code (so there might be some minor detail wrong here!) but I do hope this points you in the right direction.\n" ]
[ 1 ]
[]
[]
[ "gsl", "pygsl", "python" ]
stackoverflow_0002172128_gsl_pygsl_python.txt
Q: How to do a JOIN in SQLAlchemy on 3 tables, where one of them is mapping between other two? Suppose I have the following tables: Articles with fields article_id, title Tags with fields tag_id, name ArticleTags with fields article_id, tag_id And I wish to find all articles that have a given tag. How do I create this complicated join in SQLAlchemy? In SQL it would look like: SELECT a.article_id, a.title FROM Articles AS a JOIN ArticleTags AS at ON a.article_id = at.article_id JOIN Tags AS t ON at.tag_id = t.tag_id WHERE t.name = 'tag_name' I can't figure out how to do it in SQLAlchemy. I am using ArticleTags as "secondary" table only and I can't figure out how to involve it in the JOIN. Can anyone help? Thanks, Boda Cydo. A: Assuming that you set the ForeignKey constraints correctly and created mappers: q = Session.query(Articles).filter(Articles.article_id == ArticleTags.article_id).\ filter(ArticleTags.tag_id == Tags.tag_id).\ filter(Tags.name == 'tag_name') If you have setup a Many-to-Many relation it's even more simple: q = Session.query(Articles).filter(Articles.tags.any(name = 'tag_name')) For some more examples for blog-related queries look here. If you use the sql expression language, it should be straight forward translateable.
How to do a JOIN in SQLAlchemy on 3 tables, where one of them is mapping between other two?
Suppose I have the following tables: Articles with fields article_id, title Tags with fields tag_id, name ArticleTags with fields article_id, tag_id And I wish to find all articles that have a given tag. How do I create this complicated join in SQLAlchemy? In SQL it would look like: SELECT a.article_id, a.title FROM Articles AS a JOIN ArticleTags AS at ON a.article_id = at.article_id JOIN Tags AS t ON at.tag_id = t.tag_id WHERE t.name = 'tag_name' I can't figure out how to do it in SQLAlchemy. I am using ArticleTags as "secondary" table only and I can't figure out how to involve it in the JOIN. Can anyone help? Thanks, Boda Cydo.
[ "Assuming that you set the ForeignKey constraints correctly and created mappers:\nq = Session.query(Articles).filter(Articles.article_id == ArticleTags.article_id).\\\n filter(ArticleTags.tag_id == Tags.tag_id).\\\n filter(Tags.name == 'tag_name')\n\nIf you have setup a Many-to-Many relation it's even more simple:\nq = Session.query(Articles).filter(Articles.tags.any(name = 'tag_name'))\n\nFor some more examples for blog-related queries look here.\nIf you use the sql expression language, it should be straight forward translateable.\n" ]
[ 9 ]
[]
[]
[ "python", "sql", "sqlalchemy" ]
stackoverflow_0002173031_python_sql_sqlalchemy.txt
Q: Is there any way to create a class property in Python? The following doesn't work for some reason: >>> class foo(object): ... @property ... @classmethod ... def bar(cls): ... return "asdf" ... >>> foo.bar <property object at 0x1da8d0> >>> foo.bar + '\n' Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unsupported operand type(s) for +: 'property' and 'str' Is there a way to do this, or is my only alternative to resort to some kind of metaclass trickery? A: If you want the descriptor property to trigger when you get an attribute from object X, then you must put the descriptor in type(X). So if X is a class, the descriptor must go in the class's type, also known as the class's metaclass -- no "trickery" involved, it's just a matter of completely general rules. Alternatively, you might write your own special-purpose descriptor. See here for an excellent "how-to" treaty on descriptors. Edit for example: class classprop(object): def __init__(self, f): self.f = classmethod(f) def __get__(self, *a): return self.f.__get__(*a)() class buh(object): @classprop def bah(cls): return 23 print buh.bah emits 23, as desired.
Is there any way to create a class property in Python?
The following doesn't work for some reason: >>> class foo(object): ... @property ... @classmethod ... def bar(cls): ... return "asdf" ... >>> foo.bar <property object at 0x1da8d0> >>> foo.bar + '\n' Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unsupported operand type(s) for +: 'property' and 'str' Is there a way to do this, or is my only alternative to resort to some kind of metaclass trickery?
[ "If you want the descriptor property to trigger when you get an attribute from object X, then you must put the descriptor in type(X). So if X is a class, the descriptor must go in the class's type, also known as the class's metaclass -- no \"trickery\" involved, it's just a matter of completely general rules.\nAlternatively, you might write your own special-purpose descriptor. See here for an excellent \"how-to\" treaty on descriptors. Edit for example:\nclass classprop(object):\n def __init__(self, f):\n self.f = classmethod(f)\n def __get__(self, *a):\n return self.f.__get__(*a)()\n\nclass buh(object):\n @classprop\n def bah(cls): return 23\n\nprint buh.bah\n\nemits 23, as desired.\n" ]
[ 6 ]
[]
[]
[ "class", "class_method", "properties", "python" ]
stackoverflow_0002173206_class_class_method_properties_python.txt
Q: two conflicting meanings of builtins in python 3 (python 3.1, python 3k, python3000) I just posted below query to comp.lang.python, but i feel this kind of question has some kind of right-of-way here on Stack Overflow, too, so be it repeated. the essence: why does ‘builtins’ have two distinct interpretations in Python 3? I would be very gladly accept any commentaries about what this sentence, gleaned from http://celabs.com/python-3.1/reference/executionmodel.html, is meant to mean, or why gods have decided this is the way to go. i anticipate this guy named Kay Schluehr will have a say on that, or maybe even the BDFL will care to pronounce __builtins__ the correct way to his fallovers, followers, and fellownerds:: The built-in namespace associated with the execution of a code block is actually found by looking up the name __builtins__ in its global namespace; this should be a dictionary or a module (in the latter case the module’s dictionary is used). By default, when in the __main__ module, __builtins__ is the built-in module builtins; when in any other module, __builtins__ is an alias for the dictionary of the builtins module itself. __builtins__ can be set to a user-created dictionary to create a weak form of restricted execution. it used to be the case that there were at least two distinct terms, ‘builtin’ (in the singular) and ‘builtins’ (in the plural), some of which existed both in module and in dict form (?just guessing?). now there is only builtins, so fortunately the ambivalence between singular and plural has gone—good riddance. but why does __builtins__ change its meaning depending on whether this is the scope of the ‘script’ (i.e. the module whose name was present, when calling python foobar.py) or whether this is the scope of a secondary module (imported or executed, directly or indirectly, by foobar.py)? i cannot understand the reasoning behind this and find it highly confusing. rationale: why do i care?—i want to be able to ‘export names to the global namespace that were not marked private (by an underscore prefix) in a python module that i execute via exec( compile( get ( locator ), locator, 'exec' ), R ) where R is supposed to going to hold the private names of said module’. it is a little arcane but the basic exercise is to by-pass python’s import system and get similr results... it is all about injecting names into the all-global and the module-global namespaces. A: getattr(__builtins__, '__dict__', __builtins__) should give you the dict that you want to update to "export names to the global namespace", whether __builtins__ is a dict (then it doesn't have a __dict__ attribute so getattr returns the third argument, which is the dict __builtins__ itself) or a module (then it does have that attribute and getattr returns it). This is the workaround. As to why Python's documented to work in a way requiring such a tangled workaround, I'd classify it as an unfortunate case of an implementation issue surfacing to user-visible (and indeed documented) level (sigh). Pity we didn't think of fixing it in the move to Python 3, but it's too late to make backwards-incompatible changes now:-(.
two conflicting meanings of builtins in python 3 (python 3.1, python 3k, python3000)
I just posted below query to comp.lang.python, but i feel this kind of question has some kind of right-of-way here on Stack Overflow, too, so be it repeated. the essence: why does ‘builtins’ have two distinct interpretations in Python 3? I would be very gladly accept any commentaries about what this sentence, gleaned from http://celabs.com/python-3.1/reference/executionmodel.html, is meant to mean, or why gods have decided this is the way to go. i anticipate this guy named Kay Schluehr will have a say on that, or maybe even the BDFL will care to pronounce __builtins__ the correct way to his fallovers, followers, and fellownerds:: The built-in namespace associated with the execution of a code block is actually found by looking up the name __builtins__ in its global namespace; this should be a dictionary or a module (in the latter case the module’s dictionary is used). By default, when in the __main__ module, __builtins__ is the built-in module builtins; when in any other module, __builtins__ is an alias for the dictionary of the builtins module itself. __builtins__ can be set to a user-created dictionary to create a weak form of restricted execution. it used to be the case that there were at least two distinct terms, ‘builtin’ (in the singular) and ‘builtins’ (in the plural), some of which existed both in module and in dict form (?just guessing?). now there is only builtins, so fortunately the ambivalence between singular and plural has gone—good riddance. but why does __builtins__ change its meaning depending on whether this is the scope of the ‘script’ (i.e. the module whose name was present, when calling python foobar.py) or whether this is the scope of a secondary module (imported or executed, directly or indirectly, by foobar.py)? i cannot understand the reasoning behind this and find it highly confusing. rationale: why do i care?—i want to be able to ‘export names to the global namespace that were not marked private (by an underscore prefix) in a python module that i execute via exec( compile( get ( locator ), locator, 'exec' ), R ) where R is supposed to going to hold the private names of said module’. it is a little arcane but the basic exercise is to by-pass python’s import system and get similr results... it is all about injecting names into the all-global and the module-global namespaces.
[ "getattr(__builtins__, '__dict__', __builtins__) should give you the dict that you want to update to \"export names to the global namespace\", whether __builtins__ is a dict (then it doesn't have a __dict__ attribute so getattr returns the third argument, which is the dict __builtins__ itself) or a module (then it does have that attribute and getattr returns it). This is the workaround. As to why Python's documented to work in a way requiring such a tangled workaround, I'd classify it as an unfortunate case of an implementation issue surfacing to user-visible (and indeed documented) level (sigh). Pity we didn't think of fixing it in the move to Python 3, but it's too late to make backwards-incompatible changes now:-(.\n" ]
[ 1 ]
[]
[]
[ "built_in", "python", "python_3.x" ]
stackoverflow_0002173425_built_in_python_python_3.x.txt
Q: Returning binomal as a tuple I want to save the results of my function binomal_aux to a tuple but I don't have an idea how to, here is my code I have right now. def binomal (n): i=0 for i in range(n): binomal_aux(n,i) #want this to be in a tuple so, binomal (2) = (1,2,1) return def binomal_aux (n,k): if (k==0): return 1 elif (n==k): return 1 else: return (binomal_aux(n-1,k) + binomal_aux(n-1,k-1)) A: In your binomal function, just make the tuple you want to return. def binomal(n): return tuple(binomal_aux(n, i) for i in range(n+1)) Note also that the correct spelling is binomial. A: def binomal (n): return tuple(binomal_aux(n,i) for i in range(n+1)) A: Alternate way: def binomal(n): from itertools import combinations return tuple(len(list(combinations(range(n), r=t))) for t in range(n + 1))
Returning binomal as a tuple
I want to save the results of my function binomal_aux to a tuple but I don't have an idea how to, here is my code I have right now. def binomal (n): i=0 for i in range(n): binomal_aux(n,i) #want this to be in a tuple so, binomal (2) = (1,2,1) return def binomal_aux (n,k): if (k==0): return 1 elif (n==k): return 1 else: return (binomal_aux(n-1,k) + binomal_aux(n-1,k-1))
[ "In your binomal function, just make the tuple you want to return.\ndef binomal(n):\n return tuple(binomal_aux(n, i) for i in range(n+1))\n\nNote also that the correct spelling is binomial.\n", "def binomal (n): \n return tuple(binomal_aux(n,i) for i in range(n+1))\n\n", "Alternate way:\ndef binomal(n): \n from itertools import combinations\n return tuple(len(list(combinations(range(n), r=t))) for t in range(n + 1))\n\n" ]
[ 2, 0, 0 ]
[]
[]
[ "python", "recursion", "tuples" ]
stackoverflow_0002173451_python_recursion_tuples.txt
Q: In PyQt, how can signals and slots be used to connect a dropdownlist to a function? In PyQt, there's a concept of signals and slots to connect objects to one another's functions, but I can't seem to find them referenced to functions not associated with other objects. For example, I want a dropdown list to have algorithm A or algorithm B run. How does PyQt accomplish this functionality? A: Do you want the effect of changing the drop down list to call a function? Connect the dropdown list's appropriate signal to your function. For example with the QComboBox currentIndexChanged() signal. Connect that to a "wrapper" function that decides (based on the index) which function to call. Edit: The wrapper can be very simple, like so: functions = {0: reference_to_function_1, 1: reference_to_function_2} def wrapper(index): functions[index]() Edit2: If you want some alternate methods for connecting slots: http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/pyqt4ref.html#connecting-signals-and-slots Note when they are talking about Py or Qt signals, and when they are talking about Python functions or methods. E.g., these are the syntax for connecting a Qt signal to a Python function and a Python method: QtCore.QObject.connect(a, QtCore.SIGNAL("QtSig()"), pyFunction) #function-style QtCore.QObject.connect(a, QtCore.SIGNAL("QtSig()"), pyClass.pyMethod) #method-style
In PyQt, how can signals and slots be used to connect a dropdownlist to a function?
In PyQt, there's a concept of signals and slots to connect objects to one another's functions, but I can't seem to find them referenced to functions not associated with other objects. For example, I want a dropdown list to have algorithm A or algorithm B run. How does PyQt accomplish this functionality?
[ "Do you want the effect of changing the drop down list to call a function?\nConnect the dropdown list's appropriate signal to your function.\nFor example with the QComboBox currentIndexChanged() signal. Connect that to a \"wrapper\" function that decides (based on the index) which function to call.\nEdit: The wrapper can be very simple, like so:\nfunctions = {0: reference_to_function_1, 1: reference_to_function_2}\n\ndef wrapper(index):\n functions[index]()\n\nEdit2: If you want some alternate methods for connecting slots:\nhttp://www.riverbankcomputing.co.uk/static/Docs/PyQt4/pyqt4ref.html#connecting-signals-and-slots\nNote when they are talking about Py or Qt signals, and when they are talking about Python functions or methods. E.g., these are the syntax for connecting a Qt signal to a Python function and a Python method:\nQtCore.QObject.connect(a, QtCore.SIGNAL(\"QtSig()\"), pyFunction) #function-style\nQtCore.QObject.connect(a, QtCore.SIGNAL(\"QtSig()\"), pyClass.pyMethod) #method-style\n\n" ]
[ 3 ]
[]
[]
[ "pyqt", "python", "user_interface" ]
stackoverflow_0002173449_pyqt_python_user_interface.txt
Q: Why is this genexp performing worse than a list comprehension? I was trying to find the quickest way to count the number of items in a list matching a specific filter. In this case, finding how many odd numbers there are in a list. While doing this, I was surprised by the results of comparing a list comprehension vs the equivalent generator expression: python -m timeit -s "L = xrange(1000000)" "sum([1 for i in L if i & 1])" 10 loops, best of 3: 109 msec per loop python -m timeit -s "L = xrange(1000000)" "sum(1 for i in L if i & 1)" 10 loops, best of 3: 125 msec per loop I have also tried with L being a regular list, and different sizes, but in all cases the list comprehension wins. What is the genexp doing that causes it to be slower compared to the listcomp that creates a new list with 1 million items...? (Btw, the fastest way I found was: x = 1; len(filter(x.__and__, L)). And yes, I know writing code like that kills kittens, I'm doing it for the fun of it) A: When essentially unlimited memory is available (which will invariably be the case in tiny benchmarks, although often not in real-world problems!-), lists will tend to outperform generators because they can get allocated just once, in one "big bunch" (no memory fragmentation, etc), while generators require (internally) extra effort to avoid that "big bunch" approach by preserving the stack-frame state to allow resumption of execution. Whether a list-approach or generator-approach will be faster in a real program depends on the exact memory situation, including fragmentation, which is about impossible to reproduce accurately in a "micro-benchmark". IOW, in the end, if you truly care about performance, you must carefully benchmark (and, separately, profile) your actual program(s), not just "toy" micro-benchmarks, in the general case. A: From what I remember, a generator frame have to be activated for each result, whereas the list comprehension uses the one activation frame. The incremental cost in the list compression is the added cost of the memory -- references to int in your case. The relation may well reverse if each item is a new instance and uses more memory. update: After testing, it did reverse ~% python -m timeit -s "L = xrange(1000000);oint=type('intEx', (int,),{})" "sum([oint(1) for i in L if i & 1])" 10 loops, best of 3: 414 msec per loop ~% python -m timeit -s "L = xrange(1000000);oint=type('intEx', (int,),{})" "sum(oint(1) for i in L if i & 1)" 10 loops, best of 3: 392 msec per loop
Why is this genexp performing worse than a list comprehension?
I was trying to find the quickest way to count the number of items in a list matching a specific filter. In this case, finding how many odd numbers there are in a list. While doing this, I was surprised by the results of comparing a list comprehension vs the equivalent generator expression: python -m timeit -s "L = xrange(1000000)" "sum([1 for i in L if i & 1])" 10 loops, best of 3: 109 msec per loop python -m timeit -s "L = xrange(1000000)" "sum(1 for i in L if i & 1)" 10 loops, best of 3: 125 msec per loop I have also tried with L being a regular list, and different sizes, but in all cases the list comprehension wins. What is the genexp doing that causes it to be slower compared to the listcomp that creates a new list with 1 million items...? (Btw, the fastest way I found was: x = 1; len(filter(x.__and__, L)). And yes, I know writing code like that kills kittens, I'm doing it for the fun of it)
[ "When essentially unlimited memory is available (which will invariably be the case in tiny benchmarks, although often not in real-world problems!-), lists will tend to outperform generators because they can get allocated just once, in one \"big bunch\" (no memory fragmentation, etc), while generators require (internally) extra effort to avoid that \"big bunch\" approach by preserving the stack-frame state to allow resumption of execution.\nWhether a list-approach or generator-approach will be faster in a real program depends on the exact memory situation, including fragmentation, which is about impossible to reproduce accurately in a \"micro-benchmark\". IOW, in the end, if you truly care about performance, you must carefully benchmark (and, separately, profile) your actual program(s), not just \"toy\" micro-benchmarks, in the general case.\n", "From what I remember, a generator frame have to be activated for each result, whereas the list comprehension uses the one activation frame. The incremental cost in the list compression is the added cost of the memory -- references to int in your case. The relation may well reverse if each item is a new instance and uses more memory.\nupdate: After testing, it did reverse\n~% python -m timeit -s \"L = xrange(1000000);oint=type('intEx', (int,),{})\" \"sum([oint(1) for i in L if i & 1])\" \n10 loops, best of 3: 414 msec per loop\n\n~% python -m timeit -s \"L = xrange(1000000);oint=type('intEx', (int,),{})\" \"sum(oint(1) for i in L if i & 1)\" \n10 loops, best of 3: 392 msec per loop\n\n" ]
[ 15, 3 ]
[]
[]
[ "generator_expression", "list_comprehension", "python" ]
stackoverflow_0002173845_generator_expression_list_comprehension_python.txt
Q: How to create folders using file names and then move files into folders? I have hundreds of text files in a folder named using this kind of naming convention: Bandname1 - song1.txt Bandname1 - song2.txt Bandname2 - song1.txt Bandname2 - song2.txt Bandname2 - song3.txt Bandname3 - song1.txt ..etc. I would like to create folders for different bands and move according text files into these folders. How could I achieve this using bash, perl or python script? A: It's not necessary to use trim or xargs: for f in *.txt; do band=${f% - *} mkdir -p "$band" mv "$f" "$band" done A: with Perl use File::Copy move; while (my $file= <*.txt> ){ my ($band,$others) = split /\s+-\s+/ ,$file ; mkdir $band; move($file, $band); } A: You asked for a specific script, but if this is for organizing your music, you might want to check out EasyTAG. It has extremely specific and powerful rules that you can customize to organize your music however you want: (source: sourceforge.net) This rule says, "assume my file names are in the structure "[artist] - [album title]/[track number] - [title]". Then you can tag them as such, or move the files around to any new pattern, or do pretty much anything else. A: gregseth's answer will work, just replace trim with xargs. You could also eliminate the if test by just using mkdir -p, for example: for f in *.txt; do band=$(echo "$f" | cut -d'-' -f1 | xargs) mkdir -p "$band" mv "$f" "$band" done Strictly speaking the trim or xargs shouldn't even be necessary, but xargs will at least remove any extra formatting, so it doesn't hurt. A: How about this: for f in *.txt do band=$(echo "$f" | cut -d'-' -f1 | trim) if [ -d "$band" ] then mkdir "$band" fi mv "$f" "$band" done A: This Python program assumes that the source files are in data and that the new directory structure should be in target (and that it already exists). The key point is that os.path.walk will traverse the data directory structure and call myVisitor for each file. import os import os.path sourceDir = "data" targetDir = "target" def myVisitor(arg, dirname, names): for file in names: bandDir = file.split("-")[0] newDir = os.path.join(targetDir, bandDir) if (not os.path.exists(newDir)): os.mkdir(newDir) newName = os.path.join(newDir, file) oldName = os.path.join(dirname, file) os.rename(oldName, newName) os.path.walk(sourceDir, myVisitor, None)
How to create folders using file names and then move files into folders?
I have hundreds of text files in a folder named using this kind of naming convention: Bandname1 - song1.txt Bandname1 - song2.txt Bandname2 - song1.txt Bandname2 - song2.txt Bandname2 - song3.txt Bandname3 - song1.txt ..etc. I would like to create folders for different bands and move according text files into these folders. How could I achieve this using bash, perl or python script?
[ "It's not necessary to use trim or xargs:\nfor f in *.txt; do\n band=${f% - *}\n mkdir -p \"$band\"\n mv \"$f\" \"$band\"\ndone\n\n", "with Perl\nuse File::Copy move;\nwhile (my $file= <*.txt> ){\n my ($band,$others) = split /\\s+-\\s+/ ,$file ;\n mkdir $band;\n move($file, $band);\n}\n\n", "You asked for a specific script, but if this is for organizing your music, you might want to check out EasyTAG. It has extremely specific and powerful rules that you can customize to organize your music however you want:\n\n(source: sourceforge.net) \nThis rule says, \"assume my file names are in the structure \"[artist] - [album title]/[track number] - [title]\". Then you can tag them as such, or move the files around to any new pattern, or do pretty much anything else.\n", "gregseth's answer will work, just replace trim with xargs. You could also eliminate the if test by just using mkdir -p, for example:\nfor f in *.txt; do\n band=$(echo \"$f\" | cut -d'-' -f1 | xargs)\n mkdir -p \"$band\"\n mv \"$f\" \"$band\"\ndone\n\nStrictly speaking the trim or xargs shouldn't even be necessary, but xargs will at least remove any extra formatting, so it doesn't hurt.\n", "How about this:\nfor f in *.txt\ndo\n band=$(echo \"$f\" | cut -d'-' -f1 | trim)\n if [ -d \"$band\" ]\n then\n mkdir \"$band\"\n fi\n mv \"$f\" \"$band\"\ndone\n\n", "This Python program assumes that the source files are in data and that the new directory structure should be in target (and that it already exists).\nThe key point is that os.path.walk will traverse the data directory structure and call myVisitor for each file.\nimport os\nimport os.path\n\nsourceDir = \"data\"\ntargetDir = \"target\"\n\ndef myVisitor(arg, dirname, names):\n for file in names:\n bandDir = file.split(\"-\")[0]\n newDir = os.path.join(targetDir, bandDir)\n if (not os.path.exists(newDir)):\n os.mkdir(newDir)\n\n newName = os.path.join(newDir, file)\n oldName = os.path.join(dirname, file)\n\n os.rename(oldName, newName)\n\nos.path.walk(sourceDir, myVisitor, None)\n\n" ]
[ 4, 2, 1, 1, 0, 0 ]
[ "ls |perl -lne'$f=$_; s/(.+?) - [^-]*\\.txt/$1/; mkdir unless -d; rename $f, \"$_/$f\"'\n\n" ]
[ -1 ]
[ "bash", "batch_file", "perl", "python", "unix" ]
stackoverflow_0002172420_bash_batch_file_perl_python_unix.txt
Q: How do you get a responsive GUI if your codebehind is running an infinte loop? PyQT If you have a function consistently running an infinite loop in the background, how will your GUI ever be responsive? It is waiting for the loop to finish and this renders the interface useless. How is this solved in PyQT? A: Use threads. In Qt, they use something called Signals and Slots. I haven't used Qt since college, but there are plenty of good resources here: PyQt Wiki: Threading,_Signals_and_Slots See also this related SO post: Threading in a PyQt application: Use Qt threads or Python threads? or Python - PyQt app in seperate thread A: You would run the non-GUI code in a QThread. Then your GUI will remain responsive. For a tutorial on threading in QT, see this link: http://doc.trolltech.com/4.4/threads.html The documentation for Qt's threading class (QThread) is available at this link: http://doc.trolltech.com/4.4/qthread.html#details They are both references to the C++ documentation, but are still both valuable even when using PyQt, especially where the PyQt documentation is not as robust.
How do you get a responsive GUI if your codebehind is running an infinte loop? PyQT
If you have a function consistently running an infinite loop in the background, how will your GUI ever be responsive? It is waiting for the loop to finish and this renders the interface useless. How is this solved in PyQT?
[ "Use threads.\nIn Qt, they use something called Signals and Slots. I haven't used Qt since college, but there are plenty of good resources here:\nPyQt Wiki: Threading,_Signals_and_Slots\nSee also this related SO post: Threading in a PyQt application: Use Qt threads or Python threads? or\nPython - PyQt app in seperate thread\n", "You would run the non-GUI code in a QThread. Then your GUI will remain responsive.\nFor a tutorial on threading in QT, see this link:\nhttp://doc.trolltech.com/4.4/threads.html\nThe documentation for Qt's threading class (QThread) is available at this link:\nhttp://doc.trolltech.com/4.4/qthread.html#details\nThey are both references to the C++ documentation, but are still both valuable even when using PyQt, especially where the PyQt documentation is not as robust.\n" ]
[ 4, 0 ]
[]
[]
[ "multithreading", "pyqt", "python", "user_interface" ]
stackoverflow_0002174039_multithreading_pyqt_python_user_interface.txt
Q: Can't get wx.BufferedDC to draw anything I've got a problem with DCs. I'm trying to make an application that will draw many lines on the screens and needs to update really fast, and since I don't want flickering, I decided to give buffered dcs a shot. But when I run this code, it doesn't draw anything. What am I doing wrong? import wx class MainFrame(wx.Frame): def __init__(self): screensize = wx.GetDisplaySize() self.framesize = (screensize[0]/4*3, screensize[1]/4*3) wx.Frame.__init__(self, None, -1, "CursorTracker", size=self.framesize, style=wx.SYSTEM_MENU| wx.CAPTION| wx.CLOSE_BOX| wx.MINIMIZE_BOX) self.dc = wx.ClientDC(self) self.bdc = wx.BufferedDC(self.dc) self.SetBackgroundColour(wx.WHITE) self.Timer = wx.Timer(self) self.Bind(wx.EVT_TIMER, self.OnTimer) self.Timer.Start(100) def OnTimer(self, event): self.bdc.DrawLine(1,1,100,100) class App(wx.App): def OnInit(self): frame = MainFrame() frame.Show() return True app = App(redirect=False) app.MainLoop() A: I've used AutoBufferedPaintDC, but I've found doing my own double-buffering with a MemoryDC to be more flexible. Here's a template for you. import wx class Frame(wx.Frame): def __init__(self): super(Frame, self).__init__(None, -1, 'CursorTracker') self.mdc = None # memory dc to draw off-screen self.Bind(wx.EVT_SIZE, self.on_size) self.Bind(wx.EVT_ERASE_BACKGROUND, self.on_erase) self.Bind(wx.EVT_PAINT, self.on_paint) w, h = wx.GetDisplaySize() w, h = w * 3 / 4, h * 3 / 4 self.SetSize((w, h)) self.Center() self.on_timer() def on_size(self, event): # re-create memory dc to fill window w, h = self.GetClientSize() self.mdc = wx.MemoryDC(wx.EmptyBitmap(w, h)) self.redraw() def on_erase(self, event): pass # don't do any erasing to avoid flicker def on_paint(self, event): # just blit the memory dc dc = wx.PaintDC(self) if not self.mdc: return w, h = self.mdc.GetSize() dc.Blit(0, 0, w, h, self.mdc, 0, 0) def on_timer(self): # refresh every N milliseconds self.redraw() wx.CallLater(100, self.on_timer) def redraw(self): # do the actual drawing on the memory dc here dc = self.mdc w, h = dc.GetSize() dc.Clear() dc.DrawLine(0, 0, w, h) self.Refresh() if __name__ == '__main__': app = wx.PySimpleApp() frame = Frame() frame.Show() app.MainLoop() The basic approach is: create a memory dc for off-screen drawing if the window is resized, resize the memory dc and redraw when a paint event occurs, just blit the memory dc onto the paint dc do nothing on a erase background event to avoid flicker call redraw when and only when you actually need to change what's on the screen If you store a reference to that EmptyBitmap that's created in on_size, you can even save the window contents to an image file with wxBitmap.SaveFile() A: A BufferedDC is copied to the screen only when the object is destroy. Since you never destroy self.bdc, of course its contents will never be copied to the screen. So, you need to arrange to let go of self.bdc (maybe just replace it with a new BufferedDc instance: i.e., redo the assignment self.bdc = wc.BufferedDc(self.dc) at "strategic" moments in time when you do want the drawing to be visualized.
Can't get wx.BufferedDC to draw anything
I've got a problem with DCs. I'm trying to make an application that will draw many lines on the screens and needs to update really fast, and since I don't want flickering, I decided to give buffered dcs a shot. But when I run this code, it doesn't draw anything. What am I doing wrong? import wx class MainFrame(wx.Frame): def __init__(self): screensize = wx.GetDisplaySize() self.framesize = (screensize[0]/4*3, screensize[1]/4*3) wx.Frame.__init__(self, None, -1, "CursorTracker", size=self.framesize, style=wx.SYSTEM_MENU| wx.CAPTION| wx.CLOSE_BOX| wx.MINIMIZE_BOX) self.dc = wx.ClientDC(self) self.bdc = wx.BufferedDC(self.dc) self.SetBackgroundColour(wx.WHITE) self.Timer = wx.Timer(self) self.Bind(wx.EVT_TIMER, self.OnTimer) self.Timer.Start(100) def OnTimer(self, event): self.bdc.DrawLine(1,1,100,100) class App(wx.App): def OnInit(self): frame = MainFrame() frame.Show() return True app = App(redirect=False) app.MainLoop()
[ "I've used AutoBufferedPaintDC, but I've found doing my own double-buffering with a MemoryDC to be more flexible. Here's a template for you.\nimport wx\n\nclass Frame(wx.Frame):\n def __init__(self):\n super(Frame, self).__init__(None, -1, 'CursorTracker')\n self.mdc = None # memory dc to draw off-screen\n self.Bind(wx.EVT_SIZE, self.on_size)\n self.Bind(wx.EVT_ERASE_BACKGROUND, self.on_erase)\n self.Bind(wx.EVT_PAINT, self.on_paint)\n w, h = wx.GetDisplaySize()\n w, h = w * 3 / 4, h * 3 / 4\n self.SetSize((w, h))\n self.Center()\n self.on_timer()\n def on_size(self, event):\n # re-create memory dc to fill window\n w, h = self.GetClientSize()\n self.mdc = wx.MemoryDC(wx.EmptyBitmap(w, h))\n self.redraw()\n def on_erase(self, event):\n pass # don't do any erasing to avoid flicker\n def on_paint(self, event):\n # just blit the memory dc\n dc = wx.PaintDC(self)\n if not self.mdc:\n return\n w, h = self.mdc.GetSize()\n dc.Blit(0, 0, w, h, self.mdc, 0, 0)\n def on_timer(self):\n # refresh every N milliseconds\n self.redraw()\n wx.CallLater(100, self.on_timer)\n def redraw(self):\n # do the actual drawing on the memory dc here\n dc = self.mdc\n w, h = dc.GetSize()\n dc.Clear()\n dc.DrawLine(0, 0, w, h)\n self.Refresh()\n\nif __name__ == '__main__':\n app = wx.PySimpleApp()\n frame = Frame()\n frame.Show()\n app.MainLoop()\n\nThe basic approach is:\n\ncreate a memory dc for off-screen drawing\nif the window is resized, resize the memory dc and redraw\nwhen a paint event occurs, just blit the memory dc onto the paint dc\ndo nothing on a erase background event to avoid flicker\ncall redraw when and only when you actually need to change what's on the screen\n\nIf you store a reference to that EmptyBitmap that's created in on_size, you can even save the window contents to an image file with wxBitmap.SaveFile()\n", "A BufferedDC is copied to the screen only when the object is destroy. Since you never destroy self.bdc, of course its contents will never be copied to the screen. So, you need to arrange to let go of self.bdc (maybe just replace it with a new BufferedDc instance: i.e., redo the assignment self.bdc = wc.BufferedDc(self.dc) at \"strategic\" moments in time when you do want the drawing to be visualized.\n" ]
[ 3, 1 ]
[]
[]
[ "python", "wxwidgets" ]
stackoverflow_0002173821_python_wxwidgets.txt
Q: recursive nested expression in Python I am using Python 2.6.4. I have a series of select statements in a text file and I need to extract the field names from each select query. This would be easy if some of the fields didn't use nested functions like to_char() etc. Given select statement fields that could have several nested parenthese like "ltrim(rtrim(to_char(base_field_name, format))) renamed_field_name," or the simple case of just "base_field_name" as a field, is it possible to use Python's re module to write a regex to extract base_field_name? If so, what would the regex look like? A: Regular expressions are not suitable for parsing "nested" structures. Try, instead, a full-fledged parsing kit such as pyparsing -- examples of using pyparsing specifically to parse SQL can be found here and here, for example (you'll no doubt need to take the examples just as a starting point, and write some parsing code of your own, but, it's definitely not too difficult). A: >>> import re >>> string = 'ltrim(rtrim(to_char(base_field_name, format))) renamed_field_name' >>> rx = re.compile('^(.*?\()*(.+?)(,.*?)*(,|\).*?)*$') >>> rx.search(string).group(2) 'base_field_name' >>> rx.search('base_field_name').group(2) 'base_field_name' A: Either a table-driven parser as Alex Martelli suggests or a hand-written recursive descent parser. They're not hard and quite rewarding to write. A: This may be good enough: import re print re.match(r".*\(([^\)]+)\)", "ltrim(to_char(field_name, format)))").group(1) You would need to do further processing. For example pick up the function name as well and pull the field name according to function signature. .*(\w+)\(([^\)]+)\) A: Here's a really hacky parser that does what you want. It works by calling 'eval' on the text to be parsed, mapping all identifiers to a function which returns its first argument (which I'm guessing is what you want given your example). class FakeFunction(object): def __init__(self, name): self.name = name def __call__(self, *args): return args[0] def __str__(self): return self.name class FakeGlobals(dict): def __getitem__(self, x): return FakeFunction(x) def ExtractBaseFieldName(x): return eval(x, FakeGlobals()) print ExtractBaseFieldName('ltrim(rtrim(to_char(base_field_name, format)))') A: Do you really need regular expressions? To get the one you've got up there I'd use s[s.rfind('(')+1:s.find(')')].split(',')[0] with 's' containing the original string. Of course, it's not a general solution, but...
recursive nested expression in Python
I am using Python 2.6.4. I have a series of select statements in a text file and I need to extract the field names from each select query. This would be easy if some of the fields didn't use nested functions like to_char() etc. Given select statement fields that could have several nested parenthese like "ltrim(rtrim(to_char(base_field_name, format))) renamed_field_name," or the simple case of just "base_field_name" as a field, is it possible to use Python's re module to write a regex to extract base_field_name? If so, what would the regex look like?
[ "Regular expressions are not suitable for parsing \"nested\" structures. Try, instead, a full-fledged parsing kit such as pyparsing -- examples of using pyparsing specifically to parse SQL can be found here and here, for example (you'll no doubt need to take the examples just as a starting point, and write some parsing code of your own, but, it's definitely not too difficult).\n", ">>> import re\n>>> string = 'ltrim(rtrim(to_char(base_field_name, format))) renamed_field_name'\n>>> rx = re.compile('^(.*?\\()*(.+?)(,.*?)*(,|\\).*?)*$')\n>>> rx.search(string).group(2)\n'base_field_name'\n>>> rx.search('base_field_name').group(2)\n'base_field_name'\n\n", "Either a table-driven parser as Alex Martelli suggests or a hand-written recursive descent parser. They're not hard and quite rewarding to write.\n", "This may be good enough:\nimport re\nprint re.match(r\".*\\(([^\\)]+)\\)\", \"ltrim(to_char(field_name, format)))\").group(1)\n\nYou would need to do further processing. For example pick up the function name as well and pull the field name according to function signature.\n.*(\\w+)\\(([^\\)]+)\\)\n\n", "Here's a really hacky parser that does what you want.\nIt works by calling 'eval' on the text to be parsed, mapping all identifiers to a function which returns its first argument (which I'm guessing is what you want given your example). \nclass FakeFunction(object):\n def __init__(self, name):\n self.name = name\n def __call__(self, *args):\n return args[0]\n def __str__(self):\n return self.name\n\nclass FakeGlobals(dict):\n def __getitem__(self, x):\n return FakeFunction(x)\n\ndef ExtractBaseFieldName(x):\n return eval(x, FakeGlobals())\n\nprint ExtractBaseFieldName('ltrim(rtrim(to_char(base_field_name, format)))')\n\n", "Do you really need regular expressions? To get the one you've got up there I'd use\n s[s.rfind('(')+1:s.find(')')].split(',')[0]\n\nwith 's' containing the original string.\nOf course, it's not a general solution, but...\n" ]
[ 11, 2, 2, 1, 1, 0 ]
[]
[]
[ "expression", "nested", "python", "regex" ]
stackoverflow_0002174015_expression_nested_python_regex.txt
Q: In the Python Google App Engine, how to mock or subclass the File class so that software written to access files does not throw an exception? I would like to run some code on the Python version of Google App Engine that uses the built in File type. I’m looking for the easiest way to stop GAE from throwing errors due to illegal access. Has anyone already sub-classed or mocked File to read and write to memory rather than to the disk? I don’t need persistence, just the ability to simulate file access. A: import __builtin__ import StringIO class File(StringIO.StringIO): def __init__(self, *a, **k): pass __builtin__.file = __builtin__.open = File You'll surely want finer-grained simulation, but this works as a very rough first cut.
In the Python Google App Engine, how to mock or subclass the File class so that software written to access files does not throw an exception?
I would like to run some code on the Python version of Google App Engine that uses the built in File type. I’m looking for the easiest way to stop GAE from throwing errors due to illegal access. Has anyone already sub-classed or mocked File to read and write to memory rather than to the disk? I don’t need persistence, just the ability to simulate file access.
[ "import __builtin__\nimport StringIO\n\nclass File(StringIO.StringIO):\n def __init__(self, *a, **k): pass\n\n__builtin__.file = __builtin__.open = File\n\nYou'll surely want finer-grained simulation, but this works as a very rough first cut.\n" ]
[ 5 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0002174596_google_app_engine_python.txt
Q: pinax ImportError cannot import name UserOpenidAssociation I have these errors: ImportError at / cannot import name UserOpenidAssociation. I could not make any sense out of the traceback: Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 1.1.1 Python Version: 2.6.1 Installed Applications: ['inventory.inlanddbase'] Installed Middleware: ('django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django_openid.consumer.SessionConsumer', 'account.middleware.LocaleMiddleware', 'django.middleware.doc.XViewMiddleware', 'pagination.middleware.PaginationMiddleware', 'pinax.middleware.security.HideSensistiveFieldsMiddleware') Traceback: File "C:\Python26\lib\site-packages\django\core\handlers\base.py" in get_response 83. request.path_info) File "C:\Python26\lib\site-packages\django\core\urlresolvers.py" in resolve 216. for pattern in self.url_patterns: File "C:\Python26\lib\site-packages\django\core\urlresolvers.py" in _get_url_patterns 245. patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Python26\lib\site-packages\django\core\urlresolvers.py" in _get_urlconf_module 240. self._urlconf_module = import_module(self.urlconf_name) File "C:\Python26\lib\site-packages\django\utils\importlib.py" in import_module 35. __import__(name) File "C:\inlanddoors\Scripts\inventory\urls.py" in <module> 9. from account.openid_consumer import PinaxConsumer File "C:\inlanddoors\Lib\site-packages\pinax\apps\account\openid_consumer.py" in <module> 15. from account.views import login as account_login File "C:\inlanddoors\Lib\site-packages\pinax\apps\account\views.py" in <module> 22. from django_openid.models import UserOpenidAssociation Exception Type: ImportError at / Exception Value: cannot import name UserOpenidAssociation What am I doing wrong??? A: sudo pip install django_openid
pinax ImportError cannot import name UserOpenidAssociation
I have these errors: ImportError at / cannot import name UserOpenidAssociation. I could not make any sense out of the traceback: Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 1.1.1 Python Version: 2.6.1 Installed Applications: ['inventory.inlanddbase'] Installed Middleware: ('django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django_openid.consumer.SessionConsumer', 'account.middleware.LocaleMiddleware', 'django.middleware.doc.XViewMiddleware', 'pagination.middleware.PaginationMiddleware', 'pinax.middleware.security.HideSensistiveFieldsMiddleware') Traceback: File "C:\Python26\lib\site-packages\django\core\handlers\base.py" in get_response 83. request.path_info) File "C:\Python26\lib\site-packages\django\core\urlresolvers.py" in resolve 216. for pattern in self.url_patterns: File "C:\Python26\lib\site-packages\django\core\urlresolvers.py" in _get_url_patterns 245. patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Python26\lib\site-packages\django\core\urlresolvers.py" in _get_urlconf_module 240. self._urlconf_module = import_module(self.urlconf_name) File "C:\Python26\lib\site-packages\django\utils\importlib.py" in import_module 35. __import__(name) File "C:\inlanddoors\Scripts\inventory\urls.py" in <module> 9. from account.openid_consumer import PinaxConsumer File "C:\inlanddoors\Lib\site-packages\pinax\apps\account\openid_consumer.py" in <module> 15. from account.views import login as account_login File "C:\inlanddoors\Lib\site-packages\pinax\apps\account\views.py" in <module> 22. from django_openid.models import UserOpenidAssociation Exception Type: ImportError at / Exception Value: cannot import name UserOpenidAssociation What am I doing wrong???
[ "sudo pip install django_openid\n" ]
[ 0 ]
[]
[]
[ "django", "pinax", "python" ]
stackoverflow_0002173829_django_pinax_python.txt
Q: Migrating from Javadoc to Python Documentation So I've gotten somewhat used to Javadoc style documentation. Looking through various examples of Python code, I'm finding that, at first blush, the documentation seems to be missing a lot of information. The good: vary rarely do you see self-evident bits of documentation. Docstrings are usually a paragraph or less of English markup that integrates instead of standing out on separate lines. The bad: in conjunction with Python's duck-typing, I find that many functions are unclear about the parameters they expect. There's no type hinting (duck-hinting?) and often times it would be nice to have some idea that the parameter should be list-like, string-like, stream-like. Of course, Javadoc was designed for a lower-level language, without great introspection abilities of Python, which might account for the less verbose documentation philosophy. Any advice on Python documentation standards and best-practices? A: The reStructuredText format was designed in response to the need for Python documentation that could be embedded in docstrings, so the best thing is to learn reST and format your docstrings with that format. You might find, as I did, that you then go on to format just about any documentation in reST, but that's a side point :-) For specifically documenting your Python code, the Sphinx system is a set of extensions to the reST format, and a build system for rendering documents. Since it was designed to document Python itself, including the standard library, Sphinx allows for very well-structured documentation of source code, including of course the specifics of function signatures as you're asking. It allows a comprehensive documentation suite to be built, both auto-extracted and hand-written, all using the same formatting system. If you only want documentation generated from your source code, then Epydoc will extract API documentation from your source code; it, too, reads reST formatting for the text.
Migrating from Javadoc to Python Documentation
So I've gotten somewhat used to Javadoc style documentation. Looking through various examples of Python code, I'm finding that, at first blush, the documentation seems to be missing a lot of information. The good: vary rarely do you see self-evident bits of documentation. Docstrings are usually a paragraph or less of English markup that integrates instead of standing out on separate lines. The bad: in conjunction with Python's duck-typing, I find that many functions are unclear about the parameters they expect. There's no type hinting (duck-hinting?) and often times it would be nice to have some idea that the parameter should be list-like, string-like, stream-like. Of course, Javadoc was designed for a lower-level language, without great introspection abilities of Python, which might account for the less verbose documentation philosophy. Any advice on Python documentation standards and best-practices?
[ "The reStructuredText format was designed in response to the need for Python documentation that could be embedded in docstrings, so the best thing is to learn reST and format your docstrings with that format. You might find, as I did, that you then go on to format just about any documentation in reST, but that's a side point :-)\nFor specifically documenting your Python code, the Sphinx system is a set of extensions to the reST format, and a build system for rendering documents. Since it was designed to document Python itself, including the standard library, Sphinx allows for very well-structured documentation of source code, including of course the specifics of function signatures as you're asking. It allows a comprehensive documentation suite to be built, both auto-extracted and hand-written, all using the same formatting system.\nIf you only want documentation generated from your source code, then Epydoc will extract API documentation from your source code; it, too, reads reST formatting for the text.\n" ]
[ 9 ]
[]
[]
[ "python", "python_sphinx" ]
stackoverflow_0002175040_python_python_sphinx.txt
Q: How would I discover the memory used by an application through a python script? Recently I've found myself testing an aplication in Froglogic's Squish, using Python to create test scripts. Just the other day, the question of how much memory the program is using has come up, and I've found myself unable to answer it. It seems reasonable to assume that there's a way to query the os (windows 7) API for the information, but I've no idea where to begin. Does anyone know how I'd go about this? A: this answer has some code (for windows and unix): Total memory used by Python process? on win, you are checking Win32_PerfRawData_PerfProc_Process and on linux it's /proc/pid/status (or ps) A: Remember that Squish allows remote testing of the application. A system parameter queried via Python directly will only apply to the case of local testing. An approach that works in either case is to call the currentApplicationContext() function that will give you a handle to the Application Under Test. It has a usedMemory property you can query. I don't recall which process property exactly is being queried but it should provide a rough indication.
How would I discover the memory used by an application through a python script?
Recently I've found myself testing an aplication in Froglogic's Squish, using Python to create test scripts. Just the other day, the question of how much memory the program is using has come up, and I've found myself unable to answer it. It seems reasonable to assume that there's a way to query the os (windows 7) API for the information, but I've no idea where to begin. Does anyone know how I'd go about this?
[ "this answer has some code (for windows and unix):\nTotal memory used by Python process?\non win, you are checking Win32_PerfRawData_PerfProc_Process and on linux it's /proc/pid/status (or ps)\n", "Remember that Squish allows remote testing of the application. A system parameter queried via Python directly will only apply to the case of local testing.\nAn approach that works in either case is to call the currentApplicationContext() function that will give you a handle to the Application Under Test. It has a usedMemory property you can query. I don't recall which process property exactly is being queried but it should provide a rough indication.\n" ]
[ 2, 0 ]
[ "In command line: tasklist /FO LIST and parse the results?\nSorry, I don't know a Pythonic way. =P\n" ]
[ -1 ]
[ "memory_management", "python", "squish", "windows_7" ]
stackoverflow_0002084063_memory_management_python_squish_windows_7.txt
Q: mercurial - I want to add some custom code to be run after commit where could I place code to be run after every commit I make with mercurial? Specifically, I would like to maintain a file called latest inside the .hg folder in the root of my project - that file will hold the revision number and hash code for the most recent commit. On that same topic, how can I get those in python? # get mercurial version hash ver = ? # get mercurial revision number rev = ? # is there a shortcut to this folder through mercurial? f = open('/path/to/.hg/latest', 'w') f.write('ver=%s\nrev=%d' % ( str(ver), int(rev) ) ) f.close EDIT: I was able to accomplish the above with hooks (in .hg/hgrc): [hooks] precommit= echo node=`hg tip --template {node}` > tip && echo rev=`hg tip --template {rev}` >> tip && hg add tip The file with the tip info is created successfully, but I would also like to add it to the current commit with hg add tip, which is where the mercurial process gets stuck waiting for the lock apparently held by the pending commit. Is there a way to work around it such that the file created during/pre commit is added to it? thanks. A: http://hgbook.red-bean.com/read/handling-repository-events-with-hooks.html specifically you seem to want the commit hook which there is a tutorial for of course it sounds like what you really want is hg tip
mercurial - I want to add some custom code to be run after commit
where could I place code to be run after every commit I make with mercurial? Specifically, I would like to maintain a file called latest inside the .hg folder in the root of my project - that file will hold the revision number and hash code for the most recent commit. On that same topic, how can I get those in python? # get mercurial version hash ver = ? # get mercurial revision number rev = ? # is there a shortcut to this folder through mercurial? f = open('/path/to/.hg/latest', 'w') f.write('ver=%s\nrev=%d' % ( str(ver), int(rev) ) ) f.close EDIT: I was able to accomplish the above with hooks (in .hg/hgrc): [hooks] precommit= echo node=`hg tip --template {node}` > tip && echo rev=`hg tip --template {rev}` >> tip && hg add tip The file with the tip info is created successfully, but I would also like to add it to the current commit with hg add tip, which is where the mercurial process gets stuck waiting for the lock apparently held by the pending commit. Is there a way to work around it such that the file created during/pre commit is added to it? thanks.
[ "http://hgbook.red-bean.com/read/handling-repository-events-with-hooks.html\nspecifically you seem to want the commit hook which there is a tutorial for\nof course it sounds like what you really want is hg tip\n" ]
[ 5 ]
[]
[]
[ "automation", "customization", "mercurial", "python" ]
stackoverflow_0002175788_automation_customization_mercurial_python.txt
Q: Why do we need tuples in Python (or any immutable data type)? I've read several python tutorials (Dive Into Python, for one), and the language reference on Python.org - I don't see why the language needs tuples. Tuples have no methods compared to a list or set, and if I must convert a tuple to a set or list to be able to sort them, what's the point of using a tuple in the first place? Immutability? Why does anyone care if a variable lives at a different place in memory than when it was originally allocated? This whole business of immutability in Python seems to be over emphasized. In C/C++ if I allocate a pointer and point to some valid memory, I don't care where the address is located as long as it's not null before I use it. Whenever I reference that variable, I don't need to know if the pointer is still pointing to the original address or not. I just check for null and use it (or not). In Python, when I allocate a string (or tuple) assign it to x, then modify the string, why do I care if it's the original object? As long as the variable points to my data, that's all that matters. >>> x='hello' >>> id(x) 1234567 >>> x='good bye' >>> id(x) 5432167 x still references the data I want, why does anyone need to care if its id is the same or different? A: immutable objects can allow substantial optimization; this is presumably why strings are also immutable in Java, developed quite separately but about the same time as Python, and just about everything is immutable in truly-functional languages. in Python in particular, only immutables can be hashable (and, therefore, members of sets, or keys in dictionaries). Again, this afford optimization, but far more than just "substantial" (designing decent hash tables storing completely mutable objects is a nightmare -- either you take copies of everything as soon as you hash it, or the nightmare of checking whether the object's hash has changed since you last took a reference to it rears its ugly head). Example of optimization issue: $ python -mtimeit '["fee", "fie", "fo", "fum"]' 1000000 loops, best of 3: 0.432 usec per loop $ python -mtimeit '("fee", "fie", "fo", "fum")' 10000000 loops, best of 3: 0.0563 usec per loop A: None of the answers above point out the real issue of tuples vs lists, which many new to Python seem to not fully understand. Tuples and lists serve different purposes. Lists store homogenous data. You can and should have a list like this: ["Bob", "Joe", "John", "Sam"] The reason that is a correct use of lists is because those are all homogenous types of data, specifically, people's names. But take a list like this: ["Billy", "Bob", "Joe", 42] That list is one person's full name, and their age. That isn't one type of data. The correct way to store that information is either in a tuple, or in an object. Lets say we have a few : [("Billy", "Bob", "Joe", 42), ("Robert", "", "Smith", 31)] The immutability and mutability of Tuples and Lists is not the main difference. A list is a list of the same kind of items: files, names, objects. Tuples are a grouping of different types of objects. They have different uses, and many Python coders abuse lists for what tuples are meant for. Please don't. Edit: I think this blog post explains why I think this better than I did: Understanding tuples vs. lists in Python - E-Scribe A: if I must convert a tuple to a set or list to be able to sort them, what's the point of using a tuple in the first place? In this particular case, there probably isn't a point. This is a non-issue, because this isn't one of the cases where you'd consider using a tuple. As you point out, tuples are immutable. The reasons for having immutable types apply to tuples: copy efficiency: rather than copying an immutable object, you can alias it (bind a variable to a reference) comparison efficiency: when you're using copy-by-reference, you can compare two variables by comparing location, rather than content interning: you need to store at most one copy of any immutable value there's no need to synchronize access to immutable objects in concurrent code const correctness: some values shouldn't be allowed to change. This (to me) is the main reason for immutable types. Note that a particular Python implementation may not make use of all of the above features. Dictionary keys must be immutable, otherwise changing the properties of a key-object can invalidate invariants of the underlying data structure. Tuples can thus potentially be used as keys. This is a consequence of const correctness. See also "Introducing tuples", from Dive Into Python. A: Sometimes we like to use objects as dictionary keys For what it's worth, tuples recently (2.6+) grew index() and count() methods A: I've always found having two completely separate types for the same basic data structure (arrays) to be an awkward design, but not a real problem in practice. (Every language has its warts, Python included, but this isn't an important one.) Why does anyone care if a variable lives at a different place in memory than when it was originally allocated? This whole business of immutability in Python seems to be over emphasized. These are different things. Mutability isn't related to the place it's stored in memory; it means the stuff it points to can't change. Python objects can't change location after they're created, mutable or not. (More accurately, the value of id() can't change--same thing, in practice.) The internal storage of mutable objects can change, but that's a hidden implementation detail. >>> x='hello' >>> id(x) 1234567 >>> x='good bye' >>> id(x) 5432167 This isn't modifying ("mutating") the variable; it's creating a new variable with the same name, and discarding the old one. Compare to a mutating operation: >>> a = [1,2,3] >>> id(a) 3084599212L >>> a[1] = 5 >>> a [1, 5, 3] >>> id(a) 3084599212L As others have pointed out, this allows using arrays as keys to dictionaries, and other data structures that need immutability. Note that keys for dictionaries do not have to be completely immutable. Only the part of it used as a key needs to be immutable; for some uses, this is an important distinction. For example, you could have a class representing a user, which compares equality and a hash by the unique username. You could then hang other mutable data on the class--"user is logged in", etc. Since this doesn't affect equality or the hash, it's possible and perfectly valid to use this as a key in a dictionary. This isn't too commonly needed in Python; I just point it out since several people have claimed that keys need to be "immutable", which is only partially correct. I've used this many times with C++ maps and sets, though. A: As gnibbler offered in a comment, Guido had an opinion that is not fully accepted/appreciated: “lists are for homogeneous data, tuples are for heterogeneous data”. Of course, many of the opposers interpreted this as meaning that all elements of a list should be of the same type. I like to see it differently, not unlike others also have in the past: blue= 0, 0, 255 alist= ["red", "green", blue] Note that I consider alist to be homogeneous, even if type(alist[1]) != type(alist[2]). If I can change the order of the elements and I won't have issues in my code (apart from assumptions, e.g. “it should be sorted”), then a list should be used. If not (like in the tuple blue above), then I should use a tuple. A: They are important since they guarantee the caller that the object they pass won't be mutated. If you do this: a = [1,1,1] doWork(a) The caller has no guarantee of the value of a after the call. However, a = (1,1,1) doWorK(a) Now you as the caller or as a reader of this code know that a is the same. You could always for this scenario make a copy of the list and pass that but now you are wasting cycles instead of using a language construct that makes more semantic sense. A: you can see here for some discussion on this A: Your question (and follow-up comments) focus on whether the id() changes during an assignment. Focusing on this follow-on effect of the difference between immutable object replacement and mutable object modification rather than the difference itself is perhaps not the best approach. Before we continue, make sure that the behavior demonstrated below is what you expect from Python. >>> a1 = [1] >>> a2 = a1 >>> print a2[0] 1 >>> a1[0] = 2 >>> print a2[0] 2 In this case, the contents of a2 was changed, even though only a1 had a new value assigned. Contrast to the following: >>> a1 = (1,) >>> a2 = a1 >>> print a2[0] 1 >>> a1 = (2,) >>> print a2[0] 1 In this latter case, we replaced the entire list, rather than updating its contents. With immutable types such as tuples, this is the only behavior allowed. Why does this matter? Let's say you have a dict: >>> t1 = (1,2) >>> d1 = { t1 : 'three' } >>> print d1 {(1,2): 'three'} >>> t1[0] = 0 ## results in a TypeError, as tuples cannot be modified >>> t1 = (2,3) ## creates a new tuple, does not modify the old one >>> print d1 ## as seen here, the dict is still intact {(1,2): 'three'} Using a tuple, the dictionary is safe from having its keys changed "out from under it" to items which hash to a different value. This is critical to allow efficient implementation.
Why do we need tuples in Python (or any immutable data type)?
I've read several python tutorials (Dive Into Python, for one), and the language reference on Python.org - I don't see why the language needs tuples. Tuples have no methods compared to a list or set, and if I must convert a tuple to a set or list to be able to sort them, what's the point of using a tuple in the first place? Immutability? Why does anyone care if a variable lives at a different place in memory than when it was originally allocated? This whole business of immutability in Python seems to be over emphasized. In C/C++ if I allocate a pointer and point to some valid memory, I don't care where the address is located as long as it's not null before I use it. Whenever I reference that variable, I don't need to know if the pointer is still pointing to the original address or not. I just check for null and use it (or not). In Python, when I allocate a string (or tuple) assign it to x, then modify the string, why do I care if it's the original object? As long as the variable points to my data, that's all that matters. >>> x='hello' >>> id(x) 1234567 >>> x='good bye' >>> id(x) 5432167 x still references the data I want, why does anyone need to care if its id is the same or different?
[ "\nimmutable objects can allow substantial optimization; this is presumably why strings are also immutable in Java, developed quite separately but about the same time as Python, and just about everything is immutable in truly-functional languages.\nin Python in particular, only immutables can be hashable (and, therefore, members of sets, or keys in dictionaries). Again, this afford optimization, but far more than just \"substantial\" (designing decent hash tables storing completely mutable objects is a nightmare -- either you take copies of everything as soon as you hash it, or the nightmare of checking whether the object's hash has changed since you last took a reference to it rears its ugly head).\n\nExample of optimization issue:\n$ python -mtimeit '[\"fee\", \"fie\", \"fo\", \"fum\"]'\n1000000 loops, best of 3: 0.432 usec per loop\n$ python -mtimeit '(\"fee\", \"fie\", \"fo\", \"fum\")'\n10000000 loops, best of 3: 0.0563 usec per loop\n\n", "None of the answers above point out the real issue of tuples vs lists, which many new to Python seem to not fully understand.\nTuples and lists serve different purposes. Lists store homogenous data. You can and should have a list like this:\n[\"Bob\", \"Joe\", \"John\", \"Sam\"]\n\nThe reason that is a correct use of lists is because those are all homogenous types of data, specifically, people's names. But take a list like this:\n[\"Billy\", \"Bob\", \"Joe\", 42]\n\nThat list is one person's full name, and their age. That isn't one type of data. The correct way to store that information is either in a tuple, or in an object. Lets say we have a few :\n[(\"Billy\", \"Bob\", \"Joe\", 42), (\"Robert\", \"\", \"Smith\", 31)]\n\nThe immutability and mutability of Tuples and Lists is not the main difference. A list is a list of the same kind of items: files, names, objects. Tuples are a grouping of different types of objects. They have different uses, and many Python coders abuse lists for what tuples are meant for.\nPlease don't.\n\nEdit:\nI think this blog post explains why I think this better than I did:\n\nUnderstanding tuples vs. lists in Python - E-Scribe\n\n", "\nif I must convert a tuple to a set or list to be able to sort them, what's the point of using a tuple in the first place?\n\nIn this particular case, there probably isn't a point. This is a non-issue, because this isn't one of the cases where you'd consider using a tuple.\nAs you point out, tuples are immutable. The reasons for having immutable types apply to tuples:\n\ncopy efficiency: rather than copying an immutable object, you can alias it (bind a variable to a reference)\ncomparison efficiency: when you're using copy-by-reference, you can compare two variables by comparing location, rather than content\ninterning: you need to store at most one copy of any immutable value\nthere's no need to synchronize access to immutable objects in concurrent code\nconst correctness: some values shouldn't be allowed to change. This (to me) is the main reason for immutable types.\n\nNote that a particular Python implementation may not make use of all of the above features.\nDictionary keys must be immutable, otherwise changing the properties of a key-object can invalidate invariants of the underlying data structure. Tuples can thus potentially be used as keys. This is a consequence of const correctness.\nSee also \"Introducing tuples\", from Dive Into Python.\n", "Sometimes we like to use objects as dictionary keys\nFor what it's worth, tuples recently (2.6+) grew index() and count() methods\n", "I've always found having two completely separate types for the same basic data structure (arrays) to be an awkward design, but not a real problem in practice. (Every language has its warts, Python included, but this isn't an important one.)\n\nWhy does anyone care if a variable lives at a different place in memory than when it was originally allocated? This whole business of immutability in Python seems to be over emphasized.\n\nThese are different things. Mutability isn't related to the place it's stored in memory; it means the stuff it points to can't change.\nPython objects can't change location after they're created, mutable or not. (More accurately, the value of id() can't change--same thing, in practice.) The internal storage of mutable objects can change, but that's a hidden implementation detail.\n>>> x='hello'\n>>> id(x)\n1234567\n>>> x='good bye'\n>>> id(x)\n5432167\n\nThis isn't modifying (\"mutating\") the variable; it's creating a new variable with the same name, and discarding the old one. Compare to a mutating operation:\n>>> a = [1,2,3]\n>>> id(a)\n3084599212L\n>>> a[1] = 5\n>>> a\n[1, 5, 3]\n>>> id(a)\n3084599212L\n\nAs others have pointed out, this allows using arrays as keys to dictionaries, and other data structures that need immutability.\nNote that keys for dictionaries do not have to be completely immutable. Only the part of it used as a key needs to be immutable; for some uses, this is an important distinction. For example, you could have a class representing a user, which compares equality and a hash by the unique username. You could then hang other mutable data on the class--\"user is logged in\", etc. Since this doesn't affect equality or the hash, it's possible and perfectly valid to use this as a key in a dictionary. This isn't too commonly needed in Python; I just point it out since several people have claimed that keys need to be \"immutable\", which is only partially correct. I've used this many times with C++ maps and sets, though.\n", "As gnibbler offered in a comment, Guido had an opinion that is not fully accepted/appreciated: “lists are for homogeneous data, tuples are for heterogeneous data”. Of course, many of the opposers interpreted this as meaning that all elements of a list should be of the same type.\nI like to see it differently, not unlike others also have in the past:\nblue= 0, 0, 255\nalist= [\"red\", \"green\", blue]\n\nNote that I consider alist to be homogeneous, even if type(alist[1]) != type(alist[2]).\nIf I can change the order of the elements and I won't have issues in my code (apart from assumptions, e.g. “it should be sorted”), then a list should be used. If not (like in the tuple blue above), then I should use a tuple.\n", "They are important since they guarantee the caller that the object they pass won't be mutated.\nIf you do this:\na = [1,1,1]\ndoWork(a)\n\nThe caller has no guarantee of the value of a after the call.\nHowever, \na = (1,1,1)\ndoWorK(a)\n\nNow you as the caller or as a reader of this code know that a is the same.\nYou could always for this scenario make a copy of the list and pass that but now you are wasting cycles instead of using a language construct that makes more semantic sense.\n", "you can see here for some discussion on this\n", "Your question (and follow-up comments) focus on whether the id() changes during an assignment. Focusing on this follow-on effect of the difference between immutable object replacement and mutable object modification rather than the difference itself is perhaps not the best approach.\nBefore we continue, make sure that the behavior demonstrated below is what you expect from Python.\n>>> a1 = [1]\n>>> a2 = a1\n>>> print a2[0]\n1\n>>> a1[0] = 2\n>>> print a2[0]\n2\n\nIn this case, the contents of a2 was changed, even though only a1 had a new value assigned. Contrast to the following:\n>>> a1 = (1,)\n>>> a2 = a1\n>>> print a2[0]\n1\n>>> a1 = (2,)\n>>> print a2[0]\n1\n\nIn this latter case, we replaced the entire list, rather than updating its contents. With immutable types such as tuples, this is the only behavior allowed.\nWhy does this matter? Let's say you have a dict:\n>>> t1 = (1,2)\n>>> d1 = { t1 : 'three' }\n>>> print d1\n{(1,2): 'three'}\n>>> t1[0] = 0 ## results in a TypeError, as tuples cannot be modified\n>>> t1 = (2,3) ## creates a new tuple, does not modify the old one\n>>> print d1 ## as seen here, the dict is still intact\n{(1,2): 'three'}\n\nUsing a tuple, the dictionary is safe from having its keys changed \"out from under it\" to items which hash to a different value. This is critical to allow efficient implementation.\n" ]
[ 131, 42, 25, 15, 9, 8, 6, 1, 1 ]
[]
[]
[ "python", "tuples" ]
stackoverflow_0002174124_python_tuples.txt
Q: Implementing chat system with in Web browser We want to have web based application to track the issues, knowledge management and chat system. Once the user logged in, user can chat with the service engineers. We will be using Ajax for Chat within the browser. But the server-side we are not sure how to implement chat? The chat history must be saved for lateral viewing. When someone start chatting, the system must find the available service engineer and he will begin interfacing with customer. any better approach to handle the chat system with in the web? We are OK to use Python, PHP, Ruby/Rails, Grails or .NET We can use available systems, we need better interface/api to the available system so that it can be integrated within our application. A: Oh. If I have to implement something like this, I would take a XMPP (Jabber) server. Why to reinvent? There are two servers that are pretty stable and feature rich: ejabberd (implemented in Erlang) and OpenFire (implemented in Java). Personally I prefer OpenFire since it easier to configure and Java developers are easier to find in case you want to extend its functionality... But it is a matter of taste. For the web client there is a technology called BOSH. It allows you not to poll your server with requests every X seconds, but receive messages as soon as they are available. BOSH is a part of XMPP standard. There is a JavaScript library called Strophe JS that allows you to utilize BOSH on your web-page easily. There is an example implementation. Furthermore, your stuff could be more happy with desktop IM clients rather than web-based. If you use XMPP you automatically get an ability to connect to the service using any existing IM client with Jabber support. To get mentioned functionality to select available service engineer you could implement little server plugin and not the server as a whole. History is configurable in both servers. So finally, my opinion: take already written and proven XMPP server, its BOSH using Strophe JS and a little plugin to select free service engineer. A: We run an XMPP (jabber) server called OpenFire, which has a web-chat extension called FastPath. The one downside is that it forces us all to use the same client (Spark) or risk chat requests that reach non-Spark clients to vanish. But it is very customizable and you can capture just about any activity and stats. A: Have you considered using Erlang? It would probably require very little work to get going. I don't know of any complete systems for what you want, but Erlang is very easy to learn and there is an example of a chat server which you can probably modify to fit your needs. Obviously clear it with the author first.
Implementing chat system with in Web browser
We want to have web based application to track the issues, knowledge management and chat system. Once the user logged in, user can chat with the service engineers. We will be using Ajax for Chat within the browser. But the server-side we are not sure how to implement chat? The chat history must be saved for lateral viewing. When someone start chatting, the system must find the available service engineer and he will begin interfacing with customer. any better approach to handle the chat system with in the web? We are OK to use Python, PHP, Ruby/Rails, Grails or .NET We can use available systems, we need better interface/api to the available system so that it can be integrated within our application.
[ "Oh. If I have to implement something like this, I would take a XMPP (Jabber) server. Why to reinvent?\nThere are two servers that are pretty stable and feature rich: ejabberd (implemented in Erlang) and OpenFire (implemented in Java). Personally I prefer OpenFire since it easier to configure and Java developers are easier to find in case you want to extend its functionality... But it is a matter of taste.\nFor the web client there is a technology called BOSH. It allows you not to poll your server with requests every X seconds, but receive messages as soon as they are available. BOSH is a part of XMPP standard. There is a JavaScript library called Strophe JS that allows you to utilize BOSH on your web-page easily. There is an example implementation.\nFurthermore, your stuff could be more happy with desktop IM clients rather than web-based. If you use XMPP you automatically get an ability to connect to the service using any existing IM client with Jabber support.\nTo get mentioned functionality to select available service engineer you could implement little server plugin and not the server as a whole. History is configurable in both servers.\nSo finally, my opinion: take already written and proven XMPP server, its BOSH using Strophe JS and a little plugin to select free service engineer.\n", "We run an XMPP (jabber) server called OpenFire, which has a web-chat extension called FastPath. The one downside is that it forces us all to use the same client (Spark) or risk chat requests that reach non-Spark clients to vanish. But it is very customizable and you can capture just about any activity and stats.\n", "Have you considered using Erlang? It would probably require very little work to get going.\nI don't know of any complete systems for what you want, but Erlang is very easy to learn and there is an example of a chat server which you can probably modify to fit your needs.\nObviously clear it with the author first.\n" ]
[ 4, 2, 1 ]
[]
[]
[ ".net", "php", "python", "ruby_on_rails" ]
stackoverflow_0002175513_.net_php_python_ruby_on_rails.txt
Q: Best way to save complex Python data structures across program sessions (pickle, json, xml, database, other) Looking for advice on the best technique for saving complex Python data structures across program sessions. Here's a list of techniques I've come up with so far: pickle/cpickle json jsonpickle xml database (like SQLite) Pickle is the easiest and fastest technique, but my understanding is that there is no guarantee that pickle output will work across various versions of Python 2.x/3.x or across 32 and 64 bit implementations of Python. Json only works for simple data structures. Jsonpickle seems to correct this AND seems to be written to work across different versions of Python. Serializing to XML or to a database is possible, but represents extra effort since we would have to do the serialization ourselves manually. Thank you, Malcolm A: You have a misconception about pickles: they are guaranteed to work across Python versions. You simply have to choose a protocol version that is supported by all the Python versions you care about. The technique you left out is marshal, which is not guaranteed to work across Python versions (and btw, is how .pyc files are written). A: You left out the marshal and shelve modules. Also this python docs page covers persistence A: Have you looked at PySyck or pyYAML? A: What are your criteria for "best" ? pickle can do most Python structures, deeply nested ones too sqlite dbs can be easily queried (if you know sql :) speed / memory ? trust no benchmarks that you haven't faked yourself. (Fine print: cPickle.dump(protocol=-1) compresses, in one case 15M pickle / 60M sqlite, but can break. Strings that occur many times, e.g. country names, may take more memory than you expect; see the builtin intern(). )
Best way to save complex Python data structures across program sessions (pickle, json, xml, database, other)
Looking for advice on the best technique for saving complex Python data structures across program sessions. Here's a list of techniques I've come up with so far: pickle/cpickle json jsonpickle xml database (like SQLite) Pickle is the easiest and fastest technique, but my understanding is that there is no guarantee that pickle output will work across various versions of Python 2.x/3.x or across 32 and 64 bit implementations of Python. Json only works for simple data structures. Jsonpickle seems to correct this AND seems to be written to work across different versions of Python. Serializing to XML or to a database is possible, but represents extra effort since we would have to do the serialization ourselves manually. Thank you, Malcolm
[ "You have a misconception about pickles: they are guaranteed to work across Python versions. You simply have to choose a protocol version that is supported by all the Python versions you care about.\nThe technique you left out is marshal, which is not guaranteed to work across Python versions (and btw, is how .pyc files are written).\n", "You left out the marshal and shelve modules.\nAlso this python docs page covers persistence\n", "Have you looked at PySyck or pyYAML?\n", "What are your criteria for \"best\" ?\n\npickle can do most Python structures, deeply nested ones too\nsqlite dbs can be easily queried (if you know sql :)\nspeed / memory ? trust no benchmarks that you haven't faked yourself.\n\n(Fine print:\ncPickle.dump(protocol=-1) compresses, in one case 15M pickle / 60M sqlite, but can break.\nStrings that occur many times, e.g. country names, may take more memory than you expect;\nsee the builtin intern().\n)\n" ]
[ 15, 4, 2, 2 ]
[]
[]
[ "json", "pickle", "python", "sqlite" ]
stackoverflow_0002003693_json_pickle_python_sqlite.txt
Q: How to create "virtual root" with Python's ElementTree? I am trying to use Python's ElementTree to generate an XHTML file. However, the ElementTree.Element() just lets me create a single tag (e.g., HTML). I need to create some sort of a virtual root or whatever it is called so that I can put the various , DOCTYPES, etc. How do I do that? Thanks A: I don't know if there's a better way but I've seen this done: Create the base document as a string: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html></html> Then parse that string to start your new document. A: I have had the same problem. When parsing a document and writing the docuemnt back again the doc-type definition is not present anymore. I found a solution browsing the documentation: link text Saving HTML Files # To save a plain HTML file, just write out the tree. tree.write("outfile.htm") This works well, as long as the file doesn’t contain any embedded SCRIPT or STYLE tags. If you want, you can add a DTD reference to the beginning of the file: file = open("outfile.htm", "wb") file.write(DTD + "\n") tree.write(file) file.close()
How to create "virtual root" with Python's ElementTree?
I am trying to use Python's ElementTree to generate an XHTML file. However, the ElementTree.Element() just lets me create a single tag (e.g., HTML). I need to create some sort of a virtual root or whatever it is called so that I can put the various , DOCTYPES, etc. How do I do that? Thanks
[ "I don't know if there's a better way but I've seen this done:\nCreate the base document as a string:\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n<html></html>\n\nThen parse that string to start your new document.\n", "I have had the same problem. When parsing a document and writing the docuemnt back again the doc-type definition is not present anymore. I found a solution browsing the documentation:\nlink text\nSaving HTML Files #\nTo save a plain HTML file, just write out the tree.\ntree.write(\"outfile.htm\")\n\nThis works well, as long as the file doesn’t contain any embedded SCRIPT or STYLE tags.\nIf you want, you can add a DTD reference to the beginning of the file:\nfile = open(\"outfile.htm\", \"wb\")\nfile.write(DTD + \"\\n\")\ntree.write(file)\nfile.close()\n\n" ]
[ 7, 1 ]
[]
[]
[ "elementtree", "python" ]
stackoverflow_0001070772_elementtree_python.txt
Q: Signal handling in Python In my program I have a bunch of threads running and I'm trying to interrupt the main thread to get it to do something asynchronously. So I set up a handler and send the main process a SIGUSR1 - see the code below: def SigUSR1Handler(signum, frame): self._logger.debug('Received SIGUSR1') return signal.signal(signal.SIGUSR1, SigUSR1Handler) [signal.signal(signal.SIGUSR1, signal.SIG_IGN)] In the above case, all the threads and the main process stops - from a 'c' point of view this was unexpected - I want the threads to continue as they were before the signal. If I put the SIG_IGN in instead, everything continues fine. Can somebody tell me how to do this? Maybe I have to do something with the 'frame' manually to get back to where it was..just a guess though thanks in advance, Thanks for your help on this. To explain a bit more, I have thread instances writing string information to a socket which is also output to a file. These threads run their own timers so they independently write their outputs to the socket. When the program runs I also see their output on stdout but it all stops as soon as I see the debug line from the signal. I need the threads to constantly send this info but I need the main program to take a command so it also starts doing something else (in parallel) for a while. I thought I'd just be able to send a signal from the command line to trigger this. A: Mixing signals and threads is always a little precarious. What you describe should not happen, however. Python only handles signals in the main thread. If the OS delivered the signal to another thread, that thread may be briefly interrupted (when it's performing, say, a systemcall) but it won't execute the signal handler. The main thread will be asked to execute the signalhandler at the next opportunity. What are your threads (including the main thread) actually doing when you send the signal? How do you notice that they all 'stop'? Is it a brief pause (easily explained by the fact that the main thread will need to acquire the GIL before handling the signal) or does the process break down entirely? A: I'll sort-of answer my own question: In my first attempt at this I was using time.sleep(run_time) in the main thread to control how long the threads ran until they were stopped. By adding debug I could see that the sleep loop seemed to be exiting as soon as the signal handler returned so everything was shutting down normally but early! I've replaced the sleep with a while loop and that doesn't jump out after the signal handler returns so my threads keep running. So it solves the problem but I'm still a bit puzzled about sleep()'s behaviour. A: You should probably use a threading.Condition variable instead of sending signals. Have your main thread check it every loop and perform its special operation if it's been set. If you insist on using signals, you'll want to move to using subprocess instead of threads, as your problem is likely due to the GIL. A: Watch this presentation by David Beazley. http://blip.tv/file/2232410 It also explains some quirky behavior related to threads and signals (Python specific, not the general quirkiness of the subject :-) ). http://pyprocessing.berlios.de/ Pyprocessing is a neat library that makes it easier to work with separate processes in Python.
Signal handling in Python
In my program I have a bunch of threads running and I'm trying to interrupt the main thread to get it to do something asynchronously. So I set up a handler and send the main process a SIGUSR1 - see the code below: def SigUSR1Handler(signum, frame): self._logger.debug('Received SIGUSR1') return signal.signal(signal.SIGUSR1, SigUSR1Handler) [signal.signal(signal.SIGUSR1, signal.SIG_IGN)] In the above case, all the threads and the main process stops - from a 'c' point of view this was unexpected - I want the threads to continue as they were before the signal. If I put the SIG_IGN in instead, everything continues fine. Can somebody tell me how to do this? Maybe I have to do something with the 'frame' manually to get back to where it was..just a guess though thanks in advance, Thanks for your help on this. To explain a bit more, I have thread instances writing string information to a socket which is also output to a file. These threads run their own timers so they independently write their outputs to the socket. When the program runs I also see their output on stdout but it all stops as soon as I see the debug line from the signal. I need the threads to constantly send this info but I need the main program to take a command so it also starts doing something else (in parallel) for a while. I thought I'd just be able to send a signal from the command line to trigger this.
[ "Mixing signals and threads is always a little precarious. What you describe should not happen, however. Python only handles signals in the main thread. If the OS delivered the signal to another thread, that thread may be briefly interrupted (when it's performing, say, a systemcall) but it won't execute the signal handler. The main thread will be asked to execute the signalhandler at the next opportunity. \nWhat are your threads (including the main thread) actually doing when you send the signal? How do you notice that they all 'stop'? Is it a brief pause (easily explained by the fact that the main thread will need to acquire the GIL before handling the signal) or does the process break down entirely?\n", "I'll sort-of answer my own question:\nIn my first attempt at this I was using time.sleep(run_time) in the main\nthread to control how long the threads ran until they were stopped. By adding\ndebug I could see that the sleep loop seemed to be exiting as soon as the\nsignal handler returned so everything was shutting down normally but early!\nI've replaced the sleep with a while loop and that doesn't jump out after \nthe signal handler returns so my threads keep running. So it solves the \nproblem but I'm still a bit puzzled about sleep()'s behaviour.\n", "You should probably use a threading.Condition variable instead of sending signals. Have your main thread check it every loop and perform its special operation if it's been set.\nIf you insist on using signals, you'll want to move to using subprocess instead of threads, as your problem is likely due to the GIL.\n", "Watch this presentation by David Beazley.\nhttp://blip.tv/file/2232410\nIt also explains some quirky behavior related to threads and signals (Python specific, not the general quirkiness of the subject :-) ).\nhttp://pyprocessing.berlios.de/ Pyprocessing is a neat library that makes it easier to work with separate processes in Python.\n" ]
[ 2, 1, 0, 0 ]
[]
[]
[ "multithreading", "python", "signals" ]
stackoverflow_0002163194_multithreading_python_signals.txt
Q: How do I convert a string to a buffer in Python 3.1? I am attempting to pipe something to a subprocess using the following line: p.communicate("insert into egg values ('egg');"); TypeError: must be bytes or buffer, not str How can I convert the string to a buffer? A: The correct answer is: p.communicate(b"insert into egg values ('egg');"); Note the leading b, telling you that it's a string of bytes, not a string of unicode characters. Also, if you are reading this from a file: value = open('thefile', 'rt').read() p.communicate(value); The change that to: value = open('thefile', 'rb').read() p.communicate(value); Again, note the 'b'. Now if your value is a string you get from an API that only returns strings no matter what, then you need to encode it. p.communicate(value.encode('latin-1'); Latin-1, because unlike ASCII it supports all 256 bytes. But that said, having binary data in unicode is asking for trouble. It's better if you can make it binary from the start. A: You can convert it to bytes with encode method: >>> "insert into egg values ('egg');".encode('ascii') # ascii is just an example b"insert into egg values ('egg');"
How do I convert a string to a buffer in Python 3.1?
I am attempting to pipe something to a subprocess using the following line: p.communicate("insert into egg values ('egg');"); TypeError: must be bytes or buffer, not str How can I convert the string to a buffer?
[ "The correct answer is:\np.communicate(b\"insert into egg values ('egg');\");\n\nNote the leading b, telling you that it's a string of bytes, not a string of unicode characters. Also, if you are reading this from a file:\nvalue = open('thefile', 'rt').read()\np.communicate(value);\n\nThe change that to:\nvalue = open('thefile', 'rb').read()\np.communicate(value);\n\nAgain, note the 'b'.\nNow if your value is a string you get from an API that only returns strings no matter what, then you need to encode it.\np.communicate(value.encode('latin-1');\n\nLatin-1, because unlike ASCII it supports all 256 bytes. But that said, having binary data in unicode is asking for trouble. It's better if you can make it binary from the start.\n", "You can convert it to bytes with encode method:\n>>> \"insert into egg values ('egg');\".encode('ascii') # ascii is just an example\nb\"insert into egg values ('egg');\"\n\n" ]
[ 12, 7 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0002176511_python_python_3.x.txt
Q: Individually labeled bars for bar graphs in matplotlib / Python I am trying to create bar graphs of letter frequency in Python. I thought the best way to accomplish this would be matplotlib, but I have been unable to decipher the documentation. Is it possible to label the bars of a matplotlib.pyplot.hist plot with one letter per bar, instead of a numerical axis? I think it must be, but I have not used matplotlib before. This is the sort of graph I'm after, rendered as text: | | * | * * | * * * +---------- A B C A: Sure is! You just need to reset the tick labels. EDIT with answer and picture (can be done similarly with hist): x = scipy.arange(4) y = scipy.array([4,7,6,5]) f = pylab.figure() ax = f.add_axes([0.1, 0.1, 0.8, 0.8]) ax.bar(x, y, align='center') ax.set_xticks(x) ax.set_xticklabels(['Aye', 'Bee', 'Cee', 'Dee']) f.show() (source: stevetjoa.com)
Individually labeled bars for bar graphs in matplotlib / Python
I am trying to create bar graphs of letter frequency in Python. I thought the best way to accomplish this would be matplotlib, but I have been unable to decipher the documentation. Is it possible to label the bars of a matplotlib.pyplot.hist plot with one letter per bar, instead of a numerical axis? I think it must be, but I have not used matplotlib before. This is the sort of graph I'm after, rendered as text: | | * | * * | * * * +---------- A B C
[ "Sure is! You just need to reset the tick labels.\nEDIT with answer and picture (can be done similarly with hist):\nx = scipy.arange(4)\ny = scipy.array([4,7,6,5])\nf = pylab.figure()\nax = f.add_axes([0.1, 0.1, 0.8, 0.8])\nax.bar(x, y, align='center')\nax.set_xticks(x)\nax.set_xticklabels(['Aye', 'Bee', 'Cee', 'Dee'])\nf.show()\n\n\n(source: stevetjoa.com) \n" ]
[ 34 ]
[]
[]
[ "histogram", "label", "matplotlib", "plot", "python" ]
stackoverflow_0002177504_histogram_label_matplotlib_plot_python.txt
Q: Python: How do I disallow imports of a class from a module? I tried: __all__ = ['SpamPublicClass'] But, of course that's just for: from spammodule import * Is there a way to block importing of a class. I'm worried about confusion on the API level of my code that somebody will write: from spammodule import SimilarSpamClass and it'll cause debugging mayhem. A: The convention is to use a _ as a prefix: class PublicClass(object): pass class _PrivateClass(object): pass The following: from module import * Will not import the _PrivateClass. But this will not prevent them from importing it. They could still import it explicitly. from module import _PrivateClass A: Start the names of private classes with and underscore, so that it will be clear just by the name that it is not for public use. That will not actually prevent anybody from importing the class, but it shouldn't happen by accident. It's a well established convention that names starting with an underscore are "internal". A: There is no way to actually block access to the contents of a module or the contents of a class for that matter in Python. This sort of thing is handled by convention name your class _SimilarSpamClass (with a leading underscore) to indicate to callers that this is an implementation detail of your module and not part of the published API. To mark something as "private" in Python properly document your public API so other developers know how to use your module correctly and follow the standard naming conventions so that users of your module easily notice when they have strayed from your API to your implementation.
Python: How do I disallow imports of a class from a module?
I tried: __all__ = ['SpamPublicClass'] But, of course that's just for: from spammodule import * Is there a way to block importing of a class. I'm worried about confusion on the API level of my code that somebody will write: from spammodule import SimilarSpamClass and it'll cause debugging mayhem.
[ "The convention is to use a _ as a prefix:\nclass PublicClass(object):\n pass\n\nclass _PrivateClass(object):\n pass\n\nThe following:\nfrom module import *\n\nWill not import the _PrivateClass.\nBut this will not prevent them from importing it. They could still import it explicitly.\nfrom module import _PrivateClass\n\n", "Start the names of private classes with and underscore, so that it will be clear just by the name that it is not for public use. That will not actually prevent anybody from importing the class, but it shouldn't happen by accident. It's a well established convention that names starting with an underscore are \"internal\".\n", "There is no way to actually block access to the contents of a module or the contents of a class for that matter in Python. This sort of thing is handled by convention name your class _SimilarSpamClass (with a leading underscore) to indicate to callers that this is an implementation detail of your module and not part of the published API.\nTo mark something as \"private\" in Python properly document your public API so other developers know how to use your module correctly and follow the standard naming conventions so that users of your module easily notice when they have strayed from your API to your implementation.\n" ]
[ 20, 7, 5 ]
[]
[]
[ "import", "python", "python_import", "python_module" ]
stackoverflow_0002177817_import_python_python_import_python_module.txt
Q: Inserting multiple types into an SQLite database with Python I'm trying to create an SQLite 3 database from Python. I have a few types I'd like to insert into each record: A float, and then 3 groups of n floats, currently a tuple but could be an array or list.. I'm not well-enough versed in Python to understand all the differences. My problem is the INSERT statement. DAS = 12345 lats = (42,43,44,45) lons = (10,11,12,13) times = (1,2,3,4,5,6,7,8,9) import sqlite3 connection = sqlite3.connect("test.db") cursor = connection.cursor() cursor.execute( "create table foo(DAS LONG PRIMARY KEY,lats real(4),lons real(4), times real(9) )" ) I'm not sure what comes next. Something along the lines of: cmd = 'INSERT into foo values (?,?,?,?), ..." cursor.execute(cmd) How should I best build the SQL insert command given this data? A: The type real(4) does not mean an array/list/tuple of 4 reals; the 4 alters the 'real' type. However, SQLite mostly ignores column types due to its manifest typing, but they can still affect column affinity. You have a few options, such as storing the text representation (from repr) or using four columns, one for each. You can modify this with various hooks provided by the Python's SQLite library to handle some of the transformation for you, but separate columns (with functions to localize and handle various statements, so you don't repeat yourself) is probably the easiest to work with if you need to search/etc. in SQL on each value. If you do store a text representation, ast.literal_eval (or eval, under special conditions) will convert back into a Python object. A: Something like this: db = sqlite3.connect("test.db") cursor = db.cursor() cursor.execute("insert into foo values (?,?,?,?)", (val1, val2, val3, val4)) db.commit() # Autocommit is off by default (and rightfully so)! Please note, that I am not using string formatting to inject actual data into the query, but instead make the library do this work for me. That way the data is quoted and escaped correctly. EDIT: Obviously, considering your database schema, it doesn't work. It is impractical to attempt to store a collection-type value in a single field of a sqlite database. If I understand you correctly, you should just create a separate column for every value you are storing in the single row. That will be a lot of columns, sure, but that's the most natural way to do it. A: (A month later), two steps: 1. flatten e.g. DAS lats lons times to one long list, say 18 long 2. generate "Insert into tablename xx (?,?,... 18 question marks )" and execute that. Test = 1 def flatten( *args ): """ 1, (2,3), [4,5] -> [1 2 3 4 5] """ # 1 level only -- SO [python] [flatten] zzz all = [] for a in args: all.extend( a if hasattr( a, "__iter__" ) else [a] ) if Test: print "test flatten:", all return all def sqlinsert( db, tablename, *args ): flatargs = flatten( *args ) # one long list ncol = len(flatargs) qmarks = "?" + (ncol-1) * ",?" insert = "Insert into tablename %s values (%s)" % (tablename, qmarks) if Test: print "test sqlinsert:", insert if db: db.execute( insert, flatargs ) # db.executemany( insert, map( flatargs, rows )) return insert #............................................................................... if __name__ == "__main__": print sqlinsert( None, "Table", "hidiho", (4,5), [6] )
Inserting multiple types into an SQLite database with Python
I'm trying to create an SQLite 3 database from Python. I have a few types I'd like to insert into each record: A float, and then 3 groups of n floats, currently a tuple but could be an array or list.. I'm not well-enough versed in Python to understand all the differences. My problem is the INSERT statement. DAS = 12345 lats = (42,43,44,45) lons = (10,11,12,13) times = (1,2,3,4,5,6,7,8,9) import sqlite3 connection = sqlite3.connect("test.db") cursor = connection.cursor() cursor.execute( "create table foo(DAS LONG PRIMARY KEY,lats real(4),lons real(4), times real(9) )" ) I'm not sure what comes next. Something along the lines of: cmd = 'INSERT into foo values (?,?,?,?), ..." cursor.execute(cmd) How should I best build the SQL insert command given this data?
[ "The type real(4) does not mean an array/list/tuple of 4 reals; the 4 alters the 'real' type. However, SQLite mostly ignores column types due to its manifest typing, but they can still affect column affinity.\nYou have a few options, such as storing the text representation (from repr) or using four columns, one for each.\nYou can modify this with various hooks provided by the Python's SQLite library to handle some of the transformation for you, but separate columns (with functions to localize and handle various statements, so you don't repeat yourself) is probably the easiest to work with if you need to search/etc. in SQL on each value.\nIf you do store a text representation, ast.literal_eval (or eval, under special conditions) will convert back into a Python object.\n", "Something like this:\ndb = sqlite3.connect(\"test.db\")\ncursor = db.cursor()\ncursor.execute(\"insert into foo values (?,?,?,?)\", (val1, val2, val3, val4))\ndb.commit() # Autocommit is off by default (and rightfully so)!\n\nPlease note, that I am not using string formatting to inject actual data into the query, but instead make the library do this work for me. That way the data is quoted and escaped correctly.\nEDIT: Obviously, considering your database schema, it doesn't work. It is impractical to attempt to store a collection-type value in a single field of a sqlite database. If I understand you correctly, you should just create a separate column for every value you are storing in the single row. That will be a lot of columns, sure, but that's the most natural way to do it.\n", "(A month later), two steps:\n1. flatten e.g. DAS lats lons times to one long list, say 18 long\n2. generate \"Insert into tablename xx (?,?,... 18 question marks )\" and execute that.\nTest = 1\n\ndef flatten( *args ):\n \"\"\" 1, (2,3), [4,5] -> [1 2 3 4 5] \"\"\"\n # 1 level only -- SO [python] [flatten] zzz\n all = []\n for a in args:\n all.extend( a if hasattr( a, \"__iter__\" ) else [a] )\n if Test: print \"test flatten:\", all\n return all\n\ndef sqlinsert( db, tablename, *args ):\n flatargs = flatten( *args ) # one long list\n ncol = len(flatargs)\n qmarks = \"?\" + (ncol-1) * \",?\"\n insert = \"Insert into tablename %s values (%s)\" % (tablename, qmarks)\n if Test: print \"test sqlinsert:\", insert\n if db:\n db.execute( insert, flatargs )\n # db.executemany( insert, map( flatargs, rows ))\n return insert\n\n#...............................................................................\nif __name__ == \"__main__\":\n print sqlinsert( None, \"Table\", \"hidiho\", (4,5), [6] )\n\n" ]
[ 1, 0, 0 ]
[]
[]
[ "insert", "python", "sqlite" ]
stackoverflow_0001963790_insert_python_sqlite.txt
Q: Trying to understand Django's sorl-thumbnail I have been playing around with sorl-thumbnail for Django. And trying to understand how it works better. I've read the guide for it, installed it in my site-packages, made sure PIL is installed correctly, put sorl.thumbnail in the INSTALLED APPS in my settings.py, put from sorl.thumbnail.fields import ImageWithThumbnailsField at the top in my models.py, added image = ImageWithThumbnailsField(upload to="images/", thumbnail={'size':(80, 80)}) as one of my model fields, passed the model through my view to the template, and in the template added {% load thumbnail %} at the top and put in the variable {{ mymodel.image.thumbnail_tag }} in there too. But from what I understood is that when I upload an image through the admin, it would create the thumbnail straight away, but it only actually creates in when I see my template in the browser? Is this correct? The thumbnail shows fine, it looks great in fact, but I thought that adding the model field part of it would create the thumbnail instantly once the image has uploaded? ...Why not just use the models.ImageField in my model instead? ...or have I done this all OK and I've just got the way it works wrong? A: I'm one of the sorl-thumbnail developers. Firstly, you don't need to {% load thumbnail %} unless you're just using the thumbnail tag rather than a thumbnail field. Currently, a thumbnail is only ever created the first time it is used - even if you use the field [I'll get around to changing that one day if no-one else does first]. The advantage of the field is that you can specify the sizing rather than giving the freedom to the designer in the template level [and making it easier for an admin thumbnail]. Both ways work, you get to decide which works best for you. A: how about adding some jCrop in the admin to specify area of thumbnail ? Woul be pretty cool :)
Trying to understand Django's sorl-thumbnail
I have been playing around with sorl-thumbnail for Django. And trying to understand how it works better. I've read the guide for it, installed it in my site-packages, made sure PIL is installed correctly, put sorl.thumbnail in the INSTALLED APPS in my settings.py, put from sorl.thumbnail.fields import ImageWithThumbnailsField at the top in my models.py, added image = ImageWithThumbnailsField(upload to="images/", thumbnail={'size':(80, 80)}) as one of my model fields, passed the model through my view to the template, and in the template added {% load thumbnail %} at the top and put in the variable {{ mymodel.image.thumbnail_tag }} in there too. But from what I understood is that when I upload an image through the admin, it would create the thumbnail straight away, but it only actually creates in when I see my template in the browser? Is this correct? The thumbnail shows fine, it looks great in fact, but I thought that adding the model field part of it would create the thumbnail instantly once the image has uploaded? ...Why not just use the models.ImageField in my model instead? ...or have I done this all OK and I've just got the way it works wrong?
[ "I'm one of the sorl-thumbnail developers.\nFirstly, you don't need to {% load thumbnail %} unless you're just using the thumbnail tag rather than a thumbnail field.\nCurrently, a thumbnail is only ever created the first time it is used - even if you use the field [I'll get around to changing that one day if no-one else does first]. The advantage of the field is that you can specify the sizing rather than giving the freedom to the designer in the template level [and making it easier for an admin thumbnail].\nBoth ways work, you get to decide which works best for you.\n", "how about adding some jCrop in the admin to specify area of thumbnail ? Woul be pretty cool :) \n" ]
[ 2, 0 ]
[]
[]
[ "django", "image_processing", "python" ]
stackoverflow_0001171680_django_image_processing_python.txt
Q: How can I step into pdb to diagnose this error on a production server? ProgrammingError(1110, "Column 'about' specified twice" ProgrammingError(1110, "Column 'about' specified twice" /usr/local/lib/python2.5/site-packages/MySQLdb/connections.py errorclass <class '_mysql_exceptions.ProgrammingError'> errorvalue ProgrammingError(1110, "Column 'about' specified twice") This error seems to be happening here in django_authopenid/views.py: if 'bnewaccount' in request.POST.keys(): form1 = OpenidRegisterForm(request.POST) if form1.is_valid(): next = clean_next(form1.cleaned_data.get('next')) is_redirect = True tmp_pwd = User.objects.make_random_password() user_ = User.objects.create_user(form1.cleaned_data['username'], form1.cleaned_data['email'], tmp_pwd) ### this is the last evaluated line in my code # make association with openid uassoc = UserAssociation(openid_url=str(openid_), user_id=user_.id) uassoc.save() A: If you're asking how to break into pdb, add this line in your code where you want to drop into the debugger: import pdb; pdb.set_trace() If you need to know how to have a stdout on your production server, I don't know that.
How can I step into pdb to diagnose this error on a production server? ProgrammingError(1110, "Column 'about' specified twice"
ProgrammingError(1110, "Column 'about' specified twice" /usr/local/lib/python2.5/site-packages/MySQLdb/connections.py errorclass <class '_mysql_exceptions.ProgrammingError'> errorvalue ProgrammingError(1110, "Column 'about' specified twice") This error seems to be happening here in django_authopenid/views.py: if 'bnewaccount' in request.POST.keys(): form1 = OpenidRegisterForm(request.POST) if form1.is_valid(): next = clean_next(form1.cleaned_data.get('next')) is_redirect = True tmp_pwd = User.objects.make_random_password() user_ = User.objects.create_user(form1.cleaned_data['username'], form1.cleaned_data['email'], tmp_pwd) ### this is the last evaluated line in my code # make association with openid uassoc = UserAssociation(openid_url=str(openid_), user_id=user_.id) uassoc.save()
[ "If you're asking how to break into pdb, add this line in your code where you want to drop into the debugger:\nimport pdb; pdb.set_trace() \n\nIf you need to know how to have a stdout on your production server, I don't know that.\n" ]
[ 0 ]
[]
[]
[ "django", "pdb", "python" ]
stackoverflow_0002177929_django_pdb_python.txt
Q: Opening POSTed file with PIL Image Using WSGI, webob and PIL, I'm trying to use Image.open() on a file directly from the request. However, Image.open() always throws the exception "cannot identify image file". The image is the only field, no other POST or GET variables are used. The file is coming from a standard HTML upload form with enctype="multipart/form-data". import Image, ImageFile from webob import Request def application(environ, start_response): req = Request(environ) req.make_body_seekable() im = Image.open(req.body_file) # "Cannot identify image file" im.save('testfileio.png','PNG') My guess is I'm not loading in the uploaded image data correctly, but am not sure what the right way to do it would be. A: I'm not famaliar with webob, but my guess is that body_file contains the contents of the entire post and not just your image. The docs seem to confirm this. What's in req.POST['nameOfFileControl']? Does that have a file handle? That is going to be the file handle that Image.open needs.
Opening POSTed file with PIL Image
Using WSGI, webob and PIL, I'm trying to use Image.open() on a file directly from the request. However, Image.open() always throws the exception "cannot identify image file". The image is the only field, no other POST or GET variables are used. The file is coming from a standard HTML upload form with enctype="multipart/form-data". import Image, ImageFile from webob import Request def application(environ, start_response): req = Request(environ) req.make_body_seekable() im = Image.open(req.body_file) # "Cannot identify image file" im.save('testfileio.png','PNG') My guess is I'm not loading in the uploaded image data correctly, but am not sure what the right way to do it would be.
[ "I'm not famaliar with webob, but my guess is that body_file contains the contents of the entire post and not just your image. The docs seem to confirm this.\nWhat's in req.POST['nameOfFileControl']? Does that have a file handle? That is going to be the file handle that Image.open needs.\n" ]
[ 4 ]
[]
[]
[ "mod_wsgi", "python", "webob" ]
stackoverflow_0002174938_mod_wsgi_python_webob.txt
Q: In python, sorting on date field, field may sometimes be null I am having a hard time coming up with a slick way to handle this sort. I have data coming back from a database read. I want to sort on the accoutingdate. However, accoutingdate may sometimes be null. I am currently doing the following: results = sorted(results, key=operator.itemgetter('accountingdate'), reverse=True) But, this bombs with "TypeError: can't compare datetime.date to NoneType" due to some accoutingdates being null. What is the "most correct" or "most Pythonic" way to handle this? A: Using a key= function is definitely right, you just have to decide how you want to treat the None values -- pick a datetime value that you want to treat as the equivalent of None for sorting purposes. E.g.: import datetime mindate = datetime.date(datetime.MINYEAR, 1, 1) def getaccountingdate(x): return x['accountingdate'] or mindate results = sorted(results, key=getaccountingdate, reverse=True) Just see how much simpler this is than defining a cmp function instead -- and if you do some benchmarking you'll find it's also significantly faster! There's no upside at all in using a cmp function instead of this key function, and it would be a bad design choice to do so. A: You could use a custom sorting function that treats None specially: def nonecmp(a, b): if a is None and b is None: return 0 if a is None: return -1 if b is None: return 1 return cmp(a, b) results = sorted(results, cmp=nonecmp, ...) This treats None as being smaller than all datetime objects.
In python, sorting on date field, field may sometimes be null
I am having a hard time coming up with a slick way to handle this sort. I have data coming back from a database read. I want to sort on the accoutingdate. However, accoutingdate may sometimes be null. I am currently doing the following: results = sorted(results, key=operator.itemgetter('accountingdate'), reverse=True) But, this bombs with "TypeError: can't compare datetime.date to NoneType" due to some accoutingdates being null. What is the "most correct" or "most Pythonic" way to handle this?
[ "Using a key= function is definitely right, you just have to decide how you want to treat the None values -- pick a datetime value that you want to treat as the equivalent of None for sorting purposes. E.g.:\nimport datetime\nmindate = datetime.date(datetime.MINYEAR, 1, 1)\n\ndef getaccountingdate(x):\n return x['accountingdate'] or mindate\n\nresults = sorted(results, key=getaccountingdate, reverse=True)\n\nJust see how much simpler this is than defining a cmp function instead -- and if you do some benchmarking you'll find it's also significantly faster! There's no upside at all in using a cmp function instead of this key function, and it would be a bad design choice to do so.\n", "You could use a custom sorting function that treats None specially:\ndef nonecmp(a, b):\n if a is None and b is None:\n return 0\n if a is None:\n return -1\n if b is None:\n return 1\n return cmp(a, b)\n\nresults = sorted(results, cmp=nonecmp, ...)\n\nThis treats None as being smaller than all datetime objects.\n" ]
[ 30, 12 ]
[]
[]
[ "python", "sorting" ]
stackoverflow_0002178931_python_sorting.txt
Q: unpredicted output binary search tree in python class Node(): def __init__(self,data, left=None, right=None): self.data = data self.left = left self.right = right class BSTree(): def __init__(self): self.root = None def add(self,data): if self.root is None: self.root = Node(data) self.reset() else: while self.curNode is not None: if data < self.curNode.data: self.curNode = self.curNode.left elif data > self.curNode.data: self.curNode = self.curNode.right self.curNode=Node(data) self.reset() def pprint(self,Node,indent): if Node is not None: self.pprint(Node.left, indent+1) print indent*" ",Node.data self.pprint(Node.right, indent+1) if __name__=="__main__": y = BSTree() for pres in ["OBAMA","BUSHW","CLINTON","BUSHG","REGAN","CARTER","FORD","NIXON","JOHNSON"]: y.add(pres) y.pprint(y.root,0) This code runs without error but my output is OBAMA I cannot figure out why the code above does not have errors at runtime but only add's the first node to the tree A: def __add(self,node,data): if node is None: return Node(data) else: if data < node.data: node.left = self.__add(node.left,data) elif data > node.data: node.right = self.__add(node.right,data) This function is incorrect. It always overwrites the first left or right child of the root node, unless the root is None. Since this is homework, I won't write the correct version for you, but here is a hint - first find the spot where the new node should be added, THEN assign to the left or right child. Edit: in response to your update - you are very close now. Your last error lies in the fact that you are not actually attaching the new node to anything. Rather, you're assigning it to curNode which is not part of the structure of your tree. You instead want to link it to the parent node as either the right or left child. A: I figured out the answer. Thank you to danben for guidance in getting there! It was a combination of what he was saying and looking at some other implementations on my own. Here is what I came up with in case anyone was wondering. class Node(): def __init__(self,data, left=None, right=None): self.data = data self.left = left self.right = right class BSTree(): def __init__(self): self.root = None def __add(self,node,data): if self.root is None: self.root = Node(data) if node is None: return Node(data) else: if data < node.data: node.left = self.__add(node.left,data) elif data > node.data: node.right = self.__add(node.right,data) return node def add(self,data): self.__add(self.root,data) def __preorder(self,node): if node is not None: print node.data self.__preorder(node.left) self.__preorder(node.right) def preorder(self): self.__preorder(self.root) def __inorder(self,node): if node is not None: self.__inorder(node.left) self.__inorder(node.right) print node.data def inorder(self): self.__inorder(self.root) def __postorder(self,node): if node is not None: self.__postorder(node.left) print node.data self.__postorder(node.right) def postorder(self): self.__postorder(self.root) def pprint(self,Node,indent): if Node is not None: self.pprint(Node.right, indent+1) print indent*" ",Node.data self.pprint(Node.left, indent+1) def leafcount(self,Node): if Node is None: return 0 if self.atLeaf(Node): return 1 else: return self.leafcount(Node.left)+self.leafcount(Node.right) if __name__=="__main__": y = BSTree() for pres\ in ["OBAMA","BUSHW","CLINTON","BUSHG","REGAN","CARTER","FORD","NIXON","JOHNSON"]: y.add(pres) y.pprint(y.root,0)
unpredicted output binary search tree in python
class Node(): def __init__(self,data, left=None, right=None): self.data = data self.left = left self.right = right class BSTree(): def __init__(self): self.root = None def add(self,data): if self.root is None: self.root = Node(data) self.reset() else: while self.curNode is not None: if data < self.curNode.data: self.curNode = self.curNode.left elif data > self.curNode.data: self.curNode = self.curNode.right self.curNode=Node(data) self.reset() def pprint(self,Node,indent): if Node is not None: self.pprint(Node.left, indent+1) print indent*" ",Node.data self.pprint(Node.right, indent+1) if __name__=="__main__": y = BSTree() for pres in ["OBAMA","BUSHW","CLINTON","BUSHG","REGAN","CARTER","FORD","NIXON","JOHNSON"]: y.add(pres) y.pprint(y.root,0) This code runs without error but my output is OBAMA I cannot figure out why the code above does not have errors at runtime but only add's the first node to the tree
[ " def __add(self,node,data): \n if node is None: \n return Node(data) \n else: \n if data < node.data: \n node.left = self.__add(node.left,data) \n elif data > node.data: \n node.right = self.__add(node.right,data) \n\nThis function is incorrect. It always overwrites the first left or right child of the root node, unless the root is None.\nSince this is homework, I won't write the correct version for you, but here is a hint - first find the spot where the new node should be added, THEN assign to the left or right child.\nEdit: in response to your update - you are very close now. Your last error lies in the fact that you are not actually attaching the new node to anything. Rather, you're assigning it to curNode which is not part of the structure of your tree. You instead want to link it to the parent node as either the right or left child.\n", "I figured out the answer. Thank you to danben for guidance in getting there! It was a combination of what he was saying and looking at some other implementations on my own. Here is what I came up with in case anyone was wondering.\nclass Node(): \n def __init__(self,data, left=None, right=None): \n self.data = data \n self.left = left\n self.right = right \nclass BSTree(): \n def __init__(self): \n self.root = None\n\n def __add(self,node,data):\n if self.root is None:\n self.root = Node(data)\n if node is None:\n return Node(data)\n else:\n if data < node.data:\n node.left = self.__add(node.left,data)\n elif data > node.data:\n node.right = self.__add(node.right,data)\n return node\n\n def add(self,data):\n self.__add(self.root,data)\n\n def __preorder(self,node): \n if node is not None:\n print node.data \n self.__preorder(node.left) \n self.__preorder(node.right)\n\n def preorder(self):\n self.__preorder(self.root)\n\n def __inorder(self,node): \n if node is not None:\n self.__inorder(node.left)\n self.__inorder(node.right)\n print node.data\n\n def inorder(self):\n self.__inorder(self.root)\n\n def __postorder(self,node): \n if node is not None:\n self.__postorder(node.left)\n print node.data\n self.__postorder(node.right)\n\n def postorder(self):\n self.__postorder(self.root)\n\n def pprint(self,Node,indent): \n if Node is not None:\n self.pprint(Node.right, indent+1) \n print indent*\" \",Node.data\n self.pprint(Node.left, indent+1) \n def leafcount(self,Node): \n if Node is None: \n return 0 \n if self.atLeaf(Node): \n return 1 \n else: \n return self.leafcount(Node.left)+self.leafcount(Node.right) \n\nif __name__==\"__main__\": \n\n y = BSTree()\n\n for pres\\\n in [\"OBAMA\",\"BUSHW\",\"CLINTON\",\"BUSHG\",\"REGAN\",\"CARTER\",\"FORD\",\"NIXON\",\"JOHNSON\"]:\n y.add(pres)\n\n y.pprint(y.root,0)\n\n" ]
[ 3, 0 ]
[]
[]
[ "binary_tree", "python" ]
stackoverflow_0002174679_binary_tree_python.txt
Q: Problem installing MySQLdb on windows - Can't find python I'm trying to install the module mySQLdb on a windows vista 64 (amd) machine. I've installed python on a different folder other than suggested by Python installer. When I try to install the .exe mySQLdb installer, it can't find python 2.5 and it halts the installation. Is there anyway to supply the installer with the correct python location (even thou the registry and path are right)? A: did you use an egg? if so, python might not be able to find it. import os,sys os.environ['PYTHON_EGG_CACHE'] = 'C:/temp' sys.path.append('C:/path/to/MySQLdb.egg')
Problem installing MySQLdb on windows - Can't find python
I'm trying to install the module mySQLdb on a windows vista 64 (amd) machine. I've installed python on a different folder other than suggested by Python installer. When I try to install the .exe mySQLdb installer, it can't find python 2.5 and it halts the installation. Is there anyway to supply the installer with the correct python location (even thou the registry and path are right)?
[ "did you use an egg?\nif so, python might not be able to find it.\nimport os,sys\nos.environ['PYTHON_EGG_CACHE'] = 'C:/temp'\nsys.path.append('C:/path/to/MySQLdb.egg')\n" ]
[ 0 ]
[]
[]
[ "mysql", "python", "windows_installer" ]
stackoverflow_0001980454_mysql_python_windows_installer.txt
Q: python chaining Updated Let's say I have: dic={"z":"zv", "a":"av"} ## why doesn't the following return a sorted list of keys? keys=dic.keys().sort() I know I could do the following and have the proper result: dic={"z":"zv", "a":"av"} keys=dic.keys() skeys=keys.sort() ### skeys will be None Why doesn't the first example work? A: .sort doesn't return the list. You could do: keys = sorted(dic.keys()) A: sort() modifies the contents of the existing list. it doesn't return a list. See the manual.
python chaining
Updated Let's say I have: dic={"z":"zv", "a":"av"} ## why doesn't the following return a sorted list of keys? keys=dic.keys().sort() I know I could do the following and have the proper result: dic={"z":"zv", "a":"av"} keys=dic.keys() skeys=keys.sort() ### skeys will be None Why doesn't the first example work?
[ ".sort doesn't return the list. You could do:\nkeys = sorted(dic.keys())\n\n", "sort() modifies the contents of the existing list. it doesn't return a list. See the manual.\n" ]
[ 16, 13 ]
[]
[]
[ "python" ]
stackoverflow_0002179241_python.txt
Q: Using python properties in django models? My problem relates to this question: Default ordering for m2m items by intermediate model field in Django class Group(models.Model): name = models.CharField(max_length=128) _members = models.ManyToManyField(Person, through='Membership') @property def members(self): return self._members.order_by('membership__date_joined') def __unicode__(self): return self.name I used the best answer's solution as you see here, however, it broke my model form that's based on the group model. When I submit the form, I get _members is required in my model form's error list since the field is required and can no longer submit forms based on this model. The best answer in the prior question suggests a way to mimic the behavior of the field using the property. How would I go about doing this to completely hide _members from the model form? Thanks, Pete A: If it's a one-off, you can exclude the _members field when you create the modelform: class GroupForm(ModelForm): class Meta: model=Group exclude = {'_members',} If you do this a lot, you might consider creating a subclass of ModelForm and override the init method to automatically exclude properties starting with an underscore.
Using python properties in django models?
My problem relates to this question: Default ordering for m2m items by intermediate model field in Django class Group(models.Model): name = models.CharField(max_length=128) _members = models.ManyToManyField(Person, through='Membership') @property def members(self): return self._members.order_by('membership__date_joined') def __unicode__(self): return self.name I used the best answer's solution as you see here, however, it broke my model form that's based on the group model. When I submit the form, I get _members is required in my model form's error list since the field is required and can no longer submit forms based on this model. The best answer in the prior question suggests a way to mimic the behavior of the field using the property. How would I go about doing this to completely hide _members from the model form? Thanks, Pete
[ "If it's a one-off, you can exclude the _members field when you create the modelform:\nclass GroupForm(ModelForm):\n class Meta:\n model=Group\n exclude = {'_members',}\n\nIf you do this a lot, you might consider creating a subclass of ModelForm and override the init method to automatically exclude properties starting with an underscore.\n" ]
[ 0 ]
[]
[]
[ "django_models", "python" ]
stackoverflow_0002178688_django_models_python.txt
Q: Dynamically import a callable given the full module path? >>> import_path('os.path.join') <function join at 0x22d4050> What is the simplest way to write import_path (in Python 2.6 and above)? Assume that the last component is always a callable in a module/package. A: This seems to be what you want: def import_path(name): modname, _, attr = name.rpartition('.') if not modname: # name was just a single module name return __import__(attr) m = __import__(modname, fromlist=[attr]) return getattr(m, attr) To make it work with Python 2.5 and earlier, where __import__ doesn't take keyword arguments, you will need to use: m = __import__(modname, {}, globals(), [attr]) A: Try def import_path(name): (mod,mem) = name.rsplit('.',1) m = __import__(mod, fromlist=[mem]) return getattr(m, mem) Works at least for >>> import_path('os.walk') <function walk at 0x7f23c24f8848> and now >>> import_path('os.path.join') <function join at 0x7f7fc7728a28> A: Apparently the following works: >>> p = 'os.path.join' >>> a, b = p.rsplit('.', 1) >>> getattr(__import__(a, fromlist=True), b) <function join at 0x7f8799865230>
Dynamically import a callable given the full module path?
>>> import_path('os.path.join') <function join at 0x22d4050> What is the simplest way to write import_path (in Python 2.6 and above)? Assume that the last component is always a callable in a module/package.
[ "This seems to be what you want:\ndef import_path(name):\n modname, _, attr = name.rpartition('.')\n if not modname:\n # name was just a single module name\n return __import__(attr)\n m = __import__(modname, fromlist=[attr])\n return getattr(m, attr)\n\nTo make it work with Python 2.5 and earlier, where __import__ doesn't take keyword arguments, you will need to use:\nm = __import__(modname, {}, globals(), [attr])\n\n", "Try\ndef import_path(name):\n (mod,mem) = name.rsplit('.',1)\n m = __import__(mod, fromlist=[mem])\n return getattr(m, mem)\n\nWorks at least for\n>>> import_path('os.walk')\n<function walk at 0x7f23c24f8848>\n\nand now\n>>> import_path('os.path.join')\n<function join at 0x7f7fc7728a28>\n\n", "Apparently the following works:\n>>> p = 'os.path.join'\n>>> a, b = p.rsplit('.', 1)\n>>> getattr(__import__(a, fromlist=True), b)\n<function join at 0x7f8799865230>\n\n" ]
[ 4, 0, 0 ]
[]
[]
[ "import", "introspection", "module", "python" ]
stackoverflow_0002179251_import_introspection_module_python.txt
Q: Enable Unicode "globally" in Python Is it possible to avoid having to put this in every page? # -*- coding: utf-8 -*- I'd really like Python to default to this. A: In Python 3, the default encoding is UTF-8, so you won't need to set it explicitly anymore. There isn't a way to 'globally' set the default source encoding, though, and history has shown that such global options are generally a bad idea. (For instance, the -U and -Q options to Python, and sys.setdefaultencoding() back when we had it.) You don't (directly) control all the source that gets imported in your program, because it includes the standard library and any third-party modules you use directly or indirectly. Also note that this isn't enabling Unicode, as your question title suggests. What it does is make the source encoding UTF-8, meaning that any non-ASCII characters in unicode literals (e.g. u'spæm') will be interpreted using that encoding. It won't make non-unicode literals ('spam' and "spam") suddenly unicode, nor will it do anything for non-literals anywhere in your code. A: This is a feature of Python 3.0 It was one of the things that was done in Python 3 because it would break backward compatibility, so you won't find such a global option in 2.x
Enable Unicode "globally" in Python
Is it possible to avoid having to put this in every page? # -*- coding: utf-8 -*- I'd really like Python to default to this.
[ "In Python 3, the default encoding is UTF-8, so you won't need to set it explicitly anymore. There isn't a way to 'globally' set the default source encoding, though, and history has shown that such global options are generally a bad idea. (For instance, the -U and -Q options to Python, and sys.setdefaultencoding() back when we had it.) You don't (directly) control all the source that gets imported in your program, because it includes the standard library and any third-party modules you use directly or indirectly.\nAlso note that this isn't enabling Unicode, as your question title suggests. What it does is make the source encoding UTF-8, meaning that any non-ASCII characters in unicode literals (e.g. u'spæm') will be interpreted using that encoding. It won't make non-unicode literals ('spam' and \"spam\") suddenly unicode, nor will it do anything for non-literals anywhere in your code.\n", "This is a feature of Python 3.0\nIt was one of the things that was done in Python 3 because it would break backward compatibility, so you won't find such a global option in 2.x\n" ]
[ 9, 1 ]
[ "It's a very bad idea for Python 2 because you will be expecting behavior which is only preset on your dev machine. Which means that when your library goes out to someone else, or to a host server, or elsewhere, any use of it will flood the logs with UnicodeDecodeErrors.\n" ]
[ -1 ]
[ "python", "unicode" ]
stackoverflow_0002179253_python_unicode.txt
Q: Am I passing the string correctly to the python library? I'm using a python library called Guess Language: http://pypi.python.org/pypi/guess-language/0.1 "justwords" is a string with unicode text. I stick it in the package, but it always returns English, even though the web page is in Japanese. Does anyone know why? Am I not encoding correctly? §ç©ºéå ¶ä»æ¡å°±æ²æéç¨®å¾ é¤ï¼æä»¥ä¾é裡ç¶ç éäºï¼åæ­¤ç°å¢æ°£æ°¹³åèµ·ä¾åªè½ç®âå¾å¥½âé常好âåå ¶æ¯è¦é»é¤ï¼é¨ä¾¿é»çé»ã飲æãä¸ææ²»ç­åä¸å 便å®ï¼æ¯æ´è¥ç äºï¼æ³æ³é裡以å°é»ãæ¯è§ä¾èªªä¹è©²æpremiumï¼åªæ±é¤é»å¥½å就好äºã&lt;br /&gt;&lt;br /&gt;é¦åç¾ï¼æä»¥å°±é»å宿´ç æ­£è¦åä¸ä¸å ä¸ç å¥é¤å§ï¼å justwords = justwords.encode('utf-8') true_lang = str(guess_language.guessLanguage(justwords)) print true_lang Edit: THanks guys for your help. This is an update of the problem. I am trying to "guess" the language of this: http://feeds.feedburner.com/nchild Basically, in Python, I get the htmlSource. Then, I strip the tags using BeautifulSoup. Then, I pass it to the library to get the language. If I do not do encode('utf-8'), then ASCII-errors will come up. So , this is a must. soup = BeautifulStoneSoup(htmlSource) justwords = ''.join(soup.findAll(text=True)) justwords = justwords.encode('utf-8') true_lang = str(guess_language.guessLanguage(justwords)) A: Looking at the main page, it says """Detects over 60 languages; Greek (el), Korean (ko), Japanese (ja), Chinese (zh) and all the languages listed in the trigrams directory. """ It doesn't use trigrams for those 4 languages; it relies on what script blocks are present in the input text. Looking at the source code: if "Katakana" in scripts or "Hiragana" in scripts or "Katakana Phonetic Extensions" in scripts: return "ja" if "CJK Unified Ideographs" in scripts or "Bopomofo" in scripts \ or "Bopomofo Extended" in scripts or "KangXi Radicals" in scripts: return "zh" For a script name like Katakana or Hiragana to appear in scripts, such characters must comprise 40% or more of the input text (after normalisation which removes non-alphabetic characters etc). It may be possible that some Japanese text needs a threshold of less than 40%. HOWEVER if that was the problem with your text, I would expect it to have more than 40% kanji (CJK Unified Ideographs) and thus should return "zh" (Chinese). Update after some experimentation, including inserting a print statement to show what script blocks were detected with what percentages: A presumably typical news item from the Asahi newspaper website: 49.3 Hiragana 8.7 Katakana 42.0 CJK Unified Ideographs result ja A presumably atypical ditto: 35.9 Hiragana 49.2 CJK Unified Ideographs 13.3 Katakana 1.6 Halfwidth and Fullwidth Forms result zh (Looks like it might be a good idea to base the test on the total (Hiragana + Katakana) content) Result of shoving the raw front page (XML, HTML, everything) through the machinery: 2.4 Hiragana 6.1 CJK Unified Ideographs 0.1 Halfwidth and Fullwidth Forms 3.7 Katakana 87.7 Basic Latin result ca The high percentage of Basic Latin is of course due to the markup. I haven't investigated what made it choose "ca" (Catalan) over any other language which uses Basic Latin, including English. However the gobbledegook that you printed doesn't show any sign of including markup. End of update Update 2 Here's an example (2 headlines and next 4 paragraphs from this link) where about 83% of the characters are East Asian and the rest are Basic Latin but the result is en (English). 29.6 Hiragana 18.5 Katakana 34.9 CJK Unified Ideographs 16.9 Basic Latin result en The Basic Latin Characters are caused by the use of the English names of organisations etc in the text. The Japanese rule fails because neither Katakana nor Hiragana score 40% (together they score 48.1%). The Chinese rule fails because CJK Unified Ideographs scores less than 40%. So the 83.1% East Asian characters are ignored, and the result is decided by the 16.9% minority. These "rotten borough" rules need some reform. In generality, it could be expressed like: If (total of script blocks used by only language X) >= X-specific threshold, then select language X. As suggested above, Hiragana + Katakana >= 40% will probably do the trick for Japanese. A similar rule may well be needed for Korean. Your gobbledegook did actually contain a few characters of markup (I didn't scroll far enough to the right to see it) but certainly not enough to depress all the East Asian scores below 40%. So we're still waiting to see what your actual input is and how you got it from where. End of update2 To aid with diagnosis of your problem, please don't print gobbledegook; use print repr(justwords) That way anyone who is interested in actually doing debugging has got something to work on. It would help if you gave the URL of the webpage, and showed the Python code that you used to get your unicode justwords. Please edit your answer to show those 3 pieces of information. Update 3 Thanks for the URL. Visual inspection indicates that the language is overwhelmingly Chinese. What gave you the impression that it is Japanese? Semithanks for supplying some of your code. To avoid your correspondents having to do your work for you, and to avoid misunderstandings due to guessing, you should always supply (without being asked) a self-contained script that will reproduce your problem. Note that you say you got "ASCII errors" (no exact error message! no traceback!) if you didn't do .encode('utf8') -- my code (see below) doesn't have this problem. No thanks for not supplying the result of print repr(justwords) (even after being asked). Inspecting what intermediate data has been created is a very elementary and very effective debugging technique. This is something you should always do before asking a question. Armed with this knowledge you can ask a better question. Using this code: # coding: ascii import sys sys.path.append(r"C:\junk\wotlang\guess-language\guess_language") import guess_language URL = "http://feeds.feedburner.com/nchild" from BeautifulSoup import BeautifulStoneSoup from pprint import pprint as pp import urllib2 htmlSource = urllib2.urlopen(URL).read() soup = BeautifulStoneSoup(htmlSource) fall = soup.findAll(text=True) # pp(fall) justwords = ''.join(fall) # justwords = justwords.encode('utf-8') result = guess_language.guessLanguage(justwords) print "result", result I got these results: 29.0 CJK Unified Ideographs 0.0 Extended Latin 0.1 Katakana 70.9 Basic Latin result en Note that the URL content is not static; about an hour later I got: 27.9 CJK Unified Ideographs 0.0 Extended Latin 0.1 Katakana 72.0 Basic Latin The statistics were obtained by fiddling around line 361 of guess_language.py so that it reads: for key, value in run_types.items(): pct = (value*100.0) / totalCount # line changed so that pct is a float print "%5.1f %s" % (pct, key) # line inserted if pct >=40: relevant_runs.append(key) The statistics are symptomatic of Chinese with lots of HTML/XML/Javascript stuff (see previous example); this is confirmed by looking at the output of the pretty-print obtained by un-commenting pp(fall) -- lots of stuff like: &lt;img style="float:left; margin:0 10px 0px 10px;cursor:pointer; cursor:hand ;" width="60px" src="http://2.bp.blogspot.com/_LBJ4udkQZag/Rm6sTn1b7NI/AAAAAAAAA FA/bYkSJZ3i2bg/s400/hepinge169.gif" border="0" alt=""id="BLOGGER_PHOTO_ID_507518 3283203730642" alt="\u548c\u5e73\u6771\u8def\u4e00\u6bb5169\u865f" title="\u548c \u5e73\u6771\u8def\u4e00\u6bb5169\u865f"/&gt;\u4eca\u5929\u4e2d\u5348\u8d70\u523 0\u516c\u53f8\u5c0d\u9762\u76847-11\u8cb7\u98f2\u6599\uff0c\u7a81\u7136\u770b\u5 230\u9019\u500b7-11\u602a\u7269\uff01\u770b\u8d77\u4f86\u6bd4\u6a19\u6e96\u62db\ u724c\u6709\u4f5c\u7528\u7684\u53ea\u6709\u4e2d\u9593\u7684\u6307\u793a\u71c8\u8 00c\u5df2\uff0c\u53ef\u537b\u6709\u8d85\u7d1a\u5927\u7684footprint\uff01&lt;br / &gt;&lt;br /&gt;&lt;a href="http://4.bp.blogspot.com/_LBJ4udkQZag/Rm6wHH1b7QI/AA You need to do something about the markup. Steps: Look at your raw "htmlSource" in an XML browser. Is the XML non-compliant? How can you avoid having untranslated &lt; etc? What elements have text content that is "English" only by virtue of it being a URL or similar? Is there a problem in Beautiful[Stone]Soup? Should you be using some other functionality of Beautiful[Stone]Soup? Should you use lxml instead? I'd suggest some research followed by a new SO question. end of update 3 A: It looks like you should be able to pass your unicode as-is. guessLanguage decodes an input that is str as utf-8. So your .encode('utf-8') is safe but unnecessary. I skimmed the source code and assumed it relies exclusively on the data in its "trigrams" directory for language detection, and it would not handle Japanese because there is no "ja" subdirectory in there. That is not correct, as pointed out by John Machin. So I have to assume your input is not what you think it is (which is hard to debug since it's not showing up correctly in your question).
Am I passing the string correctly to the python library?
I'm using a python library called Guess Language: http://pypi.python.org/pypi/guess-language/0.1 "justwords" is a string with unicode text. I stick it in the package, but it always returns English, even though the web page is in Japanese. Does anyone know why? Am I not encoding correctly? §ç©ºéå ¶ä»æ¡å°±æ²æéç¨®å¾ é¤ï¼æä»¥ä¾é裡ç¶ç éäºï¼åæ­¤ç°å¢æ°£æ°¹³åèµ·ä¾åªè½ç®âå¾å¥½âé常好âåå ¶æ¯è¦é»é¤ï¼é¨ä¾¿é»çé»ã飲æãä¸ææ²»ç­åä¸å 便å®ï¼æ¯æ´è¥ç äºï¼æ³æ³é裡以å°é»ãæ¯è§ä¾èªªä¹è©²æpremiumï¼åªæ±é¤é»å¥½å就好äºã&lt;br /&gt;&lt;br /&gt;é¦åç¾ï¼æä»¥å°±é»å宿´ç æ­£è¦åä¸ä¸å ä¸ç å¥é¤å§ï¼å justwords = justwords.encode('utf-8') true_lang = str(guess_language.guessLanguage(justwords)) print true_lang Edit: THanks guys for your help. This is an update of the problem. I am trying to "guess" the language of this: http://feeds.feedburner.com/nchild Basically, in Python, I get the htmlSource. Then, I strip the tags using BeautifulSoup. Then, I pass it to the library to get the language. If I do not do encode('utf-8'), then ASCII-errors will come up. So , this is a must. soup = BeautifulStoneSoup(htmlSource) justwords = ''.join(soup.findAll(text=True)) justwords = justwords.encode('utf-8') true_lang = str(guess_language.guessLanguage(justwords))
[ "Looking at the main page, it says \"\"\"Detects over 60 languages; Greek (el), Korean (ko), Japanese (ja), Chinese (zh) and all the languages listed in the trigrams directory. \"\"\"\nIt doesn't use trigrams for those 4 languages; it relies on what script blocks are present in the input text. Looking at the source code:\nif \"Katakana\" in scripts or \"Hiragana\" in scripts or \"Katakana Phonetic Extensions\" in scripts:\n return \"ja\"\n\nif \"CJK Unified Ideographs\" in scripts or \"Bopomofo\" in scripts \\\n or \"Bopomofo Extended\" in scripts or \"KangXi Radicals\" in scripts:\n return \"zh\"\n\nFor a script name like Katakana or Hiragana to appear in scripts, such characters must comprise 40% or more of the input text (after normalisation which removes non-alphabetic characters etc). It may be possible that some Japanese text needs a threshold of less than 40%. HOWEVER if that was the problem with your text, I would expect it to have more than 40% kanji (CJK Unified Ideographs) and thus should return \"zh\" (Chinese).\nUpdate after some experimentation, including inserting a print statement to show what script blocks were detected with what percentages:\nA presumably typical news item from the Asahi newspaper website:\n 49.3 Hiragana\n 8.7 Katakana\n 42.0 CJK Unified Ideographs\nresult ja\n\nA presumably atypical ditto:\n 35.9 Hiragana\n 49.2 CJK Unified Ideographs\n 13.3 Katakana\n 1.6 Halfwidth and Fullwidth Forms\nresult zh\n\n(Looks like it might be a good idea to base the test on the total (Hiragana + Katakana) content)\nResult of shoving the raw front page (XML, HTML, everything) through the machinery:\n 2.4 Hiragana\n 6.1 CJK Unified Ideographs\n 0.1 Halfwidth and Fullwidth Forms\n 3.7 Katakana\n 87.7 Basic Latin\nresult ca\n\nThe high percentage of Basic Latin is of course due to the markup. I haven't investigated what made it choose \"ca\" (Catalan) over any other language which uses Basic Latin, including English. However the gobbledegook that you printed doesn't show any sign of including markup.\nEnd of update\nUpdate 2\nHere's an example (2 headlines and next 4 paragraphs from this link) where about 83% of the characters are East Asian and the rest are Basic Latin but the result is en (English).\n 29.6 Hiragana\n 18.5 Katakana\n 34.9 CJK Unified Ideographs\n 16.9 Basic Latin\nresult en\n\nThe Basic Latin Characters are caused by the use of the English names of organisations etc in the text. The Japanese rule fails because neither Katakana nor Hiragana score 40% (together they score 48.1%). The Chinese rule fails because CJK Unified Ideographs scores less than 40%. So the 83.1% East Asian characters are ignored, and the result is decided by the 16.9% minority. These \"rotten borough\" rules need some reform. In generality, it could be expressed like:\nIf (total of script blocks used by only language X) >= X-specific threshold, then select language X.\nAs suggested above, Hiragana + Katakana >= 40% will probably do the trick for Japanese. A similar rule may well be needed for Korean.\nYour gobbledegook did actually contain a few characters of markup (I didn't scroll far enough to the right to see it) but certainly not enough to depress all the East Asian scores below 40%. So we're still waiting to see what your actual input is and how you got it from where.\nEnd of update2\nTo aid with diagnosis of your problem, please don't print gobbledegook; use\nprint repr(justwords)\n\nThat way anyone who is interested in actually doing debugging has got something to work on. It would help if you gave the URL of the webpage, and showed the Python code that you used to get your unicode justwords. Please edit your answer to show those 3 pieces of information.\nUpdate 3 Thanks for the URL. Visual inspection indicates that the language is overwhelmingly Chinese. What gave you the impression that it is Japanese?\nSemithanks for supplying some of your code. To avoid your correspondents having to do your work for you, and to avoid misunderstandings due to guessing, you should always supply (without being asked) a self-contained script that will reproduce your problem. Note that you say you got \"ASCII errors\" (no exact error message! no traceback!) if you didn't do .encode('utf8') -- my code (see below) doesn't have this problem.\nNo thanks for not supplying the result of print repr(justwords) (even after being asked). Inspecting what intermediate data has been created is a very elementary and very effective debugging technique. This is something you should always do before asking a question. Armed with this knowledge you can ask a better question.\nUsing this code:\n# coding: ascii\nimport sys\nsys.path.append(r\"C:\\junk\\wotlang\\guess-language\\guess_language\")\nimport guess_language\nURL = \"http://feeds.feedburner.com/nchild\"\nfrom BeautifulSoup import BeautifulStoneSoup\nfrom pprint import pprint as pp\nimport urllib2\nhtmlSource = urllib2.urlopen(URL).read()\nsoup = BeautifulStoneSoup(htmlSource)\nfall = soup.findAll(text=True)\n# pp(fall)\njustwords = ''.join(fall)\n# justwords = justwords.encode('utf-8')\nresult = guess_language.guessLanguage(justwords)\nprint \"result\", result\n\nI got these results:\n 29.0 CJK Unified Ideographs\n 0.0 Extended Latin\n 0.1 Katakana\n 70.9 Basic Latin\nresult en\n\nNote that the URL content is not static; about an hour later I got:\n 27.9 CJK Unified Ideographs\n 0.0 Extended Latin\n 0.1 Katakana\n 72.0 Basic Latin\n\nThe statistics were obtained by fiddling around line 361 of guess_language.py so that it reads:\nfor key, value in run_types.items():\n pct = (value*100.0) / totalCount # line changed so that pct is a float\n print \"%5.1f %s\" % (pct, key) # line inserted\n if pct >=40:\n relevant_runs.append(key)\n\nThe statistics are symptomatic of Chinese with lots of HTML/XML/Javascript stuff (see previous example); this is confirmed by looking at the output of the pretty-print obtained by un-commenting pp(fall) -- lots of stuff like:\n&lt;img style=\"float:left; margin:0 10px 0px 10px;cursor:pointer; cursor:hand\n;\" width=\"60px\" src=\"http://2.bp.blogspot.com/_LBJ4udkQZag/Rm6sTn1b7NI/AAAAAAAAA\nFA/bYkSJZ3i2bg/s400/hepinge169.gif\" border=\"0\" alt=\"\"id=\"BLOGGER_PHOTO_ID_507518\n3283203730642\" alt=\"\\u548c\\u5e73\\u6771\\u8def\\u4e00\\u6bb5169\\u865f\" title=\"\\u548c\n\\u5e73\\u6771\\u8def\\u4e00\\u6bb5169\\u865f\"/&gt;\\u4eca\\u5929\\u4e2d\\u5348\\u8d70\\u523\n0\\u516c\\u53f8\\u5c0d\\u9762\\u76847-11\\u8cb7\\u98f2\\u6599\\uff0c\\u7a81\\u7136\\u770b\\u5\n230\\u9019\\u500b7-11\\u602a\\u7269\\uff01\\u770b\\u8d77\\u4f86\\u6bd4\\u6a19\\u6e96\\u62db\\\nu724c\\u6709\\u4f5c\\u7528\\u7684\\u53ea\\u6709\\u4e2d\\u9593\\u7684\\u6307\\u793a\\u71c8\\u8\n00c\\u5df2\\uff0c\\u53ef\\u537b\\u6709\\u8d85\\u7d1a\\u5927\\u7684footprint\\uff01&lt;br /\n&gt;&lt;br /&gt;&lt;a href=\"http://4.bp.blogspot.com/_LBJ4udkQZag/Rm6wHH1b7QI/AA\n\nYou need to do something about the markup. Steps: Look at your raw \"htmlSource\" in an XML browser. Is the XML non-compliant? How can you avoid having untranslated &lt; etc? What elements have text content that is \"English\" only by virtue of it being a URL or similar? Is there a problem in Beautiful[Stone]Soup? Should you be using some other functionality of Beautiful[Stone]Soup? Should you use lxml instead?\nI'd suggest some research followed by a new SO question.\nend of update 3\n", "It looks like you should be able to pass your unicode as-is. guessLanguage decodes an input that is str as utf-8. So your .encode('utf-8') is safe but unnecessary.\nI skimmed the source code and assumed it relies exclusively on the data in its \"trigrams\" directory for language detection, and it would not handle Japanese because there is no \"ja\" subdirectory in there. That is not correct, as pointed out by John Machin. So I have to assume your input is not what you think it is (which is hard to debug since it's not showing up correctly in your question).\n" ]
[ 7, 0 ]
[ "Google says your example is in chinese. They have a (much more advanced) webservice to translate text and guess the language.\nThey have an API and code examples for Python.\n" ]
[ -1 ]
[ "encoding", "nlp", "python", "unicode" ]
stackoverflow_0002164899_encoding_nlp_python_unicode.txt
Q: Python: penalty for sleeping threads this question relates to performance penalities that may or may not arise from having a large number of sleeping python threads on a webserver. Background: I am implementing an online shop using django/satchmo. A requirement is for delayed payment. The customer can reserve a product and allow a third party to pay for it at a later date (via a random and unique URL). To handle unreserving an item I am creating a thread which will sleep for the reservation time and then remove the reservation/mark the product as sold when it awakes. It looks like this: #Reserves a product when it is placed in the cart def reserve_cart_product(product): log.debug("Reserving %s" % product.name) product.active = False product.featured = False product.save() from threading import Timer Timer(CART_RESERVE_TIME, check_reservation, (product,)).start() I am using the same technique when culling the unique URLs after they have expired, only the Timer sleeps for much longer (typically 5 days). So, my question to you SO is as follows: Is having a large numnber of sleeping threads going to seriously effect performance? Are there better techniques for scheduling a one off event sometime in the future. I would like to keep this in python if possible; no calling at or cron via sys. The site isn't exactly high traffic; a (generous) upper limit on products ordered per week would be around 100. Combined with cart reservation, this could mean there are 100+ sleeping threads at any one time. Will I regret scheduling tasks in this manner? Thanks A: I see no reason why this shouldn't work. The underlying code for Timer (in threading.py) simply uses time.sleep. Once it's been waiting for awhile, it basically runs a loop with time.sleep(0.05) This should result in CPU usage of basically 0%, even with hundreds of threads. Here's a simple example, where I noticed 0% cpu usage for the python process: import threading def nothing(): pass def testThreads(): timers = [threading.Timer(10.0, nothing) for _ in xrange(881)] print "Starting threads." map(threading.Thread.start, timers) print "Joining threads." map(threading.Thread.join, timers) print "Done." if __name__ == "__main__": testThreads() The real issue is that you may not be able to actually start too many threads. On my 64-bit 4GB system, I can only start 881 threads before I get an error. If you really will only have a few hundred, though, I can't imagine it won't work. A: 100 threads is no problem, but as tgray pointed out, what happens if the server goes down (Power cut, Planned Maintenance, Hardware failure, etc.)? You need to store the unreservation information in your database somewhere. Then you can have a cron job periodically trigger an unreservation script for example, and you don't need to have all those threads sitting around. If you really don't want to use cron, just have one worker thread that sleeps for a minute and then checks whether any of the unreservations are due. A: Usually, sleeping threads have no overhead aside from the memory allocated for their stacks and other private data. Modern Operating System scheduling algorithms have complexity O(1) so even a running thread does not introduce overhead, other than memory footprint. At the same time, it is hard to imagine efficient design requiring a lot of threads. Only case I can imagine is communication with many other peers. In this case - asynchronous IO should be used.
Python: penalty for sleeping threads
this question relates to performance penalities that may or may not arise from having a large number of sleeping python threads on a webserver. Background: I am implementing an online shop using django/satchmo. A requirement is for delayed payment. The customer can reserve a product and allow a third party to pay for it at a later date (via a random and unique URL). To handle unreserving an item I am creating a thread which will sleep for the reservation time and then remove the reservation/mark the product as sold when it awakes. It looks like this: #Reserves a product when it is placed in the cart def reserve_cart_product(product): log.debug("Reserving %s" % product.name) product.active = False product.featured = False product.save() from threading import Timer Timer(CART_RESERVE_TIME, check_reservation, (product,)).start() I am using the same technique when culling the unique URLs after they have expired, only the Timer sleeps for much longer (typically 5 days). So, my question to you SO is as follows: Is having a large numnber of sleeping threads going to seriously effect performance? Are there better techniques for scheduling a one off event sometime in the future. I would like to keep this in python if possible; no calling at or cron via sys. The site isn't exactly high traffic; a (generous) upper limit on products ordered per week would be around 100. Combined with cart reservation, this could mean there are 100+ sleeping threads at any one time. Will I regret scheduling tasks in this manner? Thanks
[ "I see no reason why this shouldn't work. The underlying code for Timer (in threading.py) simply uses time.sleep. Once it's been waiting for awhile, it basically runs a loop with time.sleep(0.05) This should result in CPU usage of basically 0%, even with hundreds of threads. Here's a simple example, where I noticed 0% cpu usage for the python process:\nimport threading\n\ndef nothing():\n pass\n\ndef testThreads():\n timers = [threading.Timer(10.0, nothing) for _ in xrange(881)]\n print \"Starting threads.\"\n map(threading.Thread.start, timers)\n print \"Joining threads.\"\n map(threading.Thread.join, timers)\n print \"Done.\"\n\nif __name__ == \"__main__\":\n testThreads()\n\nThe real issue is that you may not be able to actually start too many threads. On my 64-bit 4GB system, I can only start 881 threads before I get an error. If you really will only have a few hundred, though, I can't imagine it won't work.\n", "100 threads is no problem, but as tgray pointed out, what happens if the server goes down (Power cut, Planned Maintenance, Hardware failure, etc.)?\nYou need to store the unreservation information in your database somewhere.\nThen you can have a cron job periodically trigger an unreservation script for example, and you don't need to have all those threads sitting around.\nIf you really don't want to use cron, just have one worker thread that sleeps for a minute and then checks whether any of the unreservations are due.\n", "Usually, sleeping threads have no overhead aside from the memory allocated for their stacks and other private data. Modern Operating System scheduling algorithms have complexity O(1) so even a running thread does not introduce overhead, other than memory footprint. \nAt the same time, it is hard to imagine efficient design requiring a lot of threads. Only case I can imagine is communication with many other peers. In this case - asynchronous IO should be used.\n" ]
[ 7, 4, 3 ]
[]
[]
[ "multithreading", "performance", "python" ]
stackoverflow_0002178563_multithreading_performance_python.txt
Q: How is the __format__ method supposed to be used for int? I saw there was a __format__ method but help(int.__format__) doesn't provide any help. I also know you're not suppose to call a __method__ directly. When is this method called? Which is its argument? A: It's used for Py3k's new string formatting scheme. You can find more info here: http://docs.python.org/whatsnew/2.6.html#pep-3101-advanced-string-formatting You are right that it isn't called directly. It's called by str.format or the new format builtin. A: It's used when you pass an integer to the format() function. The details elude me, as I can't seem to get it to tell me what exactly the argument is. (Edit: see lost-theory's link) Oh, and it only works when the integer is the only argument. If you pass a tuple to format, then the tuple.__format__ function is called, and the int.__str__ or something. '{0}'.format(4) str(4.__format__(format_spec=''))
How is the __format__ method supposed to be used for int?
I saw there was a __format__ method but help(int.__format__) doesn't provide any help. I also know you're not suppose to call a __method__ directly. When is this method called? Which is its argument?
[ "It's used for Py3k's new string formatting scheme.\nYou can find more info here:\nhttp://docs.python.org/whatsnew/2.6.html#pep-3101-advanced-string-formatting\nYou are right that it isn't called directly. It's called by str.format or the new format builtin.\n", "It's used when you pass an integer to the format() function. The details elude me, as I can't seem to get it to tell me what exactly the argument is. (Edit: see lost-theory's link)\nOh, and it only works when the integer is the only argument. If you pass a tuple to format, then the tuple.__format__ function is called, and the int.__str__ or something.\n'{0}'.format(4)\nstr(4.__format__(format_spec=''))\n\n" ]
[ 6, 4 ]
[]
[]
[ "int", "python" ]
stackoverflow_0002179926_int_python.txt
Q: SQLAlchemy sqlalchemy.sql.expression.select vs. sqlalchemy.sql.expression.Select So I'm brand new to SQLAlchemy, and I'm trying to use the SQL Expression API to create a SELECT statement that specifies the exact columns to return. I found both a class and a function defined in the sqlalchmey.sql.expressions module and I'm not too sure which to use... Why do they have both a class and a function? When would you use one over the other? And would anyone be willing to explain why they need to have both in their library? It doesn't really make much sense to me to be honest, other than just to confuse me. :) JK Thanks for the help in advance! A: Use the source. Here's the implementation of the select function, from the source code: def select(columns=None, whereclause=None, from_obj=[], **kwargs): """Returns a ``SELECT`` clause element. (... long docstring ...) """ return Select(columns, whereclause=whereclause, from_obj=from_obj, **kwargs) So, it is exactly the same. A: the expression package provides Python functions to do everything. These functions in some cases return a class instance verbatim from the function's arguments and other times compose an object from several components. It was originally the idea that the functions would be doing a lot more composition than they ended up doing in the end. In any case, the package prefers to stick to pep-8 as far as classes being in CamelCase, functions being all lowercase, and wanted the front end API to be all lower case - so you have the public "constructor" functions. The SQL expression language is very easy to grok if you start with the tutorial. A: I think it's pretty much the same. The documentation says for select (the function): The returned object is an instance of Select. As you can pass the select function the same parameters that Select.__init__() accepts, I don't really see a difference. At first glance the arguments of the class constructor seem to be a superset of the function's. But the function can be passed any of the constructor's keyword arguments.
SQLAlchemy sqlalchemy.sql.expression.select vs. sqlalchemy.sql.expression.Select
So I'm brand new to SQLAlchemy, and I'm trying to use the SQL Expression API to create a SELECT statement that specifies the exact columns to return. I found both a class and a function defined in the sqlalchmey.sql.expressions module and I'm not too sure which to use... Why do they have both a class and a function? When would you use one over the other? And would anyone be willing to explain why they need to have both in their library? It doesn't really make much sense to me to be honest, other than just to confuse me. :) JK Thanks for the help in advance!
[ "Use the source.\nHere's the implementation of the select function, from the source code:\ndef select(columns=None, whereclause=None, from_obj=[], **kwargs):\n \"\"\"Returns a ``SELECT`` clause element.\n (... long docstring ...)\n \"\"\"\n return Select(columns, whereclause=whereclause, from_obj=from_obj, **kwargs)\n\nSo, it is exactly the same.\n", "the expression package provides Python functions to do everything. These functions in some cases return a class instance verbatim from the function's arguments and other times compose an object from several components. It was originally the idea that the functions would be doing a lot more composition than they ended up doing in the end. In any case, the package prefers to stick to pep-8 as far as classes being in CamelCase, functions being all lowercase, and wanted the front end API to be all lower case - so you have the public \"constructor\" functions.\nThe SQL expression language is very easy to grok if you start with the tutorial.\n", "I think it's pretty much the same. The documentation says for select (the function):\nThe returned object is an instance of Select.\n\nAs you can pass the select function the same parameters that Select.__init__() accepts, I don't really see a difference. At first glance the arguments of the class constructor seem to be a superset of the function's. But the function can be passed any of the constructor's keyword arguments.\n" ]
[ 3, 2, 0 ]
[]
[]
[ "python", "sql", "sqlalchemy" ]
stackoverflow_0002159874_python_sql_sqlalchemy.txt
Q: JPype - Issue importing & calling methods! Here I'm attaching my code below from jpype import * from javax.swing import JFrame classpath = "-Djava.class.path=praat.jar" startJVM(getDefaultJVMPath(),"-ea",classpath) frame = javax.swing.JFrame("Hello JPype") label = javax.swing.JLabel("Hello JPype!", JLabel.CENTER) frame.add(label) frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) frame.setSize(200, 100) frame.show() shutdownJVM() When i run this program I get an error. /Library/Python/2.6/site-packages/jpype/_pykeywords.py:18: DeprecationWarning: the sets module is deprecated import sets 2010-02-01 22:26:27.473 Python[754:d07] Apple AWT Java VM was loaded on first thread -- can't start AWT. Traceback (most recent call last): File "swing.py", line 10, in <module> frame = javax.swing.JFrame("Hello Jython") File "/Library/Python/2.6/site-packages/jpype/_jpackage.py", line 53, in __call__ raise TypeError, "Package "+self.__name+" is not Callable" TypeError: Package javax.swing.JFrame is not Callable Is there any way to solve this problem. A normal Hello World program works fine, but when I'm trying to import packages I get similar issues. A: Add the Java runtime library (rt.jar) to the classpath and try again. The error indicates, that JFrame can't be found but it is inside rt.jar. A: If you import JFrame into the local namespace, use it without the full namespace: frame = JFrame("Hello Jython") Same with JLabel, but remember to import it first. To use the full namespace you need import javax.swing instead of from javax.swing import JFrame.
JPype - Issue importing & calling methods!
Here I'm attaching my code below from jpype import * from javax.swing import JFrame classpath = "-Djava.class.path=praat.jar" startJVM(getDefaultJVMPath(),"-ea",classpath) frame = javax.swing.JFrame("Hello JPype") label = javax.swing.JLabel("Hello JPype!", JLabel.CENTER) frame.add(label) frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) frame.setSize(200, 100) frame.show() shutdownJVM() When i run this program I get an error. /Library/Python/2.6/site-packages/jpype/_pykeywords.py:18: DeprecationWarning: the sets module is deprecated import sets 2010-02-01 22:26:27.473 Python[754:d07] Apple AWT Java VM was loaded on first thread -- can't start AWT. Traceback (most recent call last): File "swing.py", line 10, in <module> frame = javax.swing.JFrame("Hello Jython") File "/Library/Python/2.6/site-packages/jpype/_jpackage.py", line 53, in __call__ raise TypeError, "Package "+self.__name+" is not Callable" TypeError: Package javax.swing.JFrame is not Callable Is there any way to solve this problem. A normal Hello World program works fine, but when I'm trying to import packages I get similar issues.
[ "Add the Java runtime library (rt.jar) to the classpath and try again. The error indicates, that JFrame can't be found but it is inside rt.jar.\n", "If you import JFrame into the local namespace, use it without the full namespace:\nframe = JFrame(\"Hello Jython\")\n\nSame with JLabel, but remember to import it first.\nTo use the full namespace you need import javax.swing instead of from javax.swing import JFrame.\n" ]
[ 1, 0 ]
[]
[]
[ "java", "python" ]
stackoverflow_0002178532_java_python.txt
Q: Python: Why can't I iterate over a list? Is my exception class borked? I've already looked at this question: Python iterators – how to dynamically assign self.next within a new style class? but this doesn't help me because I want to iterate of an attribute of the error which is a list (ie, already iterable) without having to use the attribute explicitly. I'm looking to do this: class SCE(Exception): """ An error while performing SCE functions. """ def __init__(self, value=None): """ Message: A string message or an iterable of strings. """ if value is None: self._values = ['A general SCE error has occured.'] elif isinstance(value, str): self._values = [value] else: self._values = list(value) def __iter__(self): return self._values def __repr__(self): return repr(self._values) However, in the shell I get this: try: raise CSE(['error one', 'error two']) except CSE, e: for i in e: print(i) Traceback (most recent call last): File "(stdin)", line 1, in (module) TypeError: iter() returned non-iterator of type 'list' I know I could remove the _ from _values and then iterate over e.values but I don't want to do that as it exposes the implementation of my Exception class. A: The __iter__ method should return an iterator object, but you are returning a list object. Use def __iter__(self): return iter(self._values) instead to fix this. From the documentation for object.__iter__ (my highlighting): This method is called when an iterator is required for a container. This method should return a new iterator object that can iterate over all the objects in the container. A: def __iter__(self): return iter(self._values) Or a more generic: def __iter__(self): for x in self._values: yield x A: __iter__ needs to return an iterator, not a list. Try this: def __iter__(self): return iter(self._values) You could also do: def __iter__(self): for val in self._values: yield val But I can't really think of a reason you'd need to do that instead of using iter()
Python: Why can't I iterate over a list? Is my exception class borked?
I've already looked at this question: Python iterators – how to dynamically assign self.next within a new style class? but this doesn't help me because I want to iterate of an attribute of the error which is a list (ie, already iterable) without having to use the attribute explicitly. I'm looking to do this: class SCE(Exception): """ An error while performing SCE functions. """ def __init__(self, value=None): """ Message: A string message or an iterable of strings. """ if value is None: self._values = ['A general SCE error has occured.'] elif isinstance(value, str): self._values = [value] else: self._values = list(value) def __iter__(self): return self._values def __repr__(self): return repr(self._values) However, in the shell I get this: try: raise CSE(['error one', 'error two']) except CSE, e: for i in e: print(i) Traceback (most recent call last): File "(stdin)", line 1, in (module) TypeError: iter() returned non-iterator of type 'list' I know I could remove the _ from _values and then iterate over e.values but I don't want to do that as it exposes the implementation of my Exception class.
[ "The __iter__ method should return an iterator object, but you are returning a list object. Use\ndef __iter__(self):\n return iter(self._values)\n\ninstead to fix this. From the documentation for object.__iter__ (my highlighting):\n\nThis method is called when an iterator is required for a container. This method should return a new iterator object that can iterate over all the objects in the container.\n\n", "def __iter__(self):\n return iter(self._values)\n\nOr a more generic:\ndef __iter__(self):\n for x in self._values:\n yield x\n\n", "__iter__ needs to return an iterator, not a list.\nTry this:\n def __iter__(self):\n return iter(self._values)\n\nYou could also do:\n def __iter__(self):\n for val in self._values:\n yield val\n\nBut I can't really think of a reason you'd need to do that instead of using iter()\n" ]
[ 32, 8, 1 ]
[]
[]
[ "exception", "exception_handling", "iterator", "python" ]
stackoverflow_0002180578_exception_exception_handling_iterator_python.txt
Q: Python Dynamic module loading based on input I wrote a program that takes in a partial rss feed and outputs a full one, but it is one a case by case basis. The recipe for one site is not the same as the recipe for the other. So what I do is look at the domain basename(for instance nyt or wsj) and choose a module based on that. Though I need to load each and every module before hand and have a logical condition for each recipe. What I need is a way to just have the individual modules in their own respective folder and when I parse out the url basename I want it to look for the module, load it and take some action. So I want the main code base to be independent from the modules. I want to be able to add the modules in the future and never touch the portion of code which interact with them. Here is a code example if "nyt" == feed: nyt.parser(posixpath.basename(url), urldir, rss_file_path, url, feed) As you can see I call the parser of the individual module. I have many of these based on each website. I want to reed feed and then be able to look for the module, load it and call it, and then if it doesn't exist report it and try the default method. A: It sounds like you're looking for the __import__ function. This function does the same thing as the import statement, but allows you to pass a name to import that might only be known at runtime. So you might do: parsemodule = __import__(feed) parsemodule.parser(posixpath.basename(url), urldir, rss_file_path, url, feed) You will want to catch exceptions such as ImportError. A: You can use the imp module.
Python Dynamic module loading based on input
I wrote a program that takes in a partial rss feed and outputs a full one, but it is one a case by case basis. The recipe for one site is not the same as the recipe for the other. So what I do is look at the domain basename(for instance nyt or wsj) and choose a module based on that. Though I need to load each and every module before hand and have a logical condition for each recipe. What I need is a way to just have the individual modules in their own respective folder and when I parse out the url basename I want it to look for the module, load it and take some action. So I want the main code base to be independent from the modules. I want to be able to add the modules in the future and never touch the portion of code which interact with them. Here is a code example if "nyt" == feed: nyt.parser(posixpath.basename(url), urldir, rss_file_path, url, feed) As you can see I call the parser of the individual module. I have many of these based on each website. I want to reed feed and then be able to look for the module, load it and call it, and then if it doesn't exist report it and try the default method.
[ "It sounds like you're looking for the __import__ function. This function does the same thing as the import statement, but allows you to pass a name to import that might only be known at runtime.\nSo you might do:\nparsemodule = __import__(feed)\nparsemodule.parser(posixpath.basename(url), urldir, rss_file_path, url, feed)\n\nYou will want to catch exceptions such as ImportError.\n", "You can use the imp module.\n" ]
[ 3, 1 ]
[]
[]
[ "python", "web_scraping" ]
stackoverflow_0002180539_python_web_scraping.txt
Q: pygtk: find out focused element i'm creating a dialog that finds out what is focused element. that's what i wrote: import gtk import gobject class FocusedElementPath(gtk.Dialog): def __init__(self, parent, title=None): gtk.Dialog.__init__(self, title or 'Show path', parent) self.catch_within = parent self.catch_focus = True self.add_button(gtk.STOCK_OK, gtk.RESPONSE_OK) again_btn = gtk.Button('',gtk.STOCK_REFRESH) again_btn.connect('activate', self.refresh_pressed) again_btn.show() self.action_area.add(again_btn) self.add_button(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL) self.action_area.set_layout(gtk.BUTTONBOX_EDGE) self.path = gtk.Label() self.path.show() self.vbox.add(self.path) def refresh_pressed(self, btn): self.catch_focus = True def do_focus_out_event(self, evt): nl = self.catch_within.get_focus() if nl: self.catch_within.activate_focus() self.path.set_text(repr(nl)) else: self.path.set_text('None') gtk.Dialog.on_focus_event(self, evt) gobject.type_register(FocusedElementPath) the problem is it returns previously focused element. is there any way to find out currently focused element? i've tried different events (for dialog and for window), but nothing helped :( what am i doing wrong or how do i do this correctly? A: gtk.Window.get_focus (also available in gtk.Dialog) will return the currently focused child. Anyway I don't quite understand what you want to achieve here...
pygtk: find out focused element
i'm creating a dialog that finds out what is focused element. that's what i wrote: import gtk import gobject class FocusedElementPath(gtk.Dialog): def __init__(self, parent, title=None): gtk.Dialog.__init__(self, title or 'Show path', parent) self.catch_within = parent self.catch_focus = True self.add_button(gtk.STOCK_OK, gtk.RESPONSE_OK) again_btn = gtk.Button('',gtk.STOCK_REFRESH) again_btn.connect('activate', self.refresh_pressed) again_btn.show() self.action_area.add(again_btn) self.add_button(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL) self.action_area.set_layout(gtk.BUTTONBOX_EDGE) self.path = gtk.Label() self.path.show() self.vbox.add(self.path) def refresh_pressed(self, btn): self.catch_focus = True def do_focus_out_event(self, evt): nl = self.catch_within.get_focus() if nl: self.catch_within.activate_focus() self.path.set_text(repr(nl)) else: self.path.set_text('None') gtk.Dialog.on_focus_event(self, evt) gobject.type_register(FocusedElementPath) the problem is it returns previously focused element. is there any way to find out currently focused element? i've tried different events (for dialog and for window), but nothing helped :( what am i doing wrong or how do i do this correctly?
[ "gtk.Window.get_focus (also available in gtk.Dialog) will return the currently focused child.\nAnyway I don't quite understand what you want to achieve here...\n" ]
[ 1 ]
[]
[]
[ "dialog", "focus", "gtk", "pygtk", "python" ]
stackoverflow_0002180614_dialog_focus_gtk_pygtk_python.txt
Q: Is it OK to raise a built-in exception, but with a different message, in Python? Is it OK to raise a built-in exception with a custom text? or to raise a built-in warning also with custom text? The documentation reads: exception ValueError: Raised when a built-in operation or function receives an argument (…) Is it implied that only built-in operations should raise a ValueError exception? In practice, I understand that it is safe to create an exception class that inherits from ValueError or Exception. But is it OK not to do that, and directly raise a ValueError("custom text")? Since ValueError is built-in, raising a ValueError (with a custom text) allows users to quickly see what kind of problem is involved, compared to a custom exception type (something like "ValueErrorSpecificModule", which is not standard). A: There's nothing operationally wrong with doing something like: raise ValueError("invalid input encoding") In fact, I do that quite often when I'm writing the first pass of some code. The main problem with doing it that way is that clients of your code have a hard time being precise in their exception handling; in order to catch that specific exception, they would have to do string matching on the exception object they caught, which is obviously fragile and tedious. Thus, it would be better to introduce a ValueError subclass of your own; this could still be caught as ValueError, but also as the more specific exception class. A general rule of thumb is that whenever you have code like: raise ValueError('some problem: %s' % value) You should probably replace it with something like: class SomeProblem(ValueError): """ Raised to signal a problem with the specified value. """ # ... raise SomeProblem(value) You might say that the exception type specifies what went wrong, whereas the message / attributes specify how it went wrong. A: It's perfectly ok. However you may want to create your own subclass to help distinguish from the builtin exceptions For example if you have something that works like a dict, you can raise a KeyError for the usual reasons, but what if the KeyError is really coming from an underlying dict you are using in the implementation. Raising a subclass of KeyError makes it easier to see that there is a bug in the implementation, and not that the key just isn't in your object A: It's OK and I do it all the time. I find it less surprising to see TypeError than MySpecialTypeError in many situations. On the page you linked, I don't see the phrase "built-in": exception TypeError: Raised when an operation or function is applied to an object of inappropriate type. The associated value is a string giving details about the type mismatch. Perhaps someone saw your question and fixed the documentation already. EDIT: It looks like you may have inserted the documentation for ValueError instead of TypeError
Is it OK to raise a built-in exception, but with a different message, in Python?
Is it OK to raise a built-in exception with a custom text? or to raise a built-in warning also with custom text? The documentation reads: exception ValueError: Raised when a built-in operation or function receives an argument (…) Is it implied that only built-in operations should raise a ValueError exception? In practice, I understand that it is safe to create an exception class that inherits from ValueError or Exception. But is it OK not to do that, and directly raise a ValueError("custom text")? Since ValueError is built-in, raising a ValueError (with a custom text) allows users to quickly see what kind of problem is involved, compared to a custom exception type (something like "ValueErrorSpecificModule", which is not standard).
[ "There's nothing operationally wrong with doing something like:\nraise ValueError(\"invalid input encoding\")\n\nIn fact, I do that quite often when I'm writing the first pass of some code. The main problem with doing it that way is that clients of your code have a hard time being precise in their exception handling; in order to catch that specific exception, they would have to do string matching on the exception object they caught, which is obviously fragile and tedious. Thus, it would be better to introduce a ValueError subclass of your own; this could still be caught as ValueError, but also as the more specific exception class.\nA general rule of thumb is that whenever you have code like:\nraise ValueError('some problem: %s' % value)\n\nYou should probably replace it with something like:\nclass SomeProblem(ValueError):\n \"\"\"\n Raised to signal a problem with the specified value.\n \"\"\"\n# ...\nraise SomeProblem(value)\n\nYou might say that the exception type specifies what went wrong, whereas the message / attributes specify how it went wrong.\n", "It's perfectly ok. \nHowever you may want to create your own subclass to help distinguish from the builtin exceptions\nFor example if you have something that works like a dict, you can raise a KeyError for the usual reasons, but what if the KeyError is really coming from an underlying dict you are using in the implementation.\nRaising a subclass of KeyError makes it easier to see that there is a bug in the implementation, and not that the key just isn't in your object\n", "It's OK and I do it all the time. I find it less surprising to see TypeError than MySpecialTypeError in many situations.\nOn the page you linked, I don't see the phrase \"built-in\":\nexception TypeError: Raised when an operation or function is applied to an object of inappropriate type. The associated value is a string giving details about the type mismatch.\n\nPerhaps someone saw your question and fixed the documentation already.\nEDIT: It looks like you may have inserted the documentation for ValueError instead of TypeError\n" ]
[ 29, 3, 3 ]
[]
[]
[ "built_in", "exception", "python", "raise" ]
stackoverflow_0002180577_built_in_exception_python_raise.txt
Q: How do I use this Python package? (guess_language) I am trying to use this package: http://pypi.python.org/pypi/guess-language/0.1 I've read the documentation/wiki, but can't find the solution. Basically, this package allows you to pass in a string, and it will return a "language". I'm able to make it print out "en". htmlSource = download('http://feeds.feedburner.com/nchild') soup = BeautifulStoneSoup(htmlSource) justwords = ''.join(soup.findAll(text=True)) justwords = justwords.encode('utf-8') true_lang = guess_language.guessLanguage(justwords) I'd like to know...how does this person print out the scores/accuracy of the guess? Am I passing the string correctly to the python library? A: By modifying the source code of the module, from the sounds of this quote (taken from the answer you linked to): Update after some experimentation, including inserting a print statement to show what script blocks were detected with what percentages (Emphasis added by me.)
How do I use this Python package? (guess_language)
I am trying to use this package: http://pypi.python.org/pypi/guess-language/0.1 I've read the documentation/wiki, but can't find the solution. Basically, this package allows you to pass in a string, and it will return a "language". I'm able to make it print out "en". htmlSource = download('http://feeds.feedburner.com/nchild') soup = BeautifulStoneSoup(htmlSource) justwords = ''.join(soup.findAll(text=True)) justwords = justwords.encode('utf-8') true_lang = guess_language.guessLanguage(justwords) I'd like to know...how does this person print out the scores/accuracy of the guess? Am I passing the string correctly to the python library?
[ "By modifying the source code of the module, from the sounds of this quote (taken from the answer you linked to):\n\nUpdate after some experimentation, including inserting a print statement to show what script blocks were detected with what percentages\n\n(Emphasis added by me.)\n" ]
[ 1 ]
[]
[]
[ "package", "python", "wiki" ]
stackoverflow_0002180864_package_python_wiki.txt
Q: Why do I get the u"xyz" format when I print a list of unicode strings in Python? Please observe the following behavior: a = u"foo" b = u"b\xe1r" # \xe1 is an 'a' with an accent s = [a, b] print a, b print s for x in s: print x, The result is: foo bár [u'foo', u'b\xe1r'] foo bár When I just print the two values sitting in variables a and b, I get what I expect; when I put the string values in a list and print it, I get the unwanted u"xyz" form; finally, when I print values from the list with a loop, I get the first form again. Can someone please explain this seemingly odd behavior? I know there's probably a good reason. A: When you print a list, you get the repr() of each element, lists aren't really meant to be printed, so python tries to print something representative of it's structure. If you want to format it in any particular way, either be explicit about how you want it formatted, or override it's __repr__ method. A: Objects in Python have two ways to be turned into strings: roughly speaking, str() produces human readable output, and repr() produces computer-readable output. When you print something, it uses str(). But the str() of a list uses the repr() of its elements. A: You get this because lists can contain any number of elements, of mixed types. In the second case, instead of printing unicode strings, you're printing the list itself - which is very different than printing the list contents. Since the list can contain anything, you get the u'foo' syntax. If you were using non-unicode strings, you'd see the 'foo' instead of just foo, as well.
Why do I get the u"xyz" format when I print a list of unicode strings in Python?
Please observe the following behavior: a = u"foo" b = u"b\xe1r" # \xe1 is an 'a' with an accent s = [a, b] print a, b print s for x in s: print x, The result is: foo bár [u'foo', u'b\xe1r'] foo bár When I just print the two values sitting in variables a and b, I get what I expect; when I put the string values in a list and print it, I get the unwanted u"xyz" form; finally, when I print values from the list with a loop, I get the first form again. Can someone please explain this seemingly odd behavior? I know there's probably a good reason.
[ "When you print a list, you get the repr() of each element, lists aren't really meant to be printed, so python tries to print something representative of it's structure.\nIf you want to format it in any particular way, either be explicit about how you want it formatted, or override it's __repr__ method.\n", "Objects in Python have two ways to be turned into strings: roughly speaking, str() produces human readable output, and repr() produces computer-readable output. When you print something, it uses str().\nBut the str() of a list uses the repr() of its elements.\n", "You get this because lists can contain any number of elements, of mixed types. In the second case, instead of printing unicode strings, you're printing the list itself - which is very different than printing the list contents.\nSince the list can contain anything, you get the u'foo' syntax. If you were using non-unicode strings, you'd see the 'foo' instead of just foo, as well.\n" ]
[ 7, 1, 0 ]
[]
[]
[ "list", "python", "unicode" ]
stackoverflow_0002180929_list_python_unicode.txt
Q: Django generic views with multiple parameters Is it possible to use a generic view with additional parameters in the URL mapping - i.e. I got the following model: class Route(models.Model): area = models.ForeignKey(Area) slug = models.SlugField(null=True,blank=True) @models.permalink def get_absolute_url(self): return ('route_details', (), {'area': self.area.slug, 'slug': self.slug}) This URL-Mapping: url(r'^(?P<area>[-\w]+)/(?P<slug>[-\w]+)/$','routes.views.route_details', name='route_details') And this trivial view: def route_details(self, area, slug): route = get_object_or_404(Route, slug=slug) return render_to_response("routes/route_details.html", {'route': route}) As you can see, I'm actually identifying the route just by the route's slug and the area slug is just to shape the url (e.g. routes/central-park/rat-rock). Can I do the same just using a generic view? A: Sure, something like this: url(r'^(?P<area>[-\w]+)/(?P<slug>[-\w]+)/$', 'django.views.generic.list_detail.object_detail', {'queryset': Route.objects.all()} name='route_details') Should just work. Be sure to either set template_object_name to "route" or use "object" in template.
Django generic views with multiple parameters
Is it possible to use a generic view with additional parameters in the URL mapping - i.e. I got the following model: class Route(models.Model): area = models.ForeignKey(Area) slug = models.SlugField(null=True,blank=True) @models.permalink def get_absolute_url(self): return ('route_details', (), {'area': self.area.slug, 'slug': self.slug}) This URL-Mapping: url(r'^(?P<area>[-\w]+)/(?P<slug>[-\w]+)/$','routes.views.route_details', name='route_details') And this trivial view: def route_details(self, area, slug): route = get_object_or_404(Route, slug=slug) return render_to_response("routes/route_details.html", {'route': route}) As you can see, I'm actually identifying the route just by the route's slug and the area slug is just to shape the url (e.g. routes/central-park/rat-rock). Can I do the same just using a generic view?
[ "Sure, something like this:\nurl(r'^(?P<area>[-\\w]+)/(?P<slug>[-\\w]+)/$',\n 'django.views.generic.list_detail.object_detail',\n {'queryset': Route.objects.all()}\n name='route_details')\n\nShould just work.\nBe sure to either set template_object_name to \"route\" or use \"object\" in template.\n" ]
[ 0 ]
[]
[]
[ "django", "django_generic_views", "python" ]
stackoverflow_0002181002_django_django_generic_views_python.txt
Q: How to access url hash/fragment from a Django Request object As in the title: How can I access the URL hash/fragment (the part following the hash #, or 'pound symbol' in US English) from a Django view and so, I suppose, from a Django Request object? I've not found enough information on the documentation here available: http://docs.djangoproject.com/en/dev/ref/request-response/ P.S. Assume the fragment is included in the URL sent to the server. (I have verified this in my case, where I'm not actually using a browser.) A: This is not sent to the server, by definition. From URI References: Fragment Identifiers on URIs : "The HTTP engine cannot make any assumptions about it. The server is not even given it."
How to access url hash/fragment from a Django Request object
As in the title: How can I access the URL hash/fragment (the part following the hash #, or 'pound symbol' in US English) from a Django view and so, I suppose, from a Django Request object? I've not found enough information on the documentation here available: http://docs.djangoproject.com/en/dev/ref/request-response/ P.S. Assume the fragment is included in the URL sent to the server. (I have verified this in my case, where I'm not actually using a browser.)
[ "This is not sent to the server, by definition. From URI References: Fragment Identifiers on URIs :\n\n\"The HTTP engine cannot make any assumptions about it. The server is not even given it.\"\n\n" ]
[ 42 ]
[]
[]
[ "django", "django_urls", "fragment_identifier", "hash", "python" ]
stackoverflow_0002181186_django_django_urls_fragment_identifier_hash_python.txt
Q: Deleting attributes when deleting instance class A: def __get(self): return self._x def __set(self, y): self._x = y def __delete_x(self): print('DELETING') del self._x x = property(__get,__set,__delete_x) b = A() # Here, when b is deleted, i'd like b.x to be deleted, i.e __delete_x() # called (and for immediate consequence, "DELETING" printed) del b A: The semantics of the del statement don't really lend themselves to what you want here. del b simple removes the reference to the A object you just instantiated from the local scope frame / dictionary; this does not directly cause any operation to be performed on the object itself. If that was the last reference to the object, then the reference count dropping to zero, or the garbage collector collecting a cycle, may cause the object to be deallocated. You could observe this by adding a __del__ method to the object, or by adding a weakref callback that performs the desired actions. Neither of the latter two solutions seems like a great idea, though; __del__ methods prevent the garbage collector from collecting any cycles involving the object; and while weakrefs do not suffer from this problem, in either case you may be running in a strange environment (such as during program shutdown), which may make it difficult to get done what you want to accomplish. If you can expand on your exact use case, it may be that there is an entirely different approach to accomplishing your desired end goal, but it is difficult to speculate based on such a general and limited example. A: To control what happens when an instance of class A goes away (whether by being deleted or garbage collected), you can implement special method __del__(self) in A. If you want to have your code involved when a specific attribute of that instance goes away, you can either wrap that attribute with a wrapper class which has __del__, or, probably better in most cases, use the weakref module (however, not all types are subject to being target of weak references, so you may also need some wrapping for this case). Avoiding __del__ is generally preferable, if you possibly can, because it can interfere with garbage collection and thereby cause "memory leaks" if and when you have circular references. A: An ugly way to do it would be : def __del__(self): for x in dir(self.__class__): if type(getattr(self.__class__, x)) == property: getattr(self.__class__, x).fdel(self)
Deleting attributes when deleting instance
class A: def __get(self): return self._x def __set(self, y): self._x = y def __delete_x(self): print('DELETING') del self._x x = property(__get,__set,__delete_x) b = A() # Here, when b is deleted, i'd like b.x to be deleted, i.e __delete_x() # called (and for immediate consequence, "DELETING" printed) del b
[ "The semantics of the del statement don't really lend themselves to what you want here. del b simple removes the reference to the A object you just instantiated from the local scope frame / dictionary; this does not directly cause any operation to be performed on the object itself. If that was the last reference to the object, then the reference count dropping to zero, or the garbage collector collecting a cycle, may cause the object to be deallocated. You could observe this by adding a __del__ method to the object, or by adding a weakref callback that performs the desired actions.\nNeither of the latter two solutions seems like a great idea, though; __del__ methods prevent the garbage collector from collecting any cycles involving the object; and while weakrefs do not suffer from this problem, in either case you may be running in a strange environment (such as during program shutdown), which may make it difficult to get done what you want to accomplish.\nIf you can expand on your exact use case, it may be that there is an entirely different approach to accomplishing your desired end goal, but it is difficult to speculate based on such a general and limited example.\n", "To control what happens when an instance of class A goes away (whether by being deleted or garbage collected), you can implement special method __del__(self) in A. If you want to have your code involved when a specific attribute of that instance goes away, you can either wrap that attribute with a wrapper class which has __del__, or, probably better in most cases, use the weakref module (however, not all types are subject to being target of weak references, so you may also need some wrapping for this case).\nAvoiding __del__ is generally preferable, if you possibly can, because it can interfere with garbage collection and thereby cause \"memory leaks\" if and when you have circular references.\n", "An ugly way to do it would be :\ndef __del__(self):\n for x in dir(self.__class__):\n if type(getattr(self.__class__, x)) == property:\n getattr(self.__class__, x).fdel(self)\n\n" ]
[ 2, 1, 0 ]
[]
[]
[ "attributes", "class", "del", "instance", "python" ]
stackoverflow_0002181016_attributes_class_del_instance_python.txt
Q: HTML parser for GAE Generally I use lxml for my HTML parsing needs, but that isn't available on Google App Engine. The obvious alternative is BeautifulSoup, but I find it chokes too easily on malformed HTML. Currently I am testing libxml2dom and have been getting better results. Which pure Python HTML parser have you found performs best? My priority is the ability to handle bad HTML over speed. A: From the BeautifulSoup documentation: Version 3.1.0 of Beautiful Soup does significantly worse on real-world HTML than version 3.0.8 does So, it might help you to use this earlier version. That is precisely what the author himself recommends. You can pretend that Beautiful Soup version 3.1.0 was never released. Version 3.0.8 still works fine on Python 2.3 through 2.6. A: No longer a problem - lxml is supported: https://developers.google.com/appengine/docs/python/tools/libraries27
HTML parser for GAE
Generally I use lxml for my HTML parsing needs, but that isn't available on Google App Engine. The obvious alternative is BeautifulSoup, but I find it chokes too easily on malformed HTML. Currently I am testing libxml2dom and have been getting better results. Which pure Python HTML parser have you found performs best? My priority is the ability to handle bad HTML over speed.
[ "From the BeautifulSoup documentation:\n\nVersion 3.1.0 of Beautiful Soup does significantly worse on real-world HTML than version 3.0.8 does\n\nSo, it might help you to use this earlier version. That is precisely what the author himself recommends.\n\nYou can pretend that Beautiful Soup version 3.1.0 was never released. Version 3.0.8 still works fine on Python 2.3 through 2.6.\n\n", "No longer a problem - lxml is supported:\nhttps://developers.google.com/appengine/docs/python/tools/libraries27\n" ]
[ 5, 5 ]
[]
[]
[ "google_app_engine", "html_parsing", "lxml", "python" ]
stackoverflow_0002161560_google_app_engine_html_parsing_lxml_python.txt
Q: How do I use a Python regex to match the function syntax of MATLAB? I am trying to find all the inputs/outputs of all MATLAB functions in our internal library. I am new (first time) to regex and have been trying to use the multiline mode in Python's re library. The MATLAB function syntax looks like: function output = func_name(input) where the signature can span multiple lines. I started with a pattern like: re.compile(r"^.*function (.*)=(.*)\([.\n]*\)$", re.M) but I keep getting an unsupported template operator error. Any pointer is appreciated! EDIT: Now I have: pattern = re.compile(r"^\s*function (.*?)= [\w\n.]*?\(.*?\)", re.M|re.DOTALL) which gives matches like: function [fcst, spread] = ... VolFcstMKT(R,... mktVol,... calibrate,... spread_init,... fcstdays,... tsperyear) if(calibrate) if(nargin < 6) tsperyear = 252; end templen = length(R) My question is why does it give the extra lines instead of stopping at the first )? A: The peculiar (internal) error you're getting should come if you pass re.T instead of re.M as the second argument to re.compile (re.template -- a currently undocumented entry -- is the one intended to use it, and, in brief, template REs don't support repetition or backtracking). Can you print re.M to show what's its value in your code before you call this re.compile? Once that's fixed, we can discuss the details of your desired RE (in brief: if the input part can include parentheses you're out of luck, otherwise re.DOTALL and some rewriting of your pattern should help) -- but fixing this weird internal error occurrence seems to take priority. Edit: with this bug diagnosed (as per the comments below this Q), moving on to the OP's current question: the re.DOTALL|re.MULTINE, plus the '$' at the end of the pattern, plus the everywhere-greedy matches (using .*, instead of .*? for non-greedy), all together ensure that if the regex matches it will match as broad a swathe as possible... that's exactly what this combo is asking for. Probably best to open another Q with a specific example: what's the input, what gets matched, what would you like the regex to match instead, etc. A: Here's a regular expression that should match any MATLAB function declaration at the start of an m-file: ^\s*function\s+((\[[\w\s,.]*\]|[\w]*)\s*=)?[\s.]*\w+(\([^)]*\))? And here's a more detailed explanation of the components: ^\s* # Match 0 or more whitespace characters # at the start function # Match the word function \s+ # Match 1 or more whitespace characters ( # Start grouping 1 ( # Start grouping 2 \[ # Match opening bracket [\w\s,.]* # Match 0 or more letters, numbers, # whitespace, underscores, commas, # or periods... \] # Match closing bracket |[\w]* # ... or match 0 or more letters, # numbers, or underscores ) # End grouping 2 \s* # Match 0 or more whitespace characters = # Match an equal sign )? # End grouping 1; Match it 0 or 1 times [\s.]* # Match 0 or more whitespace characters # or periods \w+ # Match 1 or more letters, numbers, or # underscores ( # Start grouping 3 \( # Match opening parenthesis [^)]* # Match 0 or more characters that # aren't a closing parenthesis \) # Match closing parenthesis )? # End grouping 3; Match it 0 or 1 times Whether you use regular expressions or basic string operations, you should keep in mind the different forms that the function declaration can take in MATLAB. The general form is: function [out1,out2,...] = func_name(in1,in2,...) Specifically, you could see any of the following forms: function func_name %# No inputs or outputs function func_name(in1) %# 1 input function func_name(in1,in2) %# 2 inputs function out1 = func_name %# 1 output function [out1] = func_name %# Also 1 output function [out1,out2] = func_name %# 2 outputs ... You can also have line continuations (...) at many points, like after the equal sign or within the argument list: function out1 = ... func_name(in1,... in2,... in3) You may also want to take into account factors like variable input argument lists and ignored input arguments: function func_name(varargin) %# Any number of inputs possible function func_name(in1,~,in3) %# Second of three inputs is ignored Of course, many m-files contain more than 1 function, so you will have to decide how to deal with subfunctions, nested functions, and potentially even anonymous functions (which have a different declaration syntax). A: how about normal Python string operations? Just an example only for line in open("file"): sline=line.strip() if sline.startswith("function"): lhs,rhs =sline.split("=") out=lhs.replace("function ","") if "[" in out and "]" in out: out=out.replace("]","").replace("[","").split(",") print out m=rhs.find("(") if m!=-1: rhs=rhs[m:].replace(")","").replace("(","").split(",") print rhs output example $ cat file function [mean,stdev] = stat(x) n = length(x); mean = sum(x)/n; stdev = sqrt(sum((x-mean).^2/n)); function mean = avg(x,n) mean = sum(x)/n; $ python python.py ['mean', 'stdev '] [' statx'] mean [' avgx', 'n'] Of course, there should be many other scenarios of declaring functions in Matlab, like function nothing, function a = b etc , so add those checks yourself.
How do I use a Python regex to match the function syntax of MATLAB?
I am trying to find all the inputs/outputs of all MATLAB functions in our internal library. I am new (first time) to regex and have been trying to use the multiline mode in Python's re library. The MATLAB function syntax looks like: function output = func_name(input) where the signature can span multiple lines. I started with a pattern like: re.compile(r"^.*function (.*)=(.*)\([.\n]*\)$", re.M) but I keep getting an unsupported template operator error. Any pointer is appreciated! EDIT: Now I have: pattern = re.compile(r"^\s*function (.*?)= [\w\n.]*?\(.*?\)", re.M|re.DOTALL) which gives matches like: function [fcst, spread] = ... VolFcstMKT(R,... mktVol,... calibrate,... spread_init,... fcstdays,... tsperyear) if(calibrate) if(nargin < 6) tsperyear = 252; end templen = length(R) My question is why does it give the extra lines instead of stopping at the first )?
[ "The peculiar (internal) error you're getting should come if you pass re.T instead of re.M as the second argument to re.compile (re.template -- a currently undocumented entry -- is the one intended to use it, and, in brief, template REs don't support repetition or backtracking). Can you print re.M to show what's its value in your code before you call this re.compile?\nOnce that's fixed, we can discuss the details of your desired RE (in brief: if the input part can include parentheses you're out of luck, otherwise re.DOTALL and some rewriting of your pattern should help) -- but fixing this weird internal error occurrence seems to take priority.\nEdit: with this bug diagnosed (as per the comments below this Q), moving on to the OP's current question: the re.DOTALL|re.MULTINE, plus the '$' at the end of the pattern, plus the everywhere-greedy matches (using .*, instead of .*? for non-greedy), all together ensure that if the regex matches it will match as broad a swathe as possible... that's exactly what this combo is asking for. Probably best to open another Q with a specific example: what's the input, what gets matched, what would you like the regex to match instead, etc.\n", "Here's a regular expression that should match any MATLAB function declaration at the start of an m-file:\n^\\s*function\\s+((\\[[\\w\\s,.]*\\]|[\\w]*)\\s*=)?[\\s.]*\\w+(\\([^)]*\\))?\n\nAnd here's a more detailed explanation of the components:\n^\\s* # Match 0 or more whitespace characters\n # at the start\nfunction # Match the word function\n\\s+ # Match 1 or more whitespace characters\n( # Start grouping 1\n ( # Start grouping 2\n \\[ # Match opening bracket\n [\\w\\s,.]* # Match 0 or more letters, numbers,\n # whitespace, underscores, commas,\n # or periods...\n \\] # Match closing bracket\n |[\\w]* # ... or match 0 or more letters,\n # numbers, or underscores\n ) # End grouping 2\n \\s* # Match 0 or more whitespace characters\n = # Match an equal sign\n)? # End grouping 1; Match it 0 or 1 times\n[\\s.]* # Match 0 or more whitespace characters\n # or periods\n\\w+ # Match 1 or more letters, numbers, or\n # underscores\n( # Start grouping 3\n \\( # Match opening parenthesis\n [^)]* # Match 0 or more characters that\n # aren't a closing parenthesis\n \\) # Match closing parenthesis\n)? # End grouping 3; Match it 0 or 1 times\n\nWhether you use regular expressions or basic string operations, you should keep in mind the different forms that the function declaration can take in MATLAB. The general form is:\nfunction [out1,out2,...] = func_name(in1,in2,...)\n\nSpecifically, you could see any of the following forms:\nfunction func_name %# No inputs or outputs\nfunction func_name(in1) %# 1 input\nfunction func_name(in1,in2) %# 2 inputs\nfunction out1 = func_name %# 1 output\nfunction [out1] = func_name %# Also 1 output\nfunction [out1,out2] = func_name %# 2 outputs\n...\n\nYou can also have line continuations (...) at many points, like after the equal sign or within the argument list:\nfunction out1 = ...\n func_name(in1,...\n in2,...\n in3)\n\nYou may also want to take into account factors like variable input argument lists and ignored input arguments:\nfunction func_name(varargin) %# Any number of inputs possible\nfunction func_name(in1,~,in3) %# Second of three inputs is ignored\n\nOf course, many m-files contain more than 1 function, so you will have to decide how to deal with subfunctions, nested functions, and potentially even anonymous functions (which have a different declaration syntax).\n", "how about normal Python string operations? Just an example only\nfor line in open(\"file\"):\n sline=line.strip()\n if sline.startswith(\"function\"):\n lhs,rhs =sline.split(\"=\")\n out=lhs.replace(\"function \",\"\")\n if \"[\" in out and \"]\" in out:\n out=out.replace(\"]\",\"\").replace(\"[\",\"\").split(\",\")\n print out\n m=rhs.find(\"(\")\n if m!=-1:\n rhs=rhs[m:].replace(\")\",\"\").replace(\"(\",\"\").split(\",\") \n print rhs\n\noutput example\n$ cat file\nfunction [mean,stdev] = stat(x)\nn = length(x);\nmean = sum(x)/n;\nstdev = sqrt(sum((x-mean).^2/n));\nfunction mean = avg(x,n)\nmean = sum(x)/n;\n$ python python.py\n['mean', 'stdev ']\n[' statx']\nmean\n[' avgx', 'n']\n\nOf course, there should be many other scenarios of declaring functions in Matlab, like function nothing, function a = b etc , so add those checks yourself.\n" ]
[ 5, 2, 0 ]
[]
[]
[ "matlab", "python", "regex" ]
stackoverflow_0002180784_matlab_python_regex.txt
Q: Sorting and grouping objects by Date with the Django ORM I have an Article model which has a date field. I want to query against all Article objects, and have a datatype returned with each distinct year, and then each distinct month within that. for instance archives = { 2009: {12, [, , ...], 11: [...]}, 2008: {12, [...], 11: [...]}, } is this possible? A: This sort of question seems to come up fairly often. The easiest solution is to loop through the data and group the objects by year and month. You can do this by hand in the view or using regroup in your template. It really depends on what you want to do with the data. If grouping Archives by year and month is a very common thing for you to do in your application, you might want to consider creating a year and month field that you populate on save(). By hand it could be something like this: arch = {} for a in Archive.objects.all(): year = arch.get(a.pub_date.year, {}) month = year.get(a.pub_date.month, []) month.append(a) year[a.pub_date.month] = month arch[a.pub_date.year] = year Or pushing all the grouping logic into the template using regroup (untested): {% regroup archives by pub_date.year as year_list %} {% for year in year_list %} Year: {{ year.grouper }} {% regroup year.list by pub_date.month as month_list %} {% for month in month_list %} Month: {{ month.grouper }} {% for archive in month.list %} {{ archive }} {% endfor %} {% endfor %} {% endfor %} I would personally try to put the logic in the view instead of in the template. Here are a few related posts: Django Year/Month based posts archive In Django how to show a list of objects by year Listing blog entries by year,month A: There is no quick solution, but you may check dates() method.
Sorting and grouping objects by Date with the Django ORM
I have an Article model which has a date field. I want to query against all Article objects, and have a datatype returned with each distinct year, and then each distinct month within that. for instance archives = { 2009: {12, [, , ...], 11: [...]}, 2008: {12, [...], 11: [...]}, } is this possible?
[ "This sort of question seems to come up fairly often. The easiest solution is to loop through the data and group the objects by year and month. You can do this by hand in the view or using regroup in your template. It really depends on what you want to do with the data. \nIf grouping Archives by year and month is a very common thing for you to do in your application, you might want to consider creating a year and month field that you populate on save().\nBy hand it could be something like this:\narch = {}\nfor a in Archive.objects.all():\n year = arch.get(a.pub_date.year, {})\n month = year.get(a.pub_date.month, [])\n month.append(a)\n year[a.pub_date.month] = month\n arch[a.pub_date.year] = year\n\nOr pushing all the grouping logic into the template using regroup (untested):\n{% regroup archives by pub_date.year as year_list %}\n{% for year in year_list %}\n Year: {{ year.grouper }}\n {% regroup year.list by pub_date.month as month_list %}\n {% for month in month_list %}\n Month: {{ month.grouper }}\n {% for archive in month.list %}\n {{ archive }}\n {% endfor %}\n {% endfor %}\n{% endfor %}\n\nI would personally try to put the logic in the view instead of in the template.\nHere are a few related posts: \n\nDjango Year/Month based posts archive\nIn Django how to show a list of objects by year\nListing blog entries by year,month\n\n", "There is no quick solution, but you may check dates() method.\n" ]
[ 4, 0 ]
[]
[]
[ "django", "django_orm", "python" ]
stackoverflow_0002180847_django_django_orm_python.txt
Q: Using the Image.point() method in PIL to manipulate pixel data I am using the Python Imaging Library to colorize a black and white image with a lookup table that defines the color relationships. The lookup table is simply a 256-element list of RGB tuples: >>> len(colors) 256 >>> colors[0] (255, 237, 237) >>> colors[127] (50, 196, 33) >>> My first version used the getpixel() and putpixel() methods: for x in range(w): for y in range(h): pix = img.getpixel((x,y)) img.putpixel((x,y), colors[pix[0]]) This was horribly slow. A profile report pointed to the putpixel and getpixel methods as the culprits. A little investigation (i.e, read the docs) and I find "Note that this method is relatively slow." re: putpixel. (actual runtime: 53s in putpixel and 50s getpixel for a 1024x1024 image) Based on the suggestion in the docs, I used im.load() and direct pixel access instead: pixels = img.load() for x in range(w): for y in range(h): pix = pixels[x, y] pixels[x, y] = colors[pix[0]] Processing sped up by an order of magnitude, but is still slow: about 3.5s to process a 1024x1024 image. A more thorough study of the PIL docs seems to indicate Image.point() is exactly intended for this purpose: im.point(table) => image im.point(function) => image Returns a copy of the image where each pixel has been mapped through the given table. The table should contains 256 values per band in the image. If a function is used instead, it should take a single argument. The function is called once for each possible pixel value, and the resulting table is applied to all bands of the image. I've spent some time hacking around with the interface, but can't quite seem to get it right. Forgive my ignorance, but PIL's docs are curt and I don't have much image processing experience. I've googled around a bit and turned up a few examples, but nothing that made the usage "click" for me. Thus, finally, my questions: Is Image.point() the right tool for this job? What format/structure does Image.point() expect the table? Can someone rough out an example implementation? Every iteration I've tried so far has ended up with a straight black image. A: Is Image.point() the right tool for this job? Yes indeed, Image.point() is perfect for this job What format/structure does Image.point() expect the table? You should flatten the list so instead of [(12, 140, 10), (10, 100, 200), ...] use: [12, 140, 10, 10, 100, 200, ...] Here is a quick example I just tried: im = im.point(range(256, 0, -1) * 3) And by the way, if you need more control over colors and you feel Image.point is not for you you can also use Image.getdata and Image.putdata to change colors more quickly than both load and putpixel. It is slower than Image.point though. Image.getdata gives you the list of all pixels, modify them and write them back using Image.putdata. It is that simple. But try to do it using Image.point first. EDIT I made a mistake in the first explanation, I'll explain correctly now: The color table actually is like this [0, 1, 2, 3, 4, 5, ...255, 0, 1, 2, 3, ....255, 0, 1, 2, 3, ...255] Each band range next to the other. To change the color (0, 0, 0) to (10, 100, 10) it need to become like this: [10, 1, 2, 3, 4, 5, ...255, 100, 1, 2, 3, ....255, 10, 1, 2, 3, ...255] To transform your color list into the right format try this: table = sum(zip(*colors), ()) I think my first example should demonstrate the formate for you. A: I think it might be more typical to point on a band-by-band basis like so (lifted directly from the PIL tutorial): # split the image into individual bands source = im.split() R, G, B = 0, 1, 2 # select regions where red is less than 100 mask = source[R].point(lambda i: i < 100 and 255) # process the green band out = source[G].point(lambda i: i * 0.7) # paste the processed band back, but only where red was < 100 source[G].paste(out, None, mask) # build a new multiband image im = Image.merge(im.mode, source)
Using the Image.point() method in PIL to manipulate pixel data
I am using the Python Imaging Library to colorize a black and white image with a lookup table that defines the color relationships. The lookup table is simply a 256-element list of RGB tuples: >>> len(colors) 256 >>> colors[0] (255, 237, 237) >>> colors[127] (50, 196, 33) >>> My first version used the getpixel() and putpixel() methods: for x in range(w): for y in range(h): pix = img.getpixel((x,y)) img.putpixel((x,y), colors[pix[0]]) This was horribly slow. A profile report pointed to the putpixel and getpixel methods as the culprits. A little investigation (i.e, read the docs) and I find "Note that this method is relatively slow." re: putpixel. (actual runtime: 53s in putpixel and 50s getpixel for a 1024x1024 image) Based on the suggestion in the docs, I used im.load() and direct pixel access instead: pixels = img.load() for x in range(w): for y in range(h): pix = pixels[x, y] pixels[x, y] = colors[pix[0]] Processing sped up by an order of magnitude, but is still slow: about 3.5s to process a 1024x1024 image. A more thorough study of the PIL docs seems to indicate Image.point() is exactly intended for this purpose: im.point(table) => image im.point(function) => image Returns a copy of the image where each pixel has been mapped through the given table. The table should contains 256 values per band in the image. If a function is used instead, it should take a single argument. The function is called once for each possible pixel value, and the resulting table is applied to all bands of the image. I've spent some time hacking around with the interface, but can't quite seem to get it right. Forgive my ignorance, but PIL's docs are curt and I don't have much image processing experience. I've googled around a bit and turned up a few examples, but nothing that made the usage "click" for me. Thus, finally, my questions: Is Image.point() the right tool for this job? What format/structure does Image.point() expect the table? Can someone rough out an example implementation? Every iteration I've tried so far has ended up with a straight black image.
[ "\nIs Image.point() the right tool for\n this job?\n\nYes indeed, Image.point() is perfect for this job\n\nWhat format/structure does\n Image.point() expect the table?\n\nYou should flatten the list so instead of [(12, 140, 10), (10, 100, 200), ...] use:\n[12, 140, 10, 10, 100, 200, ...]\n\nHere is a quick example I just tried:\nim = im.point(range(256, 0, -1) * 3)\n\n\n\nAnd by the way, if you need more control over colors and you feel Image.point is not for you you can also use Image.getdata and Image.putdata to change colors more quickly than both load and putpixel. It is slower than Image.point though.\nImage.getdata gives you the list of all pixels, modify them and write them back using Image.putdata. It is that simple. But try to do it using Image.point first.\n\nEDIT\nI made a mistake in the first explanation, I'll explain correctly now:\nThe color table actually is like this\n[0, 1, 2, 3, 4, 5, ...255, 0, 1, 2, 3, ....255, 0, 1, 2, 3, ...255]\n\nEach band range next to the other.\nTo change the color (0, 0, 0) to (10, 100, 10) it need to become like this:\n[10, 1, 2, 3, 4, 5, ...255, 100, 1, 2, 3, ....255, 10, 1, 2, 3, ...255]\n\nTo transform your color list into the right format try this:\ntable = sum(zip(*colors), ())\n\nI think my first example should demonstrate the formate for you.\n", "I think it might be more typical to point on a band-by-band basis like so (lifted directly from the PIL tutorial):\n# split the image into individual bands\nsource = im.split()\n\nR, G, B = 0, 1, 2\n\n# select regions where red is less than 100\nmask = source[R].point(lambda i: i < 100 and 255)\n\n# process the green band\nout = source[G].point(lambda i: i * 0.7)\n\n# paste the processed band back, but only where red was < 100\nsource[G].paste(out, None, mask)\n\n# build a new multiband image\nim = Image.merge(im.mode, source)\n\n" ]
[ 17, 3 ]
[]
[]
[ "image", "image_manipulation", "image_processing", "python", "python_imaging_library" ]
stackoverflow_0002181292_image_image_manipulation_image_processing_python_python_imaging_library.txt
Q: Multiprocessing and niceness value Does anyone know of an easy way to set the niceness value of a Process or Pool when it is created in multiprocessing? A: os.nice(increment) Add increment to the process’s “niceness”. Return the new niceness. Availability: Unix. From http://docs.python.org/library/os.html#os.nice. Is there a reason you can't call this in the child process? A: Try importing the ctypes module and looking for pthread_schedparam() or SetThreadPriority() (Linux / Windows).
Multiprocessing and niceness value
Does anyone know of an easy way to set the niceness value of a Process or Pool when it is created in multiprocessing?
[ "os.nice(increment)\nAdd increment to the process’s “niceness”. Return the new niceness. Availability: Unix.\n\nFrom http://docs.python.org/library/os.html#os.nice.\nIs there a reason you can't call this in the child process?\n", "Try importing the ctypes module and looking for pthread_schedparam() or SetThreadPriority() (Linux / Windows).\n" ]
[ 14, 0 ]
[]
[]
[ "multiprocessing", "python" ]
stackoverflow_0002181209_multiprocessing_python.txt
Q: Python method to boost function I have a method exported to Python using boost python that takes a boost::function as an argument. From what I have read boost::python should support boost::function without much fuss, but when I try to call the function with a python method it gives me this error Boost.Python.ArgumentError: Python argument types in Class.createTimer(Class, int, method, bool) did not match C++ signature: createTimer(class Class {lvalue}, unsigned long interval, class boost::function<bool _cdecl(void)> function, bool recurring=False) I am calling it from python with this code self.__class.createTimer( 3, test.timerFunc, False ) and in C++ it is defined as boost::int32_t createTimer( boost::uint32_t interval, boost::function< bool() > function, bool recurring = false ); The goal here is a timer class where I can do something like class->createTimer( 3, boost::bind( &funcWithArgs, arg1, arg2 ) ) to create a timer that executes the funcWithArgs. Thanks to boost bind this will work with pretty much any function or method. So what is the syntax I need to use for boost::python to accept my python functions as a boost::function? A: Got an answer on the python mailing list, and after a bit of reworking and more research I got exactly what I wanted :) I did see that post before mithrandi but I did not like the idea of having to declare the functions like that. With some fancy wrappers and a bit of python magic this can work and look good at the same time! To start, wrap up your python object with code like this struct timer_func_wrapper_t { timer_func_wrapper_t( bp::object callable ) : _callable( callable ) {} bool operator()() { // These GIL calls make it thread safe, may or may not be needed depending on your use case PyGILState_STATE gstate = PyGILState_Ensure(); bool ret = _callable(); PyGILState_Release( gstate ); return ret; } bp::object _callable; }; boost::int32_t createTimerWrapper( Class* class, boost::uint64_t interval, bp::object function, bool recurring = false ) { return class->createTimer( interval, boost::function<bool ()>( timer_func_wrapper_t( function ) ), recurring ); } when in your class define the method like so .def( "createTimer", &createTimerWrapper, ( bp::arg( "interval" ), bp::arg( "function" ), bp::arg( "recurring" ) = false ) ) With that little bit of wrapper you can work magic like this import MyLib import time def callMePls(): print( "Hello world" ) return True class = MyLib.Class() class.createTimer( 3, callMePls ) time.sleep( 1 ) To mimic the C++ completely, we also need a boost::bind implementation which can be found here: http://code.activestate.com/recipes/440557/ With that, we can now do something like this import MyLib import time def callMePls( str ): print( "Hello", str ) return True class = MyLib.Class() class.createTimer( 3, bind( callMePls, "world" ) ) time.sleep( 1 ) EDIT: I like to follow up on my questions when I can. I was using this code successfully for a while but I found out that this falls apart when you want to take boost::function's in object constructors. There is a way to make it work similarly to this but the new object you construct ends up with a different signature and will not work with other objects like itself. This finally bugged me enough to do something about it and since I know more about boost::python now I came up with a pretty good 'fits all' solution using converters. This code here will convert a python callable to a boost::python< bool() > object, it can be easily modified to convert to other boost functions. // Wrapper for timer function parameter struct timer_func_wrapper_t { timer_func_wrapper_t( bp::object callable ) : _callable(callable) {} bool operator()() { return _callable(); } bp::object _callable; }; struct BoostFunc_from_Python_Callable { BoostFunc_from_Python_Callable() { bp::converter::registry::push_back( &convertible, &construct, bp::type_id< boost::function< bool() > >() ); } static void* convertible( PyObject* obj_ptr ) { if( !PyCallable_Check( obj_ptr ) ) return 0; return obj_ptr; } static void construct( PyObject* obj_ptr, bp::converter::rvalue_from_python_stage1_data* data ) { bp::object callable( bp::handle<>( bp::borrowed( obj_ptr ) ) ); void* storage = ( ( bp::converter::rvalue_from_python_storage< boost::function< bool() > >* ) data )->storage.bytes; new (storage)boost::function< bool() >( timer_func_wrapper_t( callable ) ); data->convertible = storage; } }; Then in your init code, ie, BOOST_PYTHON_MODULE(), just register the type by creating the struct BOOST_PYTHON_MODULE(Foo) { // Register function converter BoostFunc_from_Python_Callable();
Python method to boost function
I have a method exported to Python using boost python that takes a boost::function as an argument. From what I have read boost::python should support boost::function without much fuss, but when I try to call the function with a python method it gives me this error Boost.Python.ArgumentError: Python argument types in Class.createTimer(Class, int, method, bool) did not match C++ signature: createTimer(class Class {lvalue}, unsigned long interval, class boost::function<bool _cdecl(void)> function, bool recurring=False) I am calling it from python with this code self.__class.createTimer( 3, test.timerFunc, False ) and in C++ it is defined as boost::int32_t createTimer( boost::uint32_t interval, boost::function< bool() > function, bool recurring = false ); The goal here is a timer class where I can do something like class->createTimer( 3, boost::bind( &funcWithArgs, arg1, arg2 ) ) to create a timer that executes the funcWithArgs. Thanks to boost bind this will work with pretty much any function or method. So what is the syntax I need to use for boost::python to accept my python functions as a boost::function?
[ "Got an answer on the python mailing list, and after a bit of reworking and more research I got exactly what I wanted :)\nI did see that post before mithrandi but I did not like the idea of having to declare the functions like that. With some fancy wrappers and a bit of python magic this can work and look good at the same time!\nTo start, wrap up your python object with code like this\nstruct timer_func_wrapper_t\n{\n timer_func_wrapper_t( bp::object callable ) : _callable( callable ) {}\n\n bool operator()()\n {\n // These GIL calls make it thread safe, may or may not be needed depending on your use case\n PyGILState_STATE gstate = PyGILState_Ensure();\n bool ret = _callable();\n PyGILState_Release( gstate );\n return ret;\n }\n\n bp::object _callable;\n};\n\nboost::int32_t createTimerWrapper( Class* class, boost::uint64_t interval, bp::object function, bool recurring = false )\n{\n return class->createTimer( interval, boost::function<bool ()>( timer_func_wrapper_t( function ) ), recurring );\n}\n\nwhen in your class define the method like so\n.def( \"createTimer\", &createTimerWrapper, ( bp::arg( \"interval\" ), bp::arg( \"function\" ), bp::arg( \"recurring\" ) = false ) )\n\nWith that little bit of wrapper you can work magic like this\nimport MyLib\nimport time\n\ndef callMePls():\n print( \"Hello world\" )\n return True\n\nclass = MyLib.Class()\n\nclass.createTimer( 3, callMePls )\n\ntime.sleep( 1 )\n\nTo mimic the C++ completely, we also need a boost::bind implementation which can be found here: http://code.activestate.com/recipes/440557/\nWith that, we can now do something like this\nimport MyLib\nimport time\n\ndef callMePls( str ):\n print( \"Hello\", str )\n return True\n\nclass = MyLib.Class()\n\nclass.createTimer( 3, bind( callMePls, \"world\" ) )\n\ntime.sleep( 1 )\n\nEDIT:\nI like to follow up on my questions when I can. I was using this code successfully for a while but I found out that this falls apart when you want to take boost::function's in object constructors.\nThere is a way to make it work similarly to this but the new object you construct ends up with a different signature and will not work with other objects like itself.\nThis finally bugged me enough to do something about it and since I know more about boost::python now I came up with a pretty good 'fits all' solution using converters.\nThis code here will convert a python callable to a boost::python< bool() > object, it can be easily modified to convert to other boost functions.\n// Wrapper for timer function parameter\nstruct timer_func_wrapper_t\n{\n timer_func_wrapper_t( bp::object callable ) : _callable(callable) {}\n\n bool operator()()\n {\n return _callable();\n }\n\n bp::object _callable;\n};\n\nstruct BoostFunc_from_Python_Callable\n{\n BoostFunc_from_Python_Callable()\n {\n bp::converter::registry::push_back( &convertible, &construct, bp::type_id< boost::function< bool() > >() );\n }\n\n static void* convertible( PyObject* obj_ptr )\n {\n if( !PyCallable_Check( obj_ptr ) ) return 0;\n return obj_ptr;\n }\n\n static void construct( PyObject* obj_ptr, bp::converter::rvalue_from_python_stage1_data* data )\n {\n bp::object callable( bp::handle<>( bp::borrowed( obj_ptr ) ) );\n void* storage = ( ( bp::converter::rvalue_from_python_storage< boost::function< bool() > >* ) data )->storage.bytes;\n new (storage)boost::function< bool() >( timer_func_wrapper_t( callable ) );\n data->convertible = storage;\n }\n};\n\nThen in your init code, ie, BOOST_PYTHON_MODULE(), just register the type by creating the struct\nBOOST_PYTHON_MODULE(Foo)\n{\n // Register function converter\n BoostFunc_from_Python_Callable();\n\n" ]
[ 12 ]
[]
[]
[ "boost", "boost_python", "c++", "python" ]
stackoverflow_0002179345_boost_boost_python_c++_python.txt
Q: Scraping html with Python or One of the arguments I make to my (Microbiology and Genetics) students is that "data" is/are messy, and Python can help with that (of course other languages can too). So here is a practical kind of web-based data-gathering exercise. I notice that there a few people who answer Python-related questions among the users with the highest rep. Among the questions which naturally arise: I wish to recover the current rep and rate of rep increase for (top rated) Pythonistas on Stack Overflow, so as to predict whether or when Alex Martelli will overtake Steven Lott or Greg Hewgill? what about Konrad Rudolph? Is it trivial because the increases for these guys are all pegged to the limit? More generally, in the absence of an API for querying (which I don't think there is) is there any alternative to looking through the URLs of pages for patterns, loading those pages with Python and then scraping the html? I realize there is probably not a general approach, but I'm interested in how people would approach this problem. Edit: @fitzgeraldsteele: Generally. SO is really just a (contrived) example. A: There's a perfectly usable monthly "data dump" of Stack Overflow under Creative Commons license, see for example here (just the first one "under my thumb" of the many links about this -- at least one per month). For such analysis as my average weekly rep relative to some other poster's, such monthly dollops of data are much more usable than screen-scrapes. If you do want to screen-scrape some (other;-) site, and that doesn't violate their policies or their robots.txt files, Python is one of several excellent choices -- start with scrapy, and you won't have all that much extra work to do, for example.
Scraping html with Python or
One of the arguments I make to my (Microbiology and Genetics) students is that "data" is/are messy, and Python can help with that (of course other languages can too). So here is a practical kind of web-based data-gathering exercise. I notice that there a few people who answer Python-related questions among the users with the highest rep. Among the questions which naturally arise: I wish to recover the current rep and rate of rep increase for (top rated) Pythonistas on Stack Overflow, so as to predict whether or when Alex Martelli will overtake Steven Lott or Greg Hewgill? what about Konrad Rudolph? Is it trivial because the increases for these guys are all pegged to the limit? More generally, in the absence of an API for querying (which I don't think there is) is there any alternative to looking through the URLs of pages for patterns, loading those pages with Python and then scraping the html? I realize there is probably not a general approach, but I'm interested in how people would approach this problem. Edit: @fitzgeraldsteele: Generally. SO is really just a (contrived) example.
[ "There's a perfectly usable monthly \"data dump\" of Stack Overflow under Creative Commons license, see for example here (just the first one \"under my thumb\" of the many links about this -- at least one per month). For such analysis as my average weekly rep relative to some other poster's, such monthly dollops of data are much more usable than screen-scrapes.\nIf you do want to screen-scrape some (other;-) site, and that doesn't violate their policies or their robots.txt files, Python is one of several excellent choices -- start with scrapy, and you won't have all that much extra work to do, for example.\n" ]
[ 3 ]
[]
[]
[ "python", "screen_scraping" ]
stackoverflow_0002181708_python_screen_scraping.txt
Q: How do you make QT threads in python for pyqt? I see discussion about qt threads vs python threads but how do you create and call qt threads in python? how do you give it access to your functions in another thread? Thanks! A: There's a good, fully worked-out example here.
How do you make QT threads in python for pyqt?
I see discussion about qt threads vs python threads but how do you create and call qt threads in python? how do you give it access to your functions in another thread? Thanks!
[ "There's a good, fully worked-out example here.\n" ]
[ 1 ]
[]
[]
[ "multithreading", "pyqt", "python" ]
stackoverflow_0002181724_multithreading_pyqt_python.txt
Q: Parsing Python Response using httplib After connecting to a socket and capturing the response using .read() how do I parse the input stream and read lines? I see the data is returned without any CRLF <html><head><title>Apache Tomcat/6.0.16 - Error report</title><style><!--H1 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:22px;} H2 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:16px;} H3 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:14px;} BODY {font-family:Tahoma,Arial,sans-serif;color:black;background-color:white;} B {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;} P {font-family:Tahoma,Arial,sans-serif;background:white;color:black;font-size:12px;}A {color : black;}A.name {color : black;}HR {color : #525D76;}--></style> </head><body><h1>HTTP Status 404 - /index.html</h1><HR size="1" noshade="noshade"><p><b>type</b> Status report</p><p><b>message</b> <u>/index.html</u></p><p><b>description</b> <u>The requested resource (/index.html) is not available.</u></p><HR size="1" noshade="noshade"><h3>Apache Tomcat/6.0.22</h3></body></html> A: You have to parse the HTML. Python has several ways of parsing HTML - one of them the built-in HTMLParser module. Another, and probably better way, is the 3rd party BeautifulSoup module. Many other issues dealing with HTML processing are explained in this nice article. You can also read the relevant chapter of the (free online) Dive into Python book. A: Use an HTML parser. Beautiful Soup seems to be a popular one.
Parsing Python Response using httplib
After connecting to a socket and capturing the response using .read() how do I parse the input stream and read lines? I see the data is returned without any CRLF <html><head><title>Apache Tomcat/6.0.16 - Error report</title><style><!--H1 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:22px;} H2 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:16px;} H3 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:14px;} BODY {font-family:Tahoma,Arial,sans-serif;color:black;background-color:white;} B {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;} P {font-family:Tahoma,Arial,sans-serif;background:white;color:black;font-size:12px;}A {color : black;}A.name {color : black;}HR {color : #525D76;}--></style> </head><body><h1>HTTP Status 404 - /index.html</h1><HR size="1" noshade="noshade"><p><b>type</b> Status report</p><p><b>message</b> <u>/index.html</u></p><p><b>description</b> <u>The requested resource (/index.html) is not available.</u></p><HR size="1" noshade="noshade"><h3>Apache Tomcat/6.0.22</h3></body></html>
[ "You have to parse the HTML. Python has several ways of parsing HTML - one of them the built-in HTMLParser module. Another, and probably better way, is the 3rd party BeautifulSoup module.\nMany other issues dealing with HTML processing are explained in this nice article. You can also read the relevant chapter of the (free online) Dive into Python book.\n", "Use an HTML parser. Beautiful Soup seems to be a popular one.\n" ]
[ 3, 0 ]
[]
[]
[ "httplib", "python", "urllib" ]
stackoverflow_0002181817_httplib_python_urllib.txt
Q: Python Iteration Problem! I have this code here, it is supposed to remove the common letters from both the lists n1 and n2. But when i run this code it only runs once as in it removes only 'a' from both n1 and n2 and doesnt remove 'k'. Just to clarify this code should always work on only 2 words. name1 = "abdjek" name2 = "doarhsnk" n1l = list(name1) n2l = list(name2) for i in range(len(n1l)): for j in range(len(n2l)): if n1l[i] == n2l[j]: n1l.pop(i) n2l.pop(j) n1l.append('0') n2l.append('1') Ok wait, it seems to work for the above 2 names but when i have name1 = "naveen" and name2 = "darshana" it doesnt work! A: I suggest a much simpler approach: def removecommon(name1, name2): common = set(name1).intersection(name2) res1 = ''.join(n for n in name1 if n not in common) res2 = ''.join(n for n in name2 if n not in common) return res1, res2 n1, n2 = removecommon('naveen', 'darshana') print n1, n2 emits vee drsh as desired. Edit: as the OP now specified (in a comment -- pls remember to edit your question too, oh OP!) that he actually wants to remove only the first occurrence in each word of each common letter, the needed algorithm is of course completely different. A simple approach (feasible if the length of the words is not too high): def removefirstcommon(name1, name2): common = set(name1).intersection(name2) n1 = list(name1) for c in common: n1.remove(c) n2 = list(name2) for c in common: n2.remove(c) return ''.join(n1), ''.join(n2) A more elaborate approach (while slower for normal-length words) would be faster for extremely long words (since the following is O(N) while the former's O(N squared)): def removefirstcommonlongwords(name1, name2): common = set(name1).intersection(name2) def mustrem(c, copycom): res = c not in copycom copycom.discard(c) return res cop = set(common) n1 = [c for c in name1 if mustrem(c, cop)] n2 = [c for c in name2 if mustrem(c, common)] return ''.join(n1), ''.join(n2) A: A more pythonic approach would be to use sets and list comprehensions. name1 = "naveen"; name2 = "darshana" name1_set=set(name1) name2_set=set(name2) clean1=[x for x in name1 if x not in name2_set] clean2=[x for x in name2 if x not in name1_set] clean1.extend(['0']*(len(name1)-len(clean1))) clean2.extend(['1']*(len(name2)-len(clean2))) print clean1,clean2 set gives us O(1) lookups, thus making the whole process faster by making it O(N) instead of O(N^2). EDIT: In light of your later comment that the number of occurrences matter, this is the updated version that takes that into account. name1 = "naveen"; name2 = "darshana" count1={} count2={} for x in name1: count1[x]=count1.get(x,0)+1 for x in name2: count2[x]=count2.get(x,0)+1 def remove_dups(name,count,null): clean=[] for x in name: if count.get(x,0): count[x]-=1 else: clean.append(x) clean.extend([null]*(len(name)-len(clean))) return clean clean1=remove_dups(name1,count2,'0') clean2=remove_dups(name2,count1,'1') print clean1,clean2 It uses dicts to keep counts of occurrences. Whenever a character is removed, the corresponding count for the other name is decremented. Complexity is still O(N). It prints ['v', 'e', 'e', 'n', '0', '0'] and ['d', 'r', 's', 'h', 'a', 'a', '1', '1']. Is that what you wanted? A: It's working here for me. That is, if I add print statements thus: name1 = "abdjek" name2 = "doarhsnk" n1l = list(name1) n2l = list(name2) print "Lists before loop:" print n1l print n2l for i in range(len(n1l)): for j in range(len(n2l)): if n1l[i] == n2l[j]: n1l.pop(i) n2l.pop(j) n1l.append('0') n2l.append('1') print "Lists after loop:" print n1l print n2l the characters 'a', 'd', and 'k' are all removed: > python test.py Lists before loop: ['a', 'b', 'd', 'j', 'e', 'k'] ['d', 'o', 'a', 'r', 'h', 's', 'n', 'k'] Lists after loop: ['b', 'j', 'e', '0', '0', '0'] ['o', 'r', 'h', 's', 'n', '1', '1', '1'] A: Your code might not be working as you expect it to, as it is removing paired letters. For instance, you see an a, you then remove both a's from your words... A: Your code most probably fails because you pop common letters from anywhere in the list, but append the replacements ("0" and "1") to the end of the list. They should be at position i and j, respectively. So the loop should probably look like this: for i in range(len(n1l)): for j in range(len(n2l)): if n1l[i] == n2l[j] and n1l[i] not in ("0", "1"): print "common letter ", n1l[i] # Replace i-th and j-th element n1l[i] = "0" n2l[j] = "1" Anyway, there more "pythonic" ways, which are already shown in the other answers. EDIT: Tested and working also with name1 = "naveen" / name2 = "darshana". A: Here's some quite (IMHO quite elegant) code that runs in O(n). If word 1 has N occurrences of the letter x, it removes the first N x's from word 2 (and vice versa) -- I think this is what you want, but I could be wrong. from collections import defaultdict def build(s, chars_s, chars_t): """Return characters of s, with duplicate characters from t removed.""" for i, char in enumerate(s): indexes_s, indexes_t = chars_s[char], chars_t[char] if len(indexes_s) > len(indexes_t) and i >= indexes_s[len(indexes_t)]: yield char def rm_dup(a, b): """Pairwise remove duplicate letters in a and b.""" chars_a, chars_b = defaultdict(list), defaultdict(list) for i, char in enumerate(a): chars_a[char].append(i) for i, char in enumerate(b): chars_b[char].append(i) return (''.join(build(a, chars_a, chars_b)), ''.join(build(b, chars_b, chars_a))) print rm_dup('naveen', 'darshana')
Python Iteration Problem!
I have this code here, it is supposed to remove the common letters from both the lists n1 and n2. But when i run this code it only runs once as in it removes only 'a' from both n1 and n2 and doesnt remove 'k'. Just to clarify this code should always work on only 2 words. name1 = "abdjek" name2 = "doarhsnk" n1l = list(name1) n2l = list(name2) for i in range(len(n1l)): for j in range(len(n2l)): if n1l[i] == n2l[j]: n1l.pop(i) n2l.pop(j) n1l.append('0') n2l.append('1') Ok wait, it seems to work for the above 2 names but when i have name1 = "naveen" and name2 = "darshana" it doesnt work!
[ "I suggest a much simpler approach:\ndef removecommon(name1, name2):\n common = set(name1).intersection(name2)\n res1 = ''.join(n for n in name1 if n not in common)\n res2 = ''.join(n for n in name2 if n not in common)\n return res1, res2\n\nn1, n2 = removecommon('naveen', 'darshana')\nprint n1, n2\n\nemits vee drsh as desired.\nEdit: as the OP now specified (in a comment -- pls remember to edit your question too, oh OP!) that he actually wants to remove only the first occurrence in each word of each common letter, the needed algorithm is of course completely different. A simple approach (feasible if the length of the words is not too high):\ndef removefirstcommon(name1, name2):\n common = set(name1).intersection(name2)\n n1 = list(name1)\n for c in common: n1.remove(c)\n n2 = list(name2)\n for c in common: n2.remove(c)\n return ''.join(n1), ''.join(n2)\n\nA more elaborate approach (while slower for normal-length words) would be faster for extremely long words (since the following is O(N) while the former's O(N squared)):\ndef removefirstcommonlongwords(name1, name2):\n common = set(name1).intersection(name2)\n def mustrem(c, copycom):\n res = c not in copycom\n copycom.discard(c)\n return res\n cop = set(common)\n n1 = [c for c in name1 if mustrem(c, cop)]\n n2 = [c for c in name2 if mustrem(c, common)]\n return ''.join(n1), ''.join(n2)\n\n", "A more pythonic approach would be to use sets and list comprehensions.\nname1 = \"naveen\"; name2 = \"darshana\"\n\nname1_set=set(name1)\nname2_set=set(name2)\n\nclean1=[x for x in name1 if x not in name2_set]\nclean2=[x for x in name2 if x not in name1_set]\n\nclean1.extend(['0']*(len(name1)-len(clean1)))\nclean2.extend(['1']*(len(name2)-len(clean2)))\n\nprint clean1,clean2\n\nset gives us O(1) lookups, thus making the whole process faster by making it O(N) instead of O(N^2).\nEDIT: In light of your later comment that the number of occurrences matter, this is the updated version that takes that into account.\nname1 = \"naveen\"; name2 = \"darshana\"\n\ncount1={}\ncount2={}\n\n\nfor x in name1:\n count1[x]=count1.get(x,0)+1\n\nfor x in name2:\n count2[x]=count2.get(x,0)+1\n\ndef remove_dups(name,count,null):\n clean=[]\n for x in name:\n if count.get(x,0):\n count[x]-=1\n else:\n clean.append(x)\n clean.extend([null]*(len(name)-len(clean)))\n return clean\n\nclean1=remove_dups(name1,count2,'0')\nclean2=remove_dups(name2,count1,'1')\n\nprint clean1,clean2\n\nIt uses dicts to keep counts of occurrences. Whenever a character is removed, the corresponding count for the other name is decremented. Complexity is still O(N).\nIt prints ['v', 'e', 'e', 'n', '0', '0'] and ['d', 'r', 's', 'h', 'a', 'a', '1', '1']. Is that what you wanted?\n", "It's working here for me. That is, if I add print statements thus:\nname1 = \"abdjek\"\nname2 = \"doarhsnk\"\n\nn1l = list(name1)\nn2l = list(name2)\n\nprint \"Lists before loop:\"\nprint n1l\nprint n2l\n\nfor i in range(len(n1l)):\n for j in range(len(n2l)):\n if n1l[i] == n2l[j]:\n n1l.pop(i)\n n2l.pop(j)\n n1l.append('0')\n n2l.append('1')\n\nprint \"Lists after loop:\"\nprint n1l\nprint n2l\n\nthe characters 'a', 'd', and 'k' are all removed:\n> python test.py \nLists before loop:\n['a', 'b', 'd', 'j', 'e', 'k']\n['d', 'o', 'a', 'r', 'h', 's', 'n', 'k']\nLists after loop:\n['b', 'j', 'e', '0', '0', '0']\n['o', 'r', 'h', 's', 'n', '1', '1', '1']\n\n", "Your code might not be working as you expect it to, as it is removing paired letters. For instance, you see an a, you then remove both a's from your words... \n", "Your code most probably fails because you pop common letters from anywhere in the list, but append the replacements (\"0\" and \"1\") to the end of the list. They should be at position i and j, respectively.\nSo the loop should probably look like this:\nfor i in range(len(n1l)):\n for j in range(len(n2l)):\n if n1l[i] == n2l[j] and n1l[i] not in (\"0\", \"1\"):\n print \"common letter \", n1l[i]\n # Replace i-th and j-th element\n n1l[i] = \"0\"\n n2l[j] = \"1\"\n\nAnyway, there more \"pythonic\" ways, which are already shown in the other answers.\nEDIT: Tested and working also with name1 = \"naveen\" / name2 = \"darshana\".\n", "Here's some quite (IMHO quite elegant) code that runs in O(n). If word 1 has N occurrences of the letter x, it removes the first N x's from word 2 (and vice versa) -- I think this is what you want, but I could be wrong.\nfrom collections import defaultdict\n\ndef build(s, chars_s, chars_t):\n \"\"\"Return characters of s, with duplicate characters from t removed.\"\"\"\n for i, char in enumerate(s):\n indexes_s, indexes_t = chars_s[char], chars_t[char]\n if len(indexes_s) > len(indexes_t) and i >= indexes_s[len(indexes_t)]:\n yield char\n\ndef rm_dup(a, b):\n \"\"\"Pairwise remove duplicate letters in a and b.\"\"\"\n chars_a, chars_b = defaultdict(list), defaultdict(list)\n for i, char in enumerate(a): chars_a[char].append(i)\n for i, char in enumerate(b): chars_b[char].append(i)\n return (''.join(build(a, chars_a, chars_b)),\n ''.join(build(b, chars_b, chars_a)))\n\nprint rm_dup('naveen', 'darshana')\n\n" ]
[ 5, 2, 0, 0, 0, 0 ]
[]
[]
[ "iteration", "python" ]
stackoverflow_0002173238_iteration_python.txt
Q: what is 'comments' mean in this code {% load comments %} where defined 'comments' ,a viewer? or a template?? thanks A: It is a template tag library. For example: {% load cache %} loads the caching tags. Custom tags can be defined and placed within your project structure as defined here. A: It's a template tag that loads a specific set of other template tags (comments application specific tags in this case) making them available in the rest of the template file to use. So, for example, you will be able to use other comments-app specific tags like: {% get_comment_count for entry as comment_count %} You can obtain more info here: http://docs.djangoproject.com/en/dev/ref/contrib/comments/#comment-template-tags and here: http://docs.djangoproject.com/en/dev/ref/templates/builtins/#load To understand how to make a set of custom template tags yourself and how to make them available to use via the same method, look here: http://docs.djangoproject.com/en/dev/howto/custom-template-tags/#howto-custom-template-tags A: As other answers have pointed out, comments is a templatetag. To answer your question: where defined 'comments' in django/contrib/comments/templatetags/comments.py Here you go: http://github.com/django/django/blob/master/django/contrib/comments/templatetags/comments.py Source: from django import template from django.template.loader import render_to_string from django.conf import settings from django.contrib.contenttypes.models import ContentType from django.contrib import comments from django.utils.encoding import smart_unicode register = template.Library() class BaseCommentNode(template.Node): """ Base helper class (abstract) for handling the get_comment_* template tags. Looks a bit strange, but the subclasses below should make this a bit more obvious. """ #@classmethod def handle_token(cls, parser, token): """Class method to parse get_comment_list/count/form and return a Node.""" tokens = token.contents.split() if tokens[1] != 'for': raise template.TemplateSyntaxError("Second argument in %r tag must be 'for'" % tokens[0]) # {% get_whatever for obj as varname %} if len(tokens) == 5: if tokens[3] != 'as': raise template.TemplateSyntaxError("Third argument in %r must be 'as'" % tokens[0]) return cls( object_expr = parser.compile_filter(tokens[2]), as_varname = tokens[4], ) # {% get_whatever for app.model pk as varname %} elif len(tokens) == 6: if tokens[4] != 'as': raise template.TemplateSyntaxError("Fourth argument in %r must be 'as'" % tokens[0]) return cls( ctype = BaseCommentNode.lookup_content_type(tokens[2], tokens[0]), object_pk_expr = parser.compile_filter(tokens[3]), as_varname = tokens[5] ) else: raise template.TemplateSyntaxError("%r tag requires 4 or 5 arguments" % tokens[0]) handle_token = classmethod(handle_token) #@staticmethod def lookup_content_type(token, tagname): try: app, model = token.split('.') return ContentType.objects.get(app_label=app, model=model) except ValueError: raise template.TemplateSyntaxError("Third argument in %r must be in the format 'app.model'" % tagname) except ContentType.DoesNotExist: raise template.TemplateSyntaxError("%r tag has non-existant content-type: '%s.%s'" % (tagname, app, model)) lookup_content_type = staticmethod(lookup_content_type) def __init__(self, ctype=None, object_pk_expr=None, object_expr=None, as_varname=None, comment=None): if ctype is None and object_expr is None: raise template.TemplateSyntaxError("Comment nodes must be given either a literal object or a ctype and object pk.") self.comment_model = comments.get_model() self.as_varname = as_varname self.ctype = ctype self.object_pk_expr = object_pk_expr self.object_expr = object_expr self.comment = comment def render(self, context): qs = self.get_query_set(context) context[self.as_varname] = self.get_context_value_from_queryset(context, qs) return '' def get_query_set(self, context): ctype, object_pk = self.get_target_ctype_pk(context) if not object_pk: return self.comment_model.objects.none() qs = self.comment_model.objects.filter( content_type = ctype, object_pk = smart_unicode(object_pk), site__pk = settings.SITE_ID, ) # The is_public and is_removed fields are implementation details of the # built-in comment model's spam filtering system, so they might not # be present on a custom comment model subclass. If they exist, we # should filter on them. field_names = [f.name for f in self.comment_model._meta.fields] if 'is_public' in field_names: qs = qs.filter(is_public=True) if getattr(settings, 'COMMENTS_HIDE_REMOVED', True) and 'is_removed' in field_names: qs = qs.filter(is_removed=False) return qs def get_target_ctype_pk(self, context): if self.object_expr: try: obj = self.object_expr.resolve(context) except template.VariableDoesNotExist: return None, None return ContentType.objects.get_for_model(obj), obj.pk else: return self.ctype, self.object_pk_expr.resolve(context, ignore_failures=True) def get_context_value_from_queryset(self, context, qs): """Subclasses should override this.""" raise NotImplementedError class CommentListNode(BaseCommentNode): """Insert a list of comments into the context.""" def get_context_value_from_queryset(self, context, qs): return list(qs) class CommentCountNode(BaseCommentNode): """Insert a count of comments into the context.""" def get_context_value_from_queryset(self, context, qs): return qs.count() class CommentFormNode(BaseCommentNode): """Insert a form for the comment model into the context.""" def get_form(self, context): ctype, object_pk = self.get_target_ctype_pk(context) if object_pk: return comments.get_form()(ctype.get_object_for_this_type(pk=object_pk)) else: return None def render(self, context): context[self.as_varname] = self.get_form(context) return '' class RenderCommentFormNode(CommentFormNode): """Render the comment form directly""" #@classmethod def handle_token(cls, parser, token): """Class method to parse render_comment_form and return a Node.""" tokens = token.contents.split() if tokens[1] != 'for': raise template.TemplateSyntaxError("Second argument in %r tag must be 'for'" % tokens[0]) # {% render_comment_form for obj %} if len(tokens) == 3: return cls(object_expr=parser.compile_filter(tokens[2])) # {% render_comment_form for app.models pk %} elif len(tokens) == 4: return cls( ctype = BaseCommentNode.lookup_content_type(tokens[2], tokens[0]), object_pk_expr = parser.compile_filter(tokens[3]) ) handle_token = classmethod(handle_token) def render(self, context): ctype, object_pk = self.get_target_ctype_pk(context) if object_pk: template_search_list = [ "comments/%s/%s/form.html" % (ctype.app_label, ctype.model), "comments/%s/form.html" % ctype.app_label, "comments/form.html" ] context.push() formstr = render_to_string(template_search_list, {"form" : self.get_form(context)}, context) context.pop() return formstr else: return '' class RenderCommentListNode(CommentListNode): """Render the comment list directly""" #@classmethod def handle_token(cls, parser, token): """Class method to parse render_comment_list and return a Node.""" tokens = token.contents.split() if tokens[1] != 'for': raise template.TemplateSyntaxError("Second argument in %r tag must be 'for'" % tokens[0]) # {% render_comment_list for obj %} if len(tokens) == 3: return cls(object_expr=parser.compile_filter(tokens[2])) # {% render_comment_list for app.models pk %} elif len(tokens) == 4: return cls( ctype = BaseCommentNode.lookup_content_type(tokens[2], tokens[0]), object_pk_expr = parser.compile_filter(tokens[3]) ) handle_token = classmethod(handle_token) def render(self, context): ctype, object_pk = self.get_target_ctype_pk(context) if object_pk: template_search_list = [ "comments/%s/%s/list.html" % (ctype.app_label, ctype.model), "comments/%s/list.html" % ctype.app_label, "comments/list.html" ] qs = self.get_query_set(context) context.push() liststr = render_to_string(template_search_list, { "comment_list" : self.get_context_value_from_queryset(context, qs) }, context) context.pop() return liststr else: return '' # We could just register each classmethod directly, but then we'd lose out on # the automagic docstrings-into-admin-docs tricks. So each node gets a cute # wrapper function that just exists to hold the docstring. #@register.tag def get_comment_count(parser, token): """ Gets the comment count for the given params and populates the template context with a variable containing that value, whose name is defined by the 'as' clause. Syntax:: {% get_comment_count for [object] as [varname] %} {% get_comment_count for [app].[model] [object_id] as [varname] %} Example usage:: {% get_comment_count for event as comment_count %} {% get_comment_count for calendar.event event.id as comment_count %} {% get_comment_count for calendar.event 17 as comment_count %} """ return CommentCountNode.handle_token(parser, token) #@register.tag def get_comment_list(parser, token): """ Gets the list of comments for the given params and populates the template context with a variable containing that value, whose name is defined by the 'as' clause. Syntax:: {% get_comment_list for [object] as [varname] %} {% get_comment_list for [app].[model] [object_id] as [varname] %} Example usage:: {% get_comment_list for event as comment_list %} {% for comment in comment_list %} ... {% endfor %} """ return CommentListNode.handle_token(parser, token) #@register.tag def render_comment_list(parser, token): """ Render the comment list (as returned by ``{% get_comment_list %}``) through the ``comments/list.html`` template Syntax:: {% render_comment_list for [object] %} {% render_comment_list for [app].[model] [object_id] %} Example usage:: {% render_comment_list for event %} """ return RenderCommentListNode.handle_token(parser, token) #@register.tag def get_comment_form(parser, token): """ Get a (new) form object to post a new comment. Syntax:: {% get_comment_form for [object] as [varname] %} {% get_comment_form for [app].[model] [object_id] as [varname] %} """ return CommentFormNode.handle_token(parser, token) #@register.tag def render_comment_form(parser, token): """ Render the comment form (as returned by ``{% render_comment_form %}``) through the ``comments/form.html`` template. Syntax:: {% render_comment_form for [object] %} {% render_comment_form for [app].[model] [object_id] %} """ return RenderCommentFormNode.handle_token(parser, token) #@register.simple_tag def comment_form_target(): """ Get the target URL for the comment form. Example:: <form action="{% comment_form_target %}" method="post"> """ return comments.get_form_target() #@register.simple_tag def get_comment_permalink(comment, anchor_pattern=None): """ Get the permalink for a comment, optionally specifying the format of the named anchor to be appended to the end of the URL. Example:: {{ get_comment_permalink comment "#c%(id)s-by-%(user_name)s" }} """ if anchor_pattern: return comment.get_absolute_url(anchor_pattern) return comment.get_absolute_url() register.tag(get_comment_count) register.tag(get_comment_list) register.tag(get_comment_form) register.tag(render_comment_form) register.simple_tag(comment_form_target) register.simple_tag(get_comment_permalink) register.tag(render_comment_list)
what is 'comments' mean in this code
{% load comments %} where defined 'comments' ,a viewer? or a template?? thanks
[ "It is a template tag library. For example:\n{% load cache %}\n\nloads the caching tags.\nCustom tags can be defined and placed within your project structure as defined here.\n", "It's a template tag that loads a specific set of other template tags (comments application specific tags in this case) making them available in the rest of the template file to use.\nSo, for example, you will be able to use other comments-app specific tags like:\n{% get_comment_count for entry as comment_count %}\n\nYou can obtain more info here: http://docs.djangoproject.com/en/dev/ref/contrib/comments/#comment-template-tags\nand here: http://docs.djangoproject.com/en/dev/ref/templates/builtins/#load\nTo understand how to make a set of custom template tags yourself and how to make them available to use via the same method, look here: http://docs.djangoproject.com/en/dev/howto/custom-template-tags/#howto-custom-template-tags\n", "As other answers have pointed out, comments is a templatetag.\nTo answer your question: \n\nwhere defined 'comments'\n\nin django/contrib/comments/templatetags/comments.py\nHere you go: http://github.com/django/django/blob/master/django/contrib/comments/templatetags/comments.py\nSource:\nfrom django import template\nfrom django.template.loader import render_to_string\nfrom django.conf import settings\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.contrib import comments\nfrom django.utils.encoding import smart_unicode\n\nregister = template.Library()\n\nclass BaseCommentNode(template.Node):\n \"\"\"\n Base helper class (abstract) for handling the get_comment_* template tags.\n Looks a bit strange, but the subclasses below should make this a bit more\n obvious.\n \"\"\"\n\n #@classmethod\n def handle_token(cls, parser, token):\n \"\"\"Class method to parse get_comment_list/count/form and return a Node.\"\"\"\n tokens = token.contents.split()\n if tokens[1] != 'for':\n raise template.TemplateSyntaxError(\"Second argument in %r tag must be 'for'\" % tokens[0])\n\n # {% get_whatever for obj as varname %}\n if len(tokens) == 5:\n if tokens[3] != 'as':\n raise template.TemplateSyntaxError(\"Third argument in %r must be 'as'\" % tokens[0])\n return cls(\n object_expr = parser.compile_filter(tokens[2]),\n as_varname = tokens[4],\n )\n\n # {% get_whatever for app.model pk as varname %}\n elif len(tokens) == 6:\n if tokens[4] != 'as':\n raise template.TemplateSyntaxError(\"Fourth argument in %r must be 'as'\" % tokens[0])\n return cls(\n ctype = BaseCommentNode.lookup_content_type(tokens[2], tokens[0]),\n object_pk_expr = parser.compile_filter(tokens[3]),\n as_varname = tokens[5]\n )\n\n else:\n raise template.TemplateSyntaxError(\"%r tag requires 4 or 5 arguments\" % tokens[0])\n\n handle_token = classmethod(handle_token)\n\n #@staticmethod\n def lookup_content_type(token, tagname):\n try:\n app, model = token.split('.')\n return ContentType.objects.get(app_label=app, model=model)\n except ValueError:\n raise template.TemplateSyntaxError(\"Third argument in %r must be in the format 'app.model'\" % tagname)\n except ContentType.DoesNotExist:\n raise template.TemplateSyntaxError(\"%r tag has non-existant content-type: '%s.%s'\" % (tagname, app, model))\n lookup_content_type = staticmethod(lookup_content_type)\n\n def __init__(self, ctype=None, object_pk_expr=None, object_expr=None, as_varname=None, comment=None):\n if ctype is None and object_expr is None:\n raise template.TemplateSyntaxError(\"Comment nodes must be given either a literal object or a ctype and object pk.\")\n self.comment_model = comments.get_model()\n self.as_varname = as_varname\n self.ctype = ctype\n self.object_pk_expr = object_pk_expr\n self.object_expr = object_expr\n self.comment = comment\n\n def render(self, context):\n qs = self.get_query_set(context)\n context[self.as_varname] = self.get_context_value_from_queryset(context, qs)\n return ''\n\n def get_query_set(self, context):\n ctype, object_pk = self.get_target_ctype_pk(context)\n if not object_pk:\n return self.comment_model.objects.none()\n\n qs = self.comment_model.objects.filter(\n content_type = ctype,\n object_pk = smart_unicode(object_pk),\n site__pk = settings.SITE_ID,\n )\n\n # The is_public and is_removed fields are implementation details of the\n # built-in comment model's spam filtering system, so they might not\n # be present on a custom comment model subclass. If they exist, we\n # should filter on them.\n field_names = [f.name for f in self.comment_model._meta.fields]\n if 'is_public' in field_names:\n qs = qs.filter(is_public=True)\n if getattr(settings, 'COMMENTS_HIDE_REMOVED', True) and 'is_removed' in field_names:\n qs = qs.filter(is_removed=False)\n\n return qs\n\n def get_target_ctype_pk(self, context):\n if self.object_expr:\n try:\n obj = self.object_expr.resolve(context)\n except template.VariableDoesNotExist:\n return None, None\n return ContentType.objects.get_for_model(obj), obj.pk\n else:\n return self.ctype, self.object_pk_expr.resolve(context, ignore_failures=True)\n\n def get_context_value_from_queryset(self, context, qs):\n \"\"\"Subclasses should override this.\"\"\"\n raise NotImplementedError\n\nclass CommentListNode(BaseCommentNode):\n \"\"\"Insert a list of comments into the context.\"\"\"\n def get_context_value_from_queryset(self, context, qs):\n return list(qs)\n\nclass CommentCountNode(BaseCommentNode):\n \"\"\"Insert a count of comments into the context.\"\"\"\n def get_context_value_from_queryset(self, context, qs):\n return qs.count()\n\nclass CommentFormNode(BaseCommentNode):\n \"\"\"Insert a form for the comment model into the context.\"\"\"\n\n def get_form(self, context):\n ctype, object_pk = self.get_target_ctype_pk(context)\n if object_pk:\n return comments.get_form()(ctype.get_object_for_this_type(pk=object_pk))\n else:\n return None\n\n def render(self, context):\n context[self.as_varname] = self.get_form(context)\n return ''\n\nclass RenderCommentFormNode(CommentFormNode):\n \"\"\"Render the comment form directly\"\"\"\n\n #@classmethod\n def handle_token(cls, parser, token):\n \"\"\"Class method to parse render_comment_form and return a Node.\"\"\"\n tokens = token.contents.split()\n if tokens[1] != 'for':\n raise template.TemplateSyntaxError(\"Second argument in %r tag must be 'for'\" % tokens[0])\n\n # {% render_comment_form for obj %}\n if len(tokens) == 3:\n return cls(object_expr=parser.compile_filter(tokens[2]))\n\n # {% render_comment_form for app.models pk %}\n elif len(tokens) == 4:\n return cls(\n ctype = BaseCommentNode.lookup_content_type(tokens[2], tokens[0]),\n object_pk_expr = parser.compile_filter(tokens[3])\n )\n handle_token = classmethod(handle_token)\n\n def render(self, context):\n ctype, object_pk = self.get_target_ctype_pk(context)\n if object_pk:\n template_search_list = [\n \"comments/%s/%s/form.html\" % (ctype.app_label, ctype.model),\n \"comments/%s/form.html\" % ctype.app_label,\n \"comments/form.html\"\n ]\n context.push()\n formstr = render_to_string(template_search_list, {\"form\" : self.get_form(context)}, context)\n context.pop()\n return formstr\n else:\n return ''\n\nclass RenderCommentListNode(CommentListNode):\n \"\"\"Render the comment list directly\"\"\"\n\n #@classmethod\n def handle_token(cls, parser, token):\n \"\"\"Class method to parse render_comment_list and return a Node.\"\"\"\n tokens = token.contents.split()\n if tokens[1] != 'for':\n raise template.TemplateSyntaxError(\"Second argument in %r tag must be 'for'\" % tokens[0])\n\n # {% render_comment_list for obj %}\n if len(tokens) == 3:\n return cls(object_expr=parser.compile_filter(tokens[2]))\n\n # {% render_comment_list for app.models pk %}\n elif len(tokens) == 4:\n return cls(\n ctype = BaseCommentNode.lookup_content_type(tokens[2], tokens[0]),\n object_pk_expr = parser.compile_filter(tokens[3])\n )\n handle_token = classmethod(handle_token)\n\n def render(self, context):\n ctype, object_pk = self.get_target_ctype_pk(context)\n if object_pk:\n template_search_list = [\n \"comments/%s/%s/list.html\" % (ctype.app_label, ctype.model),\n \"comments/%s/list.html\" % ctype.app_label,\n \"comments/list.html\"\n ]\n qs = self.get_query_set(context)\n context.push()\n liststr = render_to_string(template_search_list, {\n \"comment_list\" : self.get_context_value_from_queryset(context, qs)\n }, context)\n context.pop()\n return liststr\n else:\n return ''\n\n# We could just register each classmethod directly, but then we'd lose out on\n# the automagic docstrings-into-admin-docs tricks. So each node gets a cute\n# wrapper function that just exists to hold the docstring.\n\n#@register.tag\ndef get_comment_count(parser, token):\n \"\"\"\n Gets the comment count for the given params and populates the template\n context with a variable containing that value, whose name is defined by the\n 'as' clause.\n\n Syntax::\n\n {% get_comment_count for [object] as [varname] %}\n {% get_comment_count for [app].[model] [object_id] as [varname] %}\n\n Example usage::\n\n {% get_comment_count for event as comment_count %}\n {% get_comment_count for calendar.event event.id as comment_count %}\n {% get_comment_count for calendar.event 17 as comment_count %}\n\n \"\"\"\n return CommentCountNode.handle_token(parser, token)\n\n#@register.tag\ndef get_comment_list(parser, token):\n \"\"\"\n Gets the list of comments for the given params and populates the template\n context with a variable containing that value, whose name is defined by the\n 'as' clause.\n\n Syntax::\n\n {% get_comment_list for [object] as [varname] %}\n {% get_comment_list for [app].[model] [object_id] as [varname] %}\n\n Example usage::\n\n {% get_comment_list for event as comment_list %}\n {% for comment in comment_list %}\n ...\n {% endfor %}\n\n \"\"\"\n return CommentListNode.handle_token(parser, token)\n\n#@register.tag\ndef render_comment_list(parser, token):\n \"\"\"\n Render the comment list (as returned by ``{% get_comment_list %}``)\n through the ``comments/list.html`` template\n\n Syntax::\n\n {% render_comment_list for [object] %}\n {% render_comment_list for [app].[model] [object_id] %}\n\n Example usage::\n\n {% render_comment_list for event %}\n\n \"\"\"\n return RenderCommentListNode.handle_token(parser, token)\n\n#@register.tag\ndef get_comment_form(parser, token):\n \"\"\"\n Get a (new) form object to post a new comment.\n\n Syntax::\n\n {% get_comment_form for [object] as [varname] %}\n {% get_comment_form for [app].[model] [object_id] as [varname] %}\n \"\"\"\n return CommentFormNode.handle_token(parser, token)\n\n#@register.tag\ndef render_comment_form(parser, token):\n \"\"\"\n Render the comment form (as returned by ``{% render_comment_form %}``) through\n the ``comments/form.html`` template.\n\n Syntax::\n\n {% render_comment_form for [object] %}\n {% render_comment_form for [app].[model] [object_id] %}\n \"\"\"\n return RenderCommentFormNode.handle_token(parser, token)\n\n#@register.simple_tag\ndef comment_form_target():\n \"\"\"\n Get the target URL for the comment form.\n\n Example::\n\n <form action=\"{% comment_form_target %}\" method=\"post\">\n \"\"\"\n return comments.get_form_target()\n\n#@register.simple_tag\ndef get_comment_permalink(comment, anchor_pattern=None):\n \"\"\"\n Get the permalink for a comment, optionally specifying the format of the\n named anchor to be appended to the end of the URL.\n\n Example::\n {{ get_comment_permalink comment \"#c%(id)s-by-%(user_name)s\" }}\n \"\"\"\n\n if anchor_pattern:\n return comment.get_absolute_url(anchor_pattern)\n return comment.get_absolute_url()\n\nregister.tag(get_comment_count)\nregister.tag(get_comment_list)\nregister.tag(get_comment_form)\nregister.tag(render_comment_form)\nregister.simple_tag(comment_form_target)\nregister.simple_tag(get_comment_permalink)\nregister.tag(render_comment_list)\n\n" ]
[ 2, 1, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002181460_django_python.txt
Q: QT4, GTK+, wxWidgets or IronPython for a native Windows app using Python I need to build a native windows app using Python (and py2exe, I guess). Feature requirements are: Taskbar icon Alert notifications (next to Taskbar Icon) Chromeless window (ideally a pretty, rounded, coloured one). Webkit to render some of the Chromeless window So far I've identified the following possible toolkits: pyGTK pyQT4 wxWidgets ironpython I haven't used any of these before and so I look to you for advice on the suitability or pitfalls of choosing one of the above. Many thanks for your thoughts! rich PS: I've considered and discounted Titanium and Air; Air is out because of the runtime, Titanium is out because of the compile / deploy model. EDIT: Here are promising (read: in development) LGPL Python bindings for QT (Why pyQT couldn't have just done LGPL I don't know): http://www.pyside.org/ A: Qt has a clean and consistent API, complete widgets set, excellent documentation and tools and Webkit integration is built in. In my opinion none of the other libraries you cite offer all of these, so my advice would be to use PyQt4 if you can live with its licensing scheme. A: I've been using wxPython for sometime for deploying commercial grade apps. You may have issues with qt's licensing. I like wx because it's still very portable, and less dated than GTK. Which imo leaves only wx, but it's still an opinion call. Good luck. wx can do all the things you've listed at the top.
QT4, GTK+, wxWidgets or IronPython for a native Windows app using Python
I need to build a native windows app using Python (and py2exe, I guess). Feature requirements are: Taskbar icon Alert notifications (next to Taskbar Icon) Chromeless window (ideally a pretty, rounded, coloured one). Webkit to render some of the Chromeless window So far I've identified the following possible toolkits: pyGTK pyQT4 wxWidgets ironpython I haven't used any of these before and so I look to you for advice on the suitability or pitfalls of choosing one of the above. Many thanks for your thoughts! rich PS: I've considered and discounted Titanium and Air; Air is out because of the runtime, Titanium is out because of the compile / deploy model. EDIT: Here are promising (read: in development) LGPL Python bindings for QT (Why pyQT couldn't have just done LGPL I don't know): http://www.pyside.org/
[ "Qt has a clean and consistent API, complete widgets set, excellent documentation and tools and Webkit integration is built in.\nIn my opinion none of the other libraries you cite offer all of these, so my advice would be to use PyQt4 if you can live with its licensing scheme.\n", "I've been using wxPython for sometime for deploying commercial grade apps.\nYou may have issues with qt's licensing.\nI like wx because it's still very portable, and less dated than GTK. Which imo leaves only wx, but it's still an opinion call. Good luck.\nwx can do all the things you've listed at the top.\n" ]
[ 4, 1 ]
[]
[]
[ "ironpython", "pygtk", "pyqt4", "python", "wxwidgets" ]
stackoverflow_0002181948_ironpython_pygtk_pyqt4_python_wxwidgets.txt
Q: Determining the frequency of Twitter tweets on a certain topic Is there a way for me to determine the total number of Twitter messages on a given trend topic (e.g. frequency of Twitter messages with subject matter on Haiti/#Haiti) at a given instance in time using the Twitter API? I'm writing a script in Python that will monitor Twitter traffic over a long spell of time and I was wondering how I could go about doing this. A: Yes. Use the Twitter Streaming API to get a representative sample. A: You might take a look at this site (see below) Drew has several sources of information and was to look at the data. Network of People who Twitter about R http://www.drewconway.com/zia/?p=1471
Determining the frequency of Twitter tweets on a certain topic
Is there a way for me to determine the total number of Twitter messages on a given trend topic (e.g. frequency of Twitter messages with subject matter on Haiti/#Haiti) at a given instance in time using the Twitter API? I'm writing a script in Python that will monitor Twitter traffic over a long spell of time and I was wondering how I could go about doing this.
[ "Yes. Use the Twitter Streaming API to get a representative sample.\n", "You might take a look at this site (see below) Drew has several sources of information and was to look at the data. \nNetwork of People who Twitter about R \nhttp://www.drewconway.com/zia/?p=1471\n" ]
[ 1, 1 ]
[]
[]
[ "python", "twitter" ]
stackoverflow_0002181230_python_twitter.txt
Q: python sqlite check points? I working with python sqlite3 , I found we have commit and rollback option. Does sqlite3 allows something like check point ? For example: Initial state is empty. ... insert something ... commit .... ..... insert something commit. update something Found some problem.Now I want to roll back to initial state. Something like multiple undo? A: No, I don't know of any SQL database engine supporting "multiple undo" -- if one exists at all, Sqlite is definitely not it! For nested transactions (a less general concept), consider (per Sqlite's docs!) the SAVEPOINT feature -- it may be sufficient to do most of what you require.
python sqlite check points?
I working with python sqlite3 , I found we have commit and rollback option. Does sqlite3 allows something like check point ? For example: Initial state is empty. ... insert something ... commit .... ..... insert something commit. update something Found some problem.Now I want to roll back to initial state. Something like multiple undo?
[ "No, I don't know of any SQL database engine supporting \"multiple undo\" -- if one exists at all, Sqlite is definitely not it! For nested transactions (a less general concept), consider (per Sqlite's docs!) the SAVEPOINT feature -- it may be sufficient to do most of what you require.\n" ]
[ 2 ]
[]
[]
[ "python", "rollback", "sqlite" ]
stackoverflow_0002182062_python_rollback_sqlite.txt
Q: Django templates condition check All, Can t we do the following in templates {% if subject.id == selected_id %} and also cannot we assign variable like {{selected="selected"}} Thank........ A: This comparison will work in Django 1.2. For 1.1 you have to use ifequal: {% ifequal subject.id selected_id %} For variable assignment you can use with. {% with selected as 'selected' %} {% endwith %} Don't hesitate to read the documentation, it doesn't hurt. A: Not as shown. Use the ifequal and with template tags instead.
Django templates condition check
All, Can t we do the following in templates {% if subject.id == selected_id %} and also cannot we assign variable like {{selected="selected"}} Thank........
[ "This comparison will work in Django 1.2. For 1.1 you have to use ifequal:\n{% ifequal subject.id selected_id %}\n\nFor variable assignment you can use with.\n{% with selected as 'selected' %}\n\n{% endwith %}\n\nDon't hesitate to read the documentation, it doesn't hurt.\n", "Not as shown. Use the ifequal and with template tags instead.\n" ]
[ 4, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002182512_django_python.txt
Q: python style question around reading small files What is the most pythonic way to read in a named file, strip lines that are either empty, contain only spaces, or have # as a first character, and then process remaining lines? Assume it all fits easily in memory. Note: it's not tough to do this -- what I'm asking is for the most pythonic way. I've been writing a lot of Ruby and Java and have lost my feel. Here's a strawman: file_lines = [line.strip() for line in open(config_file, 'r').readlines() if len(line.strip()) > 0] for line in file_lines: if line[0] == '#': continue # Do whatever with line here. I'm interested in concision, but not at the cost of becoming hard to read. A: Generators are perfect for tasks like this. They are readable, maintain perfect separation of concerns, and efficient in memory-use and time. def RemoveComments(lines): for line in lines: if not line.strip().startswith('#'): yield line def RemoveBlankLines(lines): for line in lines: if line.strip(): yield line Now applying these to your file: filehandle = open('myfile', 'r') for line in RemoveComments(RemoveBlankLines(filehandle)): Process(line) In this case, it's pretty clear that the two generators can be merged into a single one, but I left them separate to demonstrate their composability. A: lines = [r for r in open(thefile) if not r.isspace() and r[0] != '#'] The .isspace() method of strings is by far the best way to test if a string is entirely whitespace -- no need for contortions such as len(r.strip()) == 0 (ech;-). A: for line in open("file"): sline=line.strip() if sline and not sline[0]=="#" : print line.strip() output $ cat file one # # two three $ ./python.py one two three A: I would use this: processed = [process(line.strip()) for line in open(config_file, 'r') if line.strip() and not line.strip().startswith('#')] The only ugliness I see here is all the repeated stripping. Getting rid of it complicates the function a bit: processed = [process(line) for line in (line.strip() for line in open(config_file, 'r')) if line and not line.startswith('#')] A: This matches the description, ie strip lines that are either empty, contain only spaces, or have # as a first character, and then process remaining lines So lines that start or end in spaces are passed through unfettered. with open("config_file","r") as fp: data = (line for line in fp if line.strip() and not line.startswith("#")) for item in data: print repr(item) A: I like Paul Hankin's thinking, but I'd do it differently: from itertools import ifilter, ifilterfalse, imap with open(r'c:\temp\testfile.txt', 'rb') as f: s1 = ifilterfalse(str.isspace, f) s2 = ifilter(lambda x: not x.startswith('#'), s1) s3 = imap(str.rstrip, s2) print "\n".join(s3) I'd probably only do it this way instead of using some of the more obvious approaches suggested here if I were concerned about memory usage. And I might define an iscomment function to eliminate the lambda. A: The file is small, so performance is not really an issue. I will go for clarity than conciseness: fp = open('file.txt') for line in fp: line = line.strip() if line and not line.startswith('#'): # process fp.close() If you want, you can wrap this in a function. A: Using slightly newer idioms (or with Python 2.5 from __future__ import with) you could do this, which has the advantage of cleaning up safely yet is quite concise. with file('file.txt') as fp: for line in fp: line = line.strip() if not line or line[0] == '#': continue # rest of processing here Note that stripping the line first means the check for "#" will actually reject lines with that as the first non-blank, not merely "as first character". Easy enough to modify if you're strict about that.
python style question around reading small files
What is the most pythonic way to read in a named file, strip lines that are either empty, contain only spaces, or have # as a first character, and then process remaining lines? Assume it all fits easily in memory. Note: it's not tough to do this -- what I'm asking is for the most pythonic way. I've been writing a lot of Ruby and Java and have lost my feel. Here's a strawman: file_lines = [line.strip() for line in open(config_file, 'r').readlines() if len(line.strip()) > 0] for line in file_lines: if line[0] == '#': continue # Do whatever with line here. I'm interested in concision, but not at the cost of becoming hard to read.
[ "Generators are perfect for tasks like this. They are readable, maintain perfect separation of concerns, and efficient in memory-use and time.\ndef RemoveComments(lines):\n for line in lines:\n if not line.strip().startswith('#'):\n yield line\n\ndef RemoveBlankLines(lines):\n for line in lines:\n if line.strip():\n yield line\n\nNow applying these to your file:\nfilehandle = open('myfile', 'r')\nfor line in RemoveComments(RemoveBlankLines(filehandle)):\n Process(line)\n\nIn this case, it's pretty clear that the two generators can be merged into a single one, but I left them separate to demonstrate their composability.\n", "lines = [r for r in open(thefile) if not r.isspace() and r[0] != '#']\n\nThe .isspace() method of strings is by far the best way to test if a string is entirely whitespace -- no need for contortions such as len(r.strip()) == 0 (ech;-).\n", "for line in open(\"file\"):\n sline=line.strip()\n if sline and not sline[0]==\"#\" :\n print line.strip()\n\noutput\n$ cat file\none\n#\n #\n\ntwo\n\nthree\n$ ./python.py\none\ntwo\nthree\n\n", "I would use this:\nprocessed = [process(line.strip())\n for line in open(config_file, 'r')\n if line.strip() and not line.strip().startswith('#')]\n\nThe only ugliness I see here is all the repeated stripping. Getting rid of it complicates the function a bit:\nprocessed = [process(line)\n for line in (line.strip() for line in open(config_file, 'r'))\n if line and not line.startswith('#')]\n\n", "This matches the description, ie \n\nstrip lines that are either empty,\n contain only spaces, or have # as a\n first character, and then process\n remaining lines\n\nSo lines that start or end in spaces are passed through unfettered.\nwith open(\"config_file\",\"r\") as fp:\n data = (line for line in fp if line.strip() and not line.startswith(\"#\"))\n for item in data:\n print repr(item)\n\n", "I like Paul Hankin's thinking, but I'd do it differently:\nfrom itertools import ifilter, ifilterfalse, imap\n\nwith open(r'c:\\temp\\testfile.txt', 'rb') as f:\n s1 = ifilterfalse(str.isspace, f)\n s2 = ifilter(lambda x: not x.startswith('#'), s1)\n s3 = imap(str.rstrip, s2)\n print \"\\n\".join(s3)\n\nI'd probably only do it this way instead of using some of the more obvious approaches suggested here if I were concerned about memory usage. And I might define an iscomment function to eliminate the lambda.\n", "The file is small, so performance is not really an issue. I will go for clarity than conciseness:\nfp = open('file.txt')\nfor line in fp:\n line = line.strip()\n if line and not line.startswith('#'):\n # process\nfp.close()\n\nIf you want, you can wrap this in a function.\n", "Using slightly newer idioms (or with Python 2.5 from __future__ import with) you could do this, which has the advantage of cleaning up safely yet is quite concise.\nwith file('file.txt') as fp:\n for line in fp:\n line = line.strip()\n if not line or line[0] == '#':\n continue\n\n # rest of processing here\n\nNote that stripping the line first means the check for \"#\" will actually reject lines with that as the first non-blank, not merely \"as first character\". Easy enough to modify if you're strict about that.\n" ]
[ 5, 3, 2, 1, 1, 1, 0, 0 ]
[]
[]
[ "coding_style", "idioms", "python" ]
stackoverflow_0002182082_coding_style_idioms_python.txt
Q: Python: How do I access an decorated class's instance from inside a class decorator? Here's an example of what I mean: class MyDecorator(object): def __call__(self, func): # At which point would I be able to access the decorated method's parent class's instance? # In the below example, I would want to access from here: myinstance def wrapper(*args, **kwargs): return func(*args, **kwargs) return wrapper class SomeClass(object): ##self.name = 'John' #error here name="John" @MyDecorator() def nameprinter(self): print(self.name) myinstance = SomeClass() myinstance.nameprinter() Do I need to decorate the actual class? A: class MyDecorator(object): def __call__(self, func): def wrapper(that, *args, **kwargs): ## you can access the "self" of func here through the "that" parameter ## and hence do whatever you want return func(that, *args, **kwargs) return wrapper A: Please notice in this context that the use of "self" is just a convention, a method just uses the first argument as a reference to the instance object: class Example: def __init__(foo, a): foo.a = a def method(bar, b): print bar.a, b e = Example('hello') e.method('world') A: The self argument is passed as the first argument. Also your MyDecorator is a class emulating a function. Easier to make it an actual function. def MyDecorator(method): def wrapper(self, *args, **kwargs): print 'Self is', self return method(self, *args, **kwargs) return wrapper class SomeClass(object): @MyDecorator def f(self): return 42 print SomeClass().f()
Python: How do I access an decorated class's instance from inside a class decorator?
Here's an example of what I mean: class MyDecorator(object): def __call__(self, func): # At which point would I be able to access the decorated method's parent class's instance? # In the below example, I would want to access from here: myinstance def wrapper(*args, **kwargs): return func(*args, **kwargs) return wrapper class SomeClass(object): ##self.name = 'John' #error here name="John" @MyDecorator() def nameprinter(self): print(self.name) myinstance = SomeClass() myinstance.nameprinter() Do I need to decorate the actual class?
[ "class MyDecorator(object):\n def __call__(self, func):\n def wrapper(that, *args, **kwargs):\n ## you can access the \"self\" of func here through the \"that\" parameter\n ## and hence do whatever you want \n return func(that, *args, **kwargs)\n return wrapper\n\n", "Please notice in this context that the use of \"self\" is just a convention, a method just uses the first argument as a reference to the instance object:\nclass Example:\n def __init__(foo, a):\n foo.a = a\n def method(bar, b):\n print bar.a, b\n\ne = Example('hello')\ne.method('world')\n\n", "The self argument is passed as the first argument. Also your MyDecorator is a class emulating a function. Easier to make it an actual function.\ndef MyDecorator(method):\n def wrapper(self, *args, **kwargs):\n print 'Self is', self\n return method(self, *args, **kwargs)\n return wrapper\n\nclass SomeClass(object):\n @MyDecorator\n def f(self):\n return 42\n\nprint SomeClass().f()\n\n" ]
[ 8, 2, 1 ]
[]
[]
[ "decorator", "python" ]
stackoverflow_0002181275_decorator_python.txt
Q: python sqlite 3 : roll back to save point fails def rollback_savepoint(self): try: self.db.execute("rollback to savepoint pt;") except: print "roll back to save point failed" else: print "Roll back to save point. Done" In above code snippet , It says "roll back to save point failed". What went wrong? EDIT: I changed the code as shown below and getting error messages self.db.execute("savepoint pt;") print "Save point created" self.cursor.execute("insert into STK values(33)") self.db.execute("rollback to savepoint pt;") error Save point created Traceback (most recent call last): File "open_db.py", line 77, in <module> obj1.save_point() File "open_db.py", line 63, in save_point self.db.execute("rollback to savepoint pt;") sqlite3.OperationalError: no such savepoint: pt A: Don't ever catch exceptions you aren't handling. Let it raise, so you can have useful error messages and tracebacks. Example: >>> c.execute('rollback to savepoint pt;') Traceback (most recent call last): File "<stdin>", line 1, in <module> sqlite3.OperationalError: no such savepoint: pt From the traceback I can know the error is that there's no pt savepoint. I can't know what's wrong with yours because you're hiding the very information that can help you most. Catching all errors and printing some "Failed" message is dumb - the traceback is much more useful and explains the problem better. EDIT: Your code wasn't exactly a easy-to-run testcase, but by reading it I was able to write some code myself to reproduce the issue. I can't explain exactly what is going on yet, but I found a way to make it work - related to how sqlite3 module deals with transactions. Here's my full, runnable example: import sqlite3 from tempfile import NamedTemporaryFile as NF import os f = NF(suffix='.db', delete=False).name db = sqlite3.connect(f) try: db.execute('CREATE TABLE foo (id INTEGER PRIMARY KEY, data VARCHAR)') db.isolation_level = None db.execute('INSERT INTO foo (data) values (?)', ('hello',)) db.execute('INSERT INTO foo (data) values (?)', ('world',)) db.execute("savepoint pt;") db.execute('INSERT INTO foo (data) values (?)', ('bah',)) db.execute('INSERT INTO foo (data) values (?)', ('goodbye world',)) db.execute("rollback to savepoint pt;") db.execute('INSERT INTO foo (data) values (?)', ('peace',)) assert list(db.execute('select * from foo')) == [(1, 'hello'), (2, 'world'), (3, 'peace')] finally: db.close() os.remove(f) The line that makes it work is db.isolation_level = None. If you comment it out, it breaks just like your error. I've tried using all the documented values “DEFERRED”, “IMMEDIATE” and “EXCLUSIVE”, all ended in error.
python sqlite 3 : roll back to save point fails
def rollback_savepoint(self): try: self.db.execute("rollback to savepoint pt;") except: print "roll back to save point failed" else: print "Roll back to save point. Done" In above code snippet , It says "roll back to save point failed". What went wrong? EDIT: I changed the code as shown below and getting error messages self.db.execute("savepoint pt;") print "Save point created" self.cursor.execute("insert into STK values(33)") self.db.execute("rollback to savepoint pt;") error Save point created Traceback (most recent call last): File "open_db.py", line 77, in <module> obj1.save_point() File "open_db.py", line 63, in save_point self.db.execute("rollback to savepoint pt;") sqlite3.OperationalError: no such savepoint: pt
[ "Don't ever catch exceptions you aren't handling. Let it raise, so you can have useful error messages and tracebacks.\nExample:\n>>> c.execute('rollback to savepoint pt;')\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nsqlite3.OperationalError: no such savepoint: pt\n\nFrom the traceback I can know the error is that there's no pt savepoint. I can't know what's wrong with yours because you're hiding the very information that can help you most. Catching all errors and printing some \"Failed\" message is dumb - the traceback is much more useful and explains the problem better.\n\nEDIT:\nYour code wasn't exactly a easy-to-run testcase, but by reading it I was able to write some code myself to reproduce the issue. I can't explain exactly what is going on yet, but I found a way to make it work - related to how sqlite3 module deals with transactions.\nHere's my full, runnable example:\nimport sqlite3\nfrom tempfile import NamedTemporaryFile as NF\nimport os\n\nf = NF(suffix='.db', delete=False).name\n\ndb = sqlite3.connect(f)\n\ntry:\n db.execute('CREATE TABLE foo (id INTEGER PRIMARY KEY, data VARCHAR)')\n db.isolation_level = None\n\n db.execute('INSERT INTO foo (data) values (?)', ('hello',))\n db.execute('INSERT INTO foo (data) values (?)', ('world',))\n\n db.execute(\"savepoint pt;\")\n db.execute('INSERT INTO foo (data) values (?)', ('bah',))\n db.execute('INSERT INTO foo (data) values (?)', ('goodbye world',))\n db.execute(\"rollback to savepoint pt;\")\n\n db.execute('INSERT INTO foo (data) values (?)', ('peace',))\n\n assert list(db.execute('select * from foo')) == [(1, 'hello'),\n (2, 'world'),\n (3, 'peace')]\nfinally:\n db.close()\n os.remove(f)\n\nThe line that makes it work is db.isolation_level = None. If you comment it out, it breaks just like your error. I've tried using all the documented values “DEFERRED”, “IMMEDIATE” and “EXCLUSIVE”, all ended in error.\n" ]
[ 4 ]
[]
[]
[ "python", "sqlite" ]
stackoverflow_0002182591_python_sqlite.txt
Q: Django template-printing variables All, In Template condition check,whats wrong with the following code, selected_id and selected_sub are equal to 5 but still ifequal loop is not working.. <tr><td><p>Subjects:</td> <td> <select id="subjects" name="subjects" multiple="multiple"> {% for subject in subjects %} <option value="{{subject.id}}" {% for selected_id in selected_sub %}{% ifequal subject.id selected_id %} {{ selected }} {% endifequal %} {% endfor %} >{{subject.subject}}</option> {% endfor %} </select> </p></td></tr> Thanks.......... A: Ok, sorry. What is the output you get? selected should have the value 'selected="selected"'. Change to {% with selected as 'selected="selected"' %} and try again. A: If, as you say, selected_id and selected_sub are equal to 5 then for selected_id in selected_sub will not work, since 5 is not iterable.
Django template-printing variables
All, In Template condition check,whats wrong with the following code, selected_id and selected_sub are equal to 5 but still ifequal loop is not working.. <tr><td><p>Subjects:</td> <td> <select id="subjects" name="subjects" multiple="multiple"> {% for subject in subjects %} <option value="{{subject.id}}" {% for selected_id in selected_sub %}{% ifequal subject.id selected_id %} {{ selected }} {% endifequal %} {% endfor %} >{{subject.subject}}</option> {% endfor %} </select> </p></td></tr> Thanks..........
[ "Ok, sorry. What is the output you get?\nselected should have the value 'selected=\"selected\"'.\nChange to {% with selected as 'selected=\"selected\"' %} and try again.\n", "If, as you say, selected_id and selected_sub are equal to 5 then\nfor selected_id in selected_sub\n\nwill not work, since 5 is not iterable.\n" ]
[ 3, 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002182977_django_python.txt
Q: How can I pack several decorators into one? I have several decorators on each function, is there a way to pack them in to one instead? @fun1 @fun2 @fun3 def do_stuf(): pass change to: @all_funs #runs fun1 fun2 and fun3, how should all_funs look like? def do_stuf(): pass A: A decorator is in principle only syntactic sugar for this: def do_stuf(): pass do_stuf = fun1(do_stuf) So in your all_fun, all you should need to do is to wrap the function in the same kind of chain of decorators: def all_funs(funky): return fun1(fun2(fun3(fun4(funky))) Things get a little bit (but only a litte) more complex if you have parameters to the decorators. A: It's also possible to write a generic decorator that supports decorator chaining: def fun1(f): print "fun1" return f def fun2(f): print "fun2" return f def fun3(f): print "fun3" return f def chained(*dec_funs): def _inner_chain(f): for dec in reversed(dec_funs): f = dec(f) return f return _inner_chain @fun1 @fun2 @fun3 def do_stuff(): pass @chained(fun1, fun2, fun3) def do_stuff2(): pass all_funs = chained(fun1, fun2, fun3) @all_funs def do_stuff3(): pass A: def all_funs(f): return fun1(fun2(fun3(f)))
How can I pack several decorators into one?
I have several decorators on each function, is there a way to pack them in to one instead? @fun1 @fun2 @fun3 def do_stuf(): pass change to: @all_funs #runs fun1 fun2 and fun3, how should all_funs look like? def do_stuf(): pass
[ "A decorator is in principle only syntactic sugar for this:\ndef do_stuf():\n pass\n\ndo_stuf = fun1(do_stuf)\n\nSo in your all_fun, all you should need to do is to wrap the function in the same kind of chain of decorators:\ndef all_funs(funky):\n return fun1(fun2(fun3(fun4(funky)))\n\nThings get a little bit (but only a litte) more complex if you have parameters to the decorators.\n", "It's also possible to write a generic decorator that supports decorator chaining:\ndef fun1(f):\n print \"fun1\"\n return f\n\ndef fun2(f):\n print \"fun2\"\n return f\n\ndef fun3(f):\n print \"fun3\"\n return f\n\ndef chained(*dec_funs):\n def _inner_chain(f):\n for dec in reversed(dec_funs):\n f = dec(f)\n return f\n\n return _inner_chain\n\n@fun1\n@fun2\n@fun3\ndef do_stuff():\n pass\n\n@chained(fun1, fun2, fun3)\ndef do_stuff2():\n pass\n\nall_funs = chained(fun1, fun2, fun3)\n\n@all_funs\ndef do_stuff3():\n pass\n\n", "def all_funs(f):\n return fun1(fun2(fun3(f)))\n\n" ]
[ 10, 7, 1 ]
[]
[]
[ "decorator", "python" ]
stackoverflow_0002182858_decorator_python.txt
Q: importing a module in nested packages This is a python newbie question: I have the following directory structure: test -- test_file.py a -- b -- module.py where test, a and b are folders. Both test and a are on the same level. module.py has a class called shape, and I want to instantiate an instance of it in test_file.py. How can I do so? I have tried: from a.b import module but I got: ImportError: No module named a.b A: What you want is a relative import like: from ..a.b import module The problem with this is that it doesn't work if you are calling test_file.py as your main module. As stated here: Note that both explicit and implicit relative imports are based on the name of the current module. Since the name of the main module is always "main", modules intended for use as the main module of a Python application should always use absolute imports. So, if you want to call test_file.py as your main module, then you should consider changing the structure of your modules and using an absolute import, else just use the relative import from above. A: The directory a needs to be a package. Add an __init__.py file to make it a package, which is a step up from being a simple directory. The directory b also needs to be a subpackage of a. Add an __init__.py file. The directory test should probably also be a package. Hard to say if this is necessary or not. It's usually a good idea for every directory of Python modules to be a formal package. In order to import, the package needs to be on sys.path; this is built from the PYTHONPATH environment variable. By default the installed site-packages and the current working directory are (effectively) the only two places where a package can be found. That means that a must either be installed, or, your current working directory must also be a package one level above a. OR, you need to set your PYTHONPATH environment variable to include a. http://docs.python.org/tutorial/modules.html#the-module-search-path http://docs.python.org/using/cmdline.html#envvar-PYTHONPATH Also, http://docs.python.org/library/site.html for complete information on how sys.path is built. A: The first thing to do would be to quickly browse the official docs on this. To make a directory a package, you'll have to add a __init__.py file. This means that you'll have such a file in the a and b directories. Then you can directly do an import a.b.module But you'll have to refer to it as a.b.module which is tedious so you can use the as form of the import like so import a.b.module as mod #shorter name and refer to it as mod. Then you can instantiate things inside mod using the regular conventions like mod.shape(). There are a few other subtleties. Please go through the docs for details.
importing a module in nested packages
This is a python newbie question: I have the following directory structure: test -- test_file.py a -- b -- module.py where test, a and b are folders. Both test and a are on the same level. module.py has a class called shape, and I want to instantiate an instance of it in test_file.py. How can I do so? I have tried: from a.b import module but I got: ImportError: No module named a.b
[ "What you want is a relative import like:\nfrom ..a.b import module\nThe problem with this is that it doesn't work if you are calling test_file.py as your main module. As stated here:\n\nNote that both explicit and implicit relative imports are based on the name of the current module. Since the name of the main module is always \"main\", modules intended for use as the main module of a Python application should always use absolute imports.\n\nSo, if you want to call test_file.py as your main module, then you should consider changing the structure of your modules and using an absolute import, else just use the relative import from above.\n", "\nThe directory a needs to be a package. Add an __init__.py file to make it a package, which is a step up from being a simple directory.\nThe directory b also needs to be a subpackage of a. Add an __init__.py file.\nThe directory test should probably also be a package. Hard to say if this is necessary or not. It's usually a good idea for every directory of Python modules to be a formal package.\nIn order to import, the package needs to be on sys.path; this is built from the PYTHONPATH environment variable. By default the installed site-packages and the current working directory are (effectively) the only two places where a package can be found.\nThat means that a must either be installed, or, your current working directory must also be a package one level above a. \nOR, you need to set your PYTHONPATH environment variable to include a.\n\nhttp://docs.python.org/tutorial/modules.html#the-module-search-path\nhttp://docs.python.org/using/cmdline.html#envvar-PYTHONPATH\nAlso, http://docs.python.org/library/site.html for complete information on how sys.path is built.\n", "The first thing to do would be to quickly browse the official docs on this. \nTo make a directory a package, you'll have to add a __init__.py file. This means that you'll have such a file in the a and b directories. Then you can directly do an \nimport a.b.module\n\nBut you'll have to refer to it as a.b.module which is tedious so you can use the as form of the import like so\nimport a.b.module as mod #shorter name\n\nand refer to it as mod. \nThen you can instantiate things inside mod using the regular conventions like mod.shape(). \nThere are a few other subtleties. Please go through the docs for details. \n" ]
[ 34, 21, 14 ]
[]
[]
[ "import", "package", "python" ]
stackoverflow_0002183205_import_package_python.txt
Q: python regular expression to validate types of strings I want to do the following with python: Validate if a UTF8 string is an integer. Validate if a UTF8 string is a float. Validate if a UTF8 string is of length(1-255). Validate if a UTF8 string is a valid date. I'm totally new to python and I believe this should be done with regular expression, except maybe for the last one. Your help is appreciated! A: Regex is not a good solution here. Validate if a UTF8 string is an integer: try: int(val) is_int = True except ValueError: is_int = False Validate if a UTF8 string is a float: same as above, but with float(). Validate if a UTF8 string is of length(1-255): is_of_appropriate_length = 1 <= len(val) <= 255 Validate if a UTF8 string is a valid date: this is not trivial. If you know the right format, you can use time.strptime() like this: # Validate that the date is in the YYYY-MM-DD format. import time try: time.strptime(val, '%Y-%m-%d') is_in_valid_format= True except ValueError: is_in_valid_format = False EDIT: Another thing to note. Since you specifically mention UTF-8 strings, it would make sense to decode them into Unicode first. This would be done by: my_unicode_string = my_utf8_string.decode('utf8') It is interesting to note that when trying to convert a Unicode string to an integer using int(), for example, you are not limited to the "Western Arabic" numerals used in most of the world. int(u'١٧') and int(u'१७') will correctly decode as 17 even though they are Hindu-Arabic and Devangari numerals respectively. A: Why use regex? I'm convinced it would be slower and more cumbersome. The int() and float() method or better yet the isdigit() method work well here. a = "03523" a.isdigit() >>> True b = "963spam" b.isdigit() >>> False For question 3, do you mean "Validate if a UTF8 string is a NUMBER of length(1-255)"? Why not: def validnumber(n): try: if 255 > int(n) > 1: return True except ValueError: return False A: int() and check for exceptions float() - but what do you mean float? int() and then check using if using datetime formatting
python regular expression to validate types of strings
I want to do the following with python: Validate if a UTF8 string is an integer. Validate if a UTF8 string is a float. Validate if a UTF8 string is of length(1-255). Validate if a UTF8 string is a valid date. I'm totally new to python and I believe this should be done with regular expression, except maybe for the last one. Your help is appreciated!
[ "Regex is not a good solution here.\n\nValidate if a UTF8 string is an integer:\ntry:\n int(val)\n is_int = True\nexcept ValueError:\n is_int = False\n\nValidate if a UTF8 string is a float: same as above, but with float().\nValidate if a UTF8 string is of length(1-255):\nis_of_appropriate_length = 1 <= len(val) <= 255\n\nValidate if a UTF8 string is a valid date: this is not trivial. If you know the right format, you can use time.strptime() like this:\n# Validate that the date is in the YYYY-MM-DD format.\nimport time\ntry:\n time.strptime(val, '%Y-%m-%d')\n is_in_valid_format= True\nexcept ValueError:\n is_in_valid_format = False\n\n\nEDIT: Another thing to note. Since you specifically mention UTF-8 strings, it would make sense to decode them into Unicode first. This would be done by:\nmy_unicode_string = my_utf8_string.decode('utf8')\n\nIt is interesting to note that when trying to convert a Unicode string to an integer using int(), for example, you are not limited to the \"Western Arabic\" numerals used in most of the world. int(u'١٧') and int(u'१७') will correctly decode as 17 even though they are Hindu-Arabic and Devangari numerals respectively.\n", "Why use regex? I'm convinced it would be slower and more cumbersome. \nThe int() and float() method or better yet the isdigit() method work well here.\na = \"03523\"\na.isdigit()\n>>> True\n\nb = \"963spam\"\nb.isdigit()\n>>> False\n\nFor question 3, do you mean \"Validate if a UTF8 string is a NUMBER of length(1-255)\"?\nWhy not:\ndef validnumber(n):\n try:\n if 255 > int(n) > 1:\n return True\n except ValueError:\n return False\n\n", "\nint() and check for exceptions\nfloat() - but what do you mean float? \nint() and then check using if\nusing datetime formatting \n\n" ]
[ 6, 2, 1 ]
[]
[]
[ "python", "regex", "validation" ]
stackoverflow_0002183786_python_regex_validation.txt
Q: Basic google app engine (python) templating issue after going through some basic tutorials on the app engine and the webapp framework, I'm attempting to display documents that are related to a project construct I've created (e.g {% ifequal project.key doc.parentproject %} ) I have created several documents that do indeed have a doc.parentproject identical to keys from the project, but somehow this for loop never runs. If I substitute project.key for an actual project key value, then it returns true for those specific kets. Is there some basic templating thing I'm missing here? I haven't been able to find any answers on google or the django site (webapp uses the django templating engine). Any help would be appreciated. Sorry if this is basic newb material... {% for project in projects %} <blockquote> <div style="border:1px solid #999; padding:20px;"> <h3>{{ project.projectname|escape }} </h3> <h5>{{ project.key }}</h5> <table border="1" cellpadding="5" cellspacing="0" width="600"> <tr> <td>Doc Feed Name</td> <td>Feed author</td> <td>Spreadsheet URL</td> <td>Parent Project Key</td> <td>Created on</td> <td>&nbsp;</td> </tr> {% for doc in docs %} {% ifequal project.key doc.parentproject %} <tr> <td>doc name:{{ doc.name|escape }}</td> <td>{{ doc.author }}</td> <td>{{ doc.link }}</td> <td>{{ doc.parentproject }}</td> <td>{{ doc.date }}</td> <td>Delete</td> </tr> {% endifequal %} {% endfor %} </table> {% endfor %} A: Without seeing the controller code that provides the values to this template, it is difficult to really diagnose the problem that you are having, but I would guess that the docs variable isn't getting the list of doc entities that it clearly expects. From a good design standpoint, I would suggest giving the Project entity a property that contains a list of the docs that are associated with it. It looks like each doc is dependent on a parent project, so it would be cleaner and easier to have this code: {% for doc in project.docs %} ...do my rendering here... {% endfor %} than what you have. A: If a "doc" is an entity, and "parentproject" is a ReferenceProperty on that entity, the problem here is that you're attempting to compare a Key with an entity (ReferenceProperties automatically resolve their references). You need to use this instead: {% ifequal project.key doc.parentproject.key %}
Basic google app engine (python) templating issue
after going through some basic tutorials on the app engine and the webapp framework, I'm attempting to display documents that are related to a project construct I've created (e.g {% ifequal project.key doc.parentproject %} ) I have created several documents that do indeed have a doc.parentproject identical to keys from the project, but somehow this for loop never runs. If I substitute project.key for an actual project key value, then it returns true for those specific kets. Is there some basic templating thing I'm missing here? I haven't been able to find any answers on google or the django site (webapp uses the django templating engine). Any help would be appreciated. Sorry if this is basic newb material... {% for project in projects %} <blockquote> <div style="border:1px solid #999; padding:20px;"> <h3>{{ project.projectname|escape }} </h3> <h5>{{ project.key }}</h5> <table border="1" cellpadding="5" cellspacing="0" width="600"> <tr> <td>Doc Feed Name</td> <td>Feed author</td> <td>Spreadsheet URL</td> <td>Parent Project Key</td> <td>Created on</td> <td>&nbsp;</td> </tr> {% for doc in docs %} {% ifequal project.key doc.parentproject %} <tr> <td>doc name:{{ doc.name|escape }}</td> <td>{{ doc.author }}</td> <td>{{ doc.link }}</td> <td>{{ doc.parentproject }}</td> <td>{{ doc.date }}</td> <td>Delete</td> </tr> {% endifequal %} {% endfor %} </table> {% endfor %}
[ "Without seeing the controller code that provides the values to this template, it is difficult to really diagnose the problem that you are having, but I would guess that the docs variable isn't getting the list of doc entities that it clearly expects.\nFrom a good design standpoint, I would suggest giving the Project entity a property that contains a list of the docs that are associated with it. It looks like each doc is dependent on a parent project, so it would be cleaner and easier to have this code:\n {% for doc in project.docs %}\n ...do my rendering here...\n {% endfor %}\n\nthan what you have.\n", "If a \"doc\" is an entity, and \"parentproject\" is a ReferenceProperty on that entity, the problem here is that you're attempting to compare a Key with an entity (ReferenceProperties automatically resolve their references). You need to use this instead:\n{% ifequal project.key doc.parentproject.key %}\n\n" ]
[ 1, 0 ]
[]
[]
[ "django", "google_app_engine", "python" ]
stackoverflow_0002179481_django_google_app_engine_python.txt
Q: Populate ChoiceField from database I'd like to have several fields in my form being rendered as ChoiceFields which get their content from the database. I was thinking something like: class SeriesForm(ModelForm): series = forms.ChoiceField(choices=Series.objects.all()) class Meta: model = Series exclude = ('model', 'date_added',) But the field series is now not appearing at all in my form. What am I missing? After trying the solution (using the ModelChoiceField), I'm still seeing the same issue. Here is my code: series = forms.ModelChoiceField(queryset=Series.objects.values('series'), empty_label=" ") A: Use a ModelChoiceField instead.
Populate ChoiceField from database
I'd like to have several fields in my form being rendered as ChoiceFields which get their content from the database. I was thinking something like: class SeriesForm(ModelForm): series = forms.ChoiceField(choices=Series.objects.all()) class Meta: model = Series exclude = ('model', 'date_added',) But the field series is now not appearing at all in my form. What am I missing? After trying the solution (using the ModelChoiceField), I'm still seeing the same issue. Here is my code: series = forms.ModelChoiceField(queryset=Series.objects.values('series'), empty_label=" ")
[ "Use a ModelChoiceField instead.\n" ]
[ 6 ]
[]
[]
[ "django", "django_forms", "python" ]
stackoverflow_0002184108_django_django_forms_python.txt
Q: Telnet automation / scripting I have already checked this question but could not find what I'm looking for. I am running Windows (the client), and the server is a legacy mainframe type server. Basically I need to write a script, python code or whatever, to send some know commands to the server via telnet, and preferable capture the output. Then return when done. What's the best approach? A: There's a python library for telnet connections that reads and writes from/to a telnet connection. Check the link. It has some basic examples of what you are looking for. Here's an example from the link: import getpass import sys import telnetlib HOST = "localhost" user = raw_input("Enter your remote account: ") password = getpass.getpass() tn = telnetlib.Telnet(HOST) tn.read_until("login: ") tn.write(user + "\n") if password: tn.read_until("Password: ") tn.write(password + "\n") tn.write("ls\n") tn.write("exit\n") print tn.read_all() It connects to a telnet server. Sends your login credentials and then executes the unix command ls. Then exits the session and prints all output from the telnet server. A: You may want to consider Exscript as well. It simplifies some of the easy tasks but for more complicated there is additional level of abstraction (Exscript is a scripting language in itself). Either way - worth checking out. A: I've never used it myself, but maybe pexpect is what you need? "Pexpect can be used for automating interactive applications such as ssh, ftp, passwd, telnet, etc."
Telnet automation / scripting
I have already checked this question but could not find what I'm looking for. I am running Windows (the client), and the server is a legacy mainframe type server. Basically I need to write a script, python code or whatever, to send some know commands to the server via telnet, and preferable capture the output. Then return when done. What's the best approach?
[ "There's a python library for telnet connections that reads and writes from/to a telnet connection.\nCheck the link. It has some basic examples of what you are looking for.\nHere's an example from the link:\nimport getpass\nimport sys\nimport telnetlib\n\nHOST = \"localhost\"\nuser = raw_input(\"Enter your remote account: \")\npassword = getpass.getpass()\n\ntn = telnetlib.Telnet(HOST)\n\ntn.read_until(\"login: \")\ntn.write(user + \"\\n\")\nif password:\n tn.read_until(\"Password: \")\n tn.write(password + \"\\n\")\n\ntn.write(\"ls\\n\")\ntn.write(\"exit\\n\")\n\nprint tn.read_all()\n\nIt connects to a telnet server. Sends your login credentials and then executes the unix command ls. Then exits the session and prints all output from the telnet server.\n", "You may want to consider Exscript as well. It simplifies some of the easy tasks but for more complicated there is additional level of abstraction (Exscript is a scripting language in itself). Either way - worth checking out.\n", "I've never used it myself, but maybe pexpect is what you need?\n\n\"Pexpect can be used for automating\n interactive applications such as ssh,\n ftp, passwd, telnet, etc.\"\n\n" ]
[ 21, 3, 1 ]
[]
[]
[ "automation", "python", "scripting", "telnet", "windows" ]
stackoverflow_0001491494_automation_python_scripting_telnet_windows.txt
Q: Finding the length of a cubic B-spline Using scipy's interpolate.splprep function get a parametric spline on parameter u, but the domain of u is not the line integral of the spline, it is a piecewise linear connection of the input coordinates. I've tried integrate.splint, but that just gives the individual integrals over u. Obviously, I can numerically integrate a bunch of Cartesian differential distances, but I was wondering if there was closed-form method for getting the length of a spline or spline segment (using scipy or numpy) that I was overlooking. Edit: I am looking for a closed-form solution or a very fast way to converge to a machine-precision answer. I have all but given up on the numerical root-finding methods and am now primarily after a closed-form answer. If anyone has any experience integrating elliptical functions or can point me to a good resource (other than Wolfram), That would be great. I'm going to try Maxima to try to get the indefinite integral of what I believe is the function for one segment of the spline: I cross-posted this on MathOverflow A: Because both x & y are cubic parametric functions, there isn't a closed solution in terms of simple functions. Numerical integration is the way to go. Either integrating the arc length expression or simply adding line segment lengths - depends on the accuracy you are after and how much effort you want to exert. An accurate and fast "Adding length of line segments" method: Using recurvise subdivision (a form of de Casteljeau's algorithm) to generate points, can give you a highly accurate representation with minimal number of points. Only subdivide subdivisions if they fail to meet a criteria. Usually the criteria is based on the length joining the control points (the hull or cage). For cubic, usually comparing closeness of P0P1+P1P2+P2P3 to P0P3, where P0, P1, P2 & P3 are the control points that define your bezier. You can find some Delphi code here: link text It should be relatively easy to convert to Python. It will generate the points. The code already calculates the length of the segments in order to test the criteria. You can simply accumulate those length values along the way. A: You can integrate the function sqrt(x'(u)**2+y'(u)**2) over u, where you calculate the derivatives x' and y' of your coordinates with scipy.interpolate.splev. The integration can be done with one of the routines from scipy.integrate (quad is precise [Clenshaw-Curtis], romberg is generally faster). This should be more precise, and probably faster than adding up lots of small distances (which is equivalent to integrating with the rectangle rule).
Finding the length of a cubic B-spline
Using scipy's interpolate.splprep function get a parametric spline on parameter u, but the domain of u is not the line integral of the spline, it is a piecewise linear connection of the input coordinates. I've tried integrate.splint, but that just gives the individual integrals over u. Obviously, I can numerically integrate a bunch of Cartesian differential distances, but I was wondering if there was closed-form method for getting the length of a spline or spline segment (using scipy or numpy) that I was overlooking. Edit: I am looking for a closed-form solution or a very fast way to converge to a machine-precision answer. I have all but given up on the numerical root-finding methods and am now primarily after a closed-form answer. If anyone has any experience integrating elliptical functions or can point me to a good resource (other than Wolfram), That would be great. I'm going to try Maxima to try to get the indefinite integral of what I believe is the function for one segment of the spline: I cross-posted this on MathOverflow
[ "Because both x & y are cubic parametric functions, there isn't a closed solution in terms of simple functions. Numerical integration is the way to go. Either integrating the arc length expression or simply adding line segment lengths - depends on the accuracy you are after and how much effort you want to exert.\nAn accurate and fast \"Adding length of line segments\" method:\nUsing recurvise subdivision (a form of de Casteljeau's algorithm) to generate points, can give you a highly accurate representation with minimal number of points. \nOnly subdivide subdivisions if they fail to meet a criteria. Usually the criteria is based on the length joining the control points (the hull or cage).\nFor cubic, usually comparing closeness of P0P1+P1P2+P2P3 to P0P3, where P0, P1, P2 & P3 are the control points that define your bezier.\nYou can find some Delphi code here:\nlink text\nIt should be relatively easy to convert to Python. \nIt will generate the points. The code already calculates the length of the segments in order to test the criteria. You can simply accumulate those length values along the way.\n", "You can integrate the function sqrt(x'(u)**2+y'(u)**2) over u, where you calculate the derivatives x' and y' of your coordinates with scipy.interpolate.splev. The integration can be done with one of the routines from scipy.integrate (quad is precise [Clenshaw-Curtis], romberg is generally faster). This should be more precise, and probably faster than adding up lots of small distances (which is equivalent to integrating with the rectangle rule).\n" ]
[ 6, 4 ]
[]
[]
[ "interpolation", "python", "scipy" ]
stackoverflow_0002181349_interpolation_python_scipy.txt
Q: Python Leave Loop Early How do I leave a loop early in python? for a in b: if criteria in list1: print "oh no" #Force loop i.e. force next iteration without going on someList.append(a) Also, in java you can break out of a loop, is there an equivalent in Python? A: continue and break is what you want. Python works identically to Java/C++ in this regard. A: Firstly, bear in mind it might be possible to do what you want with a list comprehension. So you might be able to use something like: somelist = [a for a in b if not a.criteria in otherlist] If you want to leave a loop early in Python you can use break, just like in Java. >>> for x in xrange(1,6): ... print x ... if x == 2: ... break ... 1 2 If you want to start the next iteration of the loop early you use continue, again just as you would in Java. >>> for x in xrange(1,6): ... if x == 2: ... continue ... print x ... 1 3 4 5 Here's the documentation for break and continue. This also covers else clauses for loops, which aren't run when you break. A: continue and break work exactly like in other programming languages, except that you cannot break to a label (as you can in Java, for example). That means you can only break one loop at a time. A: Take a look at break and continue.
Python Leave Loop Early
How do I leave a loop early in python? for a in b: if criteria in list1: print "oh no" #Force loop i.e. force next iteration without going on someList.append(a) Also, in java you can break out of a loop, is there an equivalent in Python?
[ "continue and break is what you want. Python works identically to Java/C++ in this regard.\n", "Firstly, bear in mind it might be possible to do what you want with a list comprehension. So you might be able to use something like:\nsomelist = [a for a in b if not a.criteria in otherlist]\n\nIf you want to leave a loop early in Python you can use break, just like in Java.\n>>> for x in xrange(1,6):\n... print x\n... if x == 2:\n... break\n...\n1\n2\n\nIf you want to start the next iteration of the loop early you use continue, again just as you would in Java.\n>>> for x in xrange(1,6):\n... if x == 2:\n... continue\n... print x\n...\n1\n3\n4\n5\n\nHere's the documentation for break and continue. This also covers else clauses for loops, which aren't run when you break.\n", "continue and break work exactly like in other programming languages, except that you cannot break to a label (as you can in Java, for example). That means you can only break one loop at a time.\n", "Take a look at break and continue.\n" ]
[ 57, 24, 5, 2 ]
[]
[]
[ "loops", "python" ]
stackoverflow_0002184287_loops_python.txt
Q: PyQt post installation question I successfully installed PyQt in both mac and PC. To do so I had to install mingw (on PC), Xcode (on MAC) and Qt4.6 library. Now that I have PyQt working perfectly, I would like to uninstall mingw, Xcode and Qt Library from both mac and PC. I know I can remove Xcode and mingw, but what care should I take before removing Qt library. I know PyQt is still using it but it is not using whole 1.5Gig of files installed by Qt installer. So which files should I copy before removing Qt and where should I copy it to. A: You can remove the demos and examples directories inside your qt installation directory... they take up over 1GB of space and are not required. I would leave the rest there, unless you are really worried about space. If you do try to clean up the QT installation directory, start by renaming larger files/directories (e.g. add a .old suffix to the name), and see if the features you use in QT still function. If it breaks, just rename the files/directories back (remove .old).
PyQt post installation question
I successfully installed PyQt in both mac and PC. To do so I had to install mingw (on PC), Xcode (on MAC) and Qt4.6 library. Now that I have PyQt working perfectly, I would like to uninstall mingw, Xcode and Qt Library from both mac and PC. I know I can remove Xcode and mingw, but what care should I take before removing Qt library. I know PyQt is still using it but it is not using whole 1.5Gig of files installed by Qt installer. So which files should I copy before removing Qt and where should I copy it to.
[ "You can remove the demos and examples directories inside your qt installation directory... they take up over 1GB of space and are not required. I would leave the rest there, unless you are really worried about space.\nIf you do try to clean up the QT installation directory, start by renaming larger files/directories (e.g. add a .old suffix to the name), and see if the features you use in QT still function. If it breaks, just rename the files/directories back (remove .old).\n" ]
[ 1 ]
[]
[]
[ "pyqt4", "python" ]
stackoverflow_0002106178_pyqt4_python.txt
Q: Making Python Interactive Mode of Emacs Highlight and Indent I am using Emacs 23 with python-mode 5.1.0 to edit my python programs. Sometimes when writing a program I want to run a small throwaway python script and so I run the interactive move (C-c !). This is fine, but it neither indents nor highlights the code, and if I try running python mode while in it, it no longer evaluates. So, how do I set it to indent and highlight? A: Adding these to my .emacs seems to have done it. The bit where it checks the buffer name in the advice would probably be better as a test on a buffer-local variable set by set-pycomint-keywords, but you get the idea. (defun set-pycomint-keywords () (setq font-lock-keywords python-font-lock-keywords)) (add-hook 'py-shell-hook 'set-pycomint-keywords) (defadvice comint-send-input (around block-comint-formatting activate) (if (string= (buffer-name) "*Python*") (letf (((symbol-function 'add-text-properties) (lambda (x y z) nil))) ad-do-it)) ad-do-it)
Making Python Interactive Mode of Emacs Highlight and Indent
I am using Emacs 23 with python-mode 5.1.0 to edit my python programs. Sometimes when writing a program I want to run a small throwaway python script and so I run the interactive move (C-c !). This is fine, but it neither indents nor highlights the code, and if I try running python mode while in it, it no longer evaluates. So, how do I set it to indent and highlight?
[ "Adding these to my .emacs seems to have done it.\nThe bit where it checks the buffer name in the advice would probably be better as a test on a buffer-local variable set by set-pycomint-keywords, but you get the idea.\n(defun set-pycomint-keywords ()\n (setq font-lock-keywords python-font-lock-keywords))\n\n(add-hook 'py-shell-hook 'set-pycomint-keywords)\n\n\n\n (defadvice comint-send-input (around block-comint-formatting activate)\n (if (string= (buffer-name) \"*Python*\")\n (letf (((symbol-function 'add-text-properties) (lambda (x y z) nil)))\n ad-do-it))\n ad-do-it)\n\n" ]
[ 3 ]
[ "I don't have time to try it now, but i found you can replace python shell when you press C-c\nwith this that should be more powerful:\nhttp://ipython.scipy.org/moin/\nWhen i'll have time I'll give it a try\n" ]
[ -1 ]
[ "emacs", "python" ]
stackoverflow_0002063343_emacs_python.txt
Q: EventHandler, event, delegate based programming in Python any example would appreciate? Basically I'm a C# developer, I know the way C# does, EventHandler, delegate, even... but whats the best way to implement it on Python. A: I think you should be able to use a function: def do_work_and_notify(on_done): // do work on_done() def send_email_on_completion(): email_send('joe@example.com', 'you are done') do_work_and_notify(send_email_on_completion) Functions (and even methods) in python are first-class objects that can be tossed around like anything else in the language. A: This question is a lot like Python Observer Pattern: Examples, Tips? which has lots of great answers. There's even an implementation of C#-like events in Python.
EventHandler, event, delegate based programming in Python any example would appreciate?
Basically I'm a C# developer, I know the way C# does, EventHandler, delegate, even... but whats the best way to implement it on Python.
[ "I think you should be able to use a function:\ndef do_work_and_notify(on_done):\n // do work\n on_done()\n\ndef send_email_on_completion():\n email_send('joe@example.com', 'you are done')\n\ndo_work_and_notify(send_email_on_completion)\n\nFunctions (and even methods) in python are first-class objects that can be tossed around like anything else in the language.\n", "This question is a lot like Python Observer Pattern: Examples, Tips? which has lots of great answers. There's even an implementation of C#-like events in Python.\n" ]
[ 21, 2 ]
[]
[]
[ "delegates", "event_handling", "events", "function_pointers", "python" ]
stackoverflow_0002184263_delegates_event_handling_events_function_pointers_python.txt
Q: Python thinks a 3000-line text file is one line long? I have a very long text file that I'm trying to process using Python. However, the following code: for line in open('textbase.txt', 'r'): print 'hello world' produces only the following output: hello world It's as though Python thinks the file is only one line long, though it is many thousands of lines long, when viewed in a text editor. Examining it on the command line using the file command gives: $ file textbase.txt textbase.txt: Big-endian UTF-16 Unicode English text, with CR line terminators Is something wrong? Do I need to change the line terminators? A: According to the documentation for open(), you should add a U to the mode: open('textbase.txt', 'Ur') This enables "universal newlines", which normalizes them to \n in the strings it gives you. However, the correct thing to do is to decode the UTF-16BE into Unicode objects first, before translating the newlines. Otherwise, a chance 0x0d byte could get erroneously turned into a 0x0a, resulting in UnicodeDecodeError: 'utf16' codec can't decode byte 0x0a in position 12: truncated data. Python's codecs module supplies an open function that can decode Unicode and handle newlines at the same time: import codecs for line in codecs.open('textbase.txt', 'Ur', 'utf-16be'): ... If the file has a byte order mark (BOM) and you specify 'utf-16', then it detects the endianness and hides the BOM for you. If it does not (since the BOM is optional), then that decoder will just go ahead and use your system's endianness, which probably won't be good. Specifying the endianness yourself (with 'utf-16be') will not hide the BOM, so you might wish to use this hack: import codecs firstline = True for line in codecs.open('textbase.txt', 'Ur', 'utf-16be'): if firstline: firstline = False line = line.lstrip(u'\ufeff') See also: Python Unicode HOWTO A: You'll probably find it's the "with CR line terminators" that gives the game away. If you're working on a platform that uses newlines as line terminators, it will see your file as one big honkin' line. Change your input file so that it uses the correct line terminators. Your editor is probably more forgiving than your Python implementation. The CR line endings are a Mac thing as far as I'm aware and you can use the U mode modifier to open to auto-detect based on the first line terminator found. A: it looks like your file has lines terminated only by CR, and Python is probably expecting LF or CRLF. Try using the 'universal newline': for line in open('textbase.txt', 'rU'): print 'hello world' http://docs.python.org/library/functions.html?highlight=open#open
Python thinks a 3000-line text file is one line long?
I have a very long text file that I'm trying to process using Python. However, the following code: for line in open('textbase.txt', 'r'): print 'hello world' produces only the following output: hello world It's as though Python thinks the file is only one line long, though it is many thousands of lines long, when viewed in a text editor. Examining it on the command line using the file command gives: $ file textbase.txt textbase.txt: Big-endian UTF-16 Unicode English text, with CR line terminators Is something wrong? Do I need to change the line terminators?
[ "According to the documentation for open(), you should add a U to the mode:\nopen('textbase.txt', 'Ur')\n\nThis enables \"universal newlines\", which normalizes them to \\n in the strings it gives you.\nHowever, the correct thing to do is to decode the UTF-16BE into Unicode objects first, before translating the newlines. Otherwise, a chance 0x0d byte could get erroneously turned into a 0x0a, resulting in\n\nUnicodeDecodeError: 'utf16' codec can't decode byte 0x0a in position 12: truncated data.\n\nPython's codecs module supplies an open function that can decode Unicode and handle newlines at the same time:\nimport codecs\nfor line in codecs.open('textbase.txt', 'Ur', 'utf-16be'):\n ...\n\nIf the file has a byte order mark (BOM) and you specify 'utf-16', then it detects the endianness and hides the BOM for you. If it does not (since the BOM is optional), then that decoder will just go ahead and use your system's endianness, which probably won't be good.\nSpecifying the endianness yourself (with 'utf-16be') will not hide the BOM, so you might wish to use this hack:\nimport codecs\nfirstline = True\nfor line in codecs.open('textbase.txt', 'Ur', 'utf-16be'):\n if firstline:\n firstline = False\n line = line.lstrip(u'\\ufeff')\n\nSee also: Python Unicode HOWTO\n", "You'll probably find it's the \"with CR line terminators\" that gives the game away. If you're working on a platform that uses newlines as line terminators, it will see your file as one big honkin' line.\nChange your input file so that it uses the correct line terminators. Your editor is probably more forgiving than your Python implementation.\nThe CR line endings are a Mac thing as far as I'm aware and you can use the U mode modifier to open to auto-detect based on the first line terminator found.\n", "it looks like your file has lines terminated only by CR, and Python is probably expecting LF or CRLF. Try using the 'universal newline':\nfor line in open('textbase.txt', 'rU'):\n print 'hello world'\n\nhttp://docs.python.org/library/functions.html?highlight=open#open\n" ]
[ 25, 6, 1 ]
[ "open() returns a file object. You need to use:\nfor line in open('textbase.txt', 'r').readlines():\n print line\n\n" ]
[ -1 ]
[ "character_encoding", "newline", "python", "text" ]
stackoverflow_0002184543_character_encoding_newline_python_text.txt
Q: Python database access using single file/already build file I have to save some data into MySQL from Python. I have tried MySQLdb, but it needs to be built. Build fails on my Mac; moreover, I need to have one file to copy to server. I don't have access to install anything. Can you recommend me any solution, please! Even where I can find MySQLdb build for specific platforms. Thanks in advance! A: MySQL has a command line interface (similar to psql from Postgres or sqlite3 from the database of the same name). I would be surprised if this wasn't installed on the same server already. You could then generate input for that utility using Python and call it with subprocess. Depending on the data, this can be as simple as generating INSERT commands from scratch, or you can generate a temporary input file (e.g. in CSV format) and pass it to the utility by name. A: I find the easiest way to use C extensions from python on a Mac is to use Macports Yo will need to install macports and then install the port py26-mysql this will install python 2.6 and MySQL. However in this case I would have thought MySQLdb should be an easy install - to help with that can you edit your question to show the error and tell us where the mySql libraries are installed
Python database access using single file/already build file
I have to save some data into MySQL from Python. I have tried MySQLdb, but it needs to be built. Build fails on my Mac; moreover, I need to have one file to copy to server. I don't have access to install anything. Can you recommend me any solution, please! Even where I can find MySQLdb build for specific platforms. Thanks in advance!
[ "MySQL has a command line interface (similar to psql from Postgres or sqlite3 from the database of the same name). I would be surprised if this wasn't installed on the same server already.\nYou could then generate input for that utility using Python and call it with subprocess. Depending on the data, this can be as simple as generating INSERT commands from scratch, or you can generate a temporary input file (e.g. in CSV format) and pass it to the utility by name.\n", "I find the easiest way to use C extensions from python on a Mac is to use Macports\nYo will need to install macports and then install the port py26-mysql this will install python 2.6 and MySQL.\nHowever in this case I would have thought MySQLdb should be an easy install - to help with that can you edit your question to show the error and tell us where the mySql libraries are installed\n" ]
[ 2, 1 ]
[]
[]
[ "database", "mysql", "python" ]
stackoverflow_0002184156_database_mysql_python.txt
Q: Setting the RGB levels of pixels (Python, Jython) For each pixel in pic: r= random() if r < 0.25: set the red level to randrange(0,256), set the green level to randrange(0,256) set the blue level to randrange(0,256) The rest of the unseen code is correct, I just can't figure out how to phrase this function well enough for it to work. A: I don't know anything about the rest of your code, but it would be something like this: import random for pixel in pic.get_pixels(): # Replace with appropiate way of getting the pixels if random.random() < 0.25: pixel.red = random.randint(256) pixel.green = random.randint(256) pixel.blue = random.randint(256) Again, I don't know how you get a list of the pixels, or how you set the RGB values for each one, but the result would be something like this. A: Are you using PIL? If so one option is to do something like this your_image = Image.new("RGB", (512, 512), "white") for x in xrange(your_image.size[0]): for y in xrange(your_image.size[1]): your_image.putpixel((x,y),(random.randint(256), random.randint(256), random.randint(256)) Oh... I see you got it. Well I'll post this anyways.
Setting the RGB levels of pixels (Python, Jython)
For each pixel in pic: r= random() if r < 0.25: set the red level to randrange(0,256), set the green level to randrange(0,256) set the blue level to randrange(0,256) The rest of the unseen code is correct, I just can't figure out how to phrase this function well enough for it to work.
[ "I don't know anything about the rest of your code, but it would be something like this:\nimport random\n\nfor pixel in pic.get_pixels(): # Replace with appropiate way of getting the pixels\n if random.random() < 0.25:\n pixel.red = random.randint(256)\n pixel.green = random.randint(256)\n pixel.blue = random.randint(256)\n\nAgain, I don't know how you get a list of the pixels, or how you set the RGB values for each one, but the result would be something like this.\n", "Are you using PIL?\nIf so one option is to do something like this\n\nyour_image = Image.new(\"RGB\", (512, 512), \"white\")\nfor x in xrange(your_image.size[0]):\n for y in xrange(your_image.size[1]):\n your_image.putpixel((x,y),(random.randint(256), random.randint(256), random.randint(256))\n\nOh... I see you got it. Well I'll post this anyways.\n" ]
[ 1, 0 ]
[]
[]
[ "jython", "python" ]
stackoverflow_0002158228_jython_python.txt
Q: How to pass data to another function from a class (in HTMLParser)? I'm beginning to learn python. My python version is 3.1 I've never learnt OOP before, so I'm confused by the HTMLParser. from html.parser import HTMLParser class parser(HTMLParser): def handle_data(self, data): print(data) p = parser() page = """<html><h1>title</h1><p>I'm a paragraph!</p></html>""" p.feed(page) I'll get this: title I'm a paragraph! I want this data passed to a function, what should I do? Sorry for my poor English and Thank you for your help! A: I did not look into the HTMLParser module itself, but I can see that feed inherently calls handle_data, which in your derived class does a print. @ron's answer suggests passing the data directly to your function, which is totally OK. However, since you are new to OOP, maybe take a look at this code. This is Python, 2.x, but I think the only thing that would change is the package location, html.parser instead of HTMLParser. from HTMLParser import HTMLParser class MyParser(HTMLParser): def handle_data(self, data): self.output.append(data) def feed(self, data): self.output = [] HTMLParser.feed(self, data) p = MyParser() page = """<html><h1>title</h1><p>I'm a paragraph!</p></html>""" p.feed(page) print p.output output ['title', "I'm a paragraph!"] Here I am overriding the feed method of HTMLParser. Instead, when the call is made p.feed(page) it will call my method, which creates / sets an instance variable called output to an empty list and then calls the feed method in the base class (HTMLParser) and proceeds with what it does normally. So, by overriding the feed method I was able to do some extra stuff (added a new output variable). The handle_data method similarly is an override method. In fact, the handle_data method of HTMLParser doesn't even do anything... nothing at all (according to the docs.) So, just to clarify... You call p.feed(page) which calls the MyParser.feed method MyParser.feed sets a variable self.output to and empty list then calls HTMLParser.feed The handle_data method adds the line onto the end of the output list. You now have access to the data via a call to p.output. A: Just an example: def my_global_fun(data): print "processing", data class parser(HTMLParser): def my_member_fun(self, data): print "processing", data def handle_data(self, data): self.my_member_fun(data) # or my_global_fun(data) Good luck learning OOP!
How to pass data to another function from a class (in HTMLParser)?
I'm beginning to learn python. My python version is 3.1 I've never learnt OOP before, so I'm confused by the HTMLParser. from html.parser import HTMLParser class parser(HTMLParser): def handle_data(self, data): print(data) p = parser() page = """<html><h1>title</h1><p>I'm a paragraph!</p></html>""" p.feed(page) I'll get this: title I'm a paragraph! I want this data passed to a function, what should I do? Sorry for my poor English and Thank you for your help!
[ "I did not look into the HTMLParser module itself, but I can see that feed inherently calls handle_data, which in your derived class does a print. @ron's answer suggests passing the data directly to your function, which is totally OK. However, since you are new to OOP, maybe take a look at this code.\nThis is Python, 2.x, but I think the only thing that would change is the package location, html.parser instead of HTMLParser.\nfrom HTMLParser import HTMLParser\n\nclass MyParser(HTMLParser):\n def handle_data(self, data):\n self.output.append(data)\n def feed(self, data):\n self.output = []\n HTMLParser.feed(self, data)\n\n\np = MyParser()\npage = \"\"\"<html><h1>title</h1><p>I'm a paragraph!</p></html>\"\"\"\np.feed(page)\n\nprint p.output\n\noutput\n['title', \"I'm a paragraph!\"]\n\nHere I am overriding the feed method of HTMLParser. Instead, when the call is made p.feed(page) it will call my method, which creates / sets an instance variable called output to an empty list and then calls the feed method in the base class (HTMLParser) and proceeds with what it does normally. So, by overriding the feed method I was able to do some extra stuff (added a new output variable). The handle_data method similarly is an override method. In fact, the handle_data method of HTMLParser doesn't even do anything... nothing at all (according to the docs.)\nSo, just to clarify...\nYou call p.feed(page) which calls the MyParser.feed method\nMyParser.feed sets a variable self.output to and empty list then calls HTMLParser.feed\nThe handle_data method adds the line onto the end of the output list. \nYou now have access to the data via a call to p.output. \n", "Just an example:\ndef my_global_fun(data):\n print \"processing\", data\n\nclass parser(HTMLParser):\n def my_member_fun(self, data):\n print \"processing\", data\n\n def handle_data(self, data):\n self.my_member_fun(data)\n # or\n my_global_fun(data)\n\nGood luck learning OOP!\n" ]
[ 6, 2 ]
[]
[]
[ "class", "function", "python" ]
stackoverflow_0002185020_class_function_python.txt
Q: Python / Regex: exclude everything except one thing Suppose I have these strings: a = "hello" b = "-hello" c = "-" d = "hell-o" e = " - " How do I match only the -(String C)? I've tried a if "-" in something but obviously that isn't correct. Could someone please advise? Let's say we put these strings into a list, looped through and all I wanted to extract was C. How would I do this? for aa in list1: if not re.findall('[^-$]'): print aa Would that be too messy? A: If you want to match only variable c: if '-' == something: print 'hurray!' To answer the updates: yes, that would be too messy. You don't need regex there. Simple string methods are faster: >>> lst =["hello", "-hello", "-", "hell-o"," - "] >>> for i, item in enumerate(lst): if item == '-': print(i, item) 2 - A: as a regex its "^-$" A: If what you're trying to do is strip out the dash (i.e. he-llo gives hello), then this is more of a job for generator expressions. ''.join((char for char in 'he-llo' if char != '-')) A: if "-" in c and len(c) ==1 : print "do something" OR if c=="-"
Python / Regex: exclude everything except one thing
Suppose I have these strings: a = "hello" b = "-hello" c = "-" d = "hell-o" e = " - " How do I match only the -(String C)? I've tried a if "-" in something but obviously that isn't correct. Could someone please advise? Let's say we put these strings into a list, looped through and all I wanted to extract was C. How would I do this? for aa in list1: if not re.findall('[^-$]'): print aa Would that be too messy?
[ "If you want to match only variable c:\nif '-' == something:\n print 'hurray!'\n\nTo answer the updates: yes, that would be too messy. You don't need regex there. Simple string methods are faster:\n>>> lst =[\"hello\", \"-hello\", \"-\", \"hell-o\",\" - \"]\n>>> for i, item in enumerate(lst):\n if item == '-':\n print(i, item)\n\n\n2 -\n\n", "as a regex its \"^-$\" \n", "If what you're trying to do is strip out the dash (i.e. he-llo gives hello), then this is more of a job for generator expressions.\n''.join((char for char in 'he-llo' if char != '-'))\n\n", "if \"-\" in c and len(c) ==1 : print \"do something\"\n\nOR \nif c==\"-\"\n\n" ]
[ 4, 1, 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0002185229_python_regex.txt
Q: How do I detect a lost client connection in a server that inherits from pb.Root? For example, I have a client that connects to the server with the following: class MyClientFactory(pb.PBClientFactory, ReconnectingClientFactory): def __init__(self): pb.PBClientFactory.__init__(self) self.ipaddress = None def clientConnectionMade(self, broker): log.msg('Started to connect.') pb.PBClientFactory.clientConnectionMade(self, broker) def buildProtocol(self, addr): log.msg('Connected to %s' % addr) return pb.PBClientFactory.buildProtocol(self, addr) def clientConnectionLost(self, connector, reason): log.msg('Lost connection. Reason:', reason) ReconnectingClientFactory.clientConnectionLost(self, connector, reason) def clientConnectionFailed(self, connector, reason): log.msg('Connection failed. Reason:', reason) ReconnectingClientFactory.clientConnectionLost(self, connector, reason) So the client can automatically detect when a connection is lost. How do I get the same behaviour from the server should a client go down, for example crashing? I currently catch a DeadReferenceError, (by iterating through a list of potentially connected clients) but that is a non-event driven way - and frankly too late. Any ideas welcome. Thanks in advance. Ben A: You can register a callback to be invoked when the connection is lost. There are two APIs for this, one is Broker.notifyOnDisconnect, the other is RemoteReference.notifyOnDisconnect. They do the same thing, but one or the other might be more convenient to access depending on the details of your application. I'm not sure if you can use this to guarantee that you'll never get DeadReferenceError (for example, I'm not sure what happens if a remote_foo method if yours is invoked, you return a Deferred, the connection is lost, and then the Deferred fires), but you can at least drastically reduce the possibility in the common case (ie, you should be able to always avoid getting DeadReferenceError from callRemote if you never use callRemote after notifyOnDisconnect calls back your function).
How do I detect a lost client connection in a server that inherits from pb.Root?
For example, I have a client that connects to the server with the following: class MyClientFactory(pb.PBClientFactory, ReconnectingClientFactory): def __init__(self): pb.PBClientFactory.__init__(self) self.ipaddress = None def clientConnectionMade(self, broker): log.msg('Started to connect.') pb.PBClientFactory.clientConnectionMade(self, broker) def buildProtocol(self, addr): log.msg('Connected to %s' % addr) return pb.PBClientFactory.buildProtocol(self, addr) def clientConnectionLost(self, connector, reason): log.msg('Lost connection. Reason:', reason) ReconnectingClientFactory.clientConnectionLost(self, connector, reason) def clientConnectionFailed(self, connector, reason): log.msg('Connection failed. Reason:', reason) ReconnectingClientFactory.clientConnectionLost(self, connector, reason) So the client can automatically detect when a connection is lost. How do I get the same behaviour from the server should a client go down, for example crashing? I currently catch a DeadReferenceError, (by iterating through a list of potentially connected clients) but that is a non-event driven way - and frankly too late. Any ideas welcome. Thanks in advance. Ben
[ "You can register a callback to be invoked when the connection is lost. There are two APIs for this, one is Broker.notifyOnDisconnect, the other is RemoteReference.notifyOnDisconnect. They do the same thing, but one or the other might be more convenient to access depending on the details of your application.\nI'm not sure if you can use this to guarantee that you'll never get DeadReferenceError (for example, I'm not sure what happens if a remote_foo method if yours is invoked, you return a Deferred, the connection is lost, and then the Deferred fires), but you can at least drastically reduce the possibility in the common case (ie, you should be able to always avoid getting DeadReferenceError from callRemote if you never use callRemote after notifyOnDisconnect calls back your function).\n" ]
[ 4 ]
[]
[]
[ "python", "twisted" ]
stackoverflow_0002184682_python_twisted.txt
Q: How to get the most represented object from an array I have an array with some objects, and there are several objects that are alike. E.g: fruit = [apple, orange, apple, banana, banana, orange, apple, apple] What is the most efficient way to get the most represented object from this array? In this case it would be "apple" but how would you go out and calculate that in an efficient way? A: Don't reinvent the wheel. In Python 2.7+ you can use the Counter class: import collections fruit=['apple', 'orange', 'apple', 'banana', 'banana', 'orange', 'apple', 'apple'] c=collections.Counter(fruit) print(c.most_common(1)) # [('apple', 4)] If you are using an older version of Python, then you can download Counter here. While it's good to know how to implement something like this yourself, it's also a good idea to get used to using Counter, since it is (or going to be) part of the standard library. A: If the objects are hashable then you can use a dict to store the counts: results = {} for item in somelist: if item not in results: results[item] = 1 else results[item] += 1 print max(results.iteritems(), key=operator.itemgetter(1)) A: Keep a dictionary of how often each object appears. Walk through the list once, building this table. As you go, keep track of which object has appeared the most often so far. This code is untested. from collections import defaultdict def mode(objects): h = defaultdict(int) max_f = 0 max_obj = None for o in objects: f = h[o] = h[o] + 1 if f > max_f: max_f = f max_obj = o return max_obj If the objects are not hashable, you can instead hash some unique feature of them, such as id(o). A: You want an efficient method. Clearly it's possible in O(n) time, so any method that requires sorting the list is out as that would be O(n log(n)). It's not possible to do it faster than O(n) because even if you check the first n/2-1 elements, and they are all "apple", you don't know that the rest of the elements won't be bananas. So given that we're looking for O(n), you must iterate over the list and keep a count of how many items of each type you've seen. A defaultdict would be a simple way to implement this in practice. >>> from collections import defaultdict >>> d = defaultdict(int) >>> for i in ['apple', 'banana', 'apple']: ... d[i] += 1 ... >>> d defaultdict(<type 'int'>, {'apple': 2, 'banana': 1}) A: The best time you can hope to achieve here is O(n) - you'll always need to walk the entire array at least once. The easiest way will certainly be to build a histogram. If your dictionary structure (map of some kind) offers O(1) insert and retrieve then this is as easy as (groovy-ish pseudocode): def histogram = new HashMap() def maxObj = null def maxObjCount = 0 objectList.each { if(histogram.contains(it)) histogram.put(it, histogram.get(it)+1) else histogram.put(it, 1) if(histogram.get(it) > maxObjCount) { maxObj = it maxObjCount = histogram.get(it) } } A: def count_reps(item, agg): k = hash(item) try: agg[k] += 1 except KeyError: agg[k] = 1 return agg item_dict = reduce(your_array, {}) item_dict will contain the counts, then you can rate the popularity of each object. A: Heres a different approach which essentially sorts the list and then processes it in a sorted order. fruits = ['apple', 'orange', 'apple', 'banana', 'banana', 'orange', 'apple', 'apple'] max_fruit_count = 0 max_fruit = '' current_fruit_count = 0 current_fruit = '' for fruit in sorted(fruits) : if fruit != current_fruit : if current_fruit != max_fruit : if current_fruit_count > max_fruit_count : max_fruit = current_fruit max_fruit_count = current_fruit_count current_fruit = fruit current_fruit_count = 1 else : current_fruit_count += 1 if current_fruit_count > max_fruit_count : max_fruit = current_fruit max_fruit_count = current_fruit_count print max_fruit, max_fruit_count A: This is not O(n), but O(n^2), so it not may fit your bill as "most efficient way", but it's compact and avoids for loops, which are rather slow in Python. It will be faster than the O(n) option up to 11 unique items. def most_common(items): s = set(items) return max([(items.count(i), i) for i in s])[1] A: As ~unutbu says: use collections.Counter Failing that, time your code. Here is my (likely inefficient) approach: python -m timeit -s "fruit = ['apple']*4 + ['banana'] + ['orange']*2" \ "kL = set(fruit); L = [fruit.count(f) for f in kL]; D = dict(zip(kL,L)); \ sorted(D,key = lambda k: D[k],reverse=True)" 100000 loops, best of 3: 10.1 usec per loop
How to get the most represented object from an array
I have an array with some objects, and there are several objects that are alike. E.g: fruit = [apple, orange, apple, banana, banana, orange, apple, apple] What is the most efficient way to get the most represented object from this array? In this case it would be "apple" but how would you go out and calculate that in an efficient way?
[ "Don't reinvent the wheel. In Python 2.7+ you can use the Counter class:\nimport collections\nfruit=['apple', 'orange', 'apple', 'banana', 'banana', 'orange', 'apple', 'apple']\nc=collections.Counter(fruit)\nprint(c.most_common(1))\n# [('apple', 4)]\n\nIf you are using an older version of Python, then you can download Counter here. \nWhile it's good to know how to implement something like this yourself, it's also a good idea to get used to using Counter, since it is (or going to be) part of the standard library.\n", "If the objects are hashable then you can use a dict to store the counts:\nresults = {}\nfor item in somelist:\n if item not in results:\n results[item] = 1\n else\n results[item] += 1\n\nprint max(results.iteritems(), key=operator.itemgetter(1))\n\n", "Keep a dictionary of how often each object appears.\nWalk through the list once, building this table. As you go, keep track of which object has appeared the most often so far.\nThis code is untested.\nfrom collections import defaultdict\n\ndef mode(objects):\n h = defaultdict(int)\n max_f = 0\n max_obj = None\n for o in objects:\n f = h[o] = h[o] + 1\n if f > max_f:\n max_f = f\n max_obj = o\n return max_obj\n\nIf the objects are not hashable, you can instead hash some unique feature of them, such as id(o).\n", "You want an efficient method. Clearly it's possible in O(n) time, so any method that requires sorting the list is out as that would be O(n log(n)). It's not possible to do it faster than O(n) because even if you check the first n/2-1 elements, and they are all \"apple\", you don't know that the rest of the elements won't be bananas.\nSo given that we're looking for O(n), you must iterate over the list and keep a count of how many items of each type you've seen.\nA defaultdict would be a simple way to implement this in practice.\n>>> from collections import defaultdict\n>>> d = defaultdict(int)\n>>> for i in ['apple', 'banana', 'apple']:\n... d[i] += 1\n...\n>>> d\ndefaultdict(<type 'int'>, {'apple': 2, 'banana': 1})\n\n", "The best time you can hope to achieve here is O(n) - you'll always need to walk the entire array at least once. The easiest way will certainly be to build a histogram. If your dictionary structure (map of some kind) offers O(1) insert and retrieve then this is as easy as (groovy-ish pseudocode):\ndef histogram = new HashMap()\ndef maxObj = null\ndef maxObjCount = 0\nobjectList.each {\n if(histogram.contains(it)) histogram.put(it, histogram.get(it)+1)\n else histogram.put(it, 1)\n\n if(histogram.get(it) > maxObjCount) {\n maxObj = it\n maxObjCount = histogram.get(it)\n }\n}\n\n", "def count_reps(item, agg):\n k = hash(item)\n try:\n agg[k] += 1\n except KeyError:\n agg[k] = 1\n return agg\n\nitem_dict = reduce(your_array, {})\n\nitem_dict will contain the counts, then you can rate the popularity of each object.\n", "Heres a different approach which essentially sorts the list and then processes it in a sorted order.\nfruits = ['apple', 'orange', 'apple', 'banana', 'banana', 'orange', 'apple', 'apple']\n\nmax_fruit_count = 0\nmax_fruit = ''\ncurrent_fruit_count = 0\ncurrent_fruit = ''\nfor fruit in sorted(fruits) :\n if fruit != current_fruit :\n if current_fruit != max_fruit :\n if current_fruit_count > max_fruit_count :\n max_fruit = current_fruit\n max_fruit_count = current_fruit_count\n current_fruit = fruit\n current_fruit_count = 1\n else :\n current_fruit_count += 1\n\nif current_fruit_count > max_fruit_count :\n max_fruit = current_fruit\n max_fruit_count = current_fruit_count\n\nprint max_fruit, max_fruit_count\n\n", "This is not O(n), but O(n^2), so it not may fit your bill as \"most efficient way\", but it's compact and avoids for loops, which are rather slow in Python. It will be faster than the O(n) option up to 11 unique items.\ndef most_common(items):\n s = set(items)\n return max([(items.count(i), i) for i in s])[1]\n\n", "As ~unutbu says: use collections.Counter\nFailing that, time your code. Here is my (likely inefficient) approach:\npython -m timeit -s \"fruit = ['apple']*4 + ['banana'] + ['orange']*2\" \\\n\"kL = set(fruit); L = [fruit.count(f) for f in kL]; D = dict(zip(kL,L)); \\\nsorted(D,key = lambda k: D[k],reverse=True)\" \n100000 loops, best of 3: 10.1 usec per loop\n\n" ]
[ 8, 5, 3, 2, 1, 0, 0, 0, 0 ]
[]
[]
[ "algorithm", "arrays", "list", "performance", "python" ]
stackoverflow_0002184336_algorithm_arrays_list_performance_python.txt