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: How do I use regex to do this in Python? def symbolsReplaceDashes(text): I want to replace all spaces and symbols with hyphens. Because I want to use this with URL. A: import re text = "this isn't alphanumeric" result = re.sub(r'\W','-',text) # result will be "this-isn-t-alphanumeric" The \W class is the inverse of the \w class, which consists of alphanumeric characters and underscores ([a-zA-Z0-9_]). Thus, replacing any character that doesn't match \W with a dash will leave you with a string that consists of only alphanumerics, underscores, and dashes, suitable for a URL. A: This response doesn't use regular expressions, but should also work, with greater control over the types of symbols to filter. It uses the unicodedata module to remove all symbols by checking the categories of the characters. import unicodedata # See http://www.dpawson.co.uk/xsl/rev2/UnicodeCategories.html for character categories replace = ('Sc', 'Sk', 'Sm', 'So', 'Zs') def symbolsReplaceDashes(text): L = [] for char in text: if unicodedata.category(unicode(char)) in replace: L.append('-') else: L.append(char) return ''.join(L) You may need to use something like urllib.quote(output.encode('utf-8')) to encode characters if ranges are beyond basic ASCII alphanumeric characters. A: Instead of regex, if you want to escape a string to be used for an url, use urllib.quote() or urllib.quote_plus(). For more complex queries, you might want to build the url using urllib.urlencode(). You can reverse the quotation with urllib.unquote() and urllib.unquote_plus().
How do I use regex to do this in Python?
def symbolsReplaceDashes(text): I want to replace all spaces and symbols with hyphens. Because I want to use this with URL.
[ "import re\ntext = \"this isn't alphanumeric\"\nresult = re.sub(r'\\W','-',text) # result will be \"this-isn-t-alphanumeric\"\n\nThe \\W class is the inverse of the \\w class, which consists of alphanumeric characters and underscores ([a-zA-Z0-9_]). Thus, replacing any character that doesn't match \\W with a dash will leave you with a string that consists of only alphanumerics, underscores, and dashes, suitable for a URL.\n", "This response doesn't use regular expressions, but should also work, with greater control over the types of symbols to filter. It uses the unicodedata module to remove all symbols by checking the categories of the characters.\nimport unicodedata\n\n# See http://www.dpawson.co.uk/xsl/rev2/UnicodeCategories.html for character categories\nreplace = ('Sc', 'Sk', 'Sm', 'So', 'Zs')\ndef symbolsReplaceDashes(text):\n L = []\n for char in text:\n if unicodedata.category(unicode(char)) in replace:\n L.append('-')\n else: L.append(char)\n return ''.join(L)\n\nYou may need to use something like urllib.quote(output.encode('utf-8')) to encode characters if ranges are beyond basic ASCII alphanumeric characters.\n", "Instead of regex, if you want to escape a string to be used for an url, use urllib.quote() or urllib.quote_plus(). For more complex queries, you might want to build the url using urllib.urlencode(). You can reverse the quotation with urllib.unquote() and urllib.unquote_plus().\n" ]
[ 4, 1, 1 ]
[]
[]
[ "python", "regex", "url" ]
stackoverflow_0002589068_python_regex_url.txt
Q: How can I remove all words that end in ":" from a string in Python? I'm wondering how to remove a dynamic word from a string within Python. It will always have a ":" at the end of the word, and sometimes there's more than one within the string. I'd like to remove all occurrences of "word:". Thanks! :-) A: Use regular expressions. import re blah = "word word: monty py: thon" answer = re.sub(r'\w+:\s?','',blah) print answer This will also pull out a single optional space after the colon. A: This removes all words which end with a ":": def RemoveDynamicWords(s): L = [] for word in s.split(): if not word.endswith(':'): L.append(word) return ' '.join(L) print RemoveDynamicWords('word: blah') or use a generator expression: print ' '.join(i for i in word.split(' ') if not i.endswith(':')) A: [ chunk for chunk in line.split() if not chunk.endswith(":") ] this will create a list. you can join them up afterwards.
How can I remove all words that end in ":" from a string in Python?
I'm wondering how to remove a dynamic word from a string within Python. It will always have a ":" at the end of the word, and sometimes there's more than one within the string. I'd like to remove all occurrences of "word:". Thanks! :-)
[ "Use regular expressions.\nimport re\nblah = \"word word: monty py: thon\"\nanswer = re.sub(r'\\w+:\\s?','',blah)\nprint answer\n\nThis will also pull out a single optional space after the colon.\n", "This removes all words which end with a \":\":\ndef RemoveDynamicWords(s):\n L = []\n for word in s.split():\n if not word.endswith(':'):\n L.append(word)\n return ' '.join(L)\nprint RemoveDynamicWords('word: blah')\n\nor use a generator expression:\nprint ' '.join(i for i in word.split(' ') if not i.endswith(':'))\n\n", "[ chunk for chunk in line.split() if not chunk.endswith(\":\") ]\n\nthis will create a list. you can join them up afterwards.\n" ]
[ 12, 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0002589200_python_regex.txt
Q: Loading SQL dump before running Django tests I have a fairly complex Django project which makes it hard/impossible to use fixtures for loading data. What I would like to do is to load a database dump from the production database server after all tables has bene created by the testrunner and before the actual tests start running. I've tried various "magic" in MyTestCase.setUp(), but with no luck. Any suggestions would be most welcome. Thanks. A: Django supports loading SQL files when doing syncdb, reset, or starting a test runner -- this does exactly what you describe: http://docs.djangoproject.com/en/dev/howto/initial-data/#providing-initial-sql-data You need to create an "sql" directory in your app directory, and then put a file named "mymodel.sql" in that directory (where "MyModel" is the corresponding model name). myproject/ |--myapp/ |--sql/ |--mymodel.sql You can create this SQL with dump tools for your database. SQLite [1]: echo '.dump' | sqlite3 yourdbname.sqlite > myapp/sql/mymodel.sql MySQL [2]: mysqldump yourdbname > myapp/sql/mymodel.sql PostgreSQL [3]: pg_dump yourdbname > myapp/sql/mymodel.sql After dumping, you'll need to edit the file to remove everything but the appropriate INSERT statements, or other complicated stuff. In particular, you must remove transaction handling, index creating, and table creating SQL to avoid errors when loading duplicate create statements. I use this method for loading really, really big fixtures -- it takes far too long to process the json, but a straight sql import is pretty snappy. Do be aware that this method will load the sql for any invocation of synchdb, reset, etc. in addition to loading data for the test runner -- so you won't be able to have different data for different test cases, and you'd have to remove files before a reset if you didn't want them loading back onto your production server. [1] http://www.sqlite.org/sqlite.html [2] http://dev.mysql.com/doc/refman/5.1/en/mysqldump.html [3] http://www.postgresql.org/docs/8.1/static/backup.html#BACKUP-DUMP A: You may need to look into defining a custom test runner. There's some info here: https://docs.djangoproject.com/en/dev/topics/testing/advanced/#other-testing-frameworks Basically I think you can just copy the default test runner from django.test.simple.run_tests and then modify it to suit your needs. I've not done this before, but from my understanding that would be the way to customize this.
Loading SQL dump before running Django tests
I have a fairly complex Django project which makes it hard/impossible to use fixtures for loading data. What I would like to do is to load a database dump from the production database server after all tables has bene created by the testrunner and before the actual tests start running. I've tried various "magic" in MyTestCase.setUp(), but with no luck. Any suggestions would be most welcome. Thanks.
[ "Django supports loading SQL files when doing syncdb, reset, or starting a test runner -- this does exactly what you describe: \nhttp://docs.djangoproject.com/en/dev/howto/initial-data/#providing-initial-sql-data\nYou need to create an \"sql\" directory in your app directory, and then put a file named \"mymodel.sql\" in that directory (where \"MyModel\" is the corresponding model name).\nmyproject/\n |--myapp/\n |--sql/\n |--mymodel.sql\n\nYou can create this SQL with dump tools for your database.\n\nSQLite [1]: echo '.dump' | sqlite3 yourdbname.sqlite > myapp/sql/mymodel.sql\nMySQL [2]: mysqldump yourdbname > myapp/sql/mymodel.sql\nPostgreSQL [3]: pg_dump yourdbname > myapp/sql/mymodel.sql\n\nAfter dumping, you'll need to edit the file to remove everything but the appropriate INSERT statements, or other complicated stuff. In particular, you must remove transaction handling, index creating, and table creating SQL to avoid errors when loading duplicate create statements.\nI use this method for loading really, really big fixtures -- it takes far too long to process the json, but a straight sql import is pretty snappy. \nDo be aware that this method will load the sql for any invocation of synchdb, reset, etc. in addition to loading data for the test runner -- so you won't be able to have different data for different test cases, and you'd have to remove files before a reset if you didn't want them loading back onto your production server.\n[1] http://www.sqlite.org/sqlite.html\n[2] http://dev.mysql.com/doc/refman/5.1/en/mysqldump.html\n[3] http://www.postgresql.org/docs/8.1/static/backup.html#BACKUP-DUMP\n", "You may need to look into defining a custom test runner. There's some info here: https://docs.djangoproject.com/en/dev/topics/testing/advanced/#other-testing-frameworks\nBasically I think you can just copy the default test runner from django.test.simple.run_tests and then modify it to suit your needs.\nI've not done this before, but from my understanding that would be the way to customize this.\n" ]
[ 8, 1 ]
[ "Fixtures are the best option. Have you tried using ./manage.py dumpdata to create a fixture from your current database? I have not seen that fail on complex models, but I guess it's possible.\nAssuming you're using mysql, you should be able to script this by using mysqldump.\n" ]
[ -1 ]
[ "django", "django_testing", "python" ]
stackoverflow_0001979692_django_django_testing_python.txt
Q: How to get msn contact list with Python? How can I get msn contact list with a Python script having username and password? A: There are lots and lots and lots of MSN client modules for Python.
How to get msn contact list with Python?
How can I get msn contact list with a Python script having username and password?
[ "There are lots and lots and lots of MSN client modules for Python.\n" ]
[ 1 ]
[]
[]
[ "msn", "python" ]
stackoverflow_0002589480_msn_python.txt
Q: Using Complex datatype with python SUDS client I am trying to call webservice from python client using SUDS. When I call a function with a complex data type as input parameter, it is not passed correctly, but complex data type is getting returned correctly froma webservice call. Webservice Type: Soap Binding 1.1 Document/Literal Webserver: Weblogic 10.3 Python Version: 2.6.5, SUDS version: 0.3.9 here is the code I am using: Python Client: from suds.client import Client url = 'http://192.168.1.3:7001/WebServiceSecurityOWSM-simple_ws-context-root/SimpleServicePort?WSDL' client = Client(url) print client #simple function with no operation on input... result = client.service.sopHello() print result result = client.service.add10(10) print result params = client.factory.create('paramBean') print params params.intval = 10 params.longval = 20 params.strval = 'string value' #print "params" print params try: result = client.service.printParamBean(params) print result except WebFault, e: print e try: result = client.service.modifyParamBean(params) print result except WebFault, e: print e print params webservice java class: package simple_ws; import javax.jws.Oneway; import javax.jws.WebMethod; import javax.jws.WebService; import javax.jws.soap.SOAPBinding; public class SimpleService { public SimpleService() { } public void sopHello(int i) { System.out.println("sopHello: hello"); } public int add10(int i) { System.out.println("add10:"); return 10+i; } public void printParamBean(ParamBean pb) { System.out.println(pb); } public ParamBean modifyParamBean(ParamBean pb) { System.out.println(pb); pb.setIntval(pb.getIntval()+10); pb.setStrval(pb.getStrval()+"blah blah"); pb.setLongval(pb.getLongval()+200); return pb; } } and the bean Class: package simple_ws; public class ParamBean { int intval; String strval; long longval; public void setIntval(int intval) { this.intval = intval; } public int getIntval() { return intval; } public void setStrval(String strval) { this.strval = strval; } public String getStrval() { return strval; } public void setLongval(long longval) { this.longval = longval; } public long getLongval() { return longval; } public String toString() { String stri = "\nInt val:" +intval; String strstr = "\nstrval val:" +strval; String strl = "\nlong val:" +longval; return stri+strstr+strl; } } so, as issue is like this: on call: client.service.printParamBean(params) in python client, output on server side is: Int val:0 strval val:null long val:0 but on call: client.service.modifyParamBean(params) Client output is: (reply){ intval = 10 longval = 200 strval = "nullblah blah" } What am i doing wrong here?? A: From the looks of it the server-side operation printParamBean is only printing what you're passing it, but is not returning anything. Compared to modifyParamBean which is both printing and returning value. Could this be your problem? I surmise that renaming (strictly for the sake of clarity) printParamBean to getParamBean and having it return what you passed it, might do what you're expecting.
Using Complex datatype with python SUDS client
I am trying to call webservice from python client using SUDS. When I call a function with a complex data type as input parameter, it is not passed correctly, but complex data type is getting returned correctly froma webservice call. Webservice Type: Soap Binding 1.1 Document/Literal Webserver: Weblogic 10.3 Python Version: 2.6.5, SUDS version: 0.3.9 here is the code I am using: Python Client: from suds.client import Client url = 'http://192.168.1.3:7001/WebServiceSecurityOWSM-simple_ws-context-root/SimpleServicePort?WSDL' client = Client(url) print client #simple function with no operation on input... result = client.service.sopHello() print result result = client.service.add10(10) print result params = client.factory.create('paramBean') print params params.intval = 10 params.longval = 20 params.strval = 'string value' #print "params" print params try: result = client.service.printParamBean(params) print result except WebFault, e: print e try: result = client.service.modifyParamBean(params) print result except WebFault, e: print e print params webservice java class: package simple_ws; import javax.jws.Oneway; import javax.jws.WebMethod; import javax.jws.WebService; import javax.jws.soap.SOAPBinding; public class SimpleService { public SimpleService() { } public void sopHello(int i) { System.out.println("sopHello: hello"); } public int add10(int i) { System.out.println("add10:"); return 10+i; } public void printParamBean(ParamBean pb) { System.out.println(pb); } public ParamBean modifyParamBean(ParamBean pb) { System.out.println(pb); pb.setIntval(pb.getIntval()+10); pb.setStrval(pb.getStrval()+"blah blah"); pb.setLongval(pb.getLongval()+200); return pb; } } and the bean Class: package simple_ws; public class ParamBean { int intval; String strval; long longval; public void setIntval(int intval) { this.intval = intval; } public int getIntval() { return intval; } public void setStrval(String strval) { this.strval = strval; } public String getStrval() { return strval; } public void setLongval(long longval) { this.longval = longval; } public long getLongval() { return longval; } public String toString() { String stri = "\nInt val:" +intval; String strstr = "\nstrval val:" +strval; String strl = "\nlong val:" +longval; return stri+strstr+strl; } } so, as issue is like this: on call: client.service.printParamBean(params) in python client, output on server side is: Int val:0 strval val:null long val:0 but on call: client.service.modifyParamBean(params) Client output is: (reply){ intval = 10 longval = 200 strval = "nullblah blah" } What am i doing wrong here??
[ "From the looks of it the server-side operation printParamBean is only printing what you're passing it, but is not returning anything. Compared to modifyParamBean which is both printing and returning value. Could this be your problem? \nI surmise that renaming (strictly for the sake of clarity) printParamBean to getParamBean and having it return what you passed it, might do what you're expecting.\n" ]
[ 0 ]
[]
[]
[ "python", "suds", "web_services" ]
stackoverflow_0002588768_python_suds_web_services.txt
Q: How do I sort this list in Python, if my date is in a String? [{'date': '2010-04-01', 'people': 1047, 'hits': 4522}, {'date': '2010-04-03', 'people': 617, 'hits': 2582}, {'date': '2010-04-02', 'people': 736, 'hits': 3277}] Suppose I have this list. How do I sort by "date", which is an item in the dictionary. But, "date" is a string... A: .sort(key=lambda x: datetime.datetime.strptime(x['date'], '%Y-%m-%d')) A: Fortunately, ISO format dates, which seems to be what you have here, sort perfectly well as strings! So you need nothing fancy: import operator yourlistofdicts.sort(key=operator.itemgetter('date')) A: Satoru.Logic's solution is clean and simple. But, per Alex's post, you don't need to manipulate the date string to get the sort order right...so lose the .split('-') This code will suffice: records.sort(key=lambda x:x['date']) A: In python 2.6 you can use soerted w/operator.itemgetter. Since date is YYYY-MM-DD it is sorted even though its a string cause its largest to smallest - i use that format all the time for this reason >>> import operator >>> l = [{'date': '2010-04-01','people': 1047, 'hits': 4522}, {'date': '2010-04-03', 'people': 617, 'hits': 2582}, {'date': '2010-04-02', 'people': 736, 'hits': 3277}] >>> sorted( l, key = operator.itemgetter('date') ) [{'date': '2010-04-01', 'hits': 4522, 'people': 1047}, {'date': '2010-04-02', 'hits': 3277, 'people': 736}, {'date': '2010-04-03', 'hits': 2582, 'people': 617}] A: records = [ {'date': '2010-04-01', 'people': 1047, 'hits': 4522}, {'date': '2010-04-03', 'people': 617, 'hits': 2582}, {'date': '2010-04-02', 'people': 736, 'hits': 3277} ] records.sort(key=lambda x: x['date'].split('-'))
How do I sort this list in Python, if my date is in a String?
[{'date': '2010-04-01', 'people': 1047, 'hits': 4522}, {'date': '2010-04-03', 'people': 617, 'hits': 2582}, {'date': '2010-04-02', 'people': 736, 'hits': 3277}] Suppose I have this list. How do I sort by "date", which is an item in the dictionary. But, "date" is a string...
[ ".sort(key=lambda x: datetime.datetime.strptime(x['date'], '%Y-%m-%d'))\n\n", "Fortunately, ISO format dates, which seems to be what you have here, sort perfectly well as strings! So you need nothing fancy:\nimport operator\nyourlistofdicts.sort(key=operator.itemgetter('date'))\n\n", "Satoru.Logic's solution is clean and simple. But, per Alex's post, you don't need to manipulate the date string to get the sort order right...so lose the .split('-') \nThis code will suffice:\nrecords.sort(key=lambda x:x['date'])\n\n", "In python 2.6 you can use soerted w/operator.itemgetter.\nSince date is YYYY-MM-DD it is sorted even though its a string cause its largest to smallest - i use that format all the time for this reason \n>>> import operator\n>>> l = [{'date': '2010-04-01','people': 1047, 'hits': 4522}, \n {'date': '2010-04-03', 'people': 617, 'hits': 2582}, \n {'date': '2010-04-02', 'people': 736, 'hits': 3277}]\n>>> sorted( l, key = operator.itemgetter('date') )\n[{'date': '2010-04-01', 'hits': 4522, 'people': 1047}, {'date': '2010-04-02', 'hits': 3277, 'people': 736}, {'date': '2010-04-03', 'hits': 2582, 'people': 617}]\n\n", "records = [\n {'date': '2010-04-01', 'people': 1047, 'hits': 4522}, \n {'date': '2010-04-03', 'people': 617, 'hits': 2582}, \n {'date': '2010-04-02', 'people': 736, 'hits': 3277}\n ]\nrecords.sort(key=lambda x: x['date'].split('-'))\n\n" ]
[ 45, 27, 18, 4, 2 ]
[]
[]
[ "dictionary", "list", "python" ]
stackoverflow_0002589479_dictionary_list_python.txt
Q: Creating a method that is simultaneously an instance and class method In Python, I'd like to be able to create a function that behaves both as a class function and an instance method, but with the ability to change behaviors. The use case for this is for a set of serializable objects and types. As an example: >>> class Thing(object): #... >>> Thing.to_json() 'A' >>> Thing().to_json() 'B' I know that given the definition of classmethod() in funcobject.c in the Python source, this looks like it'd be simple with a C module. Is there a way to do this from within python? Thanks! With the hint of descriptors, I was able to do it with the following code: class combomethod(object): def __init__(self, method): self.method = method def __get__(self, obj=None, objtype=None): @functools.wraps(self.method) def _wrapper(*args, **kwargs): if obj is not None: return self.method(obj, *args, **kwargs) else: return self.method(objtype, *args, **kwargs) return _wrapper Thank you Alex! A: Sure, you just need to define your own descriptor type. There's an excellent tutorial on Python descriptors here.
Creating a method that is simultaneously an instance and class method
In Python, I'd like to be able to create a function that behaves both as a class function and an instance method, but with the ability to change behaviors. The use case for this is for a set of serializable objects and types. As an example: >>> class Thing(object): #... >>> Thing.to_json() 'A' >>> Thing().to_json() 'B' I know that given the definition of classmethod() in funcobject.c in the Python source, this looks like it'd be simple with a C module. Is there a way to do this from within python? Thanks! With the hint of descriptors, I was able to do it with the following code: class combomethod(object): def __init__(self, method): self.method = method def __get__(self, obj=None, objtype=None): @functools.wraps(self.method) def _wrapper(*args, **kwargs): if obj is not None: return self.method(obj, *args, **kwargs) else: return self.method(objtype, *args, **kwargs) return _wrapper Thank you Alex!
[ "Sure, you just need to define your own descriptor type. There's an excellent tutorial on Python descriptors here.\n" ]
[ 8 ]
[]
[]
[ "methods", "python" ]
stackoverflow_0002589690_methods_python.txt
Q: Command-line input causes SyntaxError I have a simple Python question that I'm having brain freeze on. This code snippet works. But when I substitue "258 494-3929" with phoneNumber, I get the following error below: # Compare phone number phone_pattern = '^\d{3} ?\d{3}-\d{4}$' # phoneNumber = str(input("Please enter a phone number: ")) if re.search(phone_pattern, "258 494-3929"): print "Pattern matches" else: print "Pattern doesn't match!" Pattern does not match Please enter a phone number: 258 494-3929 Traceback (most recent call last): File "pattern_match.py", line 16, in <module> phoneNumber = str(input("Please enter a phone number: ")) File "<string>", line 1 258 494-3929 ^ SyntaxError: invalid syntax C:\Users\Developer\Documents\PythonDemo> By the way, I did import re and tried using rstrip in case of the \n What else could I be missing? A: You should use raw_input instead of input, and you don't have to call str, because this function returns a string itself: phoneNumber = raw_input("Please enter a phone number: ") A: In Python version 2.x, input() does two things: Reads a string of data. (You want this.) Then it evaluates the string of data as if it were a Python expression. (This part is causing the error.) The function raw_input() is better in this situation because it does #1 above but not #2. If you change: input("Please enter a phone number: ") to read: raw_input("Please enter a phone number: ") you'll eliminate the error of the phone number not being a valid Python expression. The input() function has tripped up so many people learning Python that starting with Python versions 3.x, the designers of the language removed the extra evaluation step. This makes input() in versions 3.x behave the same as raw_input() in versions 2.x. See also a helpful wikibooks article. A: The input() function actually evaluates the input that's typed into it: >>> print str(input("input: ")) input: 258238 258238 >>> print str(input("input: ")) input: 3**3 + 4 31 It's trying to evaluate '258 494-3929' which is invalid Python. Use sys.stdin.readline().strip() to do your read. A: input() calls eval(raw_input(prompt)), so you want phoneNumber = raw_input("Please enter a phone number: ").strip() See also http://docs.python.org/library/functions.html#input and http://docs.python.org/library/functions.html#raw_input
Command-line input causes SyntaxError
I have a simple Python question that I'm having brain freeze on. This code snippet works. But when I substitue "258 494-3929" with phoneNumber, I get the following error below: # Compare phone number phone_pattern = '^\d{3} ?\d{3}-\d{4}$' # phoneNumber = str(input("Please enter a phone number: ")) if re.search(phone_pattern, "258 494-3929"): print "Pattern matches" else: print "Pattern doesn't match!" Pattern does not match Please enter a phone number: 258 494-3929 Traceback (most recent call last): File "pattern_match.py", line 16, in <module> phoneNumber = str(input("Please enter a phone number: ")) File "<string>", line 1 258 494-3929 ^ SyntaxError: invalid syntax C:\Users\Developer\Documents\PythonDemo> By the way, I did import re and tried using rstrip in case of the \n What else could I be missing?
[ "You should use raw_input instead of input, and you don't have to call str, because this function returns a string itself:\nphoneNumber = raw_input(\"Please enter a phone number: \")\n\n", "In Python version 2.x, input() does two things:\n\nReads a string of data. (You want this.)\nThen it evaluates the string of data as if it were a Python expression. (This part is causing the error.)\n\nThe function raw_input() is better in this situation because it does #1 above but not #2.\nIf you change:\ninput(\"Please enter a phone number: \")\n\nto read:\nraw_input(\"Please enter a phone number: \")\n\nyou'll eliminate the error of the phone number not being a valid Python expression.\nThe input() function has tripped up so many people learning Python that starting with Python versions 3.x, the designers of the language removed the extra evaluation step. This makes input() in versions 3.x behave the same as raw_input() in versions 2.x.\nSee also a helpful wikibooks article.\n", "The input() function actually evaluates the input that's typed into it:\n>>> print str(input(\"input: \"))\ninput: 258238\n258238\n>>> print str(input(\"input: \"))\ninput: 3**3 + 4\n31\n\nIt's trying to evaluate '258 494-3929' which is invalid Python.\nUse sys.stdin.readline().strip() to do your read.\n", "input() calls eval(raw_input(prompt)), so you want phoneNumber = raw_input(\"Please enter a phone number: \").strip()\nSee also http://docs.python.org/library/functions.html#input and http://docs.python.org/library/functions.html#raw_input\n" ]
[ 17, 10, 4, 2 ]
[]
[]
[ "command_line", "input", "python", "python_2.x" ]
stackoverflow_0002589309_command_line_input_python_python_2.x.txt
Q: FOSS HTML to PDF in Python, .Net or command line? I have google as much as I possible, checked stackoverflow several times, and yet I can not find a good html to pdf converter that can handle css. Is there a free and open source solution (even for commercial usage)? There are many solutions, with huge variety of price ranges, but I was looking for something open source and free. I have tried PISA for Python and it works fairly well, but is not free for commercial usage. Is there anything for .Net? I have not had success with iTextSharp. A: I've wkhtmltopdf used on a couple of projects. http://code.google.com/p/wkhtmltopdf/. It uses the webkit rendering engine, which powers the Safari browser. You'll get completely up to date rendering just like a web browser with CSS and all. Oh, and it's open source. A: I haven't found a good FOSS solution, but I can say that PrinceXML works very well, provides quite a bit of functionality through the command-line and is priced very reasonably. IIRC, the free version appends a cover page to each PDF you produce, which may or may not be a deal-killer for you, but you should definitely check it out. A: The fact that you're asking about C#/.NET makes me guess you're on a Windows platform, so this may not work for you, but I've had decent success using html2ps in conjunction with ps2pdf: #! /bin/sh TEMPDIR="/tmp" html2ps -u $1 > $TEMPDIR'temp.ps' ps2pdf $TEMPDIR'temp.ps' $2 That does handle CSS (at least all the CSS I've thrown at it so far) though there are some limitations if I remember right with regards to some in-line styles. NOTE: I think these are both available on Windows via Cygwin, if that's an acceptable solution for you. A: You can also try different approach like using virtual printers. A: I have had stunning success using the 'PISA' xhtml2pdf tool found here: http://www.xhtml2pdf.com/ Don't be scared off by the 'xhtml' part, it accepts a large range of html input, and produces PDFs according to CSS, including CSS print extensions.
FOSS HTML to PDF in Python, .Net or command line?
I have google as much as I possible, checked stackoverflow several times, and yet I can not find a good html to pdf converter that can handle css. Is there a free and open source solution (even for commercial usage)? There are many solutions, with huge variety of price ranges, but I was looking for something open source and free. I have tried PISA for Python and it works fairly well, but is not free for commercial usage. Is there anything for .Net? I have not had success with iTextSharp.
[ "I've wkhtmltopdf used on a couple of projects. http://code.google.com/p/wkhtmltopdf/. It uses the webkit rendering engine, which powers the Safari browser. You'll get completely up to date rendering just like a web browser with CSS and all.\nOh, and it's open source.\n", "I haven't found a good FOSS solution, but I can say that PrinceXML works very well, provides quite a bit of functionality through the command-line and is priced very reasonably. IIRC, the free version appends a cover page to each PDF you produce, which may or may not be a deal-killer for you, but you should definitely check it out.\n", "The fact that you're asking about C#/.NET makes me guess you're on a Windows platform, so this may not work for you, but I've had decent success using html2ps in conjunction with ps2pdf: \n#! /bin/sh\n\nTEMPDIR=\"/tmp\"\nhtml2ps -u $1 > $TEMPDIR'temp.ps'\nps2pdf $TEMPDIR'temp.ps' $2\n\nThat does handle CSS (at least all the CSS I've thrown at it so far) though there are some limitations if I remember right with regards to some in-line styles.\nNOTE: I think these are both available on Windows via Cygwin, if that's an acceptable solution for you.\n", "You can also try different approach like using virtual printers.\n", "I have had stunning success using the 'PISA' xhtml2pdf tool found here: http://www.xhtml2pdf.com/\nDon't be scared off by the 'xhtml' part, it accepts a large range of html input, and produces PDFs according to CSS, including CSS print extensions.\n" ]
[ 5, 2, 1, 0, 0 ]
[]
[]
[ ".net", "c#", "html_to_pdf", "python" ]
stackoverflow_0000597348_.net_c#_html_to_pdf_python.txt
Q: GAE and Django: What are the benefits? Currently I have a website on the Google App Engine written in Google's webapp framework. What I want to know is what are the benefits of converting my app to run with django? And what are the downsides? Also how did you guys code your GAE apps? Did you use webapp or django? Or did you go an entirely different route and use the Java api? Thanks A: With Django on GAE, you get all the benefits (and also the non-benefits) of GAE. The benefits are mainly automatic scalability and high reliability at a very low cost. You may want to start by checking out the following: Stack Overflow: Django on Google App Engine Stack Overflow: Django and App Engine Google Code: Running Django on Google App Engine YouTube: Google I/O 2008 - Python, Django, and App Engine Django on Google App Engine in 13 simple steps Google - Why App Engine? A: As it turns out, I asked this same question: Why use Django on Google App Engine? It mostly resolved to two items: In functionality where webapp and Django overlap, Django tends to be a bit nicer and/or more flexible. If you were to later want to move away from GAE, Django is a porting goal. My question (in combination with the wealth of information Daniel Vassallo provided) should answer your question completely. A: GAE is a great tool for new and small projects, that do not require a relational database. I use a range of web hosting solutions. 1) I built www.gaiagps.com on the App Engine, because it was just some brochureware, and a tiny key-value store for the blog part. 2) My colleague also built a web crawler on GAE, because it was just some simple Python scripts that collected web pages. That app actually sends the data over to EC2 though, where more work is done. 3) I host www.trailbehind.com on EC2 because it uses a geo-database (PostGIS) which you would basically have to implement yourself on App Engine. 4) I host TRAC and SVN on WebFaction, because it's off-the-shelf for any slice there. If I need to do a site in a couple of days, I use GAE. If it's a large or existing project, or has a funky database, I use something else. A: I've recently changed my development from webapp to django (using app-engine-patch b/c they have added more features). Check out app-engine-patch here: http://code.google.com/p/app-engine-patch/ I really liked how simple webapp was to use and it had all the tools I needed for a while. However when it came to adding user accounts on to my site I found that I either had to roll my own system (with sessions etc. which can get complicated on GAE) or use google/gmail accounts with webapp. I didn't want my users to have to sign up for google/gmail first before they signed up with me. Therefore I'm trying out django with app-engine-patch because they have already implemented the user functionality from django and it seems to work just fine. With Django vs. Webapp they both have similar performance, and both offer the automatic scalablity etc. Django has some nifty form validation etc. but i see the user stuff as the biggest difference between the two. Good Luck. A: I did some django/GAE work a last summer (see Plunging into Web Development). The App Engine Patch is a must. The only real problem I ran into was the 1M upload/download limit imposed by GAE. I could upload larger files by using HTTP directly to S3, but I couldn't retrieve them through GAE. I hope they've lifted this restriction since then. A: If you are looking other GAE CMS frameworks besides Django, take a look at Vosao. It is a Java CMS framework which uses Velocity for templates. The framework is still in alpha and is under heavy development. The current version (0.2.3) is stable and highly functional. You can see an example of a working Vosao site on my personal domain. A: I prefer webapp. It scales better according to Google and seems to better integrated with the App Engine infrastructure. Plus it's more lightweight. A: try kay-framework if you are looking for framework specifically designed for google app engine.
GAE and Django: What are the benefits?
Currently I have a website on the Google App Engine written in Google's webapp framework. What I want to know is what are the benefits of converting my app to run with django? And what are the downsides? Also how did you guys code your GAE apps? Did you use webapp or django? Or did you go an entirely different route and use the Java api? Thanks
[ "With Django on GAE, you get all the benefits (and also the non-benefits) of GAE. The benefits are mainly automatic scalability and high reliability at a very low cost.\nYou may want to start by checking out the following:\n\nStack Overflow: Django on Google App Engine \nStack Overflow: Django and App Engine\nGoogle Code: Running Django on Google App Engine\nYouTube: Google I/O 2008 - Python, Django, and App Engine\nDjango on Google App Engine in 13 simple steps\nGoogle - Why App Engine?\n\n", "As it turns out, I asked this same question:\nWhy use Django on Google App Engine?\nIt mostly resolved to two items:\n\nIn functionality where webapp and Django overlap, Django tends to be a bit nicer and/or more flexible.\nIf you were to later want to move away from GAE, Django is a porting goal.\n\nMy question (in combination with the wealth of information Daniel Vassallo provided) should answer your question completely.\n", "GAE is a great tool for new and small projects, that do not require a relational database. I use a range of web hosting solutions. \n1) I built www.gaiagps.com on the App Engine, because it was just some brochureware, and a tiny key-value store for the blog part.\n2) My colleague also built a web crawler on GAE, because it was just some simple Python scripts that collected web pages. That app actually sends the data over to EC2 though, where more work is done.\n3) I host www.trailbehind.com on EC2 because it uses a geo-database (PostGIS) which you would basically have to implement yourself on App Engine.\n4) I host TRAC and SVN on WebFaction, because it's off-the-shelf for any slice there.\nIf I need to do a site in a couple of days, I use GAE. If it's a large or existing project, or has a funky database, I use something else.\n", "I've recently changed my development from webapp to django (using app-engine-patch b/c they have added more features). Check out app-engine-patch here:\nhttp://code.google.com/p/app-engine-patch/\nI really liked how simple webapp was to use and it had all the tools I needed for a while. However when it came to adding user accounts on to my site I found that I either had to roll my own system (with sessions etc. which can get complicated on GAE) or use google/gmail accounts with webapp. \nI didn't want my users to have to sign up for google/gmail first before they signed up with me.\nTherefore I'm trying out django with app-engine-patch because they have already implemented the user functionality from django and it seems to work just fine.\nWith Django vs. Webapp they both have similar performance, and both offer the automatic scalablity etc.\nDjango has some nifty form validation etc. but i see the user stuff as the biggest difference between the two.\nGood Luck.\n", "I did some django/GAE work a last summer (see Plunging into Web Development). The App Engine Patch is a must.\nThe only real problem I ran into was the 1M upload/download limit imposed by GAE. I could upload larger files by using HTTP directly to S3, but I couldn't retrieve them through GAE. I hope they've lifted this restriction since then. \n", "If you are looking other GAE CMS frameworks besides Django, take a look at Vosao. It is a Java CMS framework which uses Velocity for templates. The framework is still in alpha and is under heavy development. The current version (0.2.3) is stable and highly functional. \nYou can see an example of a working Vosao site on my personal domain.\n", "I prefer webapp. It scales better according to Google and seems to better integrated with the App Engine infrastructure. Plus it's more lightweight.\n", "try kay-framework if you are looking for framework specifically designed for google app engine.\n" ]
[ 7, 5, 2, 1, 1, 1, 1, 0 ]
[]
[]
[ "django", "google_app_engine", "python" ]
stackoverflow_0002034684_django_google_app_engine_python.txt
Q: Histogram in Matplotlib with input file I wish to make a Histogram in Matplotlib from an input file containing the raw data (.txt). I am facing issues in referring to the input file. I guess it should be a rather small program. Any Matplotlib gurus, any help ? I am not asking for the code, some inputs should put me on the right way ! A: i would recommend using 'loadtxt' which is actually in the NumPy library. There are related functions in Matplotlib (csv2rec) but Matplotlib is actually standardizing on loadtxt. Here's how it works: from matplotlib import pyplot as PLT with open('name_of_your_file.csv') as f: v = NP.loadtxt(f, delimiter=",", dtype='float', comments="#", skiprows=1, usecols=None) 'v', the object returned from 'loadtxt', is an n x m NumPy array. 'loadtxt' accepts either a file or a file descriptor. The instance above has most of the method signature. 'skiprows' is an integer that specifies the number of rows counting from the top that you want to skip; it's common to set it to "1" to skip the header row; 'usecols' begins at '0' and is a list reciting the columns you want to include ('None' is the default, and means 'include all'). The other parameters work as expected. To plot a histogram from this data: from matplotlib import pyplot as PLT v_hist = NP.ravel(v) # 'flatten' v fig = PLT.figure() ax1 = fig.add_subplot(111) n, bins, patches = ax1.hist(v_hist, bins=50, normed=1, facecolor='green') PLT.show() A: You can't directly tell matplotlib to make a histogram from an input file - you'll need to open the file yourself and get the data from it. How you'd do that depends on the format of the file - if it's just a file with a number on each line, you can just go through each line, strip() spaces and newlines, and use float() to convert it to a number.
Histogram in Matplotlib with input file
I wish to make a Histogram in Matplotlib from an input file containing the raw data (.txt). I am facing issues in referring to the input file. I guess it should be a rather small program. Any Matplotlib gurus, any help ? I am not asking for the code, some inputs should put me on the right way !
[ "i would recommend using 'loadtxt' which is actually in the NumPy library. There are related functions in Matplotlib (csv2rec) but Matplotlib is actually standardizing on loadtxt.\nHere's how it works:\nfrom matplotlib import pyplot as PLT\n\nwith open('name_of_your_file.csv') as f:\n v = NP.loadtxt(f, delimiter=\",\", dtype='float', comments=\"#\", skiprows=1, usecols=None)\n\n'v', the object returned from 'loadtxt', is an n x m NumPy array.\n'loadtxt' accepts either a file or a file descriptor. The instance above has most of the method signature.\n'skiprows' is an integer that specifies the number of rows counting from the top that you want to skip; it's common to set it to \"1\" to skip the header row; 'usecols' begins at '0' and is a list reciting the columns you want to include ('None' is the default, and means 'include all'). The other parameters work as expected. \nTo plot a histogram from this data:\nfrom matplotlib import pyplot as PLT\n\nv_hist = NP.ravel(v) # 'flatten' v\nfig = PLT.figure()\nax1 = fig.add_subplot(111)\n\nn, bins, patches = ax1.hist(v_hist, bins=50, normed=1, facecolor='green')\nPLT.show()\n\n", "You can't directly tell matplotlib to make a histogram from an input file - you'll need to open the file yourself and get the data from it. How you'd do that depends on the format of the file - if it's just a file with a number on each line, you can just go through each line, strip() spaces and newlines, and use float() to convert it to a number.\n" ]
[ 9, 0 ]
[]
[]
[ "histogram", "matplotlib", "python" ]
stackoverflow_0002590328_histogram_matplotlib_python.txt
Q: MySQLdb not INSERTING, _mysql does fine Okay, I log onto the MySQL command-line client as root. I then open or otherwise run a python app using the MySQLdb module as root. When I check the results using python (IDLE), everything looks fine. When I use the MySQL command-line client, no INSERT has occurred. If I change things around to _mysql instead of MySQLdb, everything works fine. I'd appreciate any clarification(s). "Works" until IDLE/Virtual machine is reset: import MySQLdb db = MySQLdb.connect(user='root', passwd='*******',db='test') cursor = db.cursor() cursor.execute("""INSERT INTO test VALUES ('somevalue');""",) Works: import _mysql db = _mysql.connect(user='root', passwd='*******',db='test') db.query("INSERT INTO test VALUES ('somevalue');") System info: Intel x86 WinXP Python 2.5 MySQL 5.1.41 MySQL-Python 1.2.2 A: You can use db.commit() to submit data or set db.autocommit() after _mysql.connect(...) to autocommit requests. A: I think they use different autocommit settings. Use commit() after inserting data.
MySQLdb not INSERTING, _mysql does fine
Okay, I log onto the MySQL command-line client as root. I then open or otherwise run a python app using the MySQLdb module as root. When I check the results using python (IDLE), everything looks fine. When I use the MySQL command-line client, no INSERT has occurred. If I change things around to _mysql instead of MySQLdb, everything works fine. I'd appreciate any clarification(s). "Works" until IDLE/Virtual machine is reset: import MySQLdb db = MySQLdb.connect(user='root', passwd='*******',db='test') cursor = db.cursor() cursor.execute("""INSERT INTO test VALUES ('somevalue');""",) Works: import _mysql db = _mysql.connect(user='root', passwd='*******',db='test') db.query("INSERT INTO test VALUES ('somevalue');") System info: Intel x86 WinXP Python 2.5 MySQL 5.1.41 MySQL-Python 1.2.2
[ "You can use db.commit() to submit data or set db.autocommit() after _mysql.connect(...) to autocommit requests.\n", "I think they use different autocommit settings. Use commit() after inserting data.\n" ]
[ 17, 4 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0002590480_mysql_python.txt
Q: How to define and use Python generators appropriately I want to define a generator from a list that will output the elements one at a time, then use this generator object in an appropriate manner. a = ["Hello", "world", "!"] b = (x for x in a) c = next(b, None) while c != None: print c, c = next(b, None) Is there anything wrong or improvable with the while approach here? Is there a way to avoid having to assign 'c' before the loop? Thanks! A: Why would you use a while loop? In Python, for loops are absolutely designed for this: a = ["Hello", "world", "!"] b = (x for x in a) for c in b: print c, If you are stuck on a while implementation for whatever reason, your current implementation is probably the best you can do, but it's a bit clunky, don't you think? A: Clarification: you meant generator expressions not generators -- the latter is a function definition that contains at least one yield statement/expression. agreed with the earlier poster... you should be using for loops for almost everything. i rarely use while loops, which are relegated to simple counters or servers running infinite loops. :-) you can also put the genexp on the same line as the for loop... a = ["Hello", "world", "!"] for c in (x for x in a): print c, ...since the genexp can't be reused. however, it doesn't look as readable. also, this defeats the purpose of this exercise. why not just iterate over a itself? for c in ["Hello", "world", "!"]: print c, you've already used up memory to make the list; why create a genexp when it's not nec?
How to define and use Python generators appropriately
I want to define a generator from a list that will output the elements one at a time, then use this generator object in an appropriate manner. a = ["Hello", "world", "!"] b = (x for x in a) c = next(b, None) while c != None: print c, c = next(b, None) Is there anything wrong or improvable with the while approach here? Is there a way to avoid having to assign 'c' before the loop? Thanks!
[ "Why would you use a while loop? In Python, for loops are absolutely designed for this:\na = [\"Hello\", \"world\", \"!\"]\nb = (x for x in a)\nfor c in b:\n print c,\n\nIf you are stuck on a while implementation for whatever reason, your current implementation is probably the best you can do, but it's a bit clunky, don't you think?\n", "Clarification: you meant generator expressions not generators -- the latter is a function definition that contains at least one yield statement/expression.\nagreed with the earlier poster... you should be using for loops for almost everything. i rarely use while loops, which are relegated to simple counters or servers running infinite loops. :-)\nyou can also put the genexp on the same line as the for loop...\na = [\"Hello\", \"world\", \"!\"]\nfor c in (x for x in a):\n print c,\n\n...since the genexp can't be reused. however, it doesn't look as readable. also, this defeats the purpose of this exercise. why not just iterate over a itself?\nfor c in [\"Hello\", \"world\", \"!\"]:\n print c,\n\nyou've already used up memory to make the list; why create a genexp when it's not nec?\n" ]
[ 7, 3 ]
[]
[]
[ "generator", "python", "while_loop" ]
stackoverflow_0002589812_generator_python_while_loop.txt
Q: How to localize static content in database with Django My app has tables for languages and countries (actually django-countries at the moment, but open for suggestions). The tables are populated when I initialize the database and remain static after that. What would be the ideal localization mechanism for the contents of these tables, so that I can show the country and language names to users in their chosen site language? I'm aware of projects like django-multilingual and transdb, but IMO they are more suitable for dynamic content, i.e. stuff that's supposed to be modified. Please englighten me! A: Maybe I'm missing something here, but why just not use [un]gettext, i.e. {% trans lang_from_db %} and _(lang_from_db)? Alternatively, hardcode language names translated in their own language into database, e.g "English", "Svenska", "Suomi", etc.
How to localize static content in database with Django
My app has tables for languages and countries (actually django-countries at the moment, but open for suggestions). The tables are populated when I initialize the database and remain static after that. What would be the ideal localization mechanism for the contents of these tables, so that I can show the country and language names to users in their chosen site language? I'm aware of projects like django-multilingual and transdb, but IMO they are more suitable for dynamic content, i.e. stuff that's supposed to be modified. Please englighten me!
[ "Maybe I'm missing something here, but why just not use [un]gettext, i.e. {% trans lang_from_db %} and _(lang_from_db)?\nAlternatively, hardcode language names translated in their own language into database, e.g \"English\", \"Svenska\", \"Suomi\", etc.\n" ]
[ 0 ]
[]
[]
[ "django", "localization", "python" ]
stackoverflow_0002590632_django_localization_python.txt
Q: Matplotlib: plotting discrete values I am trying to plot the following ! from numpy import * from pylab import * import random for x in range(1,500): y = random.randint(1,25000) print(x,y) plot(x,y) show() However, I keep getting a blank graph (?). Just to make sure that the program logic is correct I added the code print(x,y), just the confirm that (x,y) pairs are being generated. (x,y) pairs are being generated, but there is no plot, I keep getting a blank graph. Any help ? A: First of all, I have sometimes had better success by doing from matplotlib import pyplot instead of using pylab, although this shouldn't make a difference in this case. I think your actual issue might be that points are being plotted but aren't visible. It may work better to plot all points at once by using a list: xPoints = [] yPoints = [] for x in range(1,500): y = random.randint(1,25000) xPoints.append(x) yPoints.append(y) pyplot.plot(xPoints, yPoints) pyplot.show() To make this even neater, you can use generator expressions: xPoints = range(1,500) yPoints = [random.randint(1,25000) for _ in range(1,500)] pyplot.plot(xPoints, yPoints) pyplot.show()
Matplotlib: plotting discrete values
I am trying to plot the following ! from numpy import * from pylab import * import random for x in range(1,500): y = random.randint(1,25000) print(x,y) plot(x,y) show() However, I keep getting a blank graph (?). Just to make sure that the program logic is correct I added the code print(x,y), just the confirm that (x,y) pairs are being generated. (x,y) pairs are being generated, but there is no plot, I keep getting a blank graph. Any help ?
[ "First of all, I have sometimes had better success by doing\nfrom matplotlib import pyplot\n\ninstead of using pylab, although this shouldn't make a difference in this case.\nI think your actual issue might be that points are being plotted but aren't visible. It may work better to plot all points at once by using a list:\nxPoints = []\nyPoints = []\nfor x in range(1,500):\n y = random.randint(1,25000)\n xPoints.append(x)\n yPoints.append(y)\npyplot.plot(xPoints, yPoints)\npyplot.show()\n\nTo make this even neater, you can use generator expressions:\nxPoints = range(1,500)\nyPoints = [random.randint(1,25000) for _ in range(1,500)]\npyplot.plot(xPoints, yPoints)\npyplot.show()\n\n" ]
[ 5 ]
[]
[]
[ "data_visualization", "matplotlib", "python" ]
stackoverflow_0002590768_data_visualization_matplotlib_python.txt
Q: Configuration problems with django and mod_wsgi I've got problems on getting django to work on apache 2.2 with mod_wsgi. Django is installed and mod_wsgi too. I can even see a 404 page when accessing the path and I can login to django admin. But if I want to install the tagging module I get the following error: Traceback (most recent call last): File "setup.py", line 49, in <module> version_tuple = __import__('tagging').VERSION File "/home/jim/django-tagging/tagging/__init__.py", line 3, in <module> from tagging.managers import ModelTaggedItemManager, TagDescriptor File "/home/jim/django-tagging/tagging/managers.py", line 5, in <module> from django.contrib.contenttypes.models import ContentType File "/usr/lib/python2.5/site-packages/django/contrib/contenttypes/models.py", line 1, in <module> from django.db import models File "/usr/lib/python2.5/site-packages/django/db/__init__.py", line 10, in <module> if not settings.DATABASE_ENGINE: File "/usr/lib/python2.5/site-packages/django/utils/functional.py", line 269, in __getattr__ self._setup() File "/usr/lib/python2.5/site-packages/django/conf/__init__.py", line 40, in _setup self._wrapped = Settings(settings_module) File "/usr/lib/python2.5/site-packages/django/conf/__init__.py", line 75, in __init__ raise ImportError, "Could not import settings '%s' (Is it on sys.path? Does it have syntax errors?): %s" % (self.SETTINGS_MODULE, e) ImportError: Could not import settings 'mysite.settings' (Is it on sys.path? Does it have syntax errors?): No module named mysite.settings My httpd.conf: Alias /media/ /home/jim/django/mysite/media/ <Directory /home/jim/django/mysite/media> Order deny,allow Allow from all </Directory> Alias /admin/media/ "/usr/lib/python2.5/site-packages/django/contrib/admin/media/" <Directory "/usr/lib/python2.5/site-packages/django/contrib/admin/media/"> Order allow,deny Allow from all </Directory> WSGIScriptAlias /dj /home/jim/django/mysite/apache/django.wsgi <Directory /home/jim/django/mysite/apache> Order deny,allow Allow from all </Directory> My django.wsgi: import sys, os sys.path.append('/home/jim/django') sys.path.append('/home/jim/django/mysite') os.chdir('/home/jim/django/mysite') os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings' import django.core.handlers.wsgi application = django.core.handlers.wsgi.WSGIHandler() I try to get this to work since a few days and have read several blogs and answers here on so but nothing worked. Edit: Now I tried it with this blog post and my wsgi file now looks like this: import sys sys.path.insert(0, '/home/jim/django/mysite') sys.path.insert(0, '/home/jim/django') import settings import django.core.management django.core.management.setup_environ(settings) utility = django.core.management.ManagementUtility() command = utility.fetch_command('runserver') command.validate() import django.conf import django.utils django.utils.translation.activate(django.conf.settings.LANGUAGE_CODE) import django.core.handlers.wsgi application = django.core.handlers.wsgi.WSGIHandler() admin is still working, but I'm getting the same error when I try to install the tagging module. A: Have you read Graham Dumpleton's blog post on Django and WSGI? It does a pretty good job of describing some common configuration problems, and specifically touches on mysite.settings vs. settings. UPDATE: Please read Graham Dumpleton's excellent comments below. UPDATE 2: As both Graham and becomingGuru have pointed out, the problem is not with WSGI at all. It is instead a problem with your installation of django-tagging. Take becomingGuru's advice and use pip to install django-tagging. A: First, Since your admin works, the setting with wsgi is good. Don't bother changing/editing it. To ensure that it is not a Apache/mod-wsgi setting problem, you can run the development server from the production machine python manage.py runserver 0:8080 Then point your browser to http://yoursite.com:8080/ You must see exactly the same behaviour. Then, For debugging this problem: On the python shell on your server, try import tagging. Clearly, from your traceback, import tagging is where it is raising an error and thats why, settings cannot be imported. Then, Just delete the package containing tagging, and do a fresh install by the following command, which knows how to install packages, well. . sudo pip install django-tagging
Configuration problems with django and mod_wsgi
I've got problems on getting django to work on apache 2.2 with mod_wsgi. Django is installed and mod_wsgi too. I can even see a 404 page when accessing the path and I can login to django admin. But if I want to install the tagging module I get the following error: Traceback (most recent call last): File "setup.py", line 49, in <module> version_tuple = __import__('tagging').VERSION File "/home/jim/django-tagging/tagging/__init__.py", line 3, in <module> from tagging.managers import ModelTaggedItemManager, TagDescriptor File "/home/jim/django-tagging/tagging/managers.py", line 5, in <module> from django.contrib.contenttypes.models import ContentType File "/usr/lib/python2.5/site-packages/django/contrib/contenttypes/models.py", line 1, in <module> from django.db import models File "/usr/lib/python2.5/site-packages/django/db/__init__.py", line 10, in <module> if not settings.DATABASE_ENGINE: File "/usr/lib/python2.5/site-packages/django/utils/functional.py", line 269, in __getattr__ self._setup() File "/usr/lib/python2.5/site-packages/django/conf/__init__.py", line 40, in _setup self._wrapped = Settings(settings_module) File "/usr/lib/python2.5/site-packages/django/conf/__init__.py", line 75, in __init__ raise ImportError, "Could not import settings '%s' (Is it on sys.path? Does it have syntax errors?): %s" % (self.SETTINGS_MODULE, e) ImportError: Could not import settings 'mysite.settings' (Is it on sys.path? Does it have syntax errors?): No module named mysite.settings My httpd.conf: Alias /media/ /home/jim/django/mysite/media/ <Directory /home/jim/django/mysite/media> Order deny,allow Allow from all </Directory> Alias /admin/media/ "/usr/lib/python2.5/site-packages/django/contrib/admin/media/" <Directory "/usr/lib/python2.5/site-packages/django/contrib/admin/media/"> Order allow,deny Allow from all </Directory> WSGIScriptAlias /dj /home/jim/django/mysite/apache/django.wsgi <Directory /home/jim/django/mysite/apache> Order deny,allow Allow from all </Directory> My django.wsgi: import sys, os sys.path.append('/home/jim/django') sys.path.append('/home/jim/django/mysite') os.chdir('/home/jim/django/mysite') os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings' import django.core.handlers.wsgi application = django.core.handlers.wsgi.WSGIHandler() I try to get this to work since a few days and have read several blogs and answers here on so but nothing worked. Edit: Now I tried it with this blog post and my wsgi file now looks like this: import sys sys.path.insert(0, '/home/jim/django/mysite') sys.path.insert(0, '/home/jim/django') import settings import django.core.management django.core.management.setup_environ(settings) utility = django.core.management.ManagementUtility() command = utility.fetch_command('runserver') command.validate() import django.conf import django.utils django.utils.translation.activate(django.conf.settings.LANGUAGE_CODE) import django.core.handlers.wsgi application = django.core.handlers.wsgi.WSGIHandler() admin is still working, but I'm getting the same error when I try to install the tagging module.
[ "Have you read Graham Dumpleton's blog post on Django and WSGI? It does a pretty good job of describing some common configuration problems, and specifically touches on mysite.settings vs. settings.\nUPDATE: Please read Graham Dumpleton's excellent comments below.\nUPDATE 2: As both Graham and becomingGuru have pointed out, the problem is not with WSGI at all. It is instead a problem with your installation of django-tagging. Take becomingGuru's advice and use pip to install django-tagging.\n", "First,\n\nSince your admin works, the setting with wsgi is good. Don't bother changing/editing it.\n\nTo ensure that it is not a Apache/mod-wsgi setting problem, you can run the development server from the production machine\npython manage.py runserver 0:8080\n\nThen point your browser to\nhttp://yoursite.com:8080/\n\nYou must see exactly the same behaviour.\nThen, \nFor debugging this problem:\n\nOn the python shell on your server, try import tagging. Clearly, from your traceback, import tagging is where it is raising an error and thats why, settings cannot be imported.\nThen, Just delete the package containing tagging, and do a fresh install by the following command, which knows how to install packages, well.\n\n.\nsudo pip install django-tagging\n\n" ]
[ 4, 4 ]
[]
[]
[ "apache", "django", "mod_wsgi", "python" ]
stackoverflow_0002587251_apache_django_mod_wsgi_python.txt
Q: How to read formatted input in python? I want to read from stdin five numbers entered as follows: 3, 4, 5, 1, 8 into seperate variables a,b,c,d & e. How do I do this in python? I tried this: import string a=input() b=a.split(', ') for two integers, but it does not work. I get: Traceback (most recent call last): File "C:\Users\Desktop\comb.py", line 3, in <module> b=a.split(', ') AttributeError: 'tuple' object has no attribute 'split' How to do this? and suppose I have not a fixed but a variable number n integers. Then? A: Use raw_input() instead of input(). # Python 2.5.4 >>> a = raw_input() 3, 4, 5 >>> a '3, 4, 5' >>> b = a.split(', ') >>> b ['3', '4', '5'] >>> [s.strip() for s in raw_input().split(",")] # one liner 3, 4, 5 ['3', '4', '5'] The misleadingly names input function does not do what you'd expect it to. It actually evaluates the input from stdin as python code. In your case it turns out that what you then have is a tuple of numbers in a, all parsed and ready for work, but generally you don't really want to use this curious side effect. Other inputs can cause any number of things to happen. Incidentally, in Python 3 they fixed this, and now the input function does what you'd expect. Two more things: You don't need to import string to do simple string manipulations. Like mjv said, to split a tuple or a list into several variables, you can 'unpack' it. This will not be feasible if you don't know how long the list will be, though. Unpacking: >>> l = (1,2,3,4,5) >>> a,b,c,d,e = l >>> e 5 A: Under Python 2.x only (*) after a = input() a is a tuple with the 5 values readily parsed! A quick way to assign these 5 values is a, b, c, d, e = a (*) with Python version 3.0? or for sure 3.1, input() works more like the raw_input() method of 2.x, which makes it less confusing. (thank you mshsayem to point this out!) A: If you print out a (the variable containing your input) you will find out, that a already contains a tuple. You do not have to split the contents. >>> a = input() 3, 4, 5, 1, 8 >>> print(a) (3, 4, 5, 1, 8) >>> type(a) <type 'tuple'> >>> a[0] 3 >>> len(a) 5
How to read formatted input in python?
I want to read from stdin five numbers entered as follows: 3, 4, 5, 1, 8 into seperate variables a,b,c,d & e. How do I do this in python? I tried this: import string a=input() b=a.split(', ') for two integers, but it does not work. I get: Traceback (most recent call last): File "C:\Users\Desktop\comb.py", line 3, in <module> b=a.split(', ') AttributeError: 'tuple' object has no attribute 'split' How to do this? and suppose I have not a fixed but a variable number n integers. Then?
[ "Use raw_input() instead of input().\n# Python 2.5.4\n>>> a = raw_input()\n3, 4, 5\n>>> a\n'3, 4, 5'\n>>> b = a.split(', ')\n>>> b\n['3', '4', '5']\n>>> [s.strip() for s in raw_input().split(\",\")] # one liner\n3, 4, 5\n['3', '4', '5']\n\nThe misleadingly names input function does not do what you'd expect it to. It actually evaluates the input from stdin as python code.\nIn your case it turns out that what you then have is a tuple of numbers in a, all parsed and ready for work, but generally you don't really want to use this curious side effect. Other inputs can cause any number of things to happen.\nIncidentally, in Python 3 they fixed this, and now the input function does what you'd expect.\nTwo more things:\n\nYou don't need to import string to do simple string manipulations. \nLike mjv said, to split a tuple or a list into several variables, you can 'unpack' it. This will not be feasible if you don't know how long the list will be, though.\n\nUnpacking:\n>>> l = (1,2,3,4,5)\n>>> a,b,c,d,e = l\n>>> e\n5\n\n", "Under Python 2.x only (*)\nafter a = input()\na is a tuple with the 5 values readily parsed! \nA quick way to assign these 5 values is\na, b, c, d, e = a\n\n(*) with Python version 3.0? or for sure 3.1, input() works more like the raw_input() method of 2.x, which makes it less confusing. (thank you mshsayem to point this out!)\n", "If you print out a (the variable containing your input) you will find out, that a already contains a tuple. You do not have to split the contents.\n\n>>> a = input()\n 3, 4, 5, 1, 8\n >>> print(a)\n (3, 4, 5, 1, 8)\n >>> type(a)\n <type 'tuple'>\n >>> a[0]\n 3\n >>> len(a)\n 5\n\n" ]
[ 16, 2, 0 ]
[ "in = eval(input())\n\na, b, c, d, e = in\n\n" ]
[ -3 ]
[ "input", "python" ]
stackoverflow_0001397827_input_python.txt
Q: How do I reverse the direction that my rectangles travel? I am very new at programming as it was only just introduced into my school as a subject and I need some help. I have been given the task to have an animation of three balls (rectangle images) bouncing around the screen and off each other. I have the three balls and the bouncing of the walls all down good, but I don't know how to have them bounce off each other. Any help would be greatly appreciated, my current code is as follows: import pygame import random import sys if __name__ =='__main__': ball_image1 = 'beachball1.jpg' ball_image2 = 'beachball2.jpg' ball_image3 = 'beachball3.jpg' bounce_sound = 'thump.wav' width = 800 top = 600 x = 0 y = 0 background_colour = 0,0,0 caption= 'Bouncing Ball animation' velocity1 = [-1,-1] velocity2 = [-1,1] velocity3 = [1,-1] pygame.init () frame = pygame.display.set_mode ((width, top)) pygame.display.set_caption (caption) ball1= pygame.image.load (ball_image1). convert() ball2= pygame.image.load (ball_image2). convert() ball3= pygame.image.load (ball_image3). convert() ball_boundary_1 = ball2.get_rect (center=(random.randint(50, 750),random.randint(50, 550))) ball_boundary_2 = ball2.get_rect (center=(random.randint(50, 750),random.randint(50, 550))) ball_boundary_3 = ball2.get_rect (center=(random.randint(50, 750),random.randint(50, 550))) sound = pygame.mixer.Sound (bounce_sound) while True: for event in pygame.event.get(): print event if event.type == pygame.QUIT: sys.exit(0) if ball_boundary_1.left < 0 or ball_boundary_1.right > width: sound.play() velocity1[0] = -velocity1[0] if ball_boundary_1.top < 0 or ball_boundary_1.bottom > top: sound.play() velocity1[1] = -velocity1[1] if ball_boundary_2.left < 0 or ball_boundary_2.right > width: sound.play() velocity2[0] = -velocity2[0] if ball_boundary_2.top < 0 or ball_boundary_2.bottom > top: sound.play() velocity2[1] = -velocity2[1] if ball_boundary_3.left < 0 or ball_boundary_3.right > width: sound.play() velocity3[0] = -velocity3[0] if ball_boundary_3.top < 0 or ball_boundary_3.bottom > top: sound.play() velocity3[1] = -velocity3[1] ball_boundary_1 = ball_boundary_1.move (velocity1) ball_boundary_2 = ball_boundary_2.move (velocity2) ball_boundary_3 = ball_boundary_3.move (velocity3) frame.fill (background_colour) frame.blit (ball1, ball_boundary_1) frame.blit (ball2, ball_boundary_2) frame.blit (ball3, ball_boundary_3) pygame.display.flip() A: When two objects 'collide' they basically exist in the same physical space and therefore you have to check for this. In 2d this is nice and easy, especially for rectangular shapes. Basically write a function called 'overlap' that returns a true value if two of the balls collide. For example: for (i = 0; i < numberOfBalls; i++) { for (j = i+1; j < numberOfBalls; j++) { if (overlap (ball_rect[i], ball_rect[j])) { // you will need to write this reverse velocity code differently // to comply with the code above but I recommend that the balls // go in an array with three elements so that you can index // them. (Useful in for loops as seen above) ball_xvelocity[i] *= -1; ball_xvelocity[j] *= -1; ball_yvelocity[i] *= -1; ball_yvelocity[j] *= -1; } } } I will leave the overlap function up to you but you should google 'rectangluar collision detection' and you will find out how. You will se that it is really not that scary and will give you faith that you can research and learn programming concepts. N.B. Specifically did not give python code. Since it is homework it is your job to write the answer. Sorry, just an SO policy. Hope this helps. :) A: Well you actually have some clues in the code that you provide. The way you are detecting if the ball bounces on the wall is to check if the top boundary of the ball is less than 0 meaning that it has touched the top boundary and needs to bounce so you change direction. So the code: if ball_boundary_1.top < 0 or ball_boundary_1.bottom > top: sound.play() velocity1[1] = -velocity1[1] basically changes to vertical movement of the ball if it bounces on the floor or ceiling. So to modify this you need to ask your self what it means if two balls bounce on each other...and it would mean that their boundaries overlap in any of a number of ways. So, for instance, you can check if either the left or right of ball 1 is inside ball 2's horizontal dimensions AND the top or bottom of ball 1 is inside ball 2's vertical dimensions, then the two balls are touching so change the velocity of both balls. A: As my lecturer added to my particular assessment on this, Once a second ball is bouncing around the frame, add some code to change the directions of the balls if they collide. PyGame provides a function that allows you to detect if a collision has occurred between two Rect objects. The function is named colliderect and is called in the following manner. If two Rect objects are named ball_boundary_1 and ball_boundary_2, you could check for a collision with: if ball_boundary_1.colliderect(ball_boundary_2): # alter the direction of the balls with the usual method so, this would be used to check 'if' a collision occurs, return True, and run some code to reverse velocity. good luck, :D I havnt actually done this bit yet myself, im just about to try it
How do I reverse the direction that my rectangles travel?
I am very new at programming as it was only just introduced into my school as a subject and I need some help. I have been given the task to have an animation of three balls (rectangle images) bouncing around the screen and off each other. I have the three balls and the bouncing of the walls all down good, but I don't know how to have them bounce off each other. Any help would be greatly appreciated, my current code is as follows: import pygame import random import sys if __name__ =='__main__': ball_image1 = 'beachball1.jpg' ball_image2 = 'beachball2.jpg' ball_image3 = 'beachball3.jpg' bounce_sound = 'thump.wav' width = 800 top = 600 x = 0 y = 0 background_colour = 0,0,0 caption= 'Bouncing Ball animation' velocity1 = [-1,-1] velocity2 = [-1,1] velocity3 = [1,-1] pygame.init () frame = pygame.display.set_mode ((width, top)) pygame.display.set_caption (caption) ball1= pygame.image.load (ball_image1). convert() ball2= pygame.image.load (ball_image2). convert() ball3= pygame.image.load (ball_image3). convert() ball_boundary_1 = ball2.get_rect (center=(random.randint(50, 750),random.randint(50, 550))) ball_boundary_2 = ball2.get_rect (center=(random.randint(50, 750),random.randint(50, 550))) ball_boundary_3 = ball2.get_rect (center=(random.randint(50, 750),random.randint(50, 550))) sound = pygame.mixer.Sound (bounce_sound) while True: for event in pygame.event.get(): print event if event.type == pygame.QUIT: sys.exit(0) if ball_boundary_1.left < 0 or ball_boundary_1.right > width: sound.play() velocity1[0] = -velocity1[0] if ball_boundary_1.top < 0 or ball_boundary_1.bottom > top: sound.play() velocity1[1] = -velocity1[1] if ball_boundary_2.left < 0 or ball_boundary_2.right > width: sound.play() velocity2[0] = -velocity2[0] if ball_boundary_2.top < 0 or ball_boundary_2.bottom > top: sound.play() velocity2[1] = -velocity2[1] if ball_boundary_3.left < 0 or ball_boundary_3.right > width: sound.play() velocity3[0] = -velocity3[0] if ball_boundary_3.top < 0 or ball_boundary_3.bottom > top: sound.play() velocity3[1] = -velocity3[1] ball_boundary_1 = ball_boundary_1.move (velocity1) ball_boundary_2 = ball_boundary_2.move (velocity2) ball_boundary_3 = ball_boundary_3.move (velocity3) frame.fill (background_colour) frame.blit (ball1, ball_boundary_1) frame.blit (ball2, ball_boundary_2) frame.blit (ball3, ball_boundary_3) pygame.display.flip()
[ "When two objects 'collide' they basically exist in the same physical space and therefore you have to check for this. In 2d this is nice and easy, especially for rectangular shapes. Basically write a function called 'overlap' that returns a true value if two of the balls collide. For example:\nfor (i = 0; i < numberOfBalls; i++) {\n for (j = i+1; j < numberOfBalls; j++) {\n if (overlap (ball_rect[i], ball_rect[j])) {\n // you will need to write this reverse velocity code differently\n // to comply with the code above but I recommend that the balls \n // go in an array with three elements so that you can index \n // them. (Useful in for loops as seen above)\n ball_xvelocity[i] *= -1;\n ball_xvelocity[j] *= -1;\n ball_yvelocity[i] *= -1;\n ball_yvelocity[j] *= -1;\n }\n }\n}\n\nI will leave the overlap function up to you but you should google 'rectangluar collision detection' and you will find out how. You will se that it is really not that scary and will give you faith that you can research and learn programming concepts.\nN.B. Specifically did not give python code. Since it is homework it is your job to write the answer. Sorry, just an SO policy. Hope this helps. :)\n", "Well you actually have some clues in the code that you provide. The way you are detecting if the ball bounces on the wall is to check if the top boundary of the ball is less than 0 meaning that it has touched the top boundary and needs to bounce so you change direction.\nSo the code:\nif ball_boundary_1.top < 0 or ball_boundary_1.bottom > top:\n sound.play()\n velocity1[1] = -velocity1[1]\n\nbasically changes to vertical movement of the ball if it bounces on the floor or ceiling.\nSo to modify this you need to ask your self what it means if two balls bounce on each other...and it would mean that their boundaries overlap in any of a number of ways. So, for instance, you can check if either the left or right of ball 1 is inside ball 2's horizontal dimensions AND the top or bottom of ball 1 is inside ball 2's vertical dimensions, then the two balls are touching so change the velocity of both balls.\n", "As my lecturer added to my particular assessment on this,\n\nOnce a second ball is bouncing around the frame, add some code to change the directions of the balls if they collide. PyGame provides a function that allows you to detect if a collision has occurred between two Rect objects. The function is named colliderect and is called in the following manner. If two Rect objects are named ball_boundary_1 and ball_boundary_2, you could check for a collision with:\nif ball_boundary_1.colliderect(ball_boundary_2):\n\n # alter the direction of the balls with the usual method\n\n\nso, this would be used to check 'if' a collision occurs, return True, and run some code to reverse velocity. good luck, :D I havnt actually done this bit yet myself, im just about to try it\n" ]
[ 3, 1, 1 ]
[]
[]
[ "collision_detection", "python" ]
stackoverflow_0000788966_collision_detection_python.txt
Q: Setting A Generator As The Argument Of A PyQt4 Signal I want to use a generator as the argument passed by a PyQt4 signal, and I am not sure as to the cleanest way. I could just do something like elementChosen=QtCore.pyqtSignal(type((i for i in xrange (i)))), but this just looks ugly. Any suggestions? A: You can use the types module to make the code look less ugly. from types import GeneratorType elementChosen = QtCore.pyqtSignal(GeneratorType) documentation: http://docs.python.org/library/types.html
Setting A Generator As The Argument Of A PyQt4 Signal
I want to use a generator as the argument passed by a PyQt4 signal, and I am not sure as to the cleanest way. I could just do something like elementChosen=QtCore.pyqtSignal(type((i for i in xrange (i)))), but this just looks ugly. Any suggestions?
[ "You can use the types module to make the code look less ugly.\nfrom types import GeneratorType\n\nelementChosen = QtCore.pyqtSignal(GeneratorType)\n\ndocumentation: http://docs.python.org/library/types.html\n" ]
[ 1 ]
[]
[]
[ "pyqt4", "python" ]
stackoverflow_0002590909_pyqt4_python.txt
Q: How do I write this Django model in SQL? I want to create a new column. How do I write this in SQL? class mytable(models.Model): created_at = models.DateTimeField(auto_now_add=True) A: If you don't want to use South to manage this automatically - which is highly recommended, by the way - you can easily see what SQL you need by running ./manage.py sqlall <appname>. This will show you all the SQL to create the models in your app, so you can find the definition of your new field there. A: ALTER TABLE mytable ADD created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP;
How do I write this Django model in SQL?
I want to create a new column. How do I write this in SQL? class mytable(models.Model): created_at = models.DateTimeField(auto_now_add=True)
[ "If you don't want to use South to manage this automatically - which is highly recommended, by the way - you can easily see what SQL you need by running ./manage.py sqlall <appname>. This will show you all the SQL to create the models in your app, so you can find the definition of your new field there.\n", "ALTER TABLE mytable\n ADD created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP;\n\n" ]
[ 1, 0 ]
[]
[]
[ "database", "django", "mysql", "python" ]
stackoverflow_0002591360_database_django_mysql_python.txt
Q: Itertools group by functionality I want to group by on dict key >>> x [{'a': 10, 'b': 90}, {'a': 20}, {'a': 30}, {'a': 10}] >>> [(name, list(group)) for name, group in groupby(x, lambda p:p['a'])] [(10, [{'a': 10, 'b': 90}]), (20, [{'a': 20}]), (30, [{'a': 30}]), (10, [{'a': 10}])] This must group on key 10 :( A: docs say: itertools.groupby: It generates a break or new group every time the value of the key function changes (which is why it is usually necessary to have sorted the data using the same key function). That behavior differs from SQL’s GROUP BY which aggregates common elements regardless of their input order.
Itertools group by functionality
I want to group by on dict key >>> x [{'a': 10, 'b': 90}, {'a': 20}, {'a': 30}, {'a': 10}] >>> [(name, list(group)) for name, group in groupby(x, lambda p:p['a'])] [(10, [{'a': 10, 'b': 90}]), (20, [{'a': 20}]), (30, [{'a': 30}]), (10, [{'a': 10}])] This must group on key 10 :(
[ "docs say:\n\nitertools.groupby:\n It generates a break or new group every time the value of the key function changes (which is why it is usually necessary to have sorted the data using the same key function). That behavior differs from SQL’s GROUP BY which aggregates common elements regardless of their input order.\n\n" ]
[ 4 ]
[]
[]
[ "python", "python_itertools" ]
stackoverflow_0002591621_python_python_itertools.txt
Q: What are the common patterns in web programming? I have been trying to write my first big web app (more than one cgi file) and as I kept moving forward with the rough prototype, paralelly trying to predict more tasks, this is the todo that got accumulated (In no particular order). * Validations and input sanitizations * Object versioning (to avoid edit conflicts. I dont want hard locks) * Exception handling * memcache * xss and injection protections * javascript * html * ACLs * phonetics in search, match and find duplicates (for form validation) * Ajaxify!!! (I have snipped off the project specific items.) I know that each todo will be quite tied up to its project and technologies used. What I am wondering though, is if there is a pattern in your todo items as well as the sequence in which you experienced guys have come across them. A: If this is actually a big web app that will be deployed for general consumption, then I'd add on Rate Limiting. A: The Model-View-Controller (MVC) design pattern: decouples users inputs and the presentation layer from your application data. A: Almost all of your list is "Framework". Almost none of that is functionality a user actually sees. My to do list never looks like that. Never. Consequently, I have this advice. STOP. Do this instead. Find a framework that does this. Focus on the the actual users and their actual use cases. Now your todo list will have actual use cases that an actual user will actually care about. That's what should be on your todo list. Not framework technology. Use cases. A: model view controller of course. start with some framework first. in php kohana is good , for python django is good, ruby on rail and so on...
What are the common patterns in web programming?
I have been trying to write my first big web app (more than one cgi file) and as I kept moving forward with the rough prototype, paralelly trying to predict more tasks, this is the todo that got accumulated (In no particular order). * Validations and input sanitizations * Object versioning (to avoid edit conflicts. I dont want hard locks) * Exception handling * memcache * xss and injection protections * javascript * html * ACLs * phonetics in search, match and find duplicates (for form validation) * Ajaxify!!! (I have snipped off the project specific items.) I know that each todo will be quite tied up to its project and technologies used. What I am wondering though, is if there is a pattern in your todo items as well as the sequence in which you experienced guys have come across them.
[ "If this is actually a big web app that will be deployed for general consumption, then I'd add on Rate Limiting.\n", "The Model-View-Controller (MVC) design pattern: decouples users inputs and the presentation layer from your application data.\n", "Almost all of your list is \"Framework\".\nAlmost none of that is functionality a user actually sees.\nMy to do list never looks like that. Never.\nConsequently, I have this advice.\nSTOP.\nDo this instead.\n\nFind a framework that does this. \nFocus on the the actual users and their actual use cases. \n\nNow your todo list will have actual use cases that an actual user will actually care about. That's what should be on your todo list. Not framework technology. Use cases.\n", "model view controller of course. start with some framework first. in php kohana is good , for python django is good, ruby on rail and so on...\n" ]
[ 4, 3, 3, 1 ]
[]
[]
[ "design_patterns", "python" ]
stackoverflow_0002589932_design_patterns_python.txt
Q: strip only html anchor tags i have following code that strip all tags. now i want to strip only anchor tags. x = re.compile(r'<[^<]*?/?>') how to modify so that only anchor tags stripped. A: following code that strip all tags. Not really. <div title="a>b"> is valid HTML and gets mangled. <div title="<" onmouseover="script()" class="<">"> is invalid HTML but the kind of thing you will often find on real web pages. Your regexp leaves an active tag with dangerous scripting in it. You can't do an HTML-processing task like tag-stripping with regex, unless your possible input set is heavily restricted. Better to use a real HTML parser and walk across the resulting document removing unwanted elements as you go. eg. with BeautifulSoup: def replaceWithContents(element): ix= element.parent.contents.index(element) for child in reversed(element.contents): element.parent.insert(ix, child) element.extract() doc= BeautifulSoup(html) # maybe fromEncoding= 'utf-8' for link in doc.findAll('a'): replaceWithContents(link) str(doc) A: x = re.compile(r'<[aA]\>[^<]*?/?>') This will match the 'a' or 'A' followed by a word boundary. Note that it won't clean out the closing tag. x = re.compile(r'</?[aA]\>[^<]*?/?>') will remove the closing tag as well. EDIT: Actually, it feels more reliable to switch the [^<] to [^>], like so. x = re.compile(r'</?[aA]\>[^>]*?/?>') A: I'm not sure if this Python is correct (I'm a PHP guy but am just starting to learn python in my own time). re.sub('<[aA][^>]*>([^<]+)</[aA]>','\1','<html><head> .... </body></html>') This won't remove all anchor tags in one shot, so you may have to loop over the html string. It matches the anchor tags and replaces the match with the contents of the tags. So ... <a href="/">homepage</a> -> homepage Might not be the most efficient on a large body of text but works.
strip only html anchor tags
i have following code that strip all tags. now i want to strip only anchor tags. x = re.compile(r'<[^<]*?/?>') how to modify so that only anchor tags stripped.
[ "\nfollowing code that strip all tags.\n\nNot really. <div title=\"a>b\"> is valid HTML and gets mangled. <div title=\"<\" onmouseover=\"script()\" class=\"<\">\"> is invalid HTML but the kind of thing you will often find on real web pages. Your regexp leaves an active tag with dangerous scripting in it.\nYou can't do an HTML-processing task like tag-stripping with regex, unless your possible input set is heavily restricted. Better to use a real HTML parser and walk across the resulting document removing unwanted elements as you go.\neg. with BeautifulSoup:\ndef replaceWithContents(element):\n ix= element.parent.contents.index(element)\n for child in reversed(element.contents):\n element.parent.insert(ix, child)\n element.extract()\n\ndoc= BeautifulSoup(html) # maybe fromEncoding= 'utf-8'\nfor link in doc.findAll('a'):\n replaceWithContents(link)\nstr(doc)\n\n", "x = re.compile(r'<[aA]\\>[^<]*?/?>')\n\nThis will match the 'a' or 'A' followed by a word boundary. Note that it won't clean out the closing tag.\nx = re.compile(r'</?[aA]\\>[^<]*?/?>')\n\nwill remove the closing tag as well.\nEDIT:\nActually, it feels more reliable to switch the [^<] to [^>], like so.\nx = re.compile(r'</?[aA]\\>[^>]*?/?>')\n\n", "I'm not sure if this Python is correct (I'm a PHP guy but am just starting to learn python in my own time).\nre.sub('<[aA][^>]*>([^<]+)</[aA]>','\\1','<html><head> .... </body></html>')\n\nThis won't remove all anchor tags in one shot, so you may have to loop over the html string. It matches the anchor tags and replaces the match with the contents of the tags. So ...\n<a href=\"/\">homepage</a> -> homepage\n\nMight not be the most efficient on a large body of text but works.\n" ]
[ 5, 1, 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0002591465_python_regex.txt
Q: Search a variable for an address I am trying to match information stored in a variable. I have a list of uuid's and ip addresses beside them. The code I have is: r = re.compile(r'urn:uuid:5EEF382F-JSQ9-3c45-D5E0-K15X8M8K76') m = r.match(str(serv)) if m1: print'Found' The string serv contains is: urn:uuid:7FDS890A-KD9E-3h53-G7E8-BHJSD6789D:[u'http://10.10.10.20:12365/7FDS890A-KD9E-3h53-G7E8-BHJSD6789D/'] --------------------------------------------- urn:uuid:5EEF382F-JSQ9-3c45-D5E0-K15X8M8K76:[u'http://10.10.10.10:42365'] --------------------------------------------- urn:uuid:8DSGF89S-FS90-5c87-K3DF-SDFU890US9:[u'http://10.10.10.40:5234'] --------------------------------------------- So basically I am wanting to find the uuid string and find out what it's address is and store it as a variable. So far I have just tried to get it to match the string to no avail. Can anyone point out a solution to this. Thanks A: r = re.compile(r"urn:uuid:5EEF382F-JSQ9-3c45-D5E0-K15X8M8K76:\[u'(.*)'\]") m = r.search(str(serv)) if m: print 'Found', m.group(1) A: your regex is very simple, so much so that there's no need to use regular expression at all. >>> serv=""" ... urn:uuid:7FDS890A-KD9E-3h53-G7E8-BHJSD6789D:[u'http://10.10.10.20:12365/7FDS890A-KD9E-3h53-G7E8-BHJSD6789D/'] ... --------------------------------------------- ... urn:uuid:5EEF382F-JSQ9-3c45-D5E0-K15X8M8K76:[u'http://10.10.10.10:42365'] ... --------------------------------------------- ... urn:uuid:8DSGF89S-FS90-5c87-K3DF-SDFU890US9:[u'http://10.10.10.40:5234'] ... --------------------------------------------- ... """ >>> tomatch="urn:uuid:5EEF382F-JSQ9-3c45-D5E0-K15X8M8K76" >>> for row in serv.split("\n"): ... if tomatch in row: ... print row[ row.find("[")+1 : ].replace("]","") ... u'http://10.10.10.10:42365'
Search a variable for an address
I am trying to match information stored in a variable. I have a list of uuid's and ip addresses beside them. The code I have is: r = re.compile(r'urn:uuid:5EEF382F-JSQ9-3c45-D5E0-K15X8M8K76') m = r.match(str(serv)) if m1: print'Found' The string serv contains is: urn:uuid:7FDS890A-KD9E-3h53-G7E8-BHJSD6789D:[u'http://10.10.10.20:12365/7FDS890A-KD9E-3h53-G7E8-BHJSD6789D/'] --------------------------------------------- urn:uuid:5EEF382F-JSQ9-3c45-D5E0-K15X8M8K76:[u'http://10.10.10.10:42365'] --------------------------------------------- urn:uuid:8DSGF89S-FS90-5c87-K3DF-SDFU890US9:[u'http://10.10.10.40:5234'] --------------------------------------------- So basically I am wanting to find the uuid string and find out what it's address is and store it as a variable. So far I have just tried to get it to match the string to no avail. Can anyone point out a solution to this. Thanks
[ "r = re.compile(r\"urn:uuid:5EEF382F-JSQ9-3c45-D5E0-K15X8M8K76:\\[u'(.*)'\\]\")\nm = r.search(str(serv))\nif m:\n print 'Found', m.group(1)\n\n", "your regex is very simple, so much so that there's no need to use regular expression at all.\n>>> serv=\"\"\"\n... urn:uuid:7FDS890A-KD9E-3h53-G7E8-BHJSD6789D:[u'http://10.10.10.20:12365/7FDS890A-KD9E-3h53-G7E8-BHJSD6789D/']\n... ---------------------------------------------\n... urn:uuid:5EEF382F-JSQ9-3c45-D5E0-K15X8M8K76:[u'http://10.10.10.10:42365']\n... ---------------------------------------------\n... urn:uuid:8DSGF89S-FS90-5c87-K3DF-SDFU890US9:[u'http://10.10.10.40:5234']\n... ---------------------------------------------\n... \"\"\"\n>>> tomatch=\"urn:uuid:5EEF382F-JSQ9-3c45-D5E0-K15X8M8K76\"\n>>> for row in serv.split(\"\\n\"):\n... if tomatch in row:\n... print row[ row.find(\"[\")+1 : ].replace(\"]\",\"\")\n...\nu'http://10.10.10.10:42365'\n\n" ]
[ 2, 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0002591832_python_regex.txt
Q: call a server side python script from javascript how to call a server side python script from javascript. if test.py is the python script file in server, and if the parameter to be passed to python is another url , then how this can be executed from javascript, how the return string from python script is obtained to the javascript. A: You can directly call the python script from javascript. You need to use an appropriate server-side technology (asp.net, php, servlet). The best solution will be to create a REST service, by defining a URL, which when called (through ajax for example) will execute the python script and write the output to the body of the request. This will be easier if you are using django or another python web framework.
call a server side python script from javascript
how to call a server side python script from javascript. if test.py is the python script file in server, and if the parameter to be passed to python is another url , then how this can be executed from javascript, how the return string from python script is obtained to the javascript.
[ "You can directly call the python script from javascript. You need to use an appropriate server-side technology (asp.net, php, servlet). The best solution will be to create a REST service, by defining a URL, which when called (through ajax for example) will execute the python script and write the output to the body of the request. This will be easier if you are using django or another python web framework.\n" ]
[ 3 ]
[]
[]
[ "javascript", "python" ]
stackoverflow_0002591846_javascript_python.txt
Q: Deploying Django (fastcgi, apache mod_wsgi, uwsgi, gunicorn) Can someone explain the difference between apache mod_wsgi in daemon mode and django fastcgi in threaded mode. They both use threads for concurrency I think. Supposing that I'm using nginx as front end to apache mod_wsgi. UPDATE: I'm comparing django built in fastcgi(./manage.py method=threaded maxchildren=15) and mod_wsgi in 'daemon' mode(WSGIDaemonProcess example threads=15). They both use threads and acquire GIL, am I right? UPDATAE 2: So if they both are similar, is there any benefits of apache mod_wsgi against fastcgi. I see such pros of fastcgi: we don't need apache we consume less RAM I noticed that fastcgi has lesser overhead UPDATAE 3: I'm now happy with nginx + uwsgi. UPDATAE 4: I'm now happy with nginx + gunicorn :) A: Neither have to use threads to be able to handle concurrent requests. It depends on how you configure them. You can use multiple processes where each is single threaded if you want. For more background on mod_wsgi process/threading models see: http://code.google.com/p/modwsgi/wiki/ProcessesAndThreading The models are similar albeit that mod_wsgi handles process management itself. What happens in FASTCGI as far as process management depends on what FASTCGI hosting mechanism you are using and you don't say what that is. Another difference is that FASTCGI still needs a separate FASTCGI to WSGI bridge such as flup where as mod_wsgi doesn't need any sort of bridge as implements WSGI interface natively. Finally, FASTCGI process are an exec/fork of some supervisor process or the web server, dependent on hosting mechanism. In mod_wsgi the processes are a fork only of Apache parent process. In general this doesn't matter too much but does have some implications. There are other differences but they arise more because mod_wsgi offers a lot more functionality and configurability than a FASTCGI hosting mechanism does. Anyway, the question is a bit vague, can you be more specific about what it is you are wanting to know or contrast between the two and why? Answer can then perhaps be targeted better.
Deploying Django (fastcgi, apache mod_wsgi, uwsgi, gunicorn)
Can someone explain the difference between apache mod_wsgi in daemon mode and django fastcgi in threaded mode. They both use threads for concurrency I think. Supposing that I'm using nginx as front end to apache mod_wsgi. UPDATE: I'm comparing django built in fastcgi(./manage.py method=threaded maxchildren=15) and mod_wsgi in 'daemon' mode(WSGIDaemonProcess example threads=15). They both use threads and acquire GIL, am I right? UPDATAE 2: So if they both are similar, is there any benefits of apache mod_wsgi against fastcgi. I see such pros of fastcgi: we don't need apache we consume less RAM I noticed that fastcgi has lesser overhead UPDATAE 3: I'm now happy with nginx + uwsgi. UPDATAE 4: I'm now happy with nginx + gunicorn :)
[ "Neither have to use threads to be able to handle concurrent requests. It depends on how you configure them. You can use multiple processes where each is single threaded if you want.\nFor more background on mod_wsgi process/threading models see:\nhttp://code.google.com/p/modwsgi/wiki/ProcessesAndThreading\nThe models are similar albeit that mod_wsgi handles process management itself. What happens in FASTCGI as far as process management depends on what FASTCGI hosting mechanism you are using and you don't say what that is.\nAnother difference is that FASTCGI still needs a separate FASTCGI to WSGI bridge such as flup where as mod_wsgi doesn't need any sort of bridge as implements WSGI interface natively.\nFinally, FASTCGI process are an exec/fork of some supervisor process or the web server, dependent on hosting mechanism. In mod_wsgi the processes are a fork only of Apache parent process. In general this doesn't matter too much but does have some implications.\nThere are other differences but they arise more because mod_wsgi offers a lot more functionality and configurability than a FASTCGI hosting mechanism does.\nAnyway, the question is a bit vague, can you be more specific about what it is you are wanting to know or contrast between the two and why? Answer can then perhaps be targeted better.\n" ]
[ 10 ]
[]
[]
[ "deployment", "django", "fastcgi", "mod_wsgi", "python" ]
stackoverflow_0002591715_deployment_django_fastcgi_mod_wsgi_python.txt
Q: Python: Converting a tuple to a string Given this : import os import subprocess def check_server(): cl = subprocess.Popen(["nmap","10.7.1.71"], stdout=subprocess.PIPE) result = cl.communicate() print result check_server() check_server() returns this tuple: ('\nStarting Nmap 4.53 ( http://insecure.org ) at 2010-04-07 07:26 EDT\nInteresting ports on 10.7.1.71:\nNot shown: 1711 closed ports\nPORT STATE SERVICE\n21/tcp open ftp\n22/tcp open ssh\n80/tcp open http\n\nNmap done: 1 IP address (1 host up) scanned in 0.293 seconds\n', None) Changing the second line in the method to result, err = cl.communicate() results in check_server() returning : Starting Nmap 4.53 ( http://insecure.org ) at 2010-04-07 07:27 EDT Interesting ports on 10.7.1.71: Not shown: 1711 closed ports PORT STATE SERVICE 21/tcp open ftp 22/tcp open ssh 80/tcp open http Nmap done: 1 IP address (1 host up) scanned in 0.319 seconds Looks to be the case that the tuple is converted to a string, and the \n's are being stripped.... but how? A: cl.communicate() is still returning a tuple. The assignment result, err = ... has the effect of unpacking the tuple into the variables result (a string) and err (an integer). When you print the tuple, it uses the repr(...) of each element, but when you print the string, it just prints the string, hence the absence of delimiters and \ns. A: In both cases cl.communicate() returns a two-element tuple (stdout and stderr of the command if both stdout and stderr are redirected to a PIPE). In first case you assign this tuple to the result variable. When you print it you get a text representation of the tuple. Special characters, like end-of-line are escaped (to '\n') in such representation. In the second case you unpack the tuple. This means: you assign the first element of the tuple to result and the second to err. As the result is already a string it is printed with no escaping – end-of-line characters are displayed as line breaks and not '\n'. A: print is clever. If you pass it a string, it just prints it. If you pass it something else (a tuple in this example) then it prints it's representation (as returned by repr()). The representation of a string has \n where the string contains newlines. The representation also has quotes around it. Try changing your print statement to print repr(result) and you'll see.
Python: Converting a tuple to a string
Given this : import os import subprocess def check_server(): cl = subprocess.Popen(["nmap","10.7.1.71"], stdout=subprocess.PIPE) result = cl.communicate() print result check_server() check_server() returns this tuple: ('\nStarting Nmap 4.53 ( http://insecure.org ) at 2010-04-07 07:26 EDT\nInteresting ports on 10.7.1.71:\nNot shown: 1711 closed ports\nPORT STATE SERVICE\n21/tcp open ftp\n22/tcp open ssh\n80/tcp open http\n\nNmap done: 1 IP address (1 host up) scanned in 0.293 seconds\n', None) Changing the second line in the method to result, err = cl.communicate() results in check_server() returning : Starting Nmap 4.53 ( http://insecure.org ) at 2010-04-07 07:27 EDT Interesting ports on 10.7.1.71: Not shown: 1711 closed ports PORT STATE SERVICE 21/tcp open ftp 22/tcp open ssh 80/tcp open http Nmap done: 1 IP address (1 host up) scanned in 0.319 seconds Looks to be the case that the tuple is converted to a string, and the \n's are being stripped.... but how?
[ "cl.communicate() is still returning a tuple. The assignment result, err = ... has the effect of unpacking the tuple into the variables result (a string) and err (an integer).\nWhen you print the tuple, it uses the repr(...) of each element, but when you print the string, it just prints the string, hence the absence of delimiters and \\ns.\n", "In both cases cl.communicate() returns a two-element tuple (stdout and stderr of the command if both stdout and stderr are redirected to a PIPE). In first case you assign this tuple to the result variable. When you print it you get a text representation of the tuple. Special characters, like end-of-line are escaped (to '\\n') in such representation.\nIn the second case you unpack the tuple. This means: you assign the first element of the tuple to result and the second to err. As the result is already a string it is printed with no escaping – end-of-line characters are displayed as line breaks and not '\\n'.\n", "print is clever. If you pass it a string, it just prints it. If you pass it something else (a tuple in this example) then it prints it's representation (as returned by repr()).\nThe representation of a string has \\n where the string contains newlines. The representation also has quotes around it.\nTry changing your print statement to print repr(result) and you'll see.\n" ]
[ 6, 4, 1 ]
[]
[]
[ "python", "string", "tuples" ]
stackoverflow_0002592045_python_string_tuples.txt
Q: How can I skip the current item and the next in a Python loop? This might be a really dumb question, however I've looked around online, etc. And have not seen a solid answer. Is there a simple way to do something like this? lines = open('something.txt', 'r').readlines() for line in lines: if line == '!': # force iteration forward twice line.next().next() <etc> It's easy to do in C++; just increment the iterator an extra time. Is there an easy way to do that in Python? I would just like to point, out the main purpose of this question is not about "reading files and such" and skipping things. I was more looking for C++ iterator style iteration. Also the new title is kinda dumb, and i dont really think it reflects the nature of my question. A: Try: lines = iter(open('something.txt', 'r')) for val in lines: if val == "!": lines.next() continue <etc> You may want to catch StopIteration somewhere. It'll occur if the iterator is finished. A: The file.readlines method returns a list of strings, and iterating over a list will not let you modify the iteration in the body of the loop. However if you call iter on the list first then you will get an iterator that you can modify in the loop body: lines = open('something.txt', 'r').readlines() line_iter = iter(lines) for line in line_iter: if line == '!': # force iteration forward twice line_iter.next() line_iter.next() <etc> As ebo points out the file object itself acts as an iterator, so you can get the same effect by not calling readlines and leaving out the call to iter. A: This is short, pythonic, and works: with open('something.txt', 'r') as f: # or simply f = open('something.txt', 'r') nobang = (line for line in f if line != '!\n') for line in nobang: #... Edit: As many observed, this is not the solution yet. The best I can think of is a combination of what is already on this page: with open('something.txt', 'r') as f: for line in f: if line == '!\n': next(f,None) # consume next line continue # skip this line # ... A: Not very compact: skip = False for line in open('something.txt'): if skip: skip = False continue if line.strip() == '!': skip = True continue A: You could use recursion input = iter( open('something.txt') ) def myFunc( item ): val = iter.next() if( val == '!' ): item.next() return myFunc( item ) #continue on with looping logic Editted post contained the following which actually didn't answer your question: Have you tried [line for line in open('something.txt') if line != '!'] to produce a new list? Or even better filter( lambda line: line != '!', open('something.txt') )
How can I skip the current item and the next in a Python loop?
This might be a really dumb question, however I've looked around online, etc. And have not seen a solid answer. Is there a simple way to do something like this? lines = open('something.txt', 'r').readlines() for line in lines: if line == '!': # force iteration forward twice line.next().next() <etc> It's easy to do in C++; just increment the iterator an extra time. Is there an easy way to do that in Python? I would just like to point, out the main purpose of this question is not about "reading files and such" and skipping things. I was more looking for C++ iterator style iteration. Also the new title is kinda dumb, and i dont really think it reflects the nature of my question.
[ "Try:\nlines = iter(open('something.txt', 'r'))\nfor val in lines:\n if val == \"!\":\n lines.next()\n continue\n <etc>\n\nYou may want to catch StopIteration somewhere. It'll occur if the iterator is finished.\n", "The file.readlines method returns a list of strings, and iterating over a list will not let you modify the iteration in the body of the loop. However if you call iter on the list first then you will get an iterator that you can modify in the loop body:\nlines = open('something.txt', 'r').readlines()\nline_iter = iter(lines)\nfor line in line_iter:\n if line == '!':\n # force iteration forward twice\n line_iter.next()\n line_iter.next()\n <etc>\n\nAs ebo points out the file object itself acts as an iterator, so you can get the same effect by not calling readlines and leaving out the call to iter.\n", "This is short, pythonic, and works:\nwith open('something.txt', 'r') as f: # or simply f = open('something.txt', 'r')\n nobang = (line for line in f if line != '!\\n')\n for line in nobang:\n #...\n\nEdit:\nAs many observed, this is not the solution yet. The best I can think of is a combination of what is already on this page:\nwith open('something.txt', 'r') as f:\n for line in f:\n if line == '!\\n':\n next(f,None) # consume next line\n continue # skip this line\n # ...\n\n", "Not very compact:\nskip = False\nfor line in open('something.txt'):\n if skip:\n skip = False\n continue\n\n if line.strip() == '!':\n skip = True\n continue\n\n", "You could use recursion\ninput = iter( open('something.txt') )\ndef myFunc( item ):\n val = iter.next()\n if( val == '!' ):\n item.next()\n return myFunc( item )\n #continue on with looping logic\n\nEditted post contained the following which actually didn't answer your question:\nHave you tried\n[line for line in open('something.txt') if line != '!']\n\nto produce a new list? Or even better\nfilter( lambda line: line != '!', open('something.txt') )\n\n" ]
[ 47, 8, 8, 2, 2 ]
[]
[]
[ "python" ]
stackoverflow_0002592798_python.txt
Q: Running Java, Python, Ruby and Perl programs in .NET I've .NET framework 3.5 installed in my laptop. Just .NET alone, no Visual Studio. How can I run Java, Python, Ruby and Perl programs from the console? Do I need to install something else also, for running these language files? In case there is a need for something extra to be installed and after i have all of them, what are the commands that I need to type in the console to run these programs? A: Do you want to run programs in these languages inside the .NET platform? You'd need IronPython or IronRuby (I don't think anything like IronPerl exists). If you want to run "normal" Python/Ruby/Perl/Java programs, then yes, you'll need to install a Python interpreter, a Ruby interpreter, a Perl interpreter and a Java VM. A: Perl is a bit of a problem, see this SO question. IronRuby and IronPython cover those two languages. For Java, I think you need Microsoft's J# (but I'm not entirely clear on the "visual vs not" situation for that product). A: None of those languages are supported natively with .NET. You can try IronPython or IronRuby for those languages, but to run Java or Perl I think you'll actually need to download and install a Java VM and a perl interpreter. A: There's no practical common virtual machine or binary for the options you list. You will require a separate install for each of these (note that all are unrelated to .NET)
Running Java, Python, Ruby and Perl programs in .NET
I've .NET framework 3.5 installed in my laptop. Just .NET alone, no Visual Studio. How can I run Java, Python, Ruby and Perl programs from the console? Do I need to install something else also, for running these language files? In case there is a need for something extra to be installed and after i have all of them, what are the commands that I need to type in the console to run these programs?
[ "Do you want to run programs in these languages inside the .NET platform? You'd need IronPython or IronRuby (I don't think anything like IronPerl exists).\nIf you want to run \"normal\" Python/Ruby/Perl/Java programs, then yes, you'll need to install a Python interpreter, a Ruby interpreter, a Perl interpreter and a Java VM.\n", "Perl is a bit of a problem, see this SO question. IronRuby and IronPython cover those two languages. For Java, I think you need Microsoft's J# (but I'm not entirely clear on the \"visual vs not\" situation for that product).\n", "None of those languages are supported natively with .NET. You can try IronPython or IronRuby for those languages, but to run Java or Perl I think you'll actually need to download and install a Java VM and a perl interpreter.\n", "There's no practical common virtual machine or binary for the options you list. You will require a separate install for each of these (note that all are unrelated to .NET)\n" ]
[ 7, 3, 3, 1 ]
[]
[]
[ ".net", "java", "perl", "python", "ruby" ]
stackoverflow_0002593519_.net_java_perl_python_ruby.txt
Q: Rewriting a for loop in pure NumPy to decrease execution time I recently asked about trying to optimise a Python loop for a scientific application, and received an excellent, smart way of recoding it within NumPy which reduced execution time by a factor of around 100 for me! However, calculation of the B value is actually nested within a few other loops, because it is evaluated at a regular grid of positions. Is there a similarly smart NumPy rewrite to shave time off this procedure? I suspect the performance gain for this part would be less marked, and the disadvantages would presumably be that it would not be possible to report back to the user on the progress of the calculation, that the results could not be written to the output file until the end of the calculation, and possibly that doing this in one enormous step would have memory implications? Is it possible to circumvent any of these? import numpy as np import time def reshape_vector(v): b = np.empty((3,1)) for i in range(3): b[i][0] = v[i] return b def unit_vectors(r): return r / np.sqrt((r*r).sum(0)) def calculate_dipole(mu, r_i, mom_i): relative = mu - r_i r_unit = unit_vectors(relative) A = 1e-7 num = A*(3*np.sum(mom_i*r_unit, 0)*r_unit - mom_i) den = np.sqrt(np.sum(relative*relative, 0))**3 B = np.sum(num/den, 1) return B N = 20000 # number of dipoles r_i = np.random.random((3,N)) # positions of dipoles mom_i = np.random.random((3,N)) # moments of dipoles a = np.random.random((3,3)) # three basis vectors for this crystal n = [10,10,10] # points at which to evaluate sum gamma_mu = 135.5 # a constant t_start = time.clock() for i in range(n[0]): r_frac_x = np.float(i)/np.float(n[0]) r_test_x = r_frac_x * a[0] for j in range(n[1]): r_frac_y = np.float(j)/np.float(n[1]) r_test_y = r_frac_y * a[1] for k in range(n[2]): r_frac_z = np.float(k)/np.float(n[2]) r_test = r_test_x +r_test_y + r_frac_z * a[2] r_test_fast = reshape_vector(r_test) B = calculate_dipole(r_test_fast, r_i, mom_i) omega = gamma_mu*np.sqrt(np.dot(B,B)) # write r_test, B and omega to a file frac_done = np.float(i+1)/(n[0]+1) t_elapsed = (time.clock()-t_start) t_remain = (1-frac_done)*t_elapsed/frac_done print frac_done*100,'% done in',t_elapsed/60.,'minutes...approximately',t_remain/60.,'minutes remaining' A: One obvious thing you can do is replace the line r_test_fast = reshape_vector(r_test) with r_test_fast = r_test.reshape((3,1)) Probably won't make any big difference in performance, but in any case it makes sense to use the numpy builtins instead of reinventing the wheel. Generally speaking, as you probably have noticed by now, the trick with optimizing numpy is to express the algorithm with the help of numpy whole-array operations or at least with slices instead of iterating over each element in python code. What tends to prevent this kind of "vectorization" is so-called loop-carried dependencies, i.e. loops where each iteration is dependent on the result of a previous iteration. Looking briefly at your code, you have no such thing, and it should be possible to vectorize your code just fine. EDIT: One solution I haven't verified this is correct, but should give you an idea of how to approach it. First, take the cartesian() function, which we'll use. Then def calculate_dipole_vect(mus, r_i, mom_i): # Treat each mu sequentially Bs = [] omega = [] for mu in mus: rel = mu - r_i r_norm = np.sqrt((rel * rel).sum(1)) r_unit = rel / r_norm[:, np.newaxis] A = 1e-7 num = A*(3*np.sum(mom_i * r_unit, 0)*r_unit - mom_i) den = r_norm ** 3 B = np.sum(num / den[:, np.newaxis], 0) Bs.append(B) omega.append(gamma_mu * np.sqrt(np.dot(B, B))) return Bs, omega # Transpose to get more "natural" ordering with row-major numpy r_i = r_i.T mom_i = mom_i.T t_start = time.clock() r_frac = cartesian((np.arange(n[0]) / float(n[0]), np.arange(n[1]) / float(n[1]), np.arange(n[2]) / float(n[2]))) r_test = np.dot(r_frac, a) B, omega = calculate_dipole_vect(r_test, r_i, mom_i) print 'Total time for vectorized: %f s' % (time.clock() - t_start) Well, in my testing, this is in fact slightly slower than the loop-based approach I started from. The thing is, in the original version in the question, it was already vectorized with whole-array operations over arrays of shape (20000, 3), so any further vectorization doesn't really bring much further benefit. In fact, it may worsen the performance, as above, maybe due to big temporary arrays. A: If you profile your code, you'll see that 99% of the running time is in calculate_dipole so reducing the time for this looping really won't give a noticeable reduction in execution time. You still need to focus on calculate_dipole if you want to make this faster. I tried my Cython code for calculate_dipole on this and got a reduction by about a factor of 2 in the overall time. There might be other ways to improve the Cython code too.
Rewriting a for loop in pure NumPy to decrease execution time
I recently asked about trying to optimise a Python loop for a scientific application, and received an excellent, smart way of recoding it within NumPy which reduced execution time by a factor of around 100 for me! However, calculation of the B value is actually nested within a few other loops, because it is evaluated at a regular grid of positions. Is there a similarly smart NumPy rewrite to shave time off this procedure? I suspect the performance gain for this part would be less marked, and the disadvantages would presumably be that it would not be possible to report back to the user on the progress of the calculation, that the results could not be written to the output file until the end of the calculation, and possibly that doing this in one enormous step would have memory implications? Is it possible to circumvent any of these? import numpy as np import time def reshape_vector(v): b = np.empty((3,1)) for i in range(3): b[i][0] = v[i] return b def unit_vectors(r): return r / np.sqrt((r*r).sum(0)) def calculate_dipole(mu, r_i, mom_i): relative = mu - r_i r_unit = unit_vectors(relative) A = 1e-7 num = A*(3*np.sum(mom_i*r_unit, 0)*r_unit - mom_i) den = np.sqrt(np.sum(relative*relative, 0))**3 B = np.sum(num/den, 1) return B N = 20000 # number of dipoles r_i = np.random.random((3,N)) # positions of dipoles mom_i = np.random.random((3,N)) # moments of dipoles a = np.random.random((3,3)) # three basis vectors for this crystal n = [10,10,10] # points at which to evaluate sum gamma_mu = 135.5 # a constant t_start = time.clock() for i in range(n[0]): r_frac_x = np.float(i)/np.float(n[0]) r_test_x = r_frac_x * a[0] for j in range(n[1]): r_frac_y = np.float(j)/np.float(n[1]) r_test_y = r_frac_y * a[1] for k in range(n[2]): r_frac_z = np.float(k)/np.float(n[2]) r_test = r_test_x +r_test_y + r_frac_z * a[2] r_test_fast = reshape_vector(r_test) B = calculate_dipole(r_test_fast, r_i, mom_i) omega = gamma_mu*np.sqrt(np.dot(B,B)) # write r_test, B and omega to a file frac_done = np.float(i+1)/(n[0]+1) t_elapsed = (time.clock()-t_start) t_remain = (1-frac_done)*t_elapsed/frac_done print frac_done*100,'% done in',t_elapsed/60.,'minutes...approximately',t_remain/60.,'minutes remaining'
[ "One obvious thing you can do is replace the line\nr_test_fast = reshape_vector(r_test)\n\nwith\nr_test_fast = r_test.reshape((3,1))\n\nProbably won't make any big difference in performance, but in any case it makes sense to use the numpy builtins instead of reinventing the wheel.\nGenerally speaking, as you probably have noticed by now, the trick with optimizing numpy is to express the algorithm with the help of numpy whole-array operations or at least with slices instead of iterating over each element in python code. What tends to prevent this kind of \"vectorization\" is so-called loop-carried dependencies, i.e. loops where each iteration is dependent on the result of a previous iteration. Looking briefly at your code, you have no such thing, and it should be possible to vectorize your code just fine.\nEDIT: One solution\nI haven't verified this is correct, but should give you an idea of how to approach it.\nFirst, take the cartesian() function, which we'll use. Then\n\n\ndef calculate_dipole_vect(mus, r_i, mom_i):\n # Treat each mu sequentially\n Bs = []\n omega = []\n for mu in mus:\n rel = mu - r_i\n r_norm = np.sqrt((rel * rel).sum(1))\n r_unit = rel / r_norm[:, np.newaxis]\n A = 1e-7\n\n num = A*(3*np.sum(mom_i * r_unit, 0)*r_unit - mom_i)\n den = r_norm ** 3\n B = np.sum(num / den[:, np.newaxis], 0)\n Bs.append(B)\n omega.append(gamma_mu * np.sqrt(np.dot(B, B)))\n return Bs, omega\n\n\n# Transpose to get more \"natural\" ordering with row-major numpy\nr_i = r_i.T\nmom_i = mom_i.T\n\nt_start = time.clock()\nr_frac = cartesian((np.arange(n[0]) / float(n[0]),\n np.arange(n[1]) / float(n[1]),\n np.arange(n[2]) / float(n[2])))\nr_test = np.dot(r_frac, a)\nB, omega = calculate_dipole_vect(r_test, r_i, mom_i)\n\nprint 'Total time for vectorized: %f s' % (time.clock() - t_start)\n\n\nWell, in my testing, this is in fact slightly slower than the loop-based approach I started from. The thing is, in the original version in the question, it was already vectorized with whole-array operations over arrays of shape (20000, 3), so any further vectorization doesn't really bring much further benefit. In fact, it may worsen the performance, as above, maybe due to big temporary arrays.\n", "If you profile your code, you'll see that 99% of the running time is in calculate_dipole so reducing the time for this looping really won't give a noticeable reduction in execution time. You still need to focus on calculate_dipole if you want to make this faster. I tried my Cython code for calculate_dipole on this and got a reduction by about a factor of 2 in the overall time. There might be other ways to improve the Cython code too.\n" ]
[ 2, 2 ]
[]
[]
[ "numpy", "optimization", "physics", "python" ]
stackoverflow_0002592696_numpy_optimization_physics_python.txt
Q: Process a set of files from a source directory to a destination directory in Python Being completely new in python I'm trying to run a command over a set of files in python. The command requires both source and destination file (I'm actually using imagemagick convert as in the example below). I can supply both source and destination directories, however I can't figure out how to easily retain the directory structure from the source to the destination directory. E.g. say the srcdir contains the following: srcdir/ file1 file3 dir1/ file1 file2 Then I want the program to create the following destination files on destdir: destdir/file1, destdir/file3, destdir/dir1/file1 and destdir/dir1/file2 So far this is what I came up with: import os from subprocess import call srcdir = os.curdir # just use the current directory destdir = 'path/to/destination' for root, dirs, files in os.walk(srcdir): for filename in files: sourceFile = os.path.join(root, filename) destFile = '???' cmd = "convert %s -resize 50%% %s" % (sourceFile, destFile) call(cmd, shell=True) The walk method doesn't directly provide what directory the file is under srcdir other than concatenating the root directory string with the file name. Is there some easy way to get the destination file, or do I have to do some string manipulation in order to do this? A: Change your loop to: for root, dirs, files in os.walk(srcdir): destroot = os.path.join(destdir, root[len(srcdir):]) for adir in dirs: os.makedirs(os.path.join(destroot, adir)) for filename in files: sourceFile = os.path.join(root, filename) destFile = os.path.join(destroot, filename) processFile(sourceFile, destFile) A: There are a few relative path scripts out there that will do what you want -- namely find the relative path between two paths. E.g.: http://www.voidspace.org.uk/python/pathutils.html (relpath method) http://code.activestate.com/recipes/302594-another-relative-filepath-script/ http://groups.google.com/group/comp.lang.python/browse_thread/thread/390d8d3e3ac8ef44/d8c74f96468c6a36?q=relative+path&rnum=1&pli=1 Unfortunately, I don't think this functionality has ever been added to core python. A: While not pretty, this will preserve the directory structure of the tree: _, _, subdirs = root.partition(srcdir) destfile = os.path.join(destdir, subdirs[1:], filename)
Process a set of files from a source directory to a destination directory in Python
Being completely new in python I'm trying to run a command over a set of files in python. The command requires both source and destination file (I'm actually using imagemagick convert as in the example below). I can supply both source and destination directories, however I can't figure out how to easily retain the directory structure from the source to the destination directory. E.g. say the srcdir contains the following: srcdir/ file1 file3 dir1/ file1 file2 Then I want the program to create the following destination files on destdir: destdir/file1, destdir/file3, destdir/dir1/file1 and destdir/dir1/file2 So far this is what I came up with: import os from subprocess import call srcdir = os.curdir # just use the current directory destdir = 'path/to/destination' for root, dirs, files in os.walk(srcdir): for filename in files: sourceFile = os.path.join(root, filename) destFile = '???' cmd = "convert %s -resize 50%% %s" % (sourceFile, destFile) call(cmd, shell=True) The walk method doesn't directly provide what directory the file is under srcdir other than concatenating the root directory string with the file name. Is there some easy way to get the destination file, or do I have to do some string manipulation in order to do this?
[ "Change your loop to:\nfor root, dirs, files in os.walk(srcdir):\n destroot = os.path.join(destdir, root[len(srcdir):])\n for adir in dirs:\n os.makedirs(os.path.join(destroot, adir))\n for filename in files:\n sourceFile = os.path.join(root, filename)\n destFile = os.path.join(destroot, filename)\n processFile(sourceFile, destFile)\n\n", "There are a few relative path scripts out there that will do what you want -- namely find the relative path between two paths. E.g.:\n\nhttp://www.voidspace.org.uk/python/pathutils.html\n(relpath method)\nhttp://code.activestate.com/recipes/302594-another-relative-filepath-script/\nhttp://groups.google.com/group/comp.lang.python/browse_thread/thread/390d8d3e3ac8ef44/d8c74f96468c6a36?q=relative+path&rnum=1&pli=1\n\nUnfortunately, I don't think this functionality has ever been added to core python.\n", "While not pretty, this will preserve the directory structure of the tree:\n_, _, subdirs = root.partition(srcdir)\ndestfile = os.path.join(destdir, subdirs[1:], filename)\n\n" ]
[ 2, 1, 0 ]
[]
[]
[ "path", "python" ]
stackoverflow_0002593399_path_python.txt
Q: Is there a way to backup everything in an app-engine blobstore? bulkloader.py is very handy. But as far as I can tell it doesn't appear to fetch items from the blobstore, so you can be left with broken entity relationships if you needed to dump/restore your application. Does anyone know a method for completely backing up their data from app-engine including blobstore data? A: In Java, you would instantiate a BlobInfoFactory and use BlobInfoFactory.queryBlobInfos. Then for each blob, you would run BlobstoreService.serve(...) with the BlobKeys returned from the BlobInfos. You still might end up with broken entity relationships - there's no way to guarantee each blob will end up with the same key it was originally loaded with. You'll have to account for this in your application.
Is there a way to backup everything in an app-engine blobstore?
bulkloader.py is very handy. But as far as I can tell it doesn't appear to fetch items from the blobstore, so you can be left with broken entity relationships if you needed to dump/restore your application. Does anyone know a method for completely backing up their data from app-engine including blobstore data?
[ "In Java, you would instantiate a BlobInfoFactory and use BlobInfoFactory.queryBlobInfos. \nThen for each blob, you would run BlobstoreService.serve(...) with the BlobKeys returned from the BlobInfos. You still might end up with broken entity relationships - there's no way to guarantee each blob will end up with the same key it was originally loaded with. You'll have to account for this in your application. \n" ]
[ 2 ]
[]
[]
[ "blobstore", "google_app_engine", "python" ]
stackoverflow_0002593756_blobstore_google_app_engine_python.txt
Q: Implement a server that receives and processes client request(cassandra as backend), Python or C++? I am planning to build an inverted index searching system with cassandra as its storage backend. But I need some guidances to build a highly efficient searching daemon server. I know a web server written in Python called tornado, my questions are: Is Python a good choice for developing such kind of apps? Is Nginx(or Sphinx) a good example that I can look inside to learn its architecture to implement a highly efficient server? Anything else I should learn to do this? Thank you~ A: Twisted framework is a good starting point for develop backend servers. It is fast and scalable. A: Python is unlikely to allow you to write the most efficient server possible. However, it may just be that it will be fast enough, because for most applications it is. Therefore, one path you could take is starting with Python. It's a great language for prototyping, much better than C++ for the stage in which you're not even sure which architecture to adopt. As you finish the project, you can see if Python is efficient enough. If it isn't and there's no easy way to make it much faster (such as rewriting a small routine that takes up most of the work in C), you can rewrite it in C++ using the Python prototype as a basis. A: For search, http://github.com/tjake/Lucandra may be interesting prior art.
Implement a server that receives and processes client request(cassandra as backend), Python or C++?
I am planning to build an inverted index searching system with cassandra as its storage backend. But I need some guidances to build a highly efficient searching daemon server. I know a web server written in Python called tornado, my questions are: Is Python a good choice for developing such kind of apps? Is Nginx(or Sphinx) a good example that I can look inside to learn its architecture to implement a highly efficient server? Anything else I should learn to do this? Thank you~
[ "Twisted framework is a good starting point for develop backend servers. It is fast and scalable. \n", "Python is unlikely to allow you to write the most efficient server possible. However, it may just be that it will be fast enough, because for most applications it is.\nTherefore, one path you could take is starting with Python. It's a great language for prototyping, much better than C++ for the stage in which you're not even sure which architecture to adopt. As you finish the project, you can see if Python is efficient enough. If it isn't and there's no easy way to make it much faster (such as rewriting a small routine that takes up most of the work in C), you can rewrite it in C++ using the Python prototype as a basis.\n", "For search, http://github.com/tjake/Lucandra may be interesting prior art.\n" ]
[ 1, 0, 0 ]
[]
[]
[ "c++", "full_text_search", "python", "search" ]
stackoverflow_0002582892_c++_full_text_search_python_search.txt
Q: Eclipse + PyDev: Eclipse telling me that this is an invalid import? I recently installed twython, a really sleek and awesome twitter API wrapper for Python. I installed it and it works fine from the interpreter, but when I try to import it via Eclipse, it says that twython is an invalid import. How do I "tell" eclipse where twython is so that it will let me import and use it? A: I believe I have had this problem before - try going into the menu: Window_Preferences and then select Pydev and Interpreter-Python. Then try to click Auto-config - it should update its search paths to include everything installed in Python. If that doesn't work, you should at least be able to manually add the folder by clicking "New Folder" in the bottom part of that screen and navigating to the location where you have twython installed. A: Daniel is right. As long as twython went into site-packages then Pydev will find it.
Eclipse + PyDev: Eclipse telling me that this is an invalid import?
I recently installed twython, a really sleek and awesome twitter API wrapper for Python. I installed it and it works fine from the interpreter, but when I try to import it via Eclipse, it says that twython is an invalid import. How do I "tell" eclipse where twython is so that it will let me import and use it?
[ "I believe I have had this problem before - try going into the menu: Window_Preferences and then select Pydev and Interpreter-Python. Then try to click Auto-config - it should update its search paths to include everything installed in Python. If that doesn't work, you should at least be able to manually add the folder by clicking \"New Folder\" in the bottom part of that screen and navigating to the location where you have twython installed.\n", "Daniel is right. As long as twython went into site-packages then Pydev will find it.\n" ]
[ 3, 0 ]
[]
[]
[ "eclipse", "pydev", "python", "twython" ]
stackoverflow_0002590435_eclipse_pydev_python_twython.txt
Q: Automatically execute commands on launching python shell I was wondering if there is a way to automatically run commands on entering the python shell as you would with the .bash_profile or .profile scripts with bash. I would like to automatically import some modules so I don't have to type the whole shebang everytime I hop into the shell. Thanks, A: Yup you can use the PYTHONSTARTUP environment variable to do this as outlined here A: Also consider using ipython if you're doing a lot of interactive work. Your options for this kind of automation expand significantly.
Automatically execute commands on launching python shell
I was wondering if there is a way to automatically run commands on entering the python shell as you would with the .bash_profile or .profile scripts with bash. I would like to automatically import some modules so I don't have to type the whole shebang everytime I hop into the shell. Thanks,
[ "Yup you can use the PYTHONSTARTUP environment variable to do this as outlined here\n", "Also consider using ipython if you're doing a lot of interactive work. Your options for this kind of automation expand significantly.\n" ]
[ 12, 1 ]
[]
[]
[ "python", "shell" ]
stackoverflow_0002587709_python_shell.txt
Q: Exit to command line in Python I have a script that I want to exit early under some condition: if not "id" in dir(): print "id not set, cannot continue" # exit here! # otherwise continue with the rest of the script... print "alright..." [ more code ] I run this script using execfile("foo.py") from the Python interactive prompt and I would like the script to exit going back to interactive interpreter. How do I do this? If I use sys.exit(), the Python interpreter exits completely. A: In the interactive interpreter; catch SystemExit raised by sys.exit and ignore it: try: execfile("mymodule.py") except SystemExit: pass A: Put your code block in a method and return from that method, like such: def do_the_thing(): if not "id" in dir(): print "id not set, cannot continue" return # exit here! # otherwise continue with the rest of the script... print "alright..." # [ more code ] # Call the method do_the_thing() Also, unless there is a good reason to use execfile(), this method should probably be put in a module, where it can be called from another Python script by importing it: import mymodule mymodule.do_the_thing() A: I'm a little obsessed with ipython for interactive work but check out the tutorial on shell embedding for a more robust solution than this one (which is your most direct route). A: Instead of using execfile, you should make the script importable (name=='main protection, seperated into functions, etc.), and then call the functions from the interpreter.
Exit to command line in Python
I have a script that I want to exit early under some condition: if not "id" in dir(): print "id not set, cannot continue" # exit here! # otherwise continue with the rest of the script... print "alright..." [ more code ] I run this script using execfile("foo.py") from the Python interactive prompt and I would like the script to exit going back to interactive interpreter. How do I do this? If I use sys.exit(), the Python interpreter exits completely.
[ "In the interactive interpreter; catch SystemExit raised by sys.exit and ignore it:\ntry:\n execfile(\"mymodule.py\")\nexcept SystemExit:\n pass\n\n", "Put your code block in a method and return from that method, like such:\ndef do_the_thing():\n if not \"id\" in dir():\n print \"id not set, cannot continue\"\n return\n # exit here!\n # otherwise continue with the rest of the script...\n print \"alright...\"\n # [ more code ]\n\n# Call the method\ndo_the_thing()\n\nAlso, unless there is a good reason to use execfile(), this method should probably be put in a module, where it can be called from another Python script by importing it:\nimport mymodule\nmymodule.do_the_thing()\n\n", "I'm a little obsessed with ipython for interactive work but check out the tutorial on shell embedding for a more robust solution than this one (which is your most direct route).\n", "Instead of using execfile, you should make the script importable (name=='main protection, seperated into functions, etc.), and then call the functions from the interpreter. \n" ]
[ 7, 3, 2, 0 ]
[]
[]
[ "command_line", "execfile", "exit", "python", "scripting" ]
stackoverflow_0002587083_command_line_execfile_exit_python_scripting.txt
Q: How should I write this string-prefix check so that it's idiomatic Python? I have a couple of lists of items: specials = ['apple', 'banana', 'cherry', ...] smoothies = ['banana-apple', 'mocha mango', ...] I want to make a new list, special_smoothies, consisting of elements in smoothies that start with the elements in specials. However, if specials is blank, special_smoothies should be identical to smoothies. What's the most Pythonic way to do this? Is there a way to do this without a separate conditional check on whether specials is blank? A: Since you want the behavior for empty specials to be different from the natural limit of the behavior for non-empty, you do need to special-case: if specials: specialsmoothies = [x for x in smoothies if any(x.startswith(y) for y in specials)] else: specialsmoothies = list(smoothies) In other words, you want the behavior for empty specials to be "all smoothies are specials", while the natural limit behavior would be to say that in that case "no smoothie is special" since none of them starts with one of the prefixes in specials (since there are no such prefixes in that case). So, one way or another (an if/else or otherwise) you do need to make a special case in your code to match the special, irregular case you want in its semantics. A: There are a couple of ways to do it without an explicit check on specials. But don't do them. if specials: special_smoothies = [x for x in smoothies if any(True for y in specials if x.startswith(y))] else: special_smoothies = smoothies[:] A: str.startswith() accepts tuple as an argument: if specials: specialsmoothies = [x for x in smoothies if x.startswith(tuple(specials))] else: specialsmoothies = list(smoothies) A: Why complicate things? I think this is the most readable. Alex and Ignacio both give good reasons for not avoiding the else clause. special_smoothies = [] if specials: for smoothy in smoothies: for special in specials: if smoothy.startswith(special): special_smoothies.append(smoothy) else: special_smoothies = smoothies[:]
How should I write this string-prefix check so that it's idiomatic Python?
I have a couple of lists of items: specials = ['apple', 'banana', 'cherry', ...] smoothies = ['banana-apple', 'mocha mango', ...] I want to make a new list, special_smoothies, consisting of elements in smoothies that start with the elements in specials. However, if specials is blank, special_smoothies should be identical to smoothies. What's the most Pythonic way to do this? Is there a way to do this without a separate conditional check on whether specials is blank?
[ "Since you want the behavior for empty specials to be different from the natural limit of the behavior for non-empty, you do need to special-case:\nif specials:\n specialsmoothies = [x for x in smoothies\n if any(x.startswith(y) for y in specials)]\nelse:\n specialsmoothies = list(smoothies)\n\nIn other words, you want the behavior for empty specials to be \"all smoothies are specials\", while the natural limit behavior would be to say that in that case \"no smoothie is special\" since none of them starts with one of the prefixes in specials (since there are no such prefixes in that case). So, one way or another (an if/else or otherwise) you do need to make a special case in your code to match the special, irregular case you want in its semantics.\n", "There are a couple of ways to do it without an explicit check on specials. But don't do them.\nif specials:\n special_smoothies = [x for x in smoothies if any(True for y in specials if x.startswith(y))]\nelse:\n special_smoothies = smoothies[:]\n\n", "str.startswith() accepts tuple as an argument:\nif specials:\n specialsmoothies = [x for x in smoothies if x.startswith(tuple(specials))]\nelse:\n specialsmoothies = list(smoothies)\n\n", "Why complicate things? I think this is the most readable. Alex and Ignacio both give good reasons for not avoiding the else clause.\nspecial_smoothies = []\nif specials:\n for smoothy in smoothies:\n for special in specials:\n if smoothy.startswith(special):\n special_smoothies.append(smoothy)\nelse:\n special_smoothies = smoothies[:]\n\n" ]
[ 4, 3, 1, 0 ]
[]
[]
[ "list", "python", "string" ]
stackoverflow_0002593496_list_python_string.txt
Q: How to write a shell in Python I've written a small console application that can perform certain tasks. The user interface is similar to things like version control systems or yum etc. So basically you can think of it as a domain specific language. Now I'd like to write a (bash like) shell that can execute and auto-complete this language and has a command history (so I do not have to load and save the quite large xml files on each command). In a nutshell I want something like ipython but not for executing python code but my own DSL. Are there any libraries that help me doing this? I see that there is a readline and rlcompleter module in python but its documentation seems to indicate that this is only for use with the python shell itself, or did I miss something there? A: You should check out the cmd and cmd2 modules. I think they will do what you want. There was a PyCon talk about these. A: If you need an administrative shell to be accessed via network Twisted python framework's manhole is a good solution. Example: http://www.devshed.com/c/a/Python/SSH-with-Twisted/3/
How to write a shell in Python
I've written a small console application that can perform certain tasks. The user interface is similar to things like version control systems or yum etc. So basically you can think of it as a domain specific language. Now I'd like to write a (bash like) shell that can execute and auto-complete this language and has a command history (so I do not have to load and save the quite large xml files on each command). In a nutshell I want something like ipython but not for executing python code but my own DSL. Are there any libraries that help me doing this? I see that there is a readline and rlcompleter module in python but its documentation seems to indicate that this is only for use with the python shell itself, or did I miss something there?
[ "You should check out the cmd and cmd2 modules. I think they will do what you want. There was a PyCon talk about these.\n", "If you need an administrative shell to be accessed via network Twisted python framework's manhole is a good solution. Example:\nhttp://www.devshed.com/c/a/Python/SSH-with-Twisted/3/\n" ]
[ 22, 3 ]
[]
[]
[ "python", "shell" ]
stackoverflow_0002594560_python_shell.txt
Q: sqlite3.OperationalError: database is locked - non-threaded application I have a Python application which throws the standard sqlite3.OperationalError: database is locked error. I have looked around the internet and could not find any solution which worked (please note that there is no multiprocesses/threading going on, and as you can see I have tried raising the timeout parameter). The sqlite file is stored on the local hard drive. The following function is one of many which accesses the sqlite database, and runs fine the first time it is called, but throws the above error the second time it is called (it is called as part of a for loop in another function): def update_index(filepath): path = get_setting('Local', 'web') stat = os.stat(filepath) modified = stat.st_mtime index_file = get_setting('Local', 'index') connection = sqlite3.connect(index_file, 30) cursor = connection.cursor() head, tail = os.path.split(filepath) cursor.execute('UPDATE hwlive SET date=? WHERE path=? AND name=?;', (modified, head, tail)) connection.commit() connection.close() Many thanks. A: You might particularly check for functions that keep a read-lock (unfinished cursor). That would block the commit from the update function. Note that there is a dedicated mailing list for Python-sqlite problems: http://groups.google.com/group/python-sqlite A: Do you really need to continuously open and close the database file for every single UPDATE? If you do the same thing in every function that accesses the database, is it possible that you have called the update_index function from another function that already opened the database using a different connection and is in the process of modifying the database?
sqlite3.OperationalError: database is locked - non-threaded application
I have a Python application which throws the standard sqlite3.OperationalError: database is locked error. I have looked around the internet and could not find any solution which worked (please note that there is no multiprocesses/threading going on, and as you can see I have tried raising the timeout parameter). The sqlite file is stored on the local hard drive. The following function is one of many which accesses the sqlite database, and runs fine the first time it is called, but throws the above error the second time it is called (it is called as part of a for loop in another function): def update_index(filepath): path = get_setting('Local', 'web') stat = os.stat(filepath) modified = stat.st_mtime index_file = get_setting('Local', 'index') connection = sqlite3.connect(index_file, 30) cursor = connection.cursor() head, tail = os.path.split(filepath) cursor.execute('UPDATE hwlive SET date=? WHERE path=? AND name=?;', (modified, head, tail)) connection.commit() connection.close() Many thanks.
[ "You might particularly check for functions that keep a read-lock (unfinished cursor). That would block the commit from the update function. Note that there is a dedicated mailing list for Python-sqlite problems: http://groups.google.com/group/python-sqlite \n", "Do you really need to continuously open and close the database file for every single UPDATE? If you do the same thing in every function that accesses the database, is it possible that you have called the update_index function from another function that already opened the database using a different connection and is in the process of modifying the database?\n" ]
[ 2, 1 ]
[]
[]
[ "python", "sql", "sqlite" ]
stackoverflow_0002569233_python_sql_sqlite.txt
Q: Trying to set up nested while loops using a boolean switch I'm trying to set up a while loop that will ask the user for the employee name, hours worked and hourly wage until the user enters 'DONE'. Eventually I'll modify the code to calculate the weekly pay and write it to a list, but one thing at a time. The problem is once the main while loop executes once, it just stops. Doesn't error out but just stops. I have to kill the program to get it to stop. I want it to ask the three questions again and again until the user is finished. Thoughts? Please note that this is just an exercise and not meant for any real world application. def getName(): """Asks for the employee's full name""" firstName=raw_input("\nWhat is your first name? ") lastName=raw_input("\nWhat is your last name? ") fullName=firstName.title() + " " + lastName.title() return fullName def getHours(): """Asks for the number of hours the employee worked""" hoursWorked=0 while int(hoursWorked)<1 or int(hoursWorked) > 60: hoursWorked=raw_input("\nHow many hours did the employee work: ") if int(hoursWorked)<1 or int(hoursWorked) > 60: print "Please enter an integer between 1 and 60." else: return hoursWorked def getWage(): """Asks for the employee's hourly wage""" wage=0 while float(wage)<6.00 or float(wage)>20.00: wage=raw_input("\nWhat is the employee's hourly wage: ") if float(wage)<6.00 or float(wage)>20.00: print ("Please enter an hourly wage between $6.00 and $20.00") else: return wage ##sentry variables employeeName="" employeeHours=0 employeeWage=0 booleanDone=False #Enter employee info print "Please enter payroll information for an employee or enter 'DONE' to quit." while booleanDone==False: while employeeName=="": employeeName=getName() if employeeName.lower()=="done": booleanDone=True break print "The employee's name is", employeeName while employeeHours==0: employeeHours=getHours() if employeeHours.lower()=="done": booleanDone=True break print employeeName, "worked", employeeHours, "this week." while employeeWage==0: employeeWage=getWage() if employeeWage.lower()=="done": booleanDone=True break print employeeName + "'s hourly wage is $" + employeeWage A: The problem is that after the first loop, employeeName and the other variables will already have values, so your inner while loops will be skipped. This leads to the outer loop repeating infinitely without doing anything. I would just remove the inner while loops: you don't really need them, because you already do validation inside getHours and the other functions. Another option is to reset the variable values at the start of the outer while loop. Some more things to improve (not related to this error): In getHours and getWage, you can just use while True instead of the condition you have now. If the condition is false, you would have returned from the function already anyway. You need to catch ValueError in getHours and getWage, in case non-numeric data was entered. instead of booleanDone==False, use not booleanDone. Though if you remove the inner loops as I suggested, you don't even need this boolean: Just break out of the loop when needed. A: getHours and getWage assume the input is respectively in int and float format. So the checks for ...lower()=="done" can never possibly be satisfied: if the user had entered done at the prompt in either of these functions, the program would have died with a ValueError exception. But that's a different bug. At the end of the first leg of the outer loop, we know that neither of the three strings is empty (the inner loops guarantee that). Then, those strings aren't reset -- so they're still not empty -- so on every future leg of the outer loop none of the inner loops ever execute again. This should cause infinite fast empty looping as opposed to a clean exit (i.e. it's not clear why the symptoms of the obvious bug I just described differ from your observations), so there may be further bugs yet -- but when there are two easily spotted killer bug in this small a piece of code I think it's wiser to stop digging (what's the use of spotting another few?-). You should rather refactor the structure, making the role of the functions extremely clear and precise: what do those functions return, exactly? If strings, what are the constraints on those strings? It seems they're roughly returning "a valid string for this entry" (except for the possibility of killing all the program if the user has a typo in the wages or hours, which you could avoid with a try/except) -- the first one, and that one only, could return done (but then it should make this clear in its prompting, and avoid the second useless prompt if the users says done to the first prompt). Once you document them as such it becomes clear that the inner while loops are unwarranted; the outer loop could just be while True: employeeName=getName() if employeeName.lower()=="done": break print "The employee's name is", employeeName employeeHours=getHours() print employeeName, "worked", employeeHours, "this week." employeeWage=getWage() print employeeName + "'s hourly wage is $" + employeeWage
Trying to set up nested while loops using a boolean switch
I'm trying to set up a while loop that will ask the user for the employee name, hours worked and hourly wage until the user enters 'DONE'. Eventually I'll modify the code to calculate the weekly pay and write it to a list, but one thing at a time. The problem is once the main while loop executes once, it just stops. Doesn't error out but just stops. I have to kill the program to get it to stop. I want it to ask the three questions again and again until the user is finished. Thoughts? Please note that this is just an exercise and not meant for any real world application. def getName(): """Asks for the employee's full name""" firstName=raw_input("\nWhat is your first name? ") lastName=raw_input("\nWhat is your last name? ") fullName=firstName.title() + " " + lastName.title() return fullName def getHours(): """Asks for the number of hours the employee worked""" hoursWorked=0 while int(hoursWorked)<1 or int(hoursWorked) > 60: hoursWorked=raw_input("\nHow many hours did the employee work: ") if int(hoursWorked)<1 or int(hoursWorked) > 60: print "Please enter an integer between 1 and 60." else: return hoursWorked def getWage(): """Asks for the employee's hourly wage""" wage=0 while float(wage)<6.00 or float(wage)>20.00: wage=raw_input("\nWhat is the employee's hourly wage: ") if float(wage)<6.00 or float(wage)>20.00: print ("Please enter an hourly wage between $6.00 and $20.00") else: return wage ##sentry variables employeeName="" employeeHours=0 employeeWage=0 booleanDone=False #Enter employee info print "Please enter payroll information for an employee or enter 'DONE' to quit." while booleanDone==False: while employeeName=="": employeeName=getName() if employeeName.lower()=="done": booleanDone=True break print "The employee's name is", employeeName while employeeHours==0: employeeHours=getHours() if employeeHours.lower()=="done": booleanDone=True break print employeeName, "worked", employeeHours, "this week." while employeeWage==0: employeeWage=getWage() if employeeWage.lower()=="done": booleanDone=True break print employeeName + "'s hourly wage is $" + employeeWage
[ "The problem is that after the first loop, employeeName and the other variables will already have values, so your inner while loops will be skipped. This leads to the outer loop repeating infinitely without doing anything.\nI would just remove the inner while loops: you don't really need them, because you already do validation inside getHours and the other functions. Another option is to reset the variable values at the start of the outer while loop.\nSome more things to improve (not related to this error):\n\nIn getHours and getWage, you can just use while True instead of the condition you have now. If the condition is false, you would have returned from the function already anyway.\nYou need to catch ValueError in getHours and getWage, in case non-numeric data was entered.\ninstead of booleanDone==False, use not booleanDone. Though if you remove the inner loops as I suggested, you don't even need this boolean: Just break out of the loop when needed.\n\n", "getHours and getWage assume the input is respectively in int and float format. So the checks for ...lower()==\"done\" can never possibly be satisfied: if the user had entered done at the prompt in either of these functions, the program would have died with a ValueError exception. But that's a different bug.\nAt the end of the first leg of the outer loop, we know that neither of the three strings is empty (the inner loops guarantee that). Then, those strings aren't reset -- so they're still not empty -- so on every future leg of the outer loop none of the inner loops ever execute again. This should cause infinite fast empty looping as opposed to a clean exit (i.e. it's not clear why the symptoms of the obvious bug I just described differ from your observations), so there may be further bugs yet -- but when there are two easily spotted killer bug in this small a piece of code I think it's wiser to stop digging (what's the use of spotting another few?-).\nYou should rather refactor the structure, making the role of the functions extremely clear and precise: what do those functions return, exactly? If strings, what are the constraints on those strings? It seems they're roughly returning \"a valid string for this entry\" (except for the possibility of killing all the program if the user has a typo in the wages or hours, which you could avoid with a try/except) -- the first one, and that one only, could return done (but then it should make this clear in its prompting, and avoid the second useless prompt if the users says done to the first prompt). Once you document them as such it becomes clear that the inner while loops are unwarranted; the outer loop could just be\nwhile True:\n employeeName=getName() \n if employeeName.lower()==\"done\":\n break\n print \"The employee's name is\", employeeName\n\n employeeHours=getHours() \n print employeeName, \"worked\", employeeHours, \"this week.\"\n\n employeeWage=getWage() \n print employeeName + \"'s hourly wage is $\" + employeeWage\n\n" ]
[ 3, 1 ]
[]
[]
[ "nested_loops", "python", "while_loop" ]
stackoverflow_0002594735_nested_loops_python_while_loop.txt
Q: Google App Engine: Difficulty with Users API (or maybe just a Python syntax problem) I have a simple GAE app that includes a login/logout link. This app is running on the dev server at the moment. The base page handler gets the current user, and creates a login/logout url appropriately. It then puts this information into a _template_data dictionary, for convenience of subclasses. class BasePage(webapp.RequestHandler): _user = users.get_current_user() _login_logout_link = None if _user: _login_logout_link = users.create_logout_url('/') else: _login_logout_link = users.create_login_url('/') _template_data = {} _template_data['login_logout_link'] = _login_logout_link _template_data['user'] = _user def render(self, templateName, templateData): path = os.path.join(os.path.dirname(__file__), 'Static/Templates/%s.html' % templateName) self.response.out.write(template.render(path, templateData)) Here is one such subclass: class MainPage(BasePage): def get(self): self.render('start', self._template_data) The login/logout link is displayed fine, and going to the correct devserver login/logout page. However, it seems to have no effect - the server still seems to think the user is logged out. What am I doing wrong here? A: I believe the problem is the _user attribute. Currently, the _user attribute is bound when the module containing the class is imported (probably when the application starts). You need to get the current user for each request. I would rewrite into something like: class BasePage(webapp.RequestHandler): def render(self, template_name, data={}): template_data = {} user = template_data["user"] = users.get_current_user() template_data["login_logout_link"] = users.create_logout_url() if user else users.create_login_url() template_data.update(data) path = os.path.join(os.path.dirname(__file__), 'Static', 'Templates', '%s.html' % template_name) self.response.out.write(template.render(path, template_data) The templates would then always get the values user and login_logout_link sent in. In a subclass, you can pass extra values to the template using the data argument (template_data.update(data) updates the template_data dictionary with the key/value pairs from the data dictionary). Subclass example: class MainPage(BasePage): def get(self): self.render('start', data={"now": datetime.now()})
Google App Engine: Difficulty with Users API (or maybe just a Python syntax problem)
I have a simple GAE app that includes a login/logout link. This app is running on the dev server at the moment. The base page handler gets the current user, and creates a login/logout url appropriately. It then puts this information into a _template_data dictionary, for convenience of subclasses. class BasePage(webapp.RequestHandler): _user = users.get_current_user() _login_logout_link = None if _user: _login_logout_link = users.create_logout_url('/') else: _login_logout_link = users.create_login_url('/') _template_data = {} _template_data['login_logout_link'] = _login_logout_link _template_data['user'] = _user def render(self, templateName, templateData): path = os.path.join(os.path.dirname(__file__), 'Static/Templates/%s.html' % templateName) self.response.out.write(template.render(path, templateData)) Here is one such subclass: class MainPage(BasePage): def get(self): self.render('start', self._template_data) The login/logout link is displayed fine, and going to the correct devserver login/logout page. However, it seems to have no effect - the server still seems to think the user is logged out. What am I doing wrong here?
[ "I believe the problem is the _user attribute.\nCurrently, the _user attribute is bound when the module containing the class is imported (probably when the application starts). You need to get the current user for each request.\nI would rewrite into something like:\nclass BasePage(webapp.RequestHandler):\n def render(self, template_name, data={}):\n template_data = {}\n user = template_data[\"user\"] = users.get_current_user()\n template_data[\"login_logout_link\"] = users.create_logout_url() if user else users.create_login_url()\n template_data.update(data)\n path = os.path.join(os.path.dirname(__file__), 'Static', 'Templates', '%s.html' % template_name)\n self.response.out.write(template.render(path, template_data)\n\nThe templates would then always get the values user and login_logout_link sent in. In a subclass, you can pass extra values to the template using the data argument (template_data.update(data) updates the template_data dictionary with the key/value pairs from the data dictionary). \nSubclass example:\nclass MainPage(BasePage):\n def get(self):\n self.render('start', data={\"now\": datetime.now()})\n\n" ]
[ 2 ]
[]
[]
[ "google_app_engine", "python", "syntax" ]
stackoverflow_0002595073_google_app_engine_python_syntax.txt
Q: How to display specific cookie? I'm using ActivePython 2.5.1 and the cookielib package to retrieve web pages. I'd like to display a given cookie from the cookiejar instead of the whole thing: #OK to display all the cookies for index, cookie in enumerate(cj): print index, ' : ', cookie #How to display just PHPSESSID? #AttributeError: CookieJar instance has no attribute '__getitem__' print "PHPSESSID: %s" % cj['PHPSESSID'] I'm sure it's very simple but googling for this didn't return samples. Thank you. A: The cookiejar does not have a dict-like interface, only iteration is supported. So you have to implement a lookup method yourself. I am not sure what cookie attribute you want do do the lookup on. Example, using name: def get_cookie_by_name(cj, name): return [cookie for cookie in cj if cookie.name == name][0] cookie = get_cookie_by_name(cj, "PHPSESSID") If you're not familiar with the [...] syntax, it is a list comprehension. The [0] then picks the first element of the list of matching cookies.
How to display specific cookie?
I'm using ActivePython 2.5.1 and the cookielib package to retrieve web pages. I'd like to display a given cookie from the cookiejar instead of the whole thing: #OK to display all the cookies for index, cookie in enumerate(cj): print index, ' : ', cookie #How to display just PHPSESSID? #AttributeError: CookieJar instance has no attribute '__getitem__' print "PHPSESSID: %s" % cj['PHPSESSID'] I'm sure it's very simple but googling for this didn't return samples. Thank you.
[ "The cookiejar does not have a dict-like interface, only iteration is supported. So you have to implement a lookup method yourself.\nI am not sure what cookie attribute you want do do the lookup on. Example, using name:\ndef get_cookie_by_name(cj, name):\n return [cookie for cookie in cj if cookie.name == name][0]\n\ncookie = get_cookie_by_name(cj, \"PHPSESSID\")\n\nIf you're not familiar with the [...] syntax, it is a list comprehension. The [0] then picks the first element of the list of matching cookies.\n" ]
[ 5 ]
[]
[]
[ "cookielib", "python" ]
stackoverflow_0002594947_cookielib_python.txt
Q: Iterating over a database column in Django I would like to iterate a calculation over a column of values in a MySQL database. I wondered if Django had any built-in functionality for doing this. Previously, I have just used the following to store each column as a list of tuples with the name table_column: import MySQLdb import sys try: conn = MySQLdb.connect (host = "localhost", user = "user", passwd="passwd", db="db") except MySQLdb.Error, e: print "Error %d: %s" % (e.args[0], e.args[1]) sys.exit (1) cursor = conn.cursor() for table in ['foo', 'bar']: for column in ['foobar1', 'foobar2']: cursor.execute('select %s from %s' % (column, table)) exec "%s_%s = cursor.fetchall()" % (table, column) cursor.close() conn.commit() conn.close() Is there any functionality built into Django to more conveniently iterate through the values of a column in a database table? I'm dealing with millions of rows so speed of execution is important. [SOLVED] Thanks everyone. I used the built-in iterator, combined with the values_list() call for performance optimization. Note that calling values() will return dicts, which are slow to iterate over, whereas values_list() returns much faster tuples. So, for example, if I want to iterate over every row of the column 'foobar1', in the table 'foo', I can obtain an iterator in the following way: foobar1_iterator = foo.objects.values_list('foobar1').iterator() Suppose I want to iterate over i to produce a list of all row values of 'foobar1'. Then simply do this: foobar1_list = [i for i in foobar1_iterator] A: Database microoptimalisation is not a strong part of Django ORM. However, when speed is so important, I wonder if the exec is the right way to do it. Anyways, You write "iterate through the values of a column", this means you have multiple values in single column separated by a separator (not seen in your code)? Then just for value in modelinstalnce.column.split('seprator'): print 'whatever' As for connection, it's better to use from django.db import connection instead of doing it by hand. As for pairs, I'd do something like: pairs = [] for model in (MyModel, MyModel2,): for field in model.field_names: pairs.append((field, getattr(model, field)) A: from django.db.models.loading import get_model app_name = 'your_app_name' for model_name in ['foo','bar']: model = get_model(app_name, model_name) model_values = model.objects.values('foorbar1','foobar2') # this is a ValuesQuerySet. # you can run your computation on it, # or store the values somewhere. A: Look into Django docs for only() and iterator(): http://docs.djangoproject.com/en/1.1/ref/models/querysets/#only-fields http://docs.djangoproject.com/en/1.1/ref/models/querysets/#iterator
Iterating over a database column in Django
I would like to iterate a calculation over a column of values in a MySQL database. I wondered if Django had any built-in functionality for doing this. Previously, I have just used the following to store each column as a list of tuples with the name table_column: import MySQLdb import sys try: conn = MySQLdb.connect (host = "localhost", user = "user", passwd="passwd", db="db") except MySQLdb.Error, e: print "Error %d: %s" % (e.args[0], e.args[1]) sys.exit (1) cursor = conn.cursor() for table in ['foo', 'bar']: for column in ['foobar1', 'foobar2']: cursor.execute('select %s from %s' % (column, table)) exec "%s_%s = cursor.fetchall()" % (table, column) cursor.close() conn.commit() conn.close() Is there any functionality built into Django to more conveniently iterate through the values of a column in a database table? I'm dealing with millions of rows so speed of execution is important. [SOLVED] Thanks everyone. I used the built-in iterator, combined with the values_list() call for performance optimization. Note that calling values() will return dicts, which are slow to iterate over, whereas values_list() returns much faster tuples. So, for example, if I want to iterate over every row of the column 'foobar1', in the table 'foo', I can obtain an iterator in the following way: foobar1_iterator = foo.objects.values_list('foobar1').iterator() Suppose I want to iterate over i to produce a list of all row values of 'foobar1'. Then simply do this: foobar1_list = [i for i in foobar1_iterator]
[ "Database microoptimalisation is not a strong part of Django ORM. However, when speed is so important, I wonder if the exec is the right way to do it.\nAnyways, You write \"iterate through the values of a column\", this means you have multiple values in single column separated by a separator (not seen in your code)?\nThen just\nfor value in modelinstalnce.column.split('seprator'):\n print 'whatever'\n\nAs for connection, it's better to use\nfrom django.db import connection\n\ninstead of doing it by hand.\nAs for pairs, I'd do something like:\npairs = []\n\nfor model in (MyModel, MyModel2,):\n for field in model.field_names:\n pairs.append((field, getattr(model, field))\n\n", "from django.db.models.loading import get_model\napp_name = 'your_app_name'\nfor model_name in ['foo','bar']:\n model = get_model(app_name, model_name)\n model_values = model.objects.values('foorbar1','foobar2') # this is a ValuesQuerySet. \n # you can run your computation on it, \n # or store the values somewhere.\n\n", "Look into Django docs for only() and iterator():\nhttp://docs.djangoproject.com/en/1.1/ref/models/querysets/#only-fields\nhttp://docs.djangoproject.com/en/1.1/ref/models/querysets/#iterator\n" ]
[ 2, 1, 1 ]
[]
[]
[ "database", "django", "mysql", "python" ]
stackoverflow_0002595296_database_django_mysql_python.txt
Q: Asynchronous subprocess on Windows First of all, the overall problem I am solving is a bit more complicated than I am showing here, so please do not tell me 'use threads with blocking' as it would not solve my actual situation without a fair, FAIR bit of rewriting and refactoring. I have several applications which are not mine to modify, which take data from stdin and poop it out on stdout after doing their magic. My task is to chain several of these programs. Problem is, sometimes they choke, and as such I need to track their progress which is outputted on STDERR. pA = subprocess.Popen(CommandA, shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE) # ... some more processes make up the chain, but that is irrelevant to the problem pB = subprocess.Popen(CommandB, shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=pA.stdout ) Now, reading directly through pA.stdout.readline() and pB.stdout.readline(), or the plain read() functions, is a blocking matter. Since different applications output in different paces and different formats, blocking is not an option. (And as I wrote above, threading is not an option unless at a last, last resort.) pA.communicate() is deadlock safe, but since I need the information live, that is not an option either. Thus google brought me to this asynchronous subprocess snippet on ActiveState. All good at first, until I implement it. Comparing the cmd.exe output of pA.exe | pB.exe, ignoring the fact both output to the same window making for a mess, I see very instantaneous updates. However, I implement the same thing using the above snippet and the read_some() function declared there, and it takes over 10 seconds to notify updates of a single pipe. But when it does, it has updates leading all the way upto 40% progress, for example. Thus I do some more research, and see numerous subjects concerning PeekNamedPipe, anonymous handles, and returning 0 bytes available even though there is information available in the pipe. As the subject has proven quite a bit beyond my expertise to fix or code around, I come to Stack Overflow to look for guidance. :) My platform is W7 64-bit with Python 2.6, the applications are 32-bit in case it matters, and compatibility with Unix is not a concern. I can even deal with a full ctypes or pywin32 solution that subverts subprocess entirely if it is the only solution, as long as I can read from every stderr pipe asynchronously with immediate performance and no deadlocks. :) A: How bad is it to have to use threads? I encountered much the same problem and eventually decided to use threads to gather up all the data on a sub-process's stdout and stderr and put it onto a thread-safe queue which which the main thread can read in a blocking fashion, without having to worry about the threading going on behind the scenes. It's not clear what trouble you anticipate with a solution based on threads and blocking. Are you worried about having to make the rest of your code thread-safe? That shouldn't be an issue since the IO thread wouldn't need to interact with any of the rest of your code or data. If you have very restrictive memory requirements or your pipeline is particularly long then perhaps you may feel unhappy about spawning so many threads. I don't know enough about your situation so I couldn't say if this is likely to be a problem, but it seems to me that since you're already spawning off extra processes a few threads to interact with them should not be a terrible burden. In my situation I have not found these IO threads to be particularly problematic. My thread function looked something like this: def simple_io_thread(pipe, queue, tag, stop_event): """ Read line-by-line from pipe, writing (tag, line) to the queue. Also checks for a stop_event to give up before the end of the stream. """ while True: line = pipe.readline() while True: try: # Post to the queue with a large timeout in case the # queue is full. queue.put((tag, line), block=True, timeout=60) break except Queue.Full: if stop_event.isSet(): break continue if stop_event.isSet() or line=="": break pipe.close() When I start up the subprocess I do this: outputqueue = Queue.Queue(50) stop_event = threading.Event() process = subprocess.Popen( command, cwd=workingdir, env=env, shell=useshell, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stderr_thread = threading.Thread( target=simple_io_thread, args=(process.stderr, outputqueue, "STDERR", stop_event) ) stdout_thread = threading.Thread( target=simple_io_thread, args=(process.stdout, outputqueue, "STDOUT", stop_event) ) stderr_thread.daemon = True stdout_thread.daemon = True stderr_thread.start() stdout_thread.start() Then when I want to read I can just block on outputqueue - each item read from it contains either a string to identify which pipe it came from and a line of text from that pipe. Very little code runs in a separate thread, and it only communicates with the main thread via a thread-safe queue (plus an event in case I need to give up early). Perhaps this approach would be useful and allow you to solve the problem with threads and blocking but without having to rewrite lots of code? (My solution is made more complicated because I sometimes wish to terminate the subprocesses early, and want to be sure that the threads will all finish. If that's not an issue you can get rid of all the stop_event stuff and it becomes pretty succinct.) A: I assume that the process pipeline will not deadlock if it only uses stdin and stdout; and the problem you're trying to solve is how to make it not deadlock if they write to stderr (and have to deal with stderr possibly getting backed up). If you're letting multiple processes write to stderr, you have to watch out for their output being intermingled. I'm guessing you have that sorted somehow; just putting it out there to be sure. Be aware of the -u flag to python; it is helpful when testing to see if OS buffering is screwing you up. If you want to emulate select() on file handles in win32, your only choice is to use PeekNamedPipe() and friends. I have a snippet of code that reads line-oriented output from multiple processes at once, which you may even be able to use directly -- try passing the list of proc.stderr handles to it and go. class NoLineError(Exception): pass class NoMoreLineError(Exception): pass class LineReader(object): """Helper class for multi_readlines.""" def __init__(self, f): self.fd = f.fileno() self.osf = msvcrt.get_osfhandle(self.fd) self.buf = '' def getline(self): """Returns a line of text, or raises NoLineError, or NoMoreLineError.""" try: _, avail, _ = win32pipe.PeekNamedPipe(self.osf, 0) bClosed = False except pywintypes.error: avail = 0 bClosed = True if avail: self.buf += os.read(self.fd, avail) idx = self.buf.find('\n') if idx >= 0: ret, self.buf = self.buf[:idx+1], self.buf[idx+1:] return ret elif bClosed: if self.buf: ret, self.buf = self.buf, None return ret else: raise NoMoreLineError else: raise NoLineError def multi_readlines(fs, timeout=0): """Read lines from |fs|, a list of file objects. The lines come out in arbitrary order, depending on which files have output available first.""" if type(fs) not in (list, tuple): raise Exception("argument must be a list.") objs = [LineReader(f) for f in fs] for i,obj in enumerate(objs): obj._index = i while objs: yielded = 0 for i,obj in enumerate(objs): try: yield (obj._index, obj.getline()) yielded += 1 except NoLineError: #time.sleep(timeout) pass except NoMoreLineError: del objs[i] break # Because we mutated the array if not yielded: time.sleep(timeout) pass I have never seen the "Peek returns 0 bytes even though data is available" issue myself. If this happens to others, I bet their libc is buffering their stdout/stderr before sending the data to the OS; there is nothing you can do about that from outside. You have to make the app use unbuffered output somehow (-u to python; win32/libc calls to modify the stderr file handle, ...) The fact that you are seeing nothing, then a ton of updates, makes me think that your problem is buffering on the source end. win32 libc may buffer differently if it writes to a pipe rather than a console. Again, the best you can do from outside those programs is to aggressively drain their output. A: What about using Twisted's FD's? http://twistedmatrix.com/documents/8.1.0/api/twisted.internet.fdesc.html It's not asynchronous but it is non-blocking. For asynchronous stuff, can you port to using Twisted?
Asynchronous subprocess on Windows
First of all, the overall problem I am solving is a bit more complicated than I am showing here, so please do not tell me 'use threads with blocking' as it would not solve my actual situation without a fair, FAIR bit of rewriting and refactoring. I have several applications which are not mine to modify, which take data from stdin and poop it out on stdout after doing their magic. My task is to chain several of these programs. Problem is, sometimes they choke, and as such I need to track their progress which is outputted on STDERR. pA = subprocess.Popen(CommandA, shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE) # ... some more processes make up the chain, but that is irrelevant to the problem pB = subprocess.Popen(CommandB, shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=pA.stdout ) Now, reading directly through pA.stdout.readline() and pB.stdout.readline(), or the plain read() functions, is a blocking matter. Since different applications output in different paces and different formats, blocking is not an option. (And as I wrote above, threading is not an option unless at a last, last resort.) pA.communicate() is deadlock safe, but since I need the information live, that is not an option either. Thus google brought me to this asynchronous subprocess snippet on ActiveState. All good at first, until I implement it. Comparing the cmd.exe output of pA.exe | pB.exe, ignoring the fact both output to the same window making for a mess, I see very instantaneous updates. However, I implement the same thing using the above snippet and the read_some() function declared there, and it takes over 10 seconds to notify updates of a single pipe. But when it does, it has updates leading all the way upto 40% progress, for example. Thus I do some more research, and see numerous subjects concerning PeekNamedPipe, anonymous handles, and returning 0 bytes available even though there is information available in the pipe. As the subject has proven quite a bit beyond my expertise to fix or code around, I come to Stack Overflow to look for guidance. :) My platform is W7 64-bit with Python 2.6, the applications are 32-bit in case it matters, and compatibility with Unix is not a concern. I can even deal with a full ctypes or pywin32 solution that subverts subprocess entirely if it is the only solution, as long as I can read from every stderr pipe asynchronously with immediate performance and no deadlocks. :)
[ "How bad is it to have to use threads? I encountered much the same problem and eventually decided to use threads to gather up all the data on a sub-process's stdout and stderr and put it onto a thread-safe queue which which the main thread can read in a blocking fashion, without having to worry about the threading going on behind the scenes.\nIt's not clear what trouble you anticipate with a solution based on threads and blocking. Are you worried about having to make the rest of your code thread-safe? That shouldn't be an issue since the IO thread wouldn't need to interact with any of the rest of your code or data. If you have very restrictive memory requirements or your pipeline is particularly long then perhaps you may feel unhappy about spawning so many threads. I don't know enough about your situation so I couldn't say if this is likely to be a problem, but it seems to me that since you're already spawning off extra processes a few threads to interact with them should not be a terrible burden. In my situation I have not found these IO threads to be particularly problematic.\nMy thread function looked something like this:\ndef simple_io_thread(pipe, queue, tag, stop_event):\n \"\"\"\n Read line-by-line from pipe, writing (tag, line) to the\n queue. Also checks for a stop_event to give up before\n the end of the stream.\n \"\"\"\n while True:\n line = pipe.readline()\n\n while True:\n try:\n # Post to the queue with a large timeout in case the\n # queue is full.\n queue.put((tag, line), block=True, timeout=60)\n break\n except Queue.Full:\n if stop_event.isSet():\n break\n continue\n if stop_event.isSet() or line==\"\":\n break\n pipe.close()\n\nWhen I start up the subprocess I do this:\noutputqueue = Queue.Queue(50)\nstop_event = threading.Event()\nprocess = subprocess.Popen(\n command,\n cwd=workingdir,\n env=env,\n shell=useshell,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE)\nstderr_thread = threading.Thread(\n target=simple_io_thread,\n args=(process.stderr, outputqueue, \"STDERR\", stop_event)\n)\nstdout_thread = threading.Thread(\n target=simple_io_thread,\n args=(process.stdout, outputqueue, \"STDOUT\", stop_event)\n)\nstderr_thread.daemon = True\nstdout_thread.daemon = True\nstderr_thread.start()\nstdout_thread.start()\n\nThen when I want to read I can just block on outputqueue - each item read from it contains either a string to identify which pipe it came from and a line of text from that pipe. Very little code runs in a separate thread, and it only communicates with the main thread via a thread-safe queue (plus an event in case I need to give up early). Perhaps this approach would be useful and allow you to solve the problem with threads and blocking but without having to rewrite lots of code?\n(My solution is made more complicated because I sometimes wish to terminate the subprocesses early, and want to be sure that the threads will all finish. If that's not an issue you can get rid of all the stop_event stuff and it becomes pretty succinct.)\n", "I assume that the process pipeline will not deadlock if it only uses stdin and stdout; and the problem you're trying to solve is how to make it not deadlock if they write to stderr (and have to deal with stderr possibly getting backed up).\nIf you're letting multiple processes write to stderr, you have to watch out for their output being intermingled. I'm guessing you have that sorted somehow; just putting it out there to be sure.\nBe aware of the -u flag to python; it is helpful when testing to see if OS buffering is screwing you up.\nIf you want to emulate select() on file handles in win32, your only choice is to use PeekNamedPipe() and friends. I have a snippet of code that reads line-oriented output from multiple processes at once, which you may even be able to use directly -- try passing the list of proc.stderr handles to it and go.\nclass NoLineError(Exception): pass\nclass NoMoreLineError(Exception): pass\nclass LineReader(object):\n \"\"\"Helper class for multi_readlines.\"\"\"\n def __init__(self, f):\n self.fd = f.fileno()\n self.osf = msvcrt.get_osfhandle(self.fd)\n self.buf = ''\n\n def getline(self):\n \"\"\"Returns a line of text, or raises NoLineError, or NoMoreLineError.\"\"\"\n try:\n _, avail, _ = win32pipe.PeekNamedPipe(self.osf, 0)\n bClosed = False\n except pywintypes.error:\n avail = 0\n bClosed = True\n\n if avail:\n self.buf += os.read(self.fd, avail)\n\n idx = self.buf.find('\\n')\n if idx >= 0:\n ret, self.buf = self.buf[:idx+1], self.buf[idx+1:]\n return ret\n elif bClosed:\n if self.buf:\n ret, self.buf = self.buf, None\n return ret\n else:\n raise NoMoreLineError\n else:\n raise NoLineError\n\n\ndef multi_readlines(fs, timeout=0):\n \"\"\"Read lines from |fs|, a list of file objects.\n The lines come out in arbitrary order, depending on which files\n have output available first.\"\"\"\n if type(fs) not in (list, tuple):\n raise Exception(\"argument must be a list.\")\n objs = [LineReader(f) for f in fs]\n for i,obj in enumerate(objs): obj._index = i\n while objs:\n yielded = 0\n for i,obj in enumerate(objs):\n try:\n yield (obj._index, obj.getline())\n yielded += 1\n except NoLineError:\n #time.sleep(timeout)\n pass\n except NoMoreLineError:\n del objs[i]\n break # Because we mutated the array\n\n if not yielded:\n time.sleep(timeout)\n pass\n\nI have never seen the \"Peek returns 0 bytes even though data is available\" issue myself. If this happens to others, I bet their libc is buffering their stdout/stderr before sending the data to the OS; there is nothing you can do about that from outside. You have to make the app use unbuffered output somehow (-u to python; win32/libc calls to modify the stderr file handle, ...)\nThe fact that you are seeing nothing, then a ton of updates, makes me think that your problem is buffering on the source end. win32 libc may buffer differently if it writes to a pipe rather than a console. Again, the best you can do from outside those programs is to aggressively drain their output.\n", "What about using Twisted's FD's? http://twistedmatrix.com/documents/8.1.0/api/twisted.internet.fdesc.html\nIt's not asynchronous but it is non-blocking. For asynchronous stuff, can you port to using Twisted?\n" ]
[ 4, 1, 0 ]
[]
[]
[ "asynchronous", "python", "subprocess" ]
stackoverflow_0002554514_asynchronous_python_subprocess.txt
Q: Good way to flatten a multiple file python program for distribution? I am writing a console application in python that will consist of a handful of modules, each with a couple hundred lines of code. For development it would be nice to modularize the program, but for distribution I like the idea of being able to post the program as a single python script. Are there any good scripts out there for flattening multiple python modules? I know that eventually I should brave the complicated mess that is setuptools, dpkg, etc... but I'm not ready to invest that effort yet. A: A zipfile (with just the .pyc or .pyo files in it, ideally) would suffice, especially if you're distributing code supporting a specific X.Y version of Python (any Z in X.Y.Z will do, i.e., if you support Python 2.6, that will work in 2.6.1, 2.6.2, and so on). Just make the zipfile part of the PYTHONPATH, just as if it was a directory, and you're good to go. If you support many different Python versions (in the X.Y sense) you can make a zipfile per version, it's still pretty simple. A: No code to do this seems to exist.
Good way to flatten a multiple file python program for distribution?
I am writing a console application in python that will consist of a handful of modules, each with a couple hundred lines of code. For development it would be nice to modularize the program, but for distribution I like the idea of being able to post the program as a single python script. Are there any good scripts out there for flattening multiple python modules? I know that eventually I should brave the complicated mess that is setuptools, dpkg, etc... but I'm not ready to invest that effort yet.
[ "A zipfile (with just the .pyc or .pyo files in it, ideally) would suffice, especially if you're distributing code supporting a specific X.Y version of Python (any Z in X.Y.Z will do, i.e., if you support Python 2.6, that will work in 2.6.1, 2.6.2, and so on). Just make the zipfile part of the PYTHONPATH, just as if it was a directory, and you're good to go.\nIf you support many different Python versions (in the X.Y sense) you can make a zipfile per version, it's still pretty simple.\n", "No code to do this seems to exist.\n" ]
[ 4, 0 ]
[]
[]
[ "distribution", "python" ]
stackoverflow_0002444165_distribution_python.txt
Q: Why does `print foo.communicate()[0]` differ from `print foo.communicate()`" Here is the situation: I've got a command I'm running: import subprocess foo = subprocess.Popen('ls /', shell=True, stdout=subprocess.PIPE,\ stderr=subprocess.STDOUT) Pretty basic, right? And I've figured out that I can do stuff with the output with .communicate(), like this: print foo.communicate() Which works great and produces the output that the documentation for subprocess.communicate suggests it should, a tuple: ('bin\nboot\ncdrom\n[...stuff redacted for brevity...]tmp\nusr\nvar\nvmlinuz\n', None) Notice the \n newlines in there. And I've discovered that just asking for the first element of the tuple produces output with newlines, like this: >>> print foo.communicate()[0] bin boot cdrom [...stuff redacted for brevity...] tmp usr var vmlinuz But what I don't understand is WHY printing with just the first element produces the newlines. Don't get me wrong, it is great, and I'm glad I can do it without a loop, but I'd like to understand what is going on. Thanks in advance, --jed A: In Python when you call something like print obj, you're actually calling the __str__ on the object and then interpreting the result as a string. So for example say you have: >>> a = ('foo\nbar', '5') >>> print a ('foo\nbar', '5') As you've noticed. But if you do something like: >>> class mytuple(tuple): def __str__(self): return ''.join(self) >>> b = mytuple(a) >>> print b foo bar5 This subclass of the tuple type goes beyond the standard __str__ and builds a string composed out the string representations of its constituent parts. The reason this isn't done in the general case is that you never know what objects could be inserted in a tuple, or list - not all objects have string-able representations. A: foo.communicate() returns a tuple. If you write foo.communicate()[0] you retrieve a first element in that tuple. Since this element is just a string, python interpreter prints it to your screen, printing \n as newlines. When you print a tuple from foo.communinicate() you see the \n characters, but this is just a difference in the way the tuples are printed, the newlines are always there.
Why does `print foo.communicate()[0]` differ from `print foo.communicate()`"
Here is the situation: I've got a command I'm running: import subprocess foo = subprocess.Popen('ls /', shell=True, stdout=subprocess.PIPE,\ stderr=subprocess.STDOUT) Pretty basic, right? And I've figured out that I can do stuff with the output with .communicate(), like this: print foo.communicate() Which works great and produces the output that the documentation for subprocess.communicate suggests it should, a tuple: ('bin\nboot\ncdrom\n[...stuff redacted for brevity...]tmp\nusr\nvar\nvmlinuz\n', None) Notice the \n newlines in there. And I've discovered that just asking for the first element of the tuple produces output with newlines, like this: >>> print foo.communicate()[0] bin boot cdrom [...stuff redacted for brevity...] tmp usr var vmlinuz But what I don't understand is WHY printing with just the first element produces the newlines. Don't get me wrong, it is great, and I'm glad I can do it without a loop, but I'd like to understand what is going on. Thanks in advance, --jed
[ "In Python when you call something like print obj, you're actually calling the __str__ on the object and then interpreting the result as a string.\nSo for example say you have:\n >>> a = ('foo\\nbar', '5')\n >>> print a\n ('foo\\nbar', '5')\n\nAs you've noticed. But if you do something like:\n >>> class mytuple(tuple):\n def __str__(self):\n return ''.join(self)\n >>> b = mytuple(a)\n >>> print b\n foo\n bar5\n\nThis subclass of the tuple type goes beyond the standard __str__ and builds a string composed out the string representations of its constituent parts.\nThe reason this isn't done in the general case is that you never know what objects could be inserted in a tuple, or list - not all objects have string-able representations.\n", "foo.communicate() returns a tuple. If you write foo.communicate()[0] you retrieve a first element in that tuple. Since this element is just a string, python interpreter prints it to your screen, printing \\n as newlines.\nWhen you print a tuple from foo.communinicate() you see the \\n characters, but this is just a difference in the way the tuples are printed, the newlines are always there.\n" ]
[ 3, 2 ]
[]
[]
[ "python" ]
stackoverflow_0002596261_python.txt
Q: NoneType has no attribute Append I'm new to Python. I can't understand why a variable is None at a certain point in my code: class UsersInRoom(webapp.RequestHandler): def get(self): room_id = self.request.get("room_id") username = self.request.get("username") UserInRoom_entities = UserInRoom.gql("WHERE room = :1", room_id).get() if UserInRoom_entities: for user_in_room in UserInRoom_entities: if user_in_room.username == username: user_in_room.put() # last_poll auto updates to now whenenever user_in_room is saved else: user_in_room = UserInRoom() user_in_room.username = username user_in_room.put() // error here, on line 160 UserInRoom_entities = [] UserInRoom_entities.append(user_in_room) # name is `user_at_room` intead of `user_in_room` to avoid confusion usernames = [user_at_room.username for user_at_room in UserInRoom_entities] self.response.out.write(json.dumps(usernames)) The error is: Traceback (most recent call last): File "C:\Program Files\Google\google_appengine\google\appengine\ext\webapp\__init__.py", line 507, in __call__ handler.get(*groups) File "path\to\chat.py", line 160, in get AttributeError: 'NoneType' object has no attribute 'append' How is this possible? I'm setting UserInRoom_entities = [] immediately before that call. Or is something else the None in question? UPDATE: This code works: class UsersInRoom(webapp.RequestHandler): def get(self): room_id = self.request.get("room_id") username = self.request.get("username") UserInRoom_entities = UserInRoom.gql("WHERE room = :1", room_id).get() if UserInRoom_entities: for user_in_room in UserInRoom_entities: if user_in_room.name == username: user_in_room.put() # last_modified auto updates to now whenenever user_in_room is saved else: user_in_room = UserInRoom(room=Key(room_id), name=username) user_in_room.put() UserInRoom_entities = [] UserInRoom_entities.append(user_in_room) # name is `user_at_room` intead of `user_in_room` to avoid confusion usernames = [user_at_room.name for user_at_room in UserInRoom_entities] self.response.out.write(json.dumps(usernames)) class ChatRoom(db.Model): name = db.StringProperty() last_modified = db.DateTimeProperty(auto_now=True) message_contents = db.StringListProperty() message_users = db.StringListProperty() class UserInRoom(db.Model): room = db.ReferenceProperty(ChatRoom) name = db.StringProperty() last_modified = db.DateTimeProperty(auto_now=True) A: Since it appears that my comment to the question had the answer to this, I'll repeat it as an answer, with the hope of gaining some reputation points: Is the UserInRoom instance initialized properly? I am not familiar with the GAE data model, but I could imagine that the put() ing the instance would require that the room attribute was set, if there is a relationship between UserInRoom and Room (assuming a Room class exists). A: To make sure that you're not the one raising exception, you can do something like: UserInRoom_entities = [] # raised? then your .append is missing otherwise something else is wrong UserInRoom_entities.append UserInRoom_entities.append(user_in_room)
NoneType has no attribute Append
I'm new to Python. I can't understand why a variable is None at a certain point in my code: class UsersInRoom(webapp.RequestHandler): def get(self): room_id = self.request.get("room_id") username = self.request.get("username") UserInRoom_entities = UserInRoom.gql("WHERE room = :1", room_id).get() if UserInRoom_entities: for user_in_room in UserInRoom_entities: if user_in_room.username == username: user_in_room.put() # last_poll auto updates to now whenenever user_in_room is saved else: user_in_room = UserInRoom() user_in_room.username = username user_in_room.put() // error here, on line 160 UserInRoom_entities = [] UserInRoom_entities.append(user_in_room) # name is `user_at_room` intead of `user_in_room` to avoid confusion usernames = [user_at_room.username for user_at_room in UserInRoom_entities] self.response.out.write(json.dumps(usernames)) The error is: Traceback (most recent call last): File "C:\Program Files\Google\google_appengine\google\appengine\ext\webapp\__init__.py", line 507, in __call__ handler.get(*groups) File "path\to\chat.py", line 160, in get AttributeError: 'NoneType' object has no attribute 'append' How is this possible? I'm setting UserInRoom_entities = [] immediately before that call. Or is something else the None in question? UPDATE: This code works: class UsersInRoom(webapp.RequestHandler): def get(self): room_id = self.request.get("room_id") username = self.request.get("username") UserInRoom_entities = UserInRoom.gql("WHERE room = :1", room_id).get() if UserInRoom_entities: for user_in_room in UserInRoom_entities: if user_in_room.name == username: user_in_room.put() # last_modified auto updates to now whenenever user_in_room is saved else: user_in_room = UserInRoom(room=Key(room_id), name=username) user_in_room.put() UserInRoom_entities = [] UserInRoom_entities.append(user_in_room) # name is `user_at_room` intead of `user_in_room` to avoid confusion usernames = [user_at_room.name for user_at_room in UserInRoom_entities] self.response.out.write(json.dumps(usernames)) class ChatRoom(db.Model): name = db.StringProperty() last_modified = db.DateTimeProperty(auto_now=True) message_contents = db.StringListProperty() message_users = db.StringListProperty() class UserInRoom(db.Model): room = db.ReferenceProperty(ChatRoom) name = db.StringProperty() last_modified = db.DateTimeProperty(auto_now=True)
[ "Since it appears that my comment to the question had the answer to this, I'll repeat it as an answer, with the hope of gaining some reputation points:\nIs the UserInRoom instance initialized properly? I am not familiar with the GAE data model, but I could imagine that the put() ing the instance would require that the room attribute was set, if there is a relationship between UserInRoom and Room (assuming a Room class exists).\n", "To make sure that you're not the one raising exception, you can do something like:\n UserInRoom_entities = []\n # raised? then your .append is missing otherwise something else is wrong\n UserInRoom_entities.append\n UserInRoom_entities.append(user_in_room)\n\n" ]
[ 3, 0 ]
[]
[]
[ "google_app_engine", "python", "syntax" ]
stackoverflow_0002595727_google_app_engine_python_syntax.txt
Q: Behavior of object in set operations I'm trying to create a custom object that behaves properly in set operations. I've generally got it working, but I want to make sure I fully understand the implications. In particular, I'm interested in the behavior when there is additional data in the object that is not included in the equal / hash methods. It seems that in the 'intersection' operation, it returns the set of objects that are being compared to, where the 'union' operations returns the set of objects that are being compared. To illustrate: class MyObject: def __init__(self,value,meta): self.value = value self.meta = meta def __eq__(self,other): return self.value == other.value def __hash__(self): return hash(self.value) a = MyObject('1','left') b = MyObject('1','right') c = MyObject('2','left') d = MyObject('2','right') e = MyObject('3','left') print a == b # True print a == c # False for i in set([a,c,e]).intersection(set([b,d])): print "%s %s" % (i.value,i.meta) #returns: #1 right #2 right for i in set([a,c,e]).union(set([b,d])): print "%s %s" % (i.value,i.meta) #returns: #1 left #3 left #2 left Is this behavior documented somewhere and deterministic? If so, what is the governing principle? A: Nope, it's not deterministic. The problem is that you've broken equals' and hash's invariant, that two objects are equivalent when they are equal. Fix your object, don't try to be clever and abuse how set's implementation works. If the meta value is part of MyObject's identity, it should be included in eq and hash. You can't rely on set's intersection to follow any order, so there is no way to easily do what you want. What you would end up doing is taking the intersection by value only, then look through all your objects for an older one to replace it with, for each one. No nice way to do it algorithmically. Unions are not so bad: ##fix the eq and hash to work correctly class MyObject: def __init__(self,value,meta): self.value = value self.meta = meta def __eq__(self,other): return self.value, self.meta == other.value, other.meta def __hash__(self): return hash((self.value, self.meta)) def __repr__(self): return "%s %s" % (self.value,self.meta) a = MyObject('1','left') b = MyObject('1','right') c = MyObject('2','left') d = MyObject('2','right') e = MyObject('3','left') union = set([a,c,e]).union(set([b,d])) print union #set([2 left, 2 right, 1 left, 3 left, 1 right]) ##sort the objects, so that older objs come before the newer equivalents sl = sorted(union, key= lambda x: (x.value, x.meta) ) print sl #[1 left, 1 right, 2 left, 2 right, 3 left] import itertools ##group the objects by value, groupby needs the objs to be in order to do this filtered = itertools.groupby(sl, lambda x: x.value) ##make a list of the oldest (first in group) oldest = [ next(group) for key, group in filtered] print oldest #[1 left, 2 left, 3 left] A: Order doesn't appear to matter: >>> [ (u.value, u.meta) for u in set([b,d]).intersection(set([a,c,e])) ] [('1', 'right'), ('2', 'right')] >>> [ (u.value, u.meta) for u in set([a,c,e]).intersection(set([b,d])) ] [('1', 'right'), ('2', 'right')] However, if you do this: >>> f = MyObject('3', 'right') And add f to the "right" set: >>> [ (u.value, u.meta) for u in set([a,c,e]).intersection(set([b,d,f])) ] [('1', 'right'), ('3', 'right'), ('2', 'right')] >>> [ (u.value, u.meta) for u in set([b,d,f]).intersection(set([a,c,e])) ] [('1', 'left'), ('3', 'left'), ('2', 'left')] So you can see that the behavior depends on the size of the sets (the same effect happens if you union). It may be dependent on other factors as well. I think you're hunting through the python source if you want to know why. A: Let's say your objects have two different types of attributes: key attributes and data attributes. In your example, MyObject.value is a key attribute. Store all your objects as values in a dictionary, keyed by the key attributes, making sure that only your preferred (e.g. with the oldest timestamp) are entered in the dictionary. Perform your set operations with the same key as used in the dictionary, and retrieve the actual objects from the dictionary: result= [dict1[k] for k in set_operation_result]
Behavior of object in set operations
I'm trying to create a custom object that behaves properly in set operations. I've generally got it working, but I want to make sure I fully understand the implications. In particular, I'm interested in the behavior when there is additional data in the object that is not included in the equal / hash methods. It seems that in the 'intersection' operation, it returns the set of objects that are being compared to, where the 'union' operations returns the set of objects that are being compared. To illustrate: class MyObject: def __init__(self,value,meta): self.value = value self.meta = meta def __eq__(self,other): return self.value == other.value def __hash__(self): return hash(self.value) a = MyObject('1','left') b = MyObject('1','right') c = MyObject('2','left') d = MyObject('2','right') e = MyObject('3','left') print a == b # True print a == c # False for i in set([a,c,e]).intersection(set([b,d])): print "%s %s" % (i.value,i.meta) #returns: #1 right #2 right for i in set([a,c,e]).union(set([b,d])): print "%s %s" % (i.value,i.meta) #returns: #1 left #3 left #2 left Is this behavior documented somewhere and deterministic? If so, what is the governing principle?
[ "Nope, it's not deterministic. The problem is that you've broken equals' and hash's invariant, that two objects are equivalent when they are equal. Fix your object, don't try to be clever and abuse how set's implementation works. If the meta value is part of MyObject's identity, it should be included in eq and hash.\nYou can't rely on set's intersection to follow any order, so there is no way to easily do what you want. What you would end up doing is taking the intersection by value only, then look through all your objects for an older one to replace it with, for each one. No nice way to do it algorithmically.\nUnions are not so bad:\n##fix the eq and hash to work correctly\nclass MyObject:\n def __init__(self,value,meta):\n self.value = value\n self.meta = meta\n def __eq__(self,other):\n return self.value, self.meta == other.value, other.meta\n def __hash__(self):\n return hash((self.value, self.meta))\n def __repr__(self):\n return \"%s %s\" % (self.value,self.meta)\n\na = MyObject('1','left')\nb = MyObject('1','right')\nc = MyObject('2','left')\nd = MyObject('2','right')\ne = MyObject('3','left')\n\nunion = set([a,c,e]).union(set([b,d]))\nprint union\n#set([2 left, 2 right, 1 left, 3 left, 1 right])\n\n##sort the objects, so that older objs come before the newer equivalents\nsl = sorted(union, key= lambda x: (x.value, x.meta) )\nprint sl\n#[1 left, 1 right, 2 left, 2 right, 3 left]\nimport itertools\n##group the objects by value, groupby needs the objs to be in order to do this\nfiltered = itertools.groupby(sl, lambda x: x.value)\n##make a list of the oldest (first in group)\noldest = [ next(group) for key, group in filtered]\nprint oldest\n#[1 left, 2 left, 3 left]\n\n", "Order doesn't appear to matter:\n>>> [ (u.value, u.meta) for u in set([b,d]).intersection(set([a,c,e])) ]\n[('1', 'right'), ('2', 'right')]\n\n>>> [ (u.value, u.meta) for u in set([a,c,e]).intersection(set([b,d])) ]\n[('1', 'right'), ('2', 'right')]\n\nHowever, if you do this: \n>>> f = MyObject('3', 'right')\n\nAnd add f to the \"right\" set: \n>>> [ (u.value, u.meta) for u in set([a,c,e]).intersection(set([b,d,f])) ]\n[('1', 'right'), ('3', 'right'), ('2', 'right')]\n\n>>> [ (u.value, u.meta) for u in set([b,d,f]).intersection(set([a,c,e])) ]\n[('1', 'left'), ('3', 'left'), ('2', 'left')]\n\nSo you can see that the behavior depends on the size of the sets (the same effect happens if you union). It may be dependent on other factors as well. I think you're hunting through the python source if you want to know why. \n", "Let's say your objects have two different types of attributes: key attributes and data attributes. In your example, MyObject.value is a key attribute. \nStore all your objects as values in a dictionary, keyed by the key attributes, making sure that only your preferred (e.g. with the oldest timestamp) are entered in the dictionary. Perform your set operations with the same key as used in the dictionary, and retrieve the actual objects from the dictionary:\nresult= [dict1[k] for k in set_operation_result]\n\n" ]
[ 4, 1, 0 ]
[]
[]
[ "object", "python", "set" ]
stackoverflow_0002594920_object_python_set.txt
Q: Best Python module for Berkeley DB? According to the Python 2.6.5 docs [1], the bsddb module has been deprecated for removal in Python 3.0. What module/wrapper should I be using instead? [1] http://docs.python.org/library/bsddb.html A: I recommend pyBSDdb (from which the version currently in Python standard's library was taken -- but the stand-alone project is more actively maintained and far from deprecated;-).
Best Python module for Berkeley DB?
According to the Python 2.6.5 docs [1], the bsddb module has been deprecated for removal in Python 3.0. What module/wrapper should I be using instead? [1] http://docs.python.org/library/bsddb.html
[ "I recommend pyBSDdb (from which the version currently in Python standard's library was taken -- but the stand-alone project is more actively maintained and far from deprecated;-).\n" ]
[ 15 ]
[]
[]
[ "berkeley_db", "python" ]
stackoverflow_0002597068_berkeley_db_python.txt
Q: Make dictionary from list with python I need to transform a list into dictionary as follows. The odd elements has the key, and even number elements has the value. x = (1,'a',2,'b',3,'c') -> {1: 'a', 2: 'b', 3: 'c'} def set(self, val_): i = 0 for val in val_: if i == 0: i = 1 key = val else: i = 0 self.dict[key] = val A better way to get the same results? ADDED i = iter(k) print dict(zip(i,i)) seems to be working A: dict(x[i:i+2] for i in range(0, len(x), 2)) A: Here are a couple of ways for Python3 using dict comprehensions >>> x = (1,'a',2,'b',3,'c') >>> {k:v for k,v in zip(*[iter(x)]*2)} {1: 'a', 2: 'b', 3: 'c'} >>> {x[i]:x[i+1] for i in range(0,len(x),2)} {1: 'a', 2: 'b', 3: 'c'} A: dict(zip(*[iter(val_)] * 2)) A: >>> x=(1,'a',2,'b',3,'c') >>> dict(zip(x[::2],x[1::2])) {1: 'a', 2: 'b', 3: 'c'} A: x = (1,'a',2,'b',3,'c') d = dict(x[n:n+2] for n in xrange(0, len(x), 2)) print d
Make dictionary from list with python
I need to transform a list into dictionary as follows. The odd elements has the key, and even number elements has the value. x = (1,'a',2,'b',3,'c') -> {1: 'a', 2: 'b', 3: 'c'} def set(self, val_): i = 0 for val in val_: if i == 0: i = 1 key = val else: i = 0 self.dict[key] = val A better way to get the same results? ADDED i = iter(k) print dict(zip(i,i)) seems to be working
[ "dict(x[i:i+2] for i in range(0, len(x), 2))\n\n", "Here are a couple of ways for Python3 using dict comprehensions\n>>> x = (1,'a',2,'b',3,'c')\n>>> {k:v for k,v in zip(*[iter(x)]*2)}\n{1: 'a', 2: 'b', 3: 'c'}\n>>> {x[i]:x[i+1] for i in range(0,len(x),2)}\n{1: 'a', 2: 'b', 3: 'c'}\n\n", "dict(zip(*[iter(val_)] * 2))\n\n", ">>> x=(1,'a',2,'b',3,'c')\n>>> dict(zip(x[::2],x[1::2]))\n{1: 'a', 2: 'b', 3: 'c'}\n\n", "x = (1,'a',2,'b',3,'c') \nd = dict(x[n:n+2] for n in xrange(0, len(x), 2))\nprint d\n\n" ]
[ 41, 12, 11, 11, 4 ]
[]
[]
[ "dictionary", "list", "python" ]
stackoverflow_0002597166_dictionary_list_python.txt
Q: Pylons paginator question Only comments associated with the current page should be listed, so once again the query is modified to include the page ID. In this case, though, we also have to pass the pageid argument, which will in turn get passed to any h.url_for() calls in the paginator. from http://pylonsbook.com/en/1.1/simplesite-tutorial-part-2.html i cannot get this to work, the paginator does not pass things to the h.url_for, i followed the tutorial. i had to add pageid to the h.url_for in list.html. how do i solve? part of the code: ${h.link_to( comment.id, h.url_for( controller=u'comment', action='view', id=unicode(comment.id) ) )} but it does not work properly until i put in ${h.link_to( comment.id, h.url_for( controller=u'comment', action='view', id=unicode(comment.id), pageid = c.page.id ) )} edit: the problem is that on the tutorial it said that the paginator will pass through with this code: c.paginator = paginate.Page( comments_q, page=int(request.params.get('page', 1)), items_per_page=10, pageid=c.page.id, controller='comment', action='list' ) return render('/derived/comment/list.html') but it does not happen unless I put it in manually A: You need to pass the pageid to the method url_for because the pageid is required by the route. map.connect('/page/{pageid}/{controller}/{action}', requirements={'pageid':'\d+'}) map.connect('/page/{pageid}/{controller}/{action}/{id}', requirements={'pageid':'\d+', 'id':'\d+'}) The pageid is then processed in your comment controller in the before method def __before__(self, action, pageid=None): page_q = meta.Session.query(model.Page) c.page = pageid and page_q.filter_by(id=int(pageid)).first() or None if c.page is None: abort(404) Then, the c.page is set with the current page and comment can be link to this c.page.
Pylons paginator question
Only comments associated with the current page should be listed, so once again the query is modified to include the page ID. In this case, though, we also have to pass the pageid argument, which will in turn get passed to any h.url_for() calls in the paginator. from http://pylonsbook.com/en/1.1/simplesite-tutorial-part-2.html i cannot get this to work, the paginator does not pass things to the h.url_for, i followed the tutorial. i had to add pageid to the h.url_for in list.html. how do i solve? part of the code: ${h.link_to( comment.id, h.url_for( controller=u'comment', action='view', id=unicode(comment.id) ) )} but it does not work properly until i put in ${h.link_to( comment.id, h.url_for( controller=u'comment', action='view', id=unicode(comment.id), pageid = c.page.id ) )} edit: the problem is that on the tutorial it said that the paginator will pass through with this code: c.paginator = paginate.Page( comments_q, page=int(request.params.get('page', 1)), items_per_page=10, pageid=c.page.id, controller='comment', action='list' ) return render('/derived/comment/list.html') but it does not happen unless I put it in manually
[ "You need to pass the pageid to the method url_for because the pageid is required by the route.\nmap.connect('/page/{pageid}/{controller}/{action}', requirements={'pageid':'\\d+'})\nmap.connect('/page/{pageid}/{controller}/{action}/{id}', requirements={'pageid':'\\d+', 'id':'\\d+'})\n\nThe pageid is then processed in your comment controller in the before method\ndef __before__(self, action, pageid=None):\n page_q = meta.Session.query(model.Page)\n c.page = pageid and page_q.filter_by(id=int(pageid)).first() or None\n if c.page is None:\n abort(404)\n\nThen, the c.page is set with the current page and comment can be link to this c.page.\n" ]
[ 1 ]
[]
[]
[ "pylons", "python" ]
stackoverflow_0002594604_pylons_python.txt
Q: deletion of folders how can i delete a folder using python script?and what are the return values?? A: If you want to delete a folder that's empty use os.rmdir: import os os.rmdir('/mypath') If you want to delete a folder that's not empty use shutil.rmtree: import shutil shutil.rmtree('/mypath') A: you can use os.rmdir() to remove a directory. To remove a directory tree recursively, you can use shutil.rmtree. If you know that you already have empty directory nodes, you can also check out os.removedirs()
deletion of folders
how can i delete a folder using python script?and what are the return values??
[ "If you want to delete a folder that's empty use os.rmdir:\nimport os\nos.rmdir('/mypath')\n\nIf you want to delete a folder that's not empty use shutil.rmtree:\nimport shutil \nshutil.rmtree('/mypath')\n\n", "you can use os.rmdir() to remove a directory. To remove a directory tree recursively, you can use shutil.rmtree. If you know that you already have empty directory nodes, you can also check out os.removedirs()\n" ]
[ 4, 0 ]
[]
[]
[ "directory", "python" ]
stackoverflow_0002597501_directory_python.txt
Q: How to "uninstantiate" an object? I wrote a function in Python: def instantiate(c): if inspect.isclass(c): return c() elif isinstance(c, object): return c else: raise Exception, '%s is not an object or class.' % c Now I want to do the opposite: get the class from an already instantiated object so that I can re-instantiate it with different parameters. How can I do that? Tests: >>> f = Form() >>> type(f)() Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: instance() takes at least 1 argument (0 given) >>> f.__class__() <forms.Form instance at 0xb7f4d5cc> More tests: >>> o = object() >>> type(o)() <object object at 0xb7f78478> >>> o.__class__() <object object at 0xb7f78480> Seems to work for object but not my Form class: class Form: def __init__(self, data={}, prefix='', action='', id=None): I'm guessing this has something to do with self but I don't know what. A: To get the class of x x.__class__ A: The class of object c is type(c).
How to "uninstantiate" an object?
I wrote a function in Python: def instantiate(c): if inspect.isclass(c): return c() elif isinstance(c, object): return c else: raise Exception, '%s is not an object or class.' % c Now I want to do the opposite: get the class from an already instantiated object so that I can re-instantiate it with different parameters. How can I do that? Tests: >>> f = Form() >>> type(f)() Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: instance() takes at least 1 argument (0 given) >>> f.__class__() <forms.Form instance at 0xb7f4d5cc> More tests: >>> o = object() >>> type(o)() <object object at 0xb7f78478> >>> o.__class__() <object object at 0xb7f78480> Seems to work for object but not my Form class: class Form: def __init__(self, data={}, prefix='', action='', id=None): I'm guessing this has something to do with self but I don't know what.
[ "To get the class of x\nx.__class__\n\n", "The class of object c is type(c).\n" ]
[ 3, 2 ]
[]
[]
[ "python", "syntax" ]
stackoverflow_0002597596_python_syntax.txt
Q: Encoding in XML declaration python I have created an XML file using python. But the XML declaration has only version info. How can I include encoding with XML declaration like: <?xml version="1.0" encoding="UTF-8"?> A: >>> from xml.dom.minidom import Document >>> a=Document() >>> a.toprettyxml(encoding="utf-8") '<?xml version="1.0" encoding="utf-8"?>\n' or >>> a.toxml(encoding="utf-8") '<?xml version="1.0" encoding="utf-8"?>' you can set the encoding for the document.writexml() function in the same way.
Encoding in XML declaration python
I have created an XML file using python. But the XML declaration has only version info. How can I include encoding with XML declaration like: <?xml version="1.0" encoding="UTF-8"?>
[ ">>> from xml.dom.minidom import Document\n>>> a=Document()\n>>> a.toprettyxml(encoding=\"utf-8\")\n'<?xml version=\"1.0\" encoding=\"utf-8\"?>\\n'\n\nor\n>>> a.toxml(encoding=\"utf-8\")\n'<?xml version=\"1.0\" encoding=\"utf-8\"?>'\n\nyou can set the encoding for the document.writexml() function in the same way.\n" ]
[ 11 ]
[]
[]
[ "declaration", "encoding", "python", "xml" ]
stackoverflow_0002597622_declaration_encoding_python_xml.txt
Q: random.randint(1,n) in Python Most of us know that the command random.randint(1,n) in Python (2.X.X) would generate a number in random (pseudo-random) between 1 and n. I am interested in knowing what is the upper limit for n ? A: randint() works with long integers, so there is no upper limit: >>> random.randint(1,123456789012345678901234567890) 113144971884331658209492153398L A: No doubt you have a bounded amount of memory, and address space, on your machine; for example, for a good 64-bit machine, 64 GB of RAM [[about 2**36 bytes]] and a couple of TB of disk (usable as swap space for virtual memory) [[about 2**41 bytes]]. So, the "upper bound" of a Python long integer will be the largest one representable in the available memory -- a bit less than 256**(2**40) if you are in absolutely no hurry and can swap like crazy, a bit more than 256**(2*36) (with just a little swapping but not too much) in practical terms. Unfortunately it would take quite a bit of time and space to represent these ridiculously humongous numbers in decimal, so, instead of showing them, let me check back with you -- why would you even care about such a ridiculous succession of digits as to constitute the "upper bound" you're inquiring about? I think it's more practical to put it this way: especially on a 64-bit machine with decent amounts of RAM and disk, upper bounds of long integers are way bigger than anything you'll ever compute. Technically, a mathematician would insist, they're not infinity, of course... but practically, they might as well be!-)
random.randint(1,n) in Python
Most of us know that the command random.randint(1,n) in Python (2.X.X) would generate a number in random (pseudo-random) between 1 and n. I am interested in knowing what is the upper limit for n ?
[ "randint() works with long integers, so there is no upper limit:\n>>> random.randint(1,123456789012345678901234567890)\n113144971884331658209492153398L\n\n", "No doubt you have a bounded amount of memory, and address space, on your machine; for example, for a good 64-bit machine, 64 GB of RAM [[about 2**36 bytes]] and a couple of TB of disk (usable as swap space for virtual memory) [[about 2**41 bytes]]. So, the \"upper bound\" of a Python long integer will be the largest one representable in the available memory -- a bit less than 256**(2**40) if you are in absolutely no hurry and can swap like crazy, a bit more than 256**(2*36) (with just a little swapping but not too much) in practical terms.\nUnfortunately it would take quite a bit of time and space to represent these ridiculously humongous numbers in decimal, so, instead of showing them, let me check back with you -- why would you even care about such a ridiculous succession of digits as to constitute the \"upper bound\" you're inquiring about? I think it's more practical to put it this way: especially on a 64-bit machine with decent amounts of RAM and disk, upper bounds of long integers are way bigger than anything you'll ever compute. Technically, a mathematician would insist, they're not infinity, of course... but practically, they might as well be!-)\n" ]
[ 12, 4 ]
[]
[]
[ "python", "random" ]
stackoverflow_0002597444_python_random.txt
Q: Memcache in python I want to memcache an xmldata using python,also needs to update the cache with the refreshed xmldata retreived from webserver,could any one help me with sample code. A: This could be of some help: http://code.google.com/appengine/docs/python/memcache/ Quite a few nice code samples are included.
Memcache in python
I want to memcache an xmldata using python,also needs to update the cache with the refreshed xmldata retreived from webserver,could any one help me with sample code.
[ "This could be of some help:\nhttp://code.google.com/appengine/docs/python/memcache/\nQuite a few nice code samples are included.\n" ]
[ 2 ]
[]
[]
[ "memcached", "python" ]
stackoverflow_0002597738_memcached_python.txt
Q: Is it an MD5 digest in this Python script? I am trying to understand this simple hashlib code in Python that has been given to me the other day on Stackoverflow: import hashlib m = hashlib.md5() m.update("Nobody inspects") m.update(" the spammish repetition here") m.digest() '\xbbd\x9c\x83\xdd\x1e\xa5\xc9\xd9\xde\xc9\xa1\x8d\xf0\xff\xe9' m.digest_size 16 m.block_size 64 print m I thought that print m would show me the MD5 digest of the phrase: "Nobody inspects the spammish repetition here", but as a result I got this line on my local host: <md5 HASH object @ 01806220> Strange, when I refreshed the page, I got another line: <md5 HASH object @ 018062E0> and every time when I refresh it, I get another value: md5 HASH object @ 017F8AE0 md5 HASH object @ 01806220 md5 HASH object @ 01806360 md5 HASH object @ 01806400 md5 HASH object @ 01806220 Why is it so? I guess, what I have in each line flowing "@" is not really a digest. Then, what is it? And how can I display MD5 digest here in this code? My python version is Python 2.5 and the framework I am currently using is webapp (I have downloaded it together with SDK from "Google App Engine") A: The hashlib.hash object doesn't implement its own __str__, so the default to-string operation is used, which prints the class name followed by its id (address). (Use .hexdigest() to get the hex MD5 string.) A: print m.hexdigest() UPADATE: hexdigest() gives another representation of digest(). Every character in digest is transformed into its hex representation. You can transform it with the following function: def digest_to_hex(chars): res = '' for c in chars: res = res + '%02x' % ord(c) return res You can also use the generator expresion ''.join('%02x' % ord(x) for x in m.digest()) or m.digest().encode('hex') BTW: You can use dir(some_object) to get a list of its elements, and help(some_object) (in the interactive interpreter) to get more informations about it.
Is it an MD5 digest in this Python script?
I am trying to understand this simple hashlib code in Python that has been given to me the other day on Stackoverflow: import hashlib m = hashlib.md5() m.update("Nobody inspects") m.update(" the spammish repetition here") m.digest() '\xbbd\x9c\x83\xdd\x1e\xa5\xc9\xd9\xde\xc9\xa1\x8d\xf0\xff\xe9' m.digest_size 16 m.block_size 64 print m I thought that print m would show me the MD5 digest of the phrase: "Nobody inspects the spammish repetition here", but as a result I got this line on my local host: <md5 HASH object @ 01806220> Strange, when I refreshed the page, I got another line: <md5 HASH object @ 018062E0> and every time when I refresh it, I get another value: md5 HASH object @ 017F8AE0 md5 HASH object @ 01806220 md5 HASH object @ 01806360 md5 HASH object @ 01806400 md5 HASH object @ 01806220 Why is it so? I guess, what I have in each line flowing "@" is not really a digest. Then, what is it? And how can I display MD5 digest here in this code? My python version is Python 2.5 and the framework I am currently using is webapp (I have downloaded it together with SDK from "Google App Engine")
[ "The hashlib.hash object doesn't implement its own __str__, so the default to-string operation is used, which prints the class name followed by its id (address).\n(Use .hexdigest() to get the hex MD5 string.)\n", "print m.hexdigest()\n\nUPADATE: hexdigest() gives another representation of digest(). Every character in digest is transformed into its hex representation. You can transform it with the following function: \ndef digest_to_hex(chars): \n res = '' \n for c in chars: \n res = res + '%02x' % ord(c) \n return res\n\nYou can also use the generator expresion \n''.join('%02x' % ord(x) for x in m.digest())\n\nor \nm.digest().encode('hex')\n\nBTW: You can use dir(some_object) to get a list of its elements, and help(some_object) (in the interactive interpreter) to get more informations about it.\n" ]
[ 3, 3 ]
[]
[]
[ "digest", "hashlib", "md5", "python" ]
stackoverflow_0002597863_digest_hashlib_md5_python.txt
Q: how to change [1,2,3,4] to '1234' using python How do I convert a list of ints to a single string, such that: [1, 2, 3, 4] becomes '1234' [10, 11, 12, 13] becomes '10111213' ... etc... A: ''.join(map(str, [1,2,3,4] )) map(str, array) is equivalent to [str(x) for x in array], so map(str, [1,2,3,4]) returns ['1', '2', '3', '4']. s.join(a) concatenates all items in the sequence a by the string s, for example, >>> ','.join(['foo', 'bar', '', 'baz']) 'foo,bar,,baz' Note that .join can only join string sequences. It won't call str automatically. >>> ''.join([1,2,3,4]) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: sequence item 0: expected string, int found Therefore we need to first map all items into strings first. A: ''.join(str(i) for i in [1,2,3,4])
how to change [1,2,3,4] to '1234' using python
How do I convert a list of ints to a single string, such that: [1, 2, 3, 4] becomes '1234' [10, 11, 12, 13] becomes '10111213' ... etc...
[ "''.join(map(str, [1,2,3,4] ))\n\n\nmap(str, array) is equivalent to [str(x) for x in array], so map(str, [1,2,3,4]) returns ['1', '2', '3', '4'].\ns.join(a) concatenates all items in the sequence a by the string s, for example,\n>>> ','.join(['foo', 'bar', '', 'baz'])\n'foo,bar,,baz'\n\nNote that .join can only join string sequences. It won't call str automatically. \n>>> ''.join([1,2,3,4])\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nTypeError: sequence item 0: expected string, int found\n\nTherefore we need to first map all items into strings first.\n\n", "''.join(str(i) for i in [1,2,3,4])\n\n" ]
[ 20, 12 ]
[]
[]
[ "list", "python", "string" ]
stackoverflow_0002597932_list_python_string.txt
Q: why egrep's stdout did not go through pipe? i got a weird problem regarding egrep and pipe I tried to filter a stream containing some lines who start with a topic name, such as "TICK:this is a tick message\n" When I try to use egrep to filter it : ./stream_generator | egrep 'TICK' | ./topic_processor It seems that the topic_processor never receives any messages However, when i use the following python script: ./stream_generator | python filter.py --topics TICK | ./topic_processor everything looks to be fine. I guess there need to be a 'flush' mechanism for egrep as well, is this correct? Can anyone here give me a clue? Thanks a million import sys from optparse import OptionParser if __name__ == '__main__': parser = OptionParser() parser.add_option("-m", "--topics", action="store", type="string", dest="topics") (opts, args) = parser.parse_args() topics = opts.topics.split(':') while True: s = sys.stdin.readline() for each in topics: if s[0:4] == each: sys.stdout.write(s) sys.stdout.flush() A: Have you allowed the command ./stream_generator | egrep 'TICK' | ./topic_processor to run to completion? If the command has completed without producing output then the problem does not lie with buffering since, upon the termination of ./stream_generator, egrep will flush any of its buffers and in turn terminate. Now, it is true that egrep will use heavy buffering when not outputting directly to a terminal (i.e. when outputting to a pipe or file), and it may appear for a while that egrep produces no output if not enough data has accumulated in egrep's buffer to warrant a flush. This behaviour can be changed in GNU egrep by using the --line-buffered option: ./stream_generator | egrep --line-buffered 'TICK' | ./topic_processor
why egrep's stdout did not go through pipe?
i got a weird problem regarding egrep and pipe I tried to filter a stream containing some lines who start with a topic name, such as "TICK:this is a tick message\n" When I try to use egrep to filter it : ./stream_generator | egrep 'TICK' | ./topic_processor It seems that the topic_processor never receives any messages However, when i use the following python script: ./stream_generator | python filter.py --topics TICK | ./topic_processor everything looks to be fine. I guess there need to be a 'flush' mechanism for egrep as well, is this correct? Can anyone here give me a clue? Thanks a million import sys from optparse import OptionParser if __name__ == '__main__': parser = OptionParser() parser.add_option("-m", "--topics", action="store", type="string", dest="topics") (opts, args) = parser.parse_args() topics = opts.topics.split(':') while True: s = sys.stdin.readline() for each in topics: if s[0:4] == each: sys.stdout.write(s) sys.stdout.flush()
[ "Have you allowed the command ./stream_generator | egrep 'TICK' | ./topic_processor to run to completion? If the command has completed without producing output then the problem does not lie with buffering since, upon the termination of ./stream_generator, egrep will flush any of its buffers and in turn terminate.\nNow, it is true that egrep will use heavy buffering when not outputting directly to a terminal (i.e. when outputting to a pipe or file), and it may appear for a while that egrep produces no output if not enough data has accumulated in egrep's buffer to warrant a flush. This behaviour can be changed in GNU egrep by using the --line-buffered option:\n./stream_generator | egrep --line-buffered 'TICK' | ./topic_processor \n\n" ]
[ 3 ]
[]
[]
[ "grep", "pipe", "python", "shell" ]
stackoverflow_0002598147_grep_pipe_python_shell.txt
Q: Pass logger instance to class I'm using a open-source Python library in my project. This library logs a lot of information using the logging class. ...but I can't see the output or log it to file. I know that i would have to create a logger instance and add a file-handler or a console-handler to it but how can i pass this logger instance to the class? Here's the init snippet of the class that I'm going to be using. class Periscope: ''' Main Periscope class''' def __init__(self): self.config = ConfigParser.SafeConfigParser({"lang": "en"}) if is_local: self.config_file = os.path.join(bd.xdg_config_home, "periscope", "config") if not os.path.exists(self.config_file): folder = os.path.dirname(self.config_file) if not os.path.exists(folder): logging.info("Creating folder %s" %folder) os.mkdir(folder) logging.info("Creating config file") configfile = open(self.config_file, "w") self.config.write(configfile) configfile.close() else: #Load it self.config.read(self.config_file) self.pluginNames = self.listExistingPlugins() self._preferedLanguages = None Any help? Thanks guys. A: Simplest way will be to use basicConfig function in logging module. Here's what docs are saying: Does basic configuration for the logging system by creating a StreamHandler with a default Formatter and adding it to the root logger. The function does nothing if any handlers have been defined for the root logger. The functions debug(), info(), warning(), error() and critical() will call basicConfig() automatically if no handlers are defined for the root logger. This function does nothing if the root logger already has handlers configured. logging module is designed in a way that configuration is separated from creating log messages, so there's no need of having access to logger instance. A: Try setting the level to the lowest possible (DEBUG). This enables all log levels and should give you all logging messages. The simplest way to do default configuration is to use basicConfig() import logging logging.basicConfig(level=logging.DEBUG, filename='/path/to/mylog.log') If the library you are using doesn't override the logging configuration this should be enough to get messages into the log file. If you know the name of the logger the library is using, you can set the level for the library specifically: logging.getLogger("periscope").setLevel(logging.DEBUG)
Pass logger instance to class
I'm using a open-source Python library in my project. This library logs a lot of information using the logging class. ...but I can't see the output or log it to file. I know that i would have to create a logger instance and add a file-handler or a console-handler to it but how can i pass this logger instance to the class? Here's the init snippet of the class that I'm going to be using. class Periscope: ''' Main Periscope class''' def __init__(self): self.config = ConfigParser.SafeConfigParser({"lang": "en"}) if is_local: self.config_file = os.path.join(bd.xdg_config_home, "periscope", "config") if not os.path.exists(self.config_file): folder = os.path.dirname(self.config_file) if not os.path.exists(folder): logging.info("Creating folder %s" %folder) os.mkdir(folder) logging.info("Creating config file") configfile = open(self.config_file, "w") self.config.write(configfile) configfile.close() else: #Load it self.config.read(self.config_file) self.pluginNames = self.listExistingPlugins() self._preferedLanguages = None Any help? Thanks guys.
[ "Simplest way will be to use basicConfig function in logging module. Here's what docs are saying:\n\nDoes basic configuration for the logging system by creating a StreamHandler with a default Formatter and adding it to the root logger. The function does nothing if any handlers have been defined for the root logger. The functions debug(), info(), warning(), error() and critical() will call basicConfig() automatically if no handlers are defined for the root logger.\nThis function does nothing if the root logger already has handlers configured.\n\nlogging module is designed in a way that configuration is separated from creating log messages, so there's no need of having access to logger instance.\n", "Try setting the level to the lowest possible (DEBUG). This enables all log levels and should give you all logging messages. The simplest way to do default configuration is to use basicConfig()\nimport logging \nlogging.basicConfig(level=logging.DEBUG, filename='/path/to/mylog.log')\n\nIf the library you are using doesn't override the logging configuration this should be enough to get messages into the log file. If you know the name of the logger the library is using, you can set the level for the library specifically:\nlogging.getLogger(\"periscope\").setLevel(logging.DEBUG)\n\n" ]
[ 1, 0 ]
[]
[]
[ "logging", "python" ]
stackoverflow_0002598169_logging_python.txt
Q: What does this python line mean? abc = [0, ] * datalen; "datalen" is an Integer. Then I see referencing like this: abc[-1] Any ideas? A: creates a list with datalen references to the object 0: >>> datalen = 10 >>> print [0,] * datalen [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] You don't really need the comma in there: >>> print [0] * datalen [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] A: As everyone else has said, [0] * n will give you a list of n zeros, and indexing with negative numbers with a[-k] gives k-th element from the end, like: a[-1] gives the last element of the sequence and a[-3] gives the third last element of the sequence. A: In addition to what has been said, remember that this behavior is expected when you are copying mutable objects. Classic trap for new python programmers >>> bc = [0,] * 5 >>> bc [0, 0, 0, 0, 0] >>> bc[2]=4 >>> bc [0, 0, 4, 0, 0] >>> bb = [{}, ]*5 >>> bb [{}, {}, {}, {}, {}] >>> bb[2]["hello"]="hi" >>> bb [{'hello': 'hi'}, {'hello': 'hi'}, {'hello': 'hi'}, {'hello': 'hi'}, {'hello': 'hi'}] >>> A: When used in this context, * is the "sequence repetition" operator. >>> datalen = 3 >>> abc = [0,] * datalen [0, 0, 0] In this case, it looks like it's being used as a way to create an array with datalen elements, all of which are initialized to zero. This works for strings too (since they are also sequences): >>> 'String' * 3 'StringStringString' A: creates a list with datalen number of zeroes >>> datalen=5 >>> abc = [0, ] * datalen >>> abc [0, 0, 0, 0, 0]
What does this python line mean?
abc = [0, ] * datalen; "datalen" is an Integer. Then I see referencing like this: abc[-1] Any ideas?
[ "creates a list with datalen references to the object 0:\n>>> datalen = 10\n>>> print [0,] * datalen\n[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n\nYou don't really need the comma in there:\n>>> print [0] * datalen\n[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n\n", "As everyone else has said, [0] * n will give you a list of n zeros, and indexing with negative numbers with a[-k] gives k-th element from the end, like:\n\na[-1]\n\ngives the last element of the sequence and \n\na[-3]\n\ngives the third last element of the sequence.\n", "In addition to what has been said, remember that this behavior is expected when you are copying mutable objects. Classic trap for new python programmers\n>>> bc = [0,] * 5\n>>> bc\n[0, 0, 0, 0, 0]\n>>> bc[2]=4\n>>> bc\n[0, 0, 4, 0, 0]\n\n\n>>> bb = [{}, ]*5\n>>> bb\n[{}, {}, {}, {}, {}]\n>>> bb[2][\"hello\"]=\"hi\"\n>>> bb\n[{'hello': 'hi'}, {'hello': 'hi'}, {'hello': 'hi'}, {'hello': 'hi'}, {'hello': 'hi'}]\n>>> \n\n", "When used in this context, * is the \"sequence repetition\" operator. \n>>> datalen = 3\n>>> abc = [0,] * datalen\n[0, 0, 0]\n\nIn this case, it looks like it's being used as a way to create an array with datalen elements, all of which are initialized to zero.\nThis works for strings too (since they are also sequences): \n>>> 'String' * 3\n'StringStringString'\n\n", "creates a list with datalen number of zeroes\n>>> datalen=5\n>>> abc = [0, ] * datalen\n>>> abc\n[0, 0, 0, 0, 0]\n\n" ]
[ 8, 5, 3, 1, 0 ]
[]
[]
[ "python", "syntax" ]
stackoverflow_0002598069_python_syntax.txt
Q: how to get firefox address bar url for python (pywin32) i need grab to firefox address bar. how to get address bar url for python ? (i need second part other browsers chrome and safari grabbing address bar but firefox is urgently). Thanks. A: You will need to go thru all top windows, and see if title contains firefox or check window class of firefox using spy++, then go thru all child windows to find URL, as a starting point do something like this import win32gui def enumerationCallaback(hwnd, results): text = win32gui.GetWindowText(hwnd) if text.find("Mozilla Firefox") >= 0: results.append((hwnd, text)) mywindows = [] win32gui.EnumWindows(enumerationCallaback, mywindows) for win, text in mywindows: print text def recurseChildWindow(hwnd, results): win32gui.EnumChildWindows(hwnd, recurseChildWindow, results) print hwnd # try to get window class, text etc using SendMessage and see if it is what we want mychildren = [] recurseChildWindow(mywindows[0][0], mychildren) Also you can use this module to do most of such tasks http://www.brunningonline.net/simon/blog/archives/winGuiAuto.py.html
how to get firefox address bar url for python (pywin32)
i need grab to firefox address bar. how to get address bar url for python ? (i need second part other browsers chrome and safari grabbing address bar but firefox is urgently). Thanks.
[ "You will need to go thru all top windows, and see if title contains firefox or check window class of firefox using spy++, then go thru all child windows to find URL, as a starting point do something like this\nimport win32gui\n\ndef enumerationCallaback(hwnd, results):\n text = win32gui.GetWindowText(hwnd)\n if text.find(\"Mozilla Firefox\") >= 0:\n results.append((hwnd, text))\n\nmywindows = [] \nwin32gui.EnumWindows(enumerationCallaback, mywindows)\nfor win, text in mywindows:\n print text\n\ndef recurseChildWindow(hwnd, results):\n win32gui.EnumChildWindows(hwnd, recurseChildWindow, results)\n print hwnd\n # try to get window class, text etc using SendMessage and see if it is what we want\n\nmychildren = []\nrecurseChildWindow(mywindows[0][0], mychildren)\n\nAlso you can use this module to do most of such tasks\nhttp://www.brunningonline.net/simon/blog/archives/winGuiAuto.py.html\n" ]
[ 3 ]
[]
[]
[ "firefox", "python", "pywin32" ]
stackoverflow_0002598404_firefox_python_pywin32.txt
Q: Python float copy question I'm puzzled by some behaviour I'm seeing when copying a float array member into another variable - please help! For example data_entry[1] = 9.6850069951 new_value = data_entry[1] <comment> #print both 9.6850069951 9.6850663300 I'm aware of the problem of binary storage of floats but I thought with a direct copy of memory we would end up with the same value. Any ideas? I need better precision than this! thanks in advance Stuart A: After an assignment the variable new_value is not a copy of the float, it's just another reference to the exact same object. Therefore it cannot possibly have a different printed representation. So there's definitely some detail omitted in the original question. Stuart - can you please try the following and post the result, or tell us how your actual code varies. Note below that new_value is data_entry[1] i.e. they are both the same object. >> data_entry = [0,0] >> data_entry[1] = 9.6850069951 >> new_value = data_entry[1] >> new_value is data_entry[1] True >> print data_entry[1], new_value 9.6850069951 9.6850069951 A: If you're really using the array module (or numpy's arrays) the precision loss is easy to explain, e.g.: >>> dataentry = array.array('f', [9.6850069951]) >>> dataentry[0] 9.6850070953369141 here, the 'f' first arg to array.array says we're using 32-bit floats, so only about 7 significant digits "survive". But it's easy to use 64-bit floats (once upon a time those were known as "double precision"!-): >>> dataentry = array.array('d', [9.6850069951]) >>> dataentry[0] 9.6850069951000002 As you see, this way more than a dozen significant digits "survive" (you can typically rely on about 14+, unless you do arithmetic "oops"s such as taking the difference of numbers very close to each other, which of course devours your precision;-). A: Didn't work for me with Python 2.6.2 on Linux: >>> data_entry = [1, 2] >>> data_entry[1] = 9.6850069951 >>> new_value = data_entry[1] >>> print data_entry[1] --> print(data_entry[1]) 9.6850069951 >>> print new_value --> print(new_value) 9.6850069951 One option would be to switch to using Decimal objects: >>> from decimal import Decimal >>> data_entry[1] = Decimal('9.6850069951') >>> new_value = data_entry[1] >>> print data_entry[1] --> print(data_entry[1]) 9.6850069951 >>> print new_value --> print(new_value) 9.6850069951 If you're losing precision somehow this might help. A: You've left some code out. >>> data_entry=[0,0] >>> data_entry[1] = 9.6850069951 >>> >>> new_value = data_entry[1] >>> print data_entry [0, 9.6850069951000002] >>> print new_value 9.6850069951 >>> print data_entry[1] 9.6850069951 The repr and the str of this floating-point number are producing different results. My guess is that the code you posted omitted mentioning this difference. A: Here's some edited code formatted: old code: data = [] for data_entry in data: if (data_entry[1] != 0): value = data_entry[1] modlog(logging.INFO,'raw value = %.12f',data_entry[1]) modlog(logging.INFO,'value_in = %.12f', value) output: :INFO:raw value = 2.334650748292 :INFO:value_in = 2.334685585881 new code: data = array.array('d') if (data[index] != 0): test_data = data[index] modlog(logging.INFO,'raw data = %.12f', data[(index)]) modlog(logging.INFO,'test_data = %.12f', test_data) output: :INFO:raw data = 2.333840588874 :INFO:test_data= 2.333840588874
Python float copy question
I'm puzzled by some behaviour I'm seeing when copying a float array member into another variable - please help! For example data_entry[1] = 9.6850069951 new_value = data_entry[1] <comment> #print both 9.6850069951 9.6850663300 I'm aware of the problem of binary storage of floats but I thought with a direct copy of memory we would end up with the same value. Any ideas? I need better precision than this! thanks in advance Stuart
[ "After an assignment the variable new_value is not a copy of the float, it's just another reference to the exact same object. Therefore it cannot possibly have a different printed representation. So there's definitely some detail omitted in the original question.\nStuart - can you please try the following and post the result, or tell us how your actual code varies. Note below that new_value is data_entry[1] i.e. they are both the same object.\n>> data_entry = [0,0]\n>> data_entry[1] = 9.6850069951\n>> new_value = data_entry[1]\n>> new_value is data_entry[1]\nTrue\n>> print data_entry[1], new_value\n9.6850069951 9.6850069951\n\n", "If you're really using the array module (or numpy's arrays) the precision loss is easy to explain, e.g.:\n>>> dataentry = array.array('f', [9.6850069951])\n>>> dataentry[0]\n9.6850070953369141\n\nhere, the 'f' first arg to array.array says we're using 32-bit floats, so only about 7 significant digits \"survive\". But it's easy to use 64-bit floats (once upon a time those were known as \"double precision\"!-):\n>>> dataentry = array.array('d', [9.6850069951])\n>>> dataentry[0]\n9.6850069951000002\n\nAs you see, this way more than a dozen significant digits \"survive\" (you can typically rely on about 14+, unless you do arithmetic \"oops\"s such as taking the difference of numbers very close to each other, which of course devours your precision;-).\n", "Didn't work for me with Python 2.6.2 on Linux:\n>>> data_entry = [1, 2]\n>>> data_entry[1] = 9.6850069951\n>>> new_value = data_entry[1]\n>>> print data_entry[1]\n--> print(data_entry[1])\n9.6850069951\n>>> print new_value\n--> print(new_value)\n9.6850069951\n\nOne option would be to switch to using Decimal objects:\n>>> from decimal import Decimal\n>>> data_entry[1] = Decimal('9.6850069951')\n>>> new_value = data_entry[1]\n>>> print data_entry[1]\n--> print(data_entry[1])\n9.6850069951\n>>> print new_value\n--> print(new_value)\n9.6850069951\n\nIf you're losing precision somehow this might help.\n", "You've left some code out.\n>>> data_entry=[0,0]\n>>> data_entry[1] = 9.6850069951\n>>> \n>>> new_value = data_entry[1]\n>>> print data_entry\n[0, 9.6850069951000002]\n>>> print new_value\n9.6850069951\n>>> print data_entry[1]\n9.6850069951\n\nThe repr and the str of this floating-point number are producing different results. My guess is that the code you posted omitted mentioning this difference.\n", "Here's some edited code formatted:\nold code:\ndata = []\nfor data_entry in data:\n if (data_entry[1] != 0):\n value = data_entry[1]\n modlog(logging.INFO,'raw value = %.12f',data_entry[1])\n modlog(logging.INFO,'value_in = %.12f', value)\noutput:\n:INFO:raw value = 2.334650748292\n:INFO:value_in = 2.334685585881\n\nnew code:\ndata = array.array('d') \nif (data[index] != 0):\n test_data = data[index]\n modlog(logging.INFO,'raw data = %.12f', data[(index)])\n modlog(logging.INFO,'test_data = %.12f', test_data)\noutput:\n:INFO:raw data = 2.333840588874\n:INFO:test_data= 2.333840588874\n\n" ]
[ 5, 3, 0, 0, 0 ]
[]
[]
[ "floating_point", "python", "variable_assignment" ]
stackoverflow_0002524998_floating_point_python_variable_assignment.txt
Q: HTTPSConnection module missing in Python 2.6 on CentOS 5.2 I'm playing around with a Python application on CentOS 5.2. It uses the Boto module to communicate with Amazon Web Services, which requires communication through a HTTPS connection. When I try running my application I get an error regarding HTTPSConnection being missing: "AttributeError: 'module' object has no attribute 'HTTPSConnection'" Google doesn't really return anything relevant, I've tried most of the solutions but none of them solve the problem. Has anyone come across anything like it? Here's the traceback: Traceback (most recent call last): File "./chatter.py", line 114, in <module> sys.exit(main()) File "./chatter.py", line 92, in main chatter.status( ) File "/mnt/application/chatter/__init__.py", line 161, in status cQueue.connect() File "/mnt/application/chatter/tools.py", line 42, in connect self.connection = SQSConnection(cConfig.get("AWS", "KeyId"), cConfig.get("AWS", "AccessKey")); File "/usr/local/lib/python2.6/site-packages/boto-1.7a-py2.6.egg/boto/sqs/connection.py", line 54, in __init__ self.region.endpoint, debug, https_connection_factory) File "/usr/local/lib/python2.6/site-packages/boto-1.7a-py2.6.egg/boto/connection.py", line 418, in __init__ debug, https_connection_factory) File "/usr/local/lib/python2.6/site-packages/boto-1.7a-py2.6.egg/boto/connection.py", line 189, in __init__ self.refresh_http_connection(self.server, self.is_secure) File "/usr/local/lib/python2.6/site-packages/boto-1.7a-py2.6.egg/boto/connection.py", line 247, in refresh_http_connection connection = httplib.HTTPSConnection(host) AttributeError: 'module' object has no attribute 'HTTPSConnection' A: citing from the python documentation (http://docs.python.org/library/httplib.html): Note HTTPS support is only available if the socket module was compiled with SSL support. You should find out how python on the CentOS you are using was built. A: Please install openssl and openssl-devel before you install python2.6. You can simply install those packages using yum, and do a re-install of python2.6 (no need to remove already installed python2.6) ]# yum install openssl openssl-devel Python-2.6.x]# ./configure Python-2.6.x]# make && make altinstall A: How come you have python 2.6? In CentOS 2.4 is standard, this might be the cause of your problem. Might be worth installing boto again as the library paths might not be correct
HTTPSConnection module missing in Python 2.6 on CentOS 5.2
I'm playing around with a Python application on CentOS 5.2. It uses the Boto module to communicate with Amazon Web Services, which requires communication through a HTTPS connection. When I try running my application I get an error regarding HTTPSConnection being missing: "AttributeError: 'module' object has no attribute 'HTTPSConnection'" Google doesn't really return anything relevant, I've tried most of the solutions but none of them solve the problem. Has anyone come across anything like it? Here's the traceback: Traceback (most recent call last): File "./chatter.py", line 114, in <module> sys.exit(main()) File "./chatter.py", line 92, in main chatter.status( ) File "/mnt/application/chatter/__init__.py", line 161, in status cQueue.connect() File "/mnt/application/chatter/tools.py", line 42, in connect self.connection = SQSConnection(cConfig.get("AWS", "KeyId"), cConfig.get("AWS", "AccessKey")); File "/usr/local/lib/python2.6/site-packages/boto-1.7a-py2.6.egg/boto/sqs/connection.py", line 54, in __init__ self.region.endpoint, debug, https_connection_factory) File "/usr/local/lib/python2.6/site-packages/boto-1.7a-py2.6.egg/boto/connection.py", line 418, in __init__ debug, https_connection_factory) File "/usr/local/lib/python2.6/site-packages/boto-1.7a-py2.6.egg/boto/connection.py", line 189, in __init__ self.refresh_http_connection(self.server, self.is_secure) File "/usr/local/lib/python2.6/site-packages/boto-1.7a-py2.6.egg/boto/connection.py", line 247, in refresh_http_connection connection = httplib.HTTPSConnection(host) AttributeError: 'module' object has no attribute 'HTTPSConnection'
[ "citing from the python documentation (http://docs.python.org/library/httplib.html):\nNote HTTPS support is only available if the socket module was compiled with SSL support.\nYou should find out how python on the CentOS you are using was built.\n", "Please install openssl and openssl-devel before you install python2.6.\nYou can simply install those packages using yum, and do a re-install of python2.6 (no need to remove already installed python2.6)\n]# yum install openssl openssl-devel\n\nPython-2.6.x]# ./configure\nPython-2.6.x]# make && make altinstall\n\n", "How come you have python 2.6? In CentOS 2.4 is standard, this might be the cause of your problem. Might be worth installing boto again as the library paths might not be correct\n" ]
[ 7, 7, 0 ]
[]
[]
[ "centos", "python" ]
stackoverflow_0000877072_centos_python.txt
Q: Is there a python openid apps-discovery library to get appengine apps onto the apps marketplace I'm looking for info on howto get a google appengine app onto the newly announced google apps marketplace. The page at http://code.google.com/googleapps/marketplace/sso.html does not have a python openid apps-discovery library which seems to be the stumbling block. Has anyone ported an appengine app to the marketplace? or know of the existence of a python openid apps-discovery library? or have a timeline on this? updated: please see comment re: standard python openid library vs library that supports "apps-discovery" updated: apparently it is not currently possible, however it will be soon see http://www.google.com/support/forum/p/apps-apis/thread?tid=52e36f012c2436c3&hl=en A: I answered an almost the same question at Google apps login in django. Check it out. Edited: Actually, your question can be separated into two related questions. How to build an application for Google Marketplace? How to authenticate with Google Apps Account to login into your application? You don't really have to authenticate with Google Apps. But since your user already have an Google Apps Account, it's nice to let the user login with their existing account instead of building your own user management module from scratch. For the first question, when you register your application on Google Marketplace, you provide your login url. It's in http://yourdomain.com/auth/domain.com kind of format. The domain.com part is the domain name of the organization who choose to install your application. When one organization installed your application, they will use that login url as the entrance point. It is your application determines what to do with the request. Typically, you redirect the user to the login page. Since you want the user to login with his Google Apps Account, you could generate the login request and redirect the user to Google's server. And that part is related to the second question. For the second question, you could let the user to login into your application with their Google Apps Account by implementing Google's AuthSub or OpenID authentication mechanism. As you're asking for the openid library, I guess you chose openid. If you want to use openid to authenticate, you should pay your attention to Google's custom discovery method which is not in the standard library. Check my answer in the other question I answered for more information. I just uploaded my patched version of python-openid-2.2.4 to github. Here is the link: http://github.com/adieu/python-openid/ BTW: you don't really have to ask the user to put some file on their server. But if they do so, they could change the default openid authentication backend server. Maybe I should write a blog post about this problem :) A: The python-openid library appears to support discovery.
Is there a python openid apps-discovery library to get appengine apps onto the apps marketplace
I'm looking for info on howto get a google appengine app onto the newly announced google apps marketplace. The page at http://code.google.com/googleapps/marketplace/sso.html does not have a python openid apps-discovery library which seems to be the stumbling block. Has anyone ported an appengine app to the marketplace? or know of the existence of a python openid apps-discovery library? or have a timeline on this? updated: please see comment re: standard python openid library vs library that supports "apps-discovery" updated: apparently it is not currently possible, however it will be soon see http://www.google.com/support/forum/p/apps-apis/thread?tid=52e36f012c2436c3&hl=en
[ "I answered an almost the same question at Google apps login in django. Check it out.\nEdited:\nActually, your question can be separated into two related questions.\n\nHow to build an application for Google Marketplace?\nHow to authenticate with Google Apps Account to login into your application?\n\nYou don't really have to authenticate with Google Apps. But since your user already have an Google Apps Account, it's nice to let the user login with their existing account instead of building your own user management module from scratch.\nFor the first question, when you register your application on Google Marketplace, you provide your login url. It's in http://yourdomain.com/auth/domain.com kind of format. The domain.com part is the domain name of the organization who choose to install your application. When one organization installed your application, they will use that login url as the entrance point. It is your application determines what to do with the request. Typically, you redirect the user to the login page. Since you want the user to login with his Google Apps Account, you could generate the login request and redirect the user to Google's server. And that part is related to the second question.\nFor the second question, you could let the user to login into your application with their Google Apps Account by implementing Google's AuthSub or OpenID authentication mechanism. As you're asking for the openid library, I guess you chose openid. If you want to use openid to authenticate, you should pay your attention to Google's custom discovery method which is not in the standard library. Check my answer in the other question I answered for more information.\nI just uploaded my patched version of python-openid-2.2.4 to github. Here is the link: http://github.com/adieu/python-openid/\nBTW: you don't really have to ask the user to put some file on their server. But if they do so, they could change the default openid authentication backend server.\nMaybe I should write a blog post about this problem :)\n", "The python-openid library appears to support discovery.\n" ]
[ 3, 0 ]
[]
[]
[ "google_app_engine", "marketplace", "python" ]
stackoverflow_0002422220_google_app_engine_marketplace_python.txt
Q: Python recursion with list returns None def foo(a): a.append(1) if len(a) > 10: print a return a else: foo(a) Why this recursive function returns None (see transcript below)? I can't quite understand what I am doing wrong. In [263]: x = [] In [264]: y = foo(x) [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] In [265]: print y None A: You don't return anything in the else clause: else: return foo(a)
Python recursion with list returns None
def foo(a): a.append(1) if len(a) > 10: print a return a else: foo(a) Why this recursive function returns None (see transcript below)? I can't quite understand what I am doing wrong. In [263]: x = [] In [264]: y = foo(x) [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] In [265]: print y None
[ "You don't return anything in the else clause:\n else:\n return foo(a)\n\n" ]
[ 20 ]
[]
[]
[ "list", "python", "recursion" ]
stackoverflow_0002599149_list_python_recursion.txt
Q: Django templates check condition If there are are no values in the table how can should the code be to indicate no name found else show the drop down box in the below code {% for name in dict.names %} <option value="{{name.id}}" {% for selected_id in selected_name %}{% ifequal name.id selected_id %} {{ selected }} {% endifequal %} {% endfor %}>{{name.firstname}}</option>{% endfor %} </select> Thanks.. A: I'm guessing that you want for...empty pair of tags. <select> {% for name in dict.names %} <option value="{{name.id}}" {% for selected_id in selected_name %} {% ifequal name.id selected_id %} {{ selected }} {% endifequal %} {% endfor %}> {{name.firstname}} </option> {% empty %} <option value="">No names</option> {% endfor %} </select> More details here
Django templates check condition
If there are are no values in the table how can should the code be to indicate no name found else show the drop down box in the below code {% for name in dict.names %} <option value="{{name.id}}" {% for selected_id in selected_name %}{% ifequal name.id selected_id %} {{ selected }} {% endifequal %} {% endfor %}>{{name.firstname}}</option>{% endfor %} </select> Thanks..
[ "I'm guessing that you want for...empty pair of tags. \n<select>\n {% for name in dict.names %}\n <option value=\"{{name.id}}\" \n {% for selected_id in selected_name %}\n {% ifequal name.id selected_id %} {{ selected }} {% endifequal %} \n {% endfor %}>\n {{name.firstname}}\n </option>\n {% empty %}\n <option value=\"\">No names</option>\n {% endfor %}\n</select>\n\nMore details here\n" ]
[ 2 ]
[]
[]
[ "django", "django_templates", "python" ]
stackoverflow_0002599203_django_django_templates_python.txt
Q: Python (pdb) - Queueing up commands to execute I am implementing a "breakpoint" system for use in my Python development that will allow me to call a function that, in essence, calls pdb.set_trace(); Some of the functionality that I would like to implement requires me to control pdb from code while I am within a set_trace context. Example: disableList = [] def breakpoint(name=None): def d(): disableList.append(name) #**** #issue 'run' command to pdb so user #does not have to type 'c' #**** if name in disableList: return print "Use d() to disable breakpoint, 'c' to continue" pdb.set_trace(); In the above example, how do I implement the comments demarked by the #**** ? In other parts of this system, I would like to issue an 'up' command, or two sequential 'up' commands without leaving the pdb session (so the user ends up at a pdb prompt but up two levels on the call stack). A: You could invoke lower-level methods to get more control over the debugger: def debug(): import pdb import sys # set up the debugger debugger = pdb.Pdb() debugger.reset() # your custom stuff here debugger.do_where(None) # run the "where" command # invoke the interactive debugging prompt users_frame = sys._getframe().f_back # frame where the user invoked `debug()` debugger.interaction(users_frame, None) if __name__ == '__main__': print 1 debug() print 2 You can find documentation for the pdb module here: http://docs.python.org/library/pdb and for the bdb lower-level debugging interface here: http://docs.python.org/library/bdb. You may also want to look at their source code.
Python (pdb) - Queueing up commands to execute
I am implementing a "breakpoint" system for use in my Python development that will allow me to call a function that, in essence, calls pdb.set_trace(); Some of the functionality that I would like to implement requires me to control pdb from code while I am within a set_trace context. Example: disableList = [] def breakpoint(name=None): def d(): disableList.append(name) #**** #issue 'run' command to pdb so user #does not have to type 'c' #**** if name in disableList: return print "Use d() to disable breakpoint, 'c' to continue" pdb.set_trace(); In the above example, how do I implement the comments demarked by the #**** ? In other parts of this system, I would like to issue an 'up' command, or two sequential 'up' commands without leaving the pdb session (so the user ends up at a pdb prompt but up two levels on the call stack).
[ "You could invoke lower-level methods to get more control over the debugger:\ndef debug():\n import pdb\n import sys\n\n # set up the debugger\n debugger = pdb.Pdb()\n debugger.reset()\n\n # your custom stuff here\n debugger.do_where(None) # run the \"where\" command\n\n # invoke the interactive debugging prompt\n users_frame = sys._getframe().f_back # frame where the user invoked `debug()`\n debugger.interaction(users_frame, None)\n\nif __name__ == '__main__':\n print 1\n debug()\n print 2\n\nYou can find documentation for the pdb module here: http://docs.python.org/library/pdb and for the bdb lower-level debugging interface here: http://docs.python.org/library/bdb. You may also want to look at their source code.\n" ]
[ 5 ]
[]
[]
[ "debugging", "pdb", "python" ]
stackoverflow_0002596738_debugging_pdb_python.txt
Q: Using zc.buildout, how do I install a tarball from a website? I'm trying to get zc.buildout to install Gunicorn from source. Using the following configuration: [gunicorn] recipe = collective.recipe.distutils url = http://github.com/benoitc/gunicorn/tarball/master results in the following error: SystemError: ('Failed', '"/usr/bin/python" setup.py -q install --install- purelib="/mnt/hgfs/Projects/intranation/parts/site-packages" --install-platlib="/mnt/hgfs/Projects/intranation/parts/site-packages"') Providing a --install-dir or --prefix doesn't help. Is there a recipe for zc.buildout that downloads a tarball and installs it via easy_install or similar? A: You can "just" install it. On the command line, "easy_install http://github.com/benoitc/gunicorn/tarball/master" works fine. The buildout equivalent would be to have a dependency on "gunicorn" (so that buildout attempts installing it) and to tell buildout that your github link is actually gunicorn. You do that with find-links: [buildout] find-links = http://github.com/benoitc/gunicorn/tarball/master#egg=gunicorn parts = console_scripts [console_scripts] recipe = zc.recipe.egg eggs = gunicorn
Using zc.buildout, how do I install a tarball from a website?
I'm trying to get zc.buildout to install Gunicorn from source. Using the following configuration: [gunicorn] recipe = collective.recipe.distutils url = http://github.com/benoitc/gunicorn/tarball/master results in the following error: SystemError: ('Failed', '"/usr/bin/python" setup.py -q install --install- purelib="/mnt/hgfs/Projects/intranation/parts/site-packages" --install-platlib="/mnt/hgfs/Projects/intranation/parts/site-packages"') Providing a --install-dir or --prefix doesn't help. Is there a recipe for zc.buildout that downloads a tarball and installs it via easy_install or similar?
[ "You can \"just\" install it. On the command line, \"easy_install http://github.com/benoitc/gunicorn/tarball/master\" works fine.\nThe buildout equivalent would be to have a dependency on \"gunicorn\" (so that buildout attempts installing it) and to tell buildout that your github link is actually gunicorn. You do that with find-links:\n[buildout]\n find-links =\n http://github.com/benoitc/gunicorn/tarball/master#egg=gunicorn\n parts = console_scripts\n\n\n [console_scripts]\n recipe = zc.recipe.egg\n eggs = gunicorn\n\n" ]
[ 3 ]
[]
[]
[ "buildout", "python", "recipe" ]
stackoverflow_0002572160_buildout_python_recipe.txt
Q: Designing a Tag table that tells how many times it's used I am trying to design a tagging system with a model like this: Tag: content = CharField creator = ForeignKey used = IntergerField It is a many-to-many relationship between tags and what's been tagged. Everytime I insert a record into the assotication table, Tag.used is incremented by one, and decremented by one in case of deletion. Tag.used is maintained because I want to speed up answering the question 'How many times this tag is used?'. However, this seems to slow insertion down obviously. Please tell me how to improve this design. Thanks in advance. http://www.pui.ch/phred/archives/2005/06/tagsystems-performance-tests.html A: I don't think it's a good idea to denormalize your data like that. I think a more elegant solution is to use django aggregation to track how many times the tag has been used http://docs.djangoproject.com/en/dev/topics/db/aggregation/ You could attach the used count to your tag object by calling something like this: my_tag = Tag.objects.annotate(used=Count('post'))[0] and then accessing it like this: my_tag.used assuming that you have a Post model class that has a ManyToMany field to your Tag class You can order the Tags by the named annotated field if needed: Tag.objects.annotate(used=Count('post')).order_by('-used') A: If your database support materialized indexed views then you might want to create one for this. You can get a large performance boost for frequently run queries that aggregate data, which I think you have here. your view would be on a query like: SELECT TagID,COUNT(*) FROM YourTable GROUP BY TagID The aggregations can be precomputed and stored in the index to minimize expensive computations during query execution.
Designing a Tag table that tells how many times it's used
I am trying to design a tagging system with a model like this: Tag: content = CharField creator = ForeignKey used = IntergerField It is a many-to-many relationship between tags and what's been tagged. Everytime I insert a record into the assotication table, Tag.used is incremented by one, and decremented by one in case of deletion. Tag.used is maintained because I want to speed up answering the question 'How many times this tag is used?'. However, this seems to slow insertion down obviously. Please tell me how to improve this design. Thanks in advance. http://www.pui.ch/phred/archives/2005/06/tagsystems-performance-tests.html
[ "I don't think it's a good idea to denormalize your data like that.\nI think a more elegant solution is to use django aggregation to track how many times the tag has been used http://docs.djangoproject.com/en/dev/topics/db/aggregation/\nYou could attach the used count to your tag object by calling something like this:\nmy_tag = Tag.objects.annotate(used=Count('post'))[0]\n\nand then accessing it like this:\nmy_tag.used\n\nassuming that you have a Post model class that has a ManyToMany field to your Tag class\nYou can order the Tags by the named annotated field if needed:\nTag.objects.annotate(used=Count('post')).order_by('-used')\n\n", "If your database support materialized indexed views then you might want to create one for this. You can get a large performance boost for frequently run queries that aggregate data, which I think you have here.\nyour view would be on a query like:\nSELECT\n TagID,COUNT(*)\n FROM YourTable\n GROUP BY TagID\n\nThe aggregations can be precomputed and stored in the index to minimize expensive computations during query execution.\n" ]
[ 1, 1 ]
[]
[]
[ "database_design", "django", "python", "tagging" ]
stackoverflow_0002597751_database_design_django_python_tagging.txt
Q: Generate fixed length hash in python for url parameter I am working in python on appengine. I am trying to create what is equivalent to the "v" value in the youtube url's (http://www.youtube.com/watch?v=XhMN0wlITLk) for retrieving specific entities. The datastore auto generates a key but it is way too long (34 digits). I have experimented with hashlib to build my own, but again I get a long string. I would like to keep it to under 11 digits (I am not dealing with a huge number of entities) and letters and numbers are acceptable. It seems like there should be a pretty standard solution. I am probably just missing it. A: You can use the auto generated integer id of the key to generate the hash. A simple way to generate the hash would be to convert the integer id to base62 (alphanumeric). To fetch the object simply convert to decimal back from base62 and use get_by_id to retrieve the object. Here is a simple base62 conversion function that i have used in one of my apps. import string alphabet = string.letters + string.digits max = 11 def int_to_base62(num): if num == 0: return alphabet[0] arr = [] radix = len(alphabet) while num: arr.append(alphabet[num%radix]) num /= radix arr.reverse() return (alphabet[0] * (max - len(arr))) + ''.join(arr) def base62_to_int(str): radix = len(alphabet) power = len(str) - 1 num = 0 for char in str: num += alphabet.index(char) * (radix ** power) power -= 1 return num A: If you have a value that is unique for every entity, you can get a shorter version by hashing it and truncating. Hashes like md5 or sha1 are well-mixed, meaning that every bit in the output has a 50% chance of flipping if you change one bit in the input. If you truncate the hash, you are simply increasing the odds of a collision, but you can make the tradeoff between length and collision odds. Url-safe base64 encoding is a good option for turning the hash into text. orig_id = 'weiowoeiwoeciw0eijw0eij029j20d232weifw0jiw0e20d2' # the original id shorter_id = base64.urlsafe_b64encode(hashlib.md5(orig_id).digest())[:11] With base64, you have 6 bits of information per character, 11 characters gives you 66 bits of uniqueness, or a 1 in 2**66 chance of collision.
Generate fixed length hash in python for url parameter
I am working in python on appengine. I am trying to create what is equivalent to the "v" value in the youtube url's (http://www.youtube.com/watch?v=XhMN0wlITLk) for retrieving specific entities. The datastore auto generates a key but it is way too long (34 digits). I have experimented with hashlib to build my own, but again I get a long string. I would like to keep it to under 11 digits (I am not dealing with a huge number of entities) and letters and numbers are acceptable. It seems like there should be a pretty standard solution. I am probably just missing it.
[ "You can use the auto generated integer id of the key to generate the hash. A simple way to generate the hash would be to convert the integer id to base62 (alphanumeric). To fetch the object simply convert to decimal back from base62 and use get_by_id to retrieve the object.\nHere is a simple base62 conversion function that i have used in one of my apps.\nimport string\nalphabet = string.letters + string.digits\nmax = 11\n\ndef int_to_base62(num):\n if num == 0:\n return alphabet[0]\n\n arr = []\n radix = len(alphabet)\n while num:\n arr.append(alphabet[num%radix])\n num /= radix\n arr.reverse()\n return (alphabet[0] * (max - len(arr))) + ''.join(arr)\n\ndef base62_to_int(str):\n radix = len(alphabet)\n power = len(str) - 1\n num = 0\n for char in str:\n num += alphabet.index(char) * (radix ** power)\n power -= 1\n return num\n\n", "If you have a value that is unique for every entity, you can get a shorter version by hashing it and truncating. Hashes like md5 or sha1 are well-mixed, meaning that every bit in the output has a 50% chance of flipping if you change one bit in the input. If you truncate the hash, you are simply increasing the odds of a collision, but you can make the tradeoff between length and collision odds.\nUrl-safe base64 encoding is a good option for turning the hash into text.\norig_id = 'weiowoeiwoeciw0eijw0eij029j20d232weifw0jiw0e20d2' # the original id\nshorter_id = base64.urlsafe_b64encode(hashlib.md5(orig_id).digest())[:11]\n\nWith base64, you have 6 bits of information per character, 11 characters gives you 66 bits of uniqueness, or a 1 in 2**66 chance of collision.\n" ]
[ 8, 7 ]
[]
[]
[ "google_app_engine", "hash", "python", "url" ]
stackoverflow_0002597833_google_app_engine_hash_python_url.txt
Q: Does python have one way of doing things? I have always seen in python articles/books that python is simple and it has only one way of doing things. I would like someone to explain to me this concept keeping in mind the example below, if I wanted to get the min and max values of sequence I would do the following; seq=[1,2,3,4,5,6] min(seq) #1 max(seq) #6 but I can also do this; seq[:1] #1 seq[-1] #6 surely this are two ways of doing one simple thing. This confuses me a bit. A: Not that it "has one way of doing things" as more "There should be one-- and preferably only one --obvious way to do it." (from Zen of Python). This doesn't exclude possibility of having more than one way of doing things. We're talking about programming where creativity is one of the most important skills and finding new ways of solving problems is a must. In your example you're doing two different things: getting minimum and maximum of the list getting first and the last element of the list it happens that in this particular case result is exactly the same. A: Those are two different things. max() gives you the largest element of the list (using regular number comparison by default), while [-1] gives you the last element – in your example, this happens to be the same thing. But consider this: >>> seq = [2, 7, 5, 4] >>> max(seq) 7 >>> seq[-1] 4 BTW, seq[:1] gives you something different again – namely [1] (or [2] in my example), a one-element list. What you probably meant was seq[0], which is the first element of the list, compared to min(seq), the smallest one. A: One obvious way. >>> import this A: In your example, you actually do two different things -- they just happen to give the same result, because your input list is sorted. However, there's always multiple ways of doing things. Python's approach isn't really to avoid or forbid multiple ways of doing the same thing, but have one - and preferably only one - obvious way of doing things. A: max(), min() and index slicing they all do different things. In your list, the order may not be sorted like your example, so using slicing will not get the max/min for you in those cases. if you want to get max/min values, just use max()/min() functions A: There is always more than one way to solve a problem, but the python developers try not to add language features that offer redundant functionality, which is very unlike perl.
Does python have one way of doing things?
I have always seen in python articles/books that python is simple and it has only one way of doing things. I would like someone to explain to me this concept keeping in mind the example below, if I wanted to get the min and max values of sequence I would do the following; seq=[1,2,3,4,5,6] min(seq) #1 max(seq) #6 but I can also do this; seq[:1] #1 seq[-1] #6 surely this are two ways of doing one simple thing. This confuses me a bit.
[ "Not that it \"has one way of doing things\" as more \"There should be one-- and preferably only one --obvious way to do it.\" (from Zen of Python).\nThis doesn't exclude possibility of having more than one way of doing things. We're talking about programming where creativity is one of the most important skills and finding new ways of solving problems is a must.\nIn your example you're doing two different things:\n\ngetting minimum and maximum of the list\ngetting first and the last element of the list\n\nit happens that in this particular case result is exactly the same.\n", "Those are two different things. max() gives you the largest element of the list (using regular number comparison by default), while [-1] gives you the last element – in your example, this happens to be the same thing. But consider this:\n>>> seq = [2, 7, 5, 4]\n>>> max(seq)\n7\n>>> seq[-1]\n4\n\nBTW, seq[:1] gives you something different again – namely [1] (or [2] in my example), a one-element list. What you probably meant was seq[0], which is the first element of the list, compared to min(seq), the smallest one.\n", "One obvious way.\n>>> import this\n\n", "In your example, you actually do two different things -- they just happen to give the same result, because your input list is sorted. However, there's always multiple ways of doing things. Python's approach isn't really to avoid or forbid multiple ways of doing the same thing, but have one - and preferably only one - obvious way of doing things.\n", "max(), min() and index slicing they all do different things. In your list, the order may not be sorted like your example, so using slicing will not get the max/min for you in those cases. if you want to get max/min values, just use max()/min() functions\n", "There is always more than one way to solve a problem, but the python developers try not to add language features that offer redundant functionality, which is very unlike perl.\n" ]
[ 30, 15, 7, 3, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002599410_python.txt
Q: appcfg.py upload_data entity kind problem I am developing application on app-engine-path and I would like to upload some data to datastore. For example I have a model models/places.py: class Place(db.Model): name = db.StringProperty() longitude = db.FloatProperty() latitude = db.FloatProperty() If I save this in view, kind() of this entity is "models_place". All is ok, Place.all() in view work fine. But: If I upload some next row using appcfg.py upload_data, the kind() of this entities is Place. loader.py look like this: import datetime, os, sys from google.appengine.ext import db from google.appengine.tools import bulkloader libs_path = os.path.join("/home/martin/myproject/src/") if libs_path not in sys.path: sys.path.insert(0, libs_path) from models import places class AlbumLoader(bulkloader.Loader): def __init__(self): bulkloader.Loader.__init__(self, 'Place', [('name', lambda x: x.decode('utf-8')), ('longitude', float), ('latitude', float), ]) loaders = [AlbumLoader] and command for uploading: python /usr/local/google_appengine/appcfg.py upload_data --config_file=places_loader.py --kind=models_place --filename=data/places.csv --url=http://localhost:8000/remote_api /home/martin/myproject/src/ A: I found resolution: places_loader.py: from google.appengine.ext import bulkload class PlaceLoader(bulkload.Loader): def __init__(self): bulkload.Loader.__init__(self, 'models_place', [('name', lambda x: x.decode('utf-8')), ('longitude', float), ('latitude', float), ]) if __name__ == '__main__': bulkload.main(PlaceLoader()) app.yaml: - url: /load script: places_loader.py and command: python /usr/local/google_appengine/bulkload_client.py --filename data/places.csv --kind models_place --url http://localhost:8000/load
appcfg.py upload_data entity kind problem
I am developing application on app-engine-path and I would like to upload some data to datastore. For example I have a model models/places.py: class Place(db.Model): name = db.StringProperty() longitude = db.FloatProperty() latitude = db.FloatProperty() If I save this in view, kind() of this entity is "models_place". All is ok, Place.all() in view work fine. But: If I upload some next row using appcfg.py upload_data, the kind() of this entities is Place. loader.py look like this: import datetime, os, sys from google.appengine.ext import db from google.appengine.tools import bulkloader libs_path = os.path.join("/home/martin/myproject/src/") if libs_path not in sys.path: sys.path.insert(0, libs_path) from models import places class AlbumLoader(bulkloader.Loader): def __init__(self): bulkloader.Loader.__init__(self, 'Place', [('name', lambda x: x.decode('utf-8')), ('longitude', float), ('latitude', float), ]) loaders = [AlbumLoader] and command for uploading: python /usr/local/google_appengine/appcfg.py upload_data --config_file=places_loader.py --kind=models_place --filename=data/places.csv --url=http://localhost:8000/remote_api /home/martin/myproject/src/
[ "I found resolution:\nplaces_loader.py:\nfrom google.appengine.ext import bulkload\n\nclass PlaceLoader(bulkload.Loader):\n def __init__(self):\n bulkload.Loader.__init__(self, 'models_place',\n [('name', lambda x: x.decode('utf-8')),\n ('longitude', float),\n ('latitude', float),\n ])\nif __name__ == '__main__':\n bulkload.main(PlaceLoader())\n\napp.yaml:\n- url: /load\n script: places_loader.py \n\nand command:\npython /usr/local/google_appengine/bulkload_client.py --filename data/places.csv --kind models_place --url http://localhost:8000/load\n\n" ]
[ 1 ]
[]
[]
[ "app_engine_patch", "django", "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0002599937_app_engine_patch_django_google_app_engine_google_cloud_datastore_python.txt
Q: Problem building a complete binary tree of height 'h' in Python Here is my code. The complete binary tree has 2^k nodes at depth k. class Node: def __init__(self, data): # initializes the data members self.left = None self.right = None self.data = data root = Node(data_root) def create_complete_tree(): row = [root] for i in range(h): newrow = [] for node in row: left = Node(data1) right = Node(data2) node.left = left node.right = right newrow.append(left) newrow.append(right) row = copy.deepcopy(newrow) def traverse_tree(node): if node == None: return else: traverse_tree(node.left) print node.data traverse_tree(node.right) create_complete_tree() print 'Node traversal' traverse_tree(root) The tree traversal only gives the data of root and its children. What am I doing wrong? A: The main problem here is that you are using deepcopy on the temporary list. Consider what happens each iteration: Your initial root gets inspected, and child nodes get created These child nodes are placed in newrow Copies of these child nodes are copied into row for the next iteration. This means the subsequent iteration will not be mutating the nodes you created (and which root.left and root.right points to), but copies of them, leaving the originals in their current state (with None for .left and .right)
Problem building a complete binary tree of height 'h' in Python
Here is my code. The complete binary tree has 2^k nodes at depth k. class Node: def __init__(self, data): # initializes the data members self.left = None self.right = None self.data = data root = Node(data_root) def create_complete_tree(): row = [root] for i in range(h): newrow = [] for node in row: left = Node(data1) right = Node(data2) node.left = left node.right = right newrow.append(left) newrow.append(right) row = copy.deepcopy(newrow) def traverse_tree(node): if node == None: return else: traverse_tree(node.left) print node.data traverse_tree(node.right) create_complete_tree() print 'Node traversal' traverse_tree(root) The tree traversal only gives the data of root and its children. What am I doing wrong?
[ "The main problem here is that you are using deepcopy on the temporary list. Consider what happens each iteration:\n\nYour initial root gets inspected, and child nodes get created\nThese child nodes are placed in newrow\nCopies of these child nodes are copied into row for the next iteration.\n\nThis means the subsequent iteration will not be mutating the nodes you created (and which root.left and root.right points to), but copies of them, leaving the originals in their current state (with None for .left and .right)\n" ]
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0002600426_python.txt
Q: Types in Python - Google Appengine Getting a bit peeved now; I have a model and a class thats just storing a get request in the database; basic tracking. class SearchRec(db.Model): WebSite = db.StringProperty()#required=True WebPage = db.StringProperty() CountryNM = db.StringProperty() PrefMailing = db.BooleanProperty() DateStamp = db.DateTimeProperty(auto_now_add=True) IP = db.StringProperty() class AddSearch(webapp.RequestHandler): def get(self): searchRec = SearchRec() searchRec.WebSite = self.request.get('WEBSITE') searchRec.WebPage = self.request.get('WEBPAGE') searchRec.CountryNM = self.request.get('COUNTRY') searchRec.PrefMailing = bool(self.request.get('MAIL')) searchRec.IP = self.request.get('IP') Bool has my biscuit; I thought that setting bool(self.reque....) would set the type of the string but no matter what I pass it it still stores it as TRUE in the database. I had the same issue with using required=True on strings for the model; the damn thing kept saying that nothing was being passed... but it had. Ta A: You've added a lot of layers of complication to understanding what the bool() build-in function does. Why don't you test it out directly on the command-line, before embedding it deep in your google app engine code. What you'd discover is that the bool() function uses python's truth values: http://docs.python.org/library/stdtypes.html#truth-value-testing The following values are considered false: * None * False * zero of any numeric type, for example, 0, 0L, 0.0, 0j. * any empty sequence, for example, '', (), []. * any empty mapping, for example, {}. * instances of user-defined classes, if the class defines a `__nonzero__()` or `__len__()` method, when that method returns the integer zero or bool value False. [1] All other values are considered true — so objects of many types are always true. In particular - any non-empty string is True. A: Bool has my biscuit; I thought that setting bool(self.reque....) would set the type of the string but no matter what I pass it it still stores it as TRUE in the database. Well, what's the value of self.request.get('MAIL')? If it's anything other than an empty string or None, bool will see it as True. I had the same issue with using required=True on strings for the model; the damn thing kept saying that nothing was being passed... but it had. If you set a property to required=True, then you must pass it to the model's constructor. So, if WebSite is a required property, you need to construct your searchRec like so: searchRec = SearchRec(WebSite=self.request.get('WEBSITE'))
Types in Python - Google Appengine
Getting a bit peeved now; I have a model and a class thats just storing a get request in the database; basic tracking. class SearchRec(db.Model): WebSite = db.StringProperty()#required=True WebPage = db.StringProperty() CountryNM = db.StringProperty() PrefMailing = db.BooleanProperty() DateStamp = db.DateTimeProperty(auto_now_add=True) IP = db.StringProperty() class AddSearch(webapp.RequestHandler): def get(self): searchRec = SearchRec() searchRec.WebSite = self.request.get('WEBSITE') searchRec.WebPage = self.request.get('WEBPAGE') searchRec.CountryNM = self.request.get('COUNTRY') searchRec.PrefMailing = bool(self.request.get('MAIL')) searchRec.IP = self.request.get('IP') Bool has my biscuit; I thought that setting bool(self.reque....) would set the type of the string but no matter what I pass it it still stores it as TRUE in the database. I had the same issue with using required=True on strings for the model; the damn thing kept saying that nothing was being passed... but it had. Ta
[ "You've added a lot of layers of complication to understanding what the bool() build-in function does. Why don't you test it out directly on the command-line, before embedding it deep in your google app engine code.\nWhat you'd discover is that the bool() function uses python's truth values:\nhttp://docs.python.org/library/stdtypes.html#truth-value-testing\n\nThe following values are considered\n false:\n* None\n* False\n* zero of any numeric type, for example, 0, 0L, 0.0, 0j.\n* any empty sequence, for example, '', (), [].\n* any empty mapping, for example, {}.\n* instances of user-defined classes, if the class defines a\n `__nonzero__()` or `__len__()` method, when that method returns the integer\n zero or bool value False. [1]\n\nAll other values are considered true —\n so objects of many types are always\n true.\n\nIn particular - any non-empty string is True.\n", "\nBool has my biscuit; I thought that setting bool(self.reque....) would set the type of the string but no matter what I pass it it still stores it as TRUE in the database.\n\nWell, what's the value of self.request.get('MAIL')? If it's anything other than an empty string or None, bool will see it as True.\n\nI had the same issue with using required=True on strings for the model; the damn thing kept saying that nothing was being passed... but it had.\n\nIf you set a property to required=True, then you must pass it to the model's constructor. So, if WebSite is a required property, you need to construct your searchRec like so:\nsearchRec = SearchRec(WebSite=self.request.get('WEBSITE'))\n\n" ]
[ 3, 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0002600907_google_app_engine_python.txt
Q: Executing / Running a python script from ubuntu server Can anybody help me how to run a python script through command line? My python script http://buffis.com/2007/07/25/getting-info_hash-for-xbt-tracker/comment-page-1/ I am using this command /var/www/hash_info.py /var/www/Muha_Album.7912.torrent I have copied dependency file bencode.py mentioned in article link above. When I execute the above command I get error No such file or directory but when i chmod the file to 644 it says Permission denied the file is present at the location. I have installed pythong using this command apt-get install python-gtk2 python-glade2 A: python /var/www/hash_info.py /var/www/Muha_Album.7912.torrent A: Maybe it says: bad interpreter: No such file or directory Then, the first line, so called shebang line is the issue here. I guess you need to change it to where your python is really installed. On my Ubuntu installation it's /usr/bin/python. Also, the solution from voyager should work for you as well. A: Try chmod 744
Executing / Running a python script from ubuntu server
Can anybody help me how to run a python script through command line? My python script http://buffis.com/2007/07/25/getting-info_hash-for-xbt-tracker/comment-page-1/ I am using this command /var/www/hash_info.py /var/www/Muha_Album.7912.torrent I have copied dependency file bencode.py mentioned in article link above. When I execute the above command I get error No such file or directory but when i chmod the file to 644 it says Permission denied the file is present at the location. I have installed pythong using this command apt-get install python-gtk2 python-glade2
[ "python /var/www/hash_info.py /var/www/Muha_Album.7912.torrent\n\n", "Maybe it says:\nbad interpreter: No such file or directory\n\nThen, the first line, so called shebang line is the issue here. I guess you need to change it to where your python is really installed. On my Ubuntu installation it's /usr/bin/python.\nAlso, the solution from voyager should work for you as well.\n", "Try chmod 744\n" ]
[ 4, 3, 0 ]
[]
[]
[ "bash", "linux", "python" ]
stackoverflow_0002601714_bash_linux_python.txt
Q: Return unicode string from python via ajax I have a small webapp that runs Python on the server side and javascript (jQuery) on the client side. Now upon a certain request my Python script returns a unicode string and the client is supposed to put that string inside a div in the browser. However i get a unicode encode error from Python. If i run the script from the shell (bash on debian linux) teh script runs fine and prints the unicode string. Any ideas ? Thanks! EDIT This is the print statement that causes the error: print u'öäü°' This is the error message i get: UnicodeEncodeError: 'ascii' codec can't encode characters in position 34-36: ordinal not in range(128) However i only get that message when calling the script via ajax ( $('#somediv').load('myscript.py'); ) Thank you ! A: If the python interpreter can't determine the encoding of sys.stdout ascii is used as a fallback however the characters in the string are not part of ascii, therefore a UnicodeEncodeError exception is raised. A solution would be to encode the string yourself using something like .encode(sys.stdout.encoding or "utf-8"). This way utf-8 is used as a fallback instead of ascii.
Return unicode string from python via ajax
I have a small webapp that runs Python on the server side and javascript (jQuery) on the client side. Now upon a certain request my Python script returns a unicode string and the client is supposed to put that string inside a div in the browser. However i get a unicode encode error from Python. If i run the script from the shell (bash on debian linux) teh script runs fine and prints the unicode string. Any ideas ? Thanks! EDIT This is the print statement that causes the error: print u'öäü°' This is the error message i get: UnicodeEncodeError: 'ascii' codec can't encode characters in position 34-36: ordinal not in range(128) However i only get that message when calling the script via ajax ( $('#somediv').load('myscript.py'); ) Thank you !
[ "If the python interpreter can't determine the encoding of sys.stdout ascii is used as a fallback however the characters in the string are not part of ascii, therefore a UnicodeEncodeError exception is raised.\nA solution would be to encode the string yourself using something like .encode(sys.stdout.encoding or \"utf-8\"). This way utf-8 is used as a fallback instead of ascii.\n" ]
[ 3 ]
[]
[]
[ "ajax", "python", "unicode" ]
stackoverflow_0002601306_ajax_python_unicode.txt
Q: How to use methods defined in a python scipt from a console like ipython I have written a python script with methods in it. Now I want to use methods from that script in ipython. How do I import it for use in ipython? Cheers A: If the file with your functions in it is called mod.py, just: >>> import mod >>> mod.myfunction() A: There are several options and all of them work with specific advantages and disadvantages: from module import * import module %edit module.py A: Inside IPython: cd folder/containing/module import module module.function(1, 2, 3)
How to use methods defined in a python scipt from a console like ipython
I have written a python script with methods in it. Now I want to use methods from that script in ipython. How do I import it for use in ipython? Cheers
[ "If the file with your functions in it is called mod.py, just:\n>>> import mod\n>>> mod.myfunction()\n\n", "There are several options and all of them work with specific advantages and disadvantages:\nfrom module import *\nimport module\n%edit module.py\n\n", "Inside IPython:\ncd folder/containing/module\nimport module\nmodule.function(1, 2, 3)\n\n" ]
[ 2, 1, 0 ]
[]
[]
[ "import", "ipython", "python", "scripting" ]
stackoverflow_0002602188_import_ipython_python_scripting.txt
Q: Scope of "library" methods I'm apparently laboring under a poor understanding of Python scoping. Perhaps you can help. Background: I'm using the if __name__ == "__main__" construct to perform "self-tests" in my module(s). Each self test makes calls to the various public methods and prints their results for visual checking as I develop the modules. To keep things "purdy" and manageable, I've created a small method to simplify the testing of method calls: def pprint_vars(var_in): print("%s = '%s'" % (var_in, eval(var_in))) When foo = "bar" Calling pprint_vars with: pprint_vars('foo') prints: foo = 'bar' All fine and good. Problem statement: Not happy to just KISS, I had the brain-drizzle to move my handy-dandy 'pprint_vars' method into a separate file named 'debug_tools.py' and simply import 'debug_tools' whenever I wanted access to 'pprint_vars'. Here's where things fall apart. I would expect import debug_tools foo = bar debug_tools.pprint_vars('foo') to continue working its magic and print: foo = 'bar' Instead, it greets me with: NameError: name 'some_var' is not defined Irrational belief: I believed (apparently mistakenly) that import puts imported methods (more or less) "inline" with the code, and thus the variable scoping rules would remain similar to if the method were defined inline. Plea for help: Can someone please correct my (mis)understanding of scoping regards imports? Thanks, JS A: "Global scope" doesn't actually exist in Python. What is commonly called "global scope" is actually module scope. That is to say, names defined at the module level. Putting the function in another module means that its module scope changes. A: In python each file is its own namespace. A function, when called, resolves its variables in the following order: local variables (that includes captured variables or in a closure) (module) global variables builtins You can use the (interpreter specific) inspect module to navigate the callstack as a list of frames. Since a frame knows its locals, globals, builtins and parent frame, you can 'see' the interpreter through the eyes of your caller like this (please only use for debugging): import inspect def log_var(name): f = inspect.currentframe().f_back if name in f.f_locals: print "local `%s` = %r" % (name, f.f_locals[name]) elif name in f.f_globals: print "global `%s` = %r" % (name, f.f_globals[name]) elif name in f.f_builtins: print "builtin `%s` = %r" % (name, f.f_builtins[name]) else: print "`%s` not found" % name A: I would recommend passing the locals() to the function, like so... def pprint_var(var_name, D): print "%s = %r" % (var_name, D[var_name]) ... pprint_var(var_name, locals()) if you don't want that, you can use the inspect module or sys._getframe to do the same thing, as other have suggested. A: eval accepts two optional parameters -- global and local -- which you can specify as the context to evaluate your source: print("%s = '%s'" % (var_in, eval(var_in, globals()))) A: The basic issue I'm running into is that Python has no sense of name for simple objects. For methods, classes, etc. yes, for simple objects, no. So in languages that feature variables, my 'ppvar' function would look something like this (pseudo-code): ppvar( var_name ): print("%s = '%s'", var_name, $var_name) I could import the file containing 'ppvar' in any project and call it and it would essentially be "inlined" into my code. Alas this is most likely a "functional programming" concept and not suitable for object-oriented approaches. All languages have the pluses and minuses. Every language has a few "simple" things it falls down on. Being able to peform something like: print("%s = '%s'" % (var.__name__, var) in Python is (as of yet) not something that will work. Oh well.
Scope of "library" methods
I'm apparently laboring under a poor understanding of Python scoping. Perhaps you can help. Background: I'm using the if __name__ == "__main__" construct to perform "self-tests" in my module(s). Each self test makes calls to the various public methods and prints their results for visual checking as I develop the modules. To keep things "purdy" and manageable, I've created a small method to simplify the testing of method calls: def pprint_vars(var_in): print("%s = '%s'" % (var_in, eval(var_in))) When foo = "bar" Calling pprint_vars with: pprint_vars('foo') prints: foo = 'bar' All fine and good. Problem statement: Not happy to just KISS, I had the brain-drizzle to move my handy-dandy 'pprint_vars' method into a separate file named 'debug_tools.py' and simply import 'debug_tools' whenever I wanted access to 'pprint_vars'. Here's where things fall apart. I would expect import debug_tools foo = bar debug_tools.pprint_vars('foo') to continue working its magic and print: foo = 'bar' Instead, it greets me with: NameError: name 'some_var' is not defined Irrational belief: I believed (apparently mistakenly) that import puts imported methods (more or less) "inline" with the code, and thus the variable scoping rules would remain similar to if the method were defined inline. Plea for help: Can someone please correct my (mis)understanding of scoping regards imports? Thanks, JS
[ "\"Global scope\" doesn't actually exist in Python. What is commonly called \"global scope\" is actually module scope. That is to say, names defined at the module level. Putting the function in another module means that its module scope changes.\n", "In python each file is its own namespace. A function, when called, resolves its variables in the following order:\n\nlocal variables (that includes captured variables or in a closure)\n(module) global variables\nbuiltins\n\nYou can use the (interpreter specific) inspect module to navigate the callstack as a list of frames. Since a frame knows its locals, globals, builtins and parent frame, you can 'see' the interpreter through the eyes of your caller like this (please only use for debugging):\nimport inspect\ndef log_var(name):\n f = inspect.currentframe().f_back\n if name in f.f_locals:\n print \"local `%s` = %r\" % (name, f.f_locals[name])\n elif name in f.f_globals:\n print \"global `%s` = %r\" % (name, f.f_globals[name])\n elif name in f.f_builtins:\n print \"builtin `%s` = %r\" % (name, f.f_builtins[name])\n else:\n print \"`%s` not found\" % name\n\n", "I would recommend passing the locals() to the function, like so...\ndef pprint_var(var_name, D):\n print \"%s = %r\" % (var_name, D[var_name])\n\n...\npprint_var(var_name, locals())\n\nif you don't want that, you can use the inspect module or sys._getframe to do the same thing, as other have suggested.\n", "eval accepts two optional parameters -- global and local -- which you can specify as the context to evaluate your source:\nprint(\"%s = '%s'\" % (var_in, eval(var_in, globals())))\n\n", "The basic issue I'm running into is that Python has no sense of name for simple objects. For methods, classes, etc. yes, for simple objects, no.\nSo in languages that feature variables, my 'ppvar' function would look something like this (pseudo-code):\nppvar( var_name ):\n print(\"%s = '%s'\", var_name, $var_name)\n\nI could import the file containing 'ppvar' in any project and call it and it would essentially be \"inlined\" into my code.\nAlas this is most likely a \"functional programming\" concept and not suitable for object-oriented approaches.\nAll languages have the pluses and minuses. Every language has a few \"simple\" things it falls down on. Being able to peform something like:\nprint(\"%s = '%s'\" % (var.__name__, var)\n\nin Python is (as of yet) not something that will work. Oh well.\n" ]
[ 2, 2, 1, 0, 0 ]
[]
[]
[ "import", "module", "python", "scope" ]
stackoverflow_0002596610_import_module_python_scope.txt
Q: Looking for a Python IDE with good support for libraries (Twisted) I'm looking for a Python IDE that can help me easily locate and manage and use the libraries on my system (Ubuntu). Specifically Twisted. Code completion is important including the symbols I import. (I've so far had a look at PyDev as well as OpenKomodo, but while both offer code completion for default Python concepts, I wasn't able to get either to import Twisted into my project and was thus getting reference errors.) Usual disclaimer: I don't like EMACS or vi, please, nothing regarding those. A: Using Wing IDE with Twisted discusses how to debug twisted using their IDE - although unfortunately WingWare is not free. Are you sure you have given PyDev a fair look? It seems to be the most popular Python IDE, and I have always had good experiences with it in the past. A: I've just downloaded the preview of netbeans and it seems to have done quite well so far. It has detected inherited methods & properties. I haven't had to add a single library reference in my project, so this seems to be the most fluid so far. A: eclipse + pydev seems to work well for me. Just remember to right-click on the project and select Properties and make sure that your libraries are on the path. Sometimes this doesn't happen for easy_installed libraries. A: Check out JetBrains PyCharm. It features: Code completion of any imported library Good support for unit testing Refactoring Debugging Version control integration It's built on the same platform as IntelliJ IDEA which is a generally considered one of the best Java IDEs. There's a community edition which is free and open-source. A: Like Eclipse is primarily a Java IDE written in Java, you could try Eric which is a Python IDE written in Python. I have had some issues with it in the past but I really enjoy the ability to stop your code at a breakpoint and have access to the python console to manipulate your data or even to inject new functions. PyDev could really use a console like that. A: for a small proyects Scribes. Otherwise Eclipse+pydev.
Looking for a Python IDE with good support for libraries (Twisted)
I'm looking for a Python IDE that can help me easily locate and manage and use the libraries on my system (Ubuntu). Specifically Twisted. Code completion is important including the symbols I import. (I've so far had a look at PyDev as well as OpenKomodo, but while both offer code completion for default Python concepts, I wasn't able to get either to import Twisted into my project and was thus getting reference errors.) Usual disclaimer: I don't like EMACS or vi, please, nothing regarding those.
[ "Using Wing IDE with Twisted discusses how to debug twisted using their IDE - although unfortunately WingWare is not free.\nAre you sure you have given PyDev a fair look? It seems to be the most popular Python IDE, and I have always had good experiences with it in the past.\n", "I've just downloaded the preview of netbeans and it seems to have done quite well so far.\nIt has detected inherited methods & properties. I haven't had to add a single library reference in my project, so this seems to be the most fluid so far.\n", "eclipse + pydev seems to work well for me.\nJust remember to right-click on the project and select Properties and make sure that your libraries are on the path. Sometimes this doesn't happen for easy_installed libraries.\n", "Check out JetBrains PyCharm. It features:\n\nCode completion of any imported library\nGood support for unit testing\nRefactoring\nDebugging\nVersion control integration\n\nIt's built on the same platform as IntelliJ IDEA which is a generally considered one of the best Java IDEs. There's a community edition which is free and open-source.\n", "Like Eclipse is primarily a Java IDE written in Java, you could try Eric which is a Python IDE written in Python. I have had some issues with it in the past but I really enjoy the ability to stop your code at a breakpoint and have access to the python console to manipulate your data or even to inject new functions. PyDev could really use a console like that.\n", "for a small proyects Scribes. Otherwise Eclipse+pydev.\n" ]
[ 3, 2, 2, 1, 0, 0 ]
[]
[]
[ "code_completion", "ide", "import", "libraries", "python" ]
stackoverflow_0002586274_code_completion_ide_import_libraries_python.txt
Q: Python Tkinter Tix: How to use ScrolledWindow with grid in Tix NoteBook I'm adding several widgets to a Frame which is located in a tix.NoteBook. When there are too much widgets to fit in the window, I want to use a scrollbar, so I put tix.ScrolledWindow inside that Frame and add my widgets to this ScrolledWindow instead. The problem is that when using the grid() geometry manager, the scrollbar appears, but it is not working (The drag bar occupies the whole scroll bar). from Tkinter import * import Tix class Window: def __init__(self, root): self.labelList = [] self.notebook = Tix.NoteBook(root, ipadx=3, ipady=3) self.notebook.add('sheet_1', label="Sheet 1", underline=0) self.notebook.add('sheet_2', label="Sheet 2", underline=0) self.notebook.add('sheet_3', label="Sheet 3", underline=0) self.notebook.pack() #self.notebook.grid(row=0, column=0) tab1=self.notebook.sheet_1 tab2=self.notebook.sheet_2 tab3=self.notebook.sheet_3 self.myMainContainer = Frame(tab1) self.myMainContainer.pack() #self.myMainContainer.grid(row=0, column=0) scrwin = Tix.ScrolledWindow(self.myMainContainer, scrollbar='y') scrwin.pack() #scrwin.grid(row=0, column=0) self.win = scrwin.window for i in range (100): self.labelList.append((Label(self.win))) self.labelList[-1].config(text= "Bla", relief = SUNKEN) self.labelList[-1].grid(row=i, column=0, sticky=W+E) root = Tix.Tk() myWindow = Window(root) root.mainloop() Whenever I change at least one of the geometry managers from pack() to grid(), the problem occurs. (Actually, I'd prefer using grid() for all containers.) When I don't use the NoteBook widget, the problem does not occur either. The other examples here all seem to rely on pack(). Any ideas? Many thanks, Sano A: I solved it without using ´tix.scrolledWindow´. Instead, I went for the autoscrollbar suggested by Fred Lundh here. The main problem was the adaption to the NoteBook widget. First, I tried to put the scrollbar to the root, so that they would surround the whole window. Now, I wanted to change the hook for the scrollbar whenever I changed a tab, but the ´raisecmd´ of the Notebook did not work. Next, I thought of using the configure event on each tab - whenever a new tab is raised, its size changes and configure is called. Well, after much trying without ever being satisfied I changed my approach and put the scrollbars inside of the tabs. The tabs and all subcontainers must get the ´grid_columnconfigure(0, weight=1)´ and ´grid_rowconfigure(0, weight=1)´ settings, or else they will not grow with the tabs.
Python Tkinter Tix: How to use ScrolledWindow with grid in Tix NoteBook
I'm adding several widgets to a Frame which is located in a tix.NoteBook. When there are too much widgets to fit in the window, I want to use a scrollbar, so I put tix.ScrolledWindow inside that Frame and add my widgets to this ScrolledWindow instead. The problem is that when using the grid() geometry manager, the scrollbar appears, but it is not working (The drag bar occupies the whole scroll bar). from Tkinter import * import Tix class Window: def __init__(self, root): self.labelList = [] self.notebook = Tix.NoteBook(root, ipadx=3, ipady=3) self.notebook.add('sheet_1', label="Sheet 1", underline=0) self.notebook.add('sheet_2', label="Sheet 2", underline=0) self.notebook.add('sheet_3', label="Sheet 3", underline=0) self.notebook.pack() #self.notebook.grid(row=0, column=0) tab1=self.notebook.sheet_1 tab2=self.notebook.sheet_2 tab3=self.notebook.sheet_3 self.myMainContainer = Frame(tab1) self.myMainContainer.pack() #self.myMainContainer.grid(row=0, column=0) scrwin = Tix.ScrolledWindow(self.myMainContainer, scrollbar='y') scrwin.pack() #scrwin.grid(row=0, column=0) self.win = scrwin.window for i in range (100): self.labelList.append((Label(self.win))) self.labelList[-1].config(text= "Bla", relief = SUNKEN) self.labelList[-1].grid(row=i, column=0, sticky=W+E) root = Tix.Tk() myWindow = Window(root) root.mainloop() Whenever I change at least one of the geometry managers from pack() to grid(), the problem occurs. (Actually, I'd prefer using grid() for all containers.) When I don't use the NoteBook widget, the problem does not occur either. The other examples here all seem to rely on pack(). Any ideas? Many thanks, Sano
[ "I solved it without using ´tix.scrolledWindow´. Instead, I went for the autoscrollbar suggested by Fred Lundh here.\nThe main problem was the adaption to the NoteBook widget. First, I tried to put the scrollbar to the root, so that they would surround the whole window. Now, I wanted to change the hook for the scrollbar whenever I changed a tab, but the ´raisecmd´ of the Notebook did not work. Next, I thought of using the configure event on each tab - whenever a new tab is raised, its size changes and configure is called.\nWell, after much trying without ever being satisfied I changed my approach and put the scrollbars inside of the tabs. The tabs and all subcontainers must get the ´grid_columnconfigure(0, weight=1)´ and ´grid_rowconfigure(0, weight=1)´ settings, or else they will not grow with the tabs.\n" ]
[ 2 ]
[]
[]
[ "grid", "python", "scrolledwindow", "tix" ]
stackoverflow_0002575451_grid_python_scrolledwindow_tix.txt
Q: What is the better error handling method for decoding Python bytes to unicode strings? I have an old C# program that is being ported to Python 3 for different reasons. Basically, what the program does is to fetch a website and search its content (and process it, but that is not really relevant). I have never really had any issues with the actual fetch-and-search routine, but once I ported it to Python it started complaining about invalid unicode at certain locations. This is not really a problem since the actual source webpage-data is the same as in the old C# application and the old program achieved its goal with the broken data. However, what I want is the Python 3 decode() method to behave as similar to the internal handling of such cases in C#. Unfortunately, after reading the Python manual and looking into the 'ignore' and 'replace" error handling methods I really don't get which is better to best mimic the C# behavior (which I also have failed to identify). To add some code into the discussion, here is the C# code that handles everything transparently: HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); response = (HttpWebResponse)request.GetResponse(); reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8); string html = reader.ReadToEnd(); The corresponding Python 3 code is as follows: req = Request(url) r = urlopen(req) data = r.read().decode("utf_8") However, I want to find out which of the following pieces of code that will best mimic the unicode behavior of the C# code: data = r.read().decode("utf_8", "replace") or data = r.read().decode("utf_8", "ignore") Anyone with in-depth unicode experience which can give me some pointers on which method is better? The Python manual does describe the behavior, but not so that I understand which I should use... Thanks in advance for any help! A: According to http://msdn.microsoft.com/en-us/library/system.text.encoding.utf8.aspx the default UTF-8 decoder of C# ignores invalid bytes. Python's 'ignore' option for decoding unicode is the same as this.
What is the better error handling method for decoding Python bytes to unicode strings?
I have an old C# program that is being ported to Python 3 for different reasons. Basically, what the program does is to fetch a website and search its content (and process it, but that is not really relevant). I have never really had any issues with the actual fetch-and-search routine, but once I ported it to Python it started complaining about invalid unicode at certain locations. This is not really a problem since the actual source webpage-data is the same as in the old C# application and the old program achieved its goal with the broken data. However, what I want is the Python 3 decode() method to behave as similar to the internal handling of such cases in C#. Unfortunately, after reading the Python manual and looking into the 'ignore' and 'replace" error handling methods I really don't get which is better to best mimic the C# behavior (which I also have failed to identify). To add some code into the discussion, here is the C# code that handles everything transparently: HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); response = (HttpWebResponse)request.GetResponse(); reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8); string html = reader.ReadToEnd(); The corresponding Python 3 code is as follows: req = Request(url) r = urlopen(req) data = r.read().decode("utf_8") However, I want to find out which of the following pieces of code that will best mimic the unicode behavior of the C# code: data = r.read().decode("utf_8", "replace") or data = r.read().decode("utf_8", "ignore") Anyone with in-depth unicode experience which can give me some pointers on which method is better? The Python manual does describe the behavior, but not so that I understand which I should use... Thanks in advance for any help!
[ "According to http://msdn.microsoft.com/en-us/library/system.text.encoding.utf8.aspx the default UTF-8 decoder of C# ignores invalid bytes.\nPython's 'ignore' option for decoding unicode is the same as this.\n" ]
[ 2 ]
[]
[]
[ "python", "unicode" ]
stackoverflow_0002601294_python_unicode.txt
Q: Is it possible to install SSL on Google app engine for iPhone application? I am using python language for google app engine based iphone application .I want to install/access ssl on python. I am unable to find a way to install/enable it in python file. please guide me how can I make my application to connect to ssl As I want to Apple enable push notification services on my application Its urgent. A: See the App Engine Python documentation on setting up secure URLs. Note that this will only work when accessed via your appspot.com domain - it's not possible to have SSL on a custom domain through App Engine, currently. A: Nick Johnson has already provided a link and mentioned that this functionality is not currently available on your domain (only on apps running on Google's hotspot domain). Obviously, most developers need their apps to run on their own domains, so this is a very highly requested feature. Fortunately, Google has recently added this feature to their GAE roadmap indicating that it will be available soon. Unfortunately, we don't know what 'soon' means.
Is it possible to install SSL on Google app engine for iPhone application?
I am using python language for google app engine based iphone application .I want to install/access ssl on python. I am unable to find a way to install/enable it in python file. please guide me how can I make my application to connect to ssl As I want to Apple enable push notification services on my application Its urgent.
[ "See the App Engine Python documentation on setting up secure URLs. Note that this will only work when accessed via your appspot.com domain - it's not possible to have SSL on a custom domain through App Engine, currently.\n", "Nick Johnson has already provided a link and mentioned that this functionality is not currently available on your domain (only on apps running on Google's hotspot domain).\nObviously, most developers need their apps to run on their own domains, so this is a very highly requested feature. Fortunately, Google has recently added this feature to their GAE roadmap indicating that it will be available soon. Unfortunately, we don't know what 'soon' means.\n" ]
[ 5, 0 ]
[]
[]
[ "google_app_engine", "python", "ssl" ]
stackoverflow_0001191936_google_app_engine_python_ssl.txt
Q: shelve gives strange error I'm trying to put some sites i crawled into a shelve, but the shelve won't accept any Site-objects. It will accept lists, strings, tuples, what have you, but as soon as i put in a Site-object, it crashes when i try to get the contents of the shelve So when i fill up my shelve like this: def add_to_shelve(self, site): db = shelve.open("database") print site, site.url for word in site.content: db[word] = site.url #site.url is a string, word has to be one too shelve.open("database")['whatever'] works perfectly. But if I do this: def add_to_shelve(self, site): db = shelve.open("database") print site, site.url for word in site.content: db[word] = site #site is now an object of Site shelve.open("database")['whatever'] errors out with this error message: AttributeError: 'module' object has no attribute 'Site' I'm completely stumped, and the pythondocs, strangely, don't have much info either. All they say is that the key in a shelve has to be a string, but the value or data can be "an arbitrary object" A: It looks like you refactored your code after saving objects in the shelve. When retrieving objects from the shelve, Python rebuilds the object, and it needs to find the original class that, presumably, you have moved. This problem is typical when working with pickle (as the shelve module does). The solution, as pduel suggests, is to provide a backwards-compatibility reference to the class in the same location that it used to be, so that pickle can find it. If you re-save all the objects, thereby rebuilding the pickles, you can remove that backwards-comatibility referece. A: It seems that Python is looking for a constructor for a 'Site' object, and not finding it. I have not used shelve, but I recall the rules for what can be pickled are byzantine, and suspect the shelve rules are similar. Try adding the line: Site = sitemodule.Site (with the name of the module providing 'Site') before you try unshelving. This ensures that a Site class can be found.
shelve gives strange error
I'm trying to put some sites i crawled into a shelve, but the shelve won't accept any Site-objects. It will accept lists, strings, tuples, what have you, but as soon as i put in a Site-object, it crashes when i try to get the contents of the shelve So when i fill up my shelve like this: def add_to_shelve(self, site): db = shelve.open("database") print site, site.url for word in site.content: db[word] = site.url #site.url is a string, word has to be one too shelve.open("database")['whatever'] works perfectly. But if I do this: def add_to_shelve(self, site): db = shelve.open("database") print site, site.url for word in site.content: db[word] = site #site is now an object of Site shelve.open("database")['whatever'] errors out with this error message: AttributeError: 'module' object has no attribute 'Site' I'm completely stumped, and the pythondocs, strangely, don't have much info either. All they say is that the key in a shelve has to be a string, but the value or data can be "an arbitrary object"
[ "It looks like you refactored your code after saving objects in the shelve. When retrieving objects from the shelve, Python rebuilds the object, and it needs to find the original class that, presumably, you have moved. This problem is typical when working with pickle (as the shelve module does).\nThe solution, as pduel suggests, is to provide a backwards-compatibility reference to the class in the same location that it used to be, so that pickle can find it. If you re-save all the objects, thereby rebuilding the pickles, you can remove that backwards-comatibility referece.\n", "It seems that Python is looking for a constructor for a 'Site' object, and not finding it. I have not used shelve, but I recall the rules for what can be pickled are byzantine, and suspect the shelve rules are similar.\nTry adding the line:\nSite = sitemodule.Site \n(with the name of the module providing 'Site') before you try unshelving. This ensures that a Site class can be found.\n" ]
[ 5, 0 ]
[]
[]
[ "python", "shelve" ]
stackoverflow_0002601081_python_shelve.txt
Q: Removing duplicates (within a given tolerance) from a Numpy array of vectors I have an Nx5 array containing N vectors of form 'id', 'x', 'y', 'z' and 'energy'. I need to remove duplicate points (i.e. where x, y, z all match) within a tolerance of say 0.1. Ideally I could create a function where I pass in the array, columns that need to match and a tolerance on the match. Following this thread on Scipy-user, I can remove duplicates based on a full array using record arrays, but I need to just match part of an array. Moreover this will not match within a certain tolerance. I could laboriously iterate through with a for loop in Python but is there a better Numponic way? A: You might look at scipy.spatial.KDTree. How big is N ? Added: oops, tree.query_pairs is not in scipy 0.7.1 . When in doubt, use brute force: split the space (here side^3) into little cells, one point per cell: """ scatter points to little cells, 1 per cell """ from __future__ import division import sys import numpy as np side = 100 npercell = 1 # 1: ~ 1/e empty exec "\n".join( sys.argv[1:] ) # side= ... N = side**3 * npercell print "side: %d npercell: %d N: %d" % (side, npercell, N) np.random.seed( 1 ) points = np.random.uniform( 0, side, size=(N,3) ) cells = np.zeros( (side,side,side), dtype=np.uint ) id = 1 for p in points.astype(int): cells[tuple(p)] = id id += 1 cells = cells.flatten() # A C, an E-flat, and a G walk into a bar. # The bartender says, "Sorry, but we don't serve minors." nz = np.nonzero(cells)[0] print "%d cells have points" % len(nz) print "first few ids:", cells[nz][:10] A: I have finally got a solution that I am happy with, this is a slightly cleaned up cut and paste from my own code. There may yet be some bugs. Note: that it still uses a 'for' loop. I could use Denis's idea of KDTree above coupled with the rounding to get the full solution. import numpy as np def remove_duplicates(data, dp_tol=None, cols=None, sort_by=None): ''' Removes duplicate vectors from a list of data points Parameters: data An MxN array of N vectors of dimension M cols An iterable of the columns that must match in order to constitute a duplicate (default: [1,2,3] for typical Klist data array) dp_tol An iterable of three tolerances or a single tolerance for all dimensions. Uses this to round the values to specified number of decimal places before performing the removal. (default: None) sort_by An iterable of columns to sort by (default: [0]) Returns: MxI Array An array of I vectors (minus the duplicates) EXAMPLES: Remove a duplicate >>> import wien2k.utils >>> import numpy as np >>> vecs1 = np.array([[1, 0, 0, 0], ... [2, 0, 0, 0], ... [3, 0, 0, 1]]) >>> remove_duplicates(vecs1) array([[1, 0, 0, 0], [3, 0, 0, 1]]) Remove duplicates with a tolerance >>> vecs2 = np.array([[1, 0, 0, 0 ], ... [2, 0, 0, 0.001 ], ... [3, 0, 0, 0.02 ], ... [4, 0, 0, 1 ]]) >>> remove_duplicates(vecs2, dp_tol=2) array([[ 1. , 0. , 0. , 0. ], [ 3. , 0. , 0. , 0.02], [ 4. , 0. , 0. , 1. ]]) Remove duplicates and sort by k values >>> vecs3 = np.array([[1, 0, 0, 0], ... [2, 0, 0, 2], ... [3, 0, 0, 0], ... [4, 0, 0, 1]]) >>> remove_duplicates(vecs3, sort_by=[3]) array([[1, 0, 0, 0], [4, 0, 0, 1], [2, 0, 0, 2]]) Change the columns that constitute a duplicate >>> vecs4 = np.array([[1, 0, 0, 0], ... [2, 0, 0, 2], ... [1, 0, 0, 0], ... [4, 0, 0, 1]]) >>> remove_duplicates(vecs4, cols=[0]) array([[1, 0, 0, 0], [2, 0, 0, 2], [4, 0, 0, 1]]) ''' # Deal with the parameters if sort_by is None: sort_by = [0] if cols is None: cols = [1,2,3] if dp_tol is not None: # test to see if already an iterable try: null = iter(dp_tol) tols = np.array(dp_tol) except TypeError: tols = np.ones_like(cols) * dp_tol # Convert to numbers of decimal places # Find the 'order' of the axes else: tols = None rnd_data = data.copy() # set the tolerances if tols is not None: for col,tol in zip(cols, tols): rnd_data[:,col] = np.around(rnd_data[:,col], decimals=tol) # TODO: For now, use a slow Python 'for' loop, try to find a more # numponic way later - see: http://stackoverflow.com/questions/2433882/ sorted_indexes = np.lexsort(tuple([rnd_data[:,col] for col in cols])) rnd_data = rnd_data[sorted_indexes] unique_kpts = [] for i in xrange(len(rnd_data)): if i == 0: unique_kpts.append(i) else: if (rnd_data[i, cols] == rnd_data[i-1, cols]).all(): continue else: unique_kpts.append(i) rnd_data = rnd_data[unique_kpts] # Now sort sorted_indexes = np.lexsort(tuple([rnd_data[:,col] for col in sort_by])) rnd_data = rnd_data[sorted_indexes] return rnd_data if __name__ == '__main__': import doctest doctest.testmod() A: Have not tested this but if you sort your array along x then y then z this should get you the list of duplicates. You then need to choose which to keep. def find_dup_xyz(anarray, x, y, z): #for example in an data = array([id,x,y,z,energy]) x=1 y=2 z=3 dup_xyz=[] for i, row in enumerated(sortedArray): nx=1 while (abs(row[x] - sortedArray[i+nx[x])<0.1) and (abs(row[z] and sortedArray[i+nx[y])<0.1) and (abs(row[z] - sortedArray[i+nx[z])<0.1): nx=+1 dup_xyz.append(row) return dup_xyz Also just found this http://mail.scipy.org/pipermail/scipy-user/2008-April/016504.html
Removing duplicates (within a given tolerance) from a Numpy array of vectors
I have an Nx5 array containing N vectors of form 'id', 'x', 'y', 'z' and 'energy'. I need to remove duplicate points (i.e. where x, y, z all match) within a tolerance of say 0.1. Ideally I could create a function where I pass in the array, columns that need to match and a tolerance on the match. Following this thread on Scipy-user, I can remove duplicates based on a full array using record arrays, but I need to just match part of an array. Moreover this will not match within a certain tolerance. I could laboriously iterate through with a for loop in Python but is there a better Numponic way?
[ "You might look at scipy.spatial.KDTree.\nHow big is N ?\nAdded: oops, tree.query_pairs is not in scipy 0.7.1 .\nWhen in doubt, use brute force: split the space (here side^3) into little cells,\none point per cell:\n\"\"\" scatter points to little cells, 1 per cell \"\"\"\nfrom __future__ import division \nimport sys \nimport numpy as np \n\nside = 100 \nnpercell = 1 # 1: ~ 1/e empty \nexec \"\\n\".join( sys.argv[1:] ) # side= ...\nN = side**3 * npercell \nprint \"side: %d npercell: %d N: %d\" % (side, npercell, N)\nnp.random.seed( 1 ) \npoints = np.random.uniform( 0, side, size=(N,3) )\n\ncells = np.zeros( (side,side,side), dtype=np.uint )\nid = 1\nfor p in points.astype(int):\n cells[tuple(p)] = id \n id += 1 \n\ncells = cells.flatten()\n # A C, an E-flat, and a G walk into a bar. \n # The bartender says, \"Sorry, but we don't serve minors.\"\nnz = np.nonzero(cells)[0] \nprint \"%d cells have points\" % len(nz)\nprint \"first few ids:\", cells[nz][:10]\n\n", "I have finally got a solution that I am happy with, this is a slightly cleaned up cut and paste from my own code. There may yet be some bugs.\nNote: that it still uses a 'for' loop. I could use Denis's idea of KDTree above coupled with the rounding to get the full solution.\nimport numpy as np\n\ndef remove_duplicates(data, dp_tol=None, cols=None, sort_by=None):\n '''\n Removes duplicate vectors from a list of data points\n Parameters:\n data An MxN array of N vectors of dimension M \n cols An iterable of the columns that must match \n in order to constitute a duplicate \n (default: [1,2,3] for typical Klist data array) \n dp_tol An iterable of three tolerances or a single \n tolerance for all dimensions. Uses this to round \n the values to specified number of decimal places \n before performing the removal. \n (default: None)\n sort_by An iterable of columns to sort by (default: [0])\n\n Returns:\n MxI Array An array of I vectors (minus the \n duplicates)\n\n EXAMPLES:\n\n Remove a duplicate\n\n >>> import wien2k.utils\n >>> import numpy as np\n >>> vecs1 = np.array([[1, 0, 0, 0],\n ... [2, 0, 0, 0],\n ... [3, 0, 0, 1]])\n >>> remove_duplicates(vecs1)\n array([[1, 0, 0, 0],\n [3, 0, 0, 1]])\n\n Remove duplicates with a tolerance\n\n >>> vecs2 = np.array([[1, 0, 0, 0 ],\n ... [2, 0, 0, 0.001 ],\n ... [3, 0, 0, 0.02 ],\n ... [4, 0, 0, 1 ]])\n >>> remove_duplicates(vecs2, dp_tol=2)\n array([[ 1. , 0. , 0. , 0. ],\n [ 3. , 0. , 0. , 0.02],\n [ 4. , 0. , 0. , 1. ]])\n\n Remove duplicates and sort by k values\n\n >>> vecs3 = np.array([[1, 0, 0, 0],\n ... [2, 0, 0, 2],\n ... [3, 0, 0, 0],\n ... [4, 0, 0, 1]])\n >>> remove_duplicates(vecs3, sort_by=[3])\n array([[1, 0, 0, 0],\n [4, 0, 0, 1],\n [2, 0, 0, 2]])\n\n Change the columns that constitute a duplicate\n\n >>> vecs4 = np.array([[1, 0, 0, 0],\n ... [2, 0, 0, 2],\n ... [1, 0, 0, 0],\n ... [4, 0, 0, 1]])\n >>> remove_duplicates(vecs4, cols=[0])\n array([[1, 0, 0, 0],\n [2, 0, 0, 2],\n [4, 0, 0, 1]])\n\n '''\n # Deal with the parameters\n if sort_by is None:\n sort_by = [0]\n if cols is None:\n cols = [1,2,3]\n if dp_tol is not None:\n # test to see if already an iterable\n try:\n null = iter(dp_tol)\n tols = np.array(dp_tol)\n except TypeError:\n tols = np.ones_like(cols) * dp_tol\n # Convert to numbers of decimal places\n # Find the 'order' of the axes\n else:\n tols = None\n\n rnd_data = data.copy()\n # set the tolerances\n if tols is not None:\n for col,tol in zip(cols, tols):\n rnd_data[:,col] = np.around(rnd_data[:,col], decimals=tol)\n\n # TODO: For now, use a slow Python 'for' loop, try to find a more\n # numponic way later - see: http://stackoverflow.com/questions/2433882/\n sorted_indexes = np.lexsort(tuple([rnd_data[:,col] for col in cols]))\n rnd_data = rnd_data[sorted_indexes]\n unique_kpts = []\n for i in xrange(len(rnd_data)):\n if i == 0:\n unique_kpts.append(i) \n else:\n if (rnd_data[i, cols] == rnd_data[i-1, cols]).all():\n continue\n else:\n unique_kpts.append(i) \n\n rnd_data = rnd_data[unique_kpts]\n # Now sort\n sorted_indexes = np.lexsort(tuple([rnd_data[:,col] for col in sort_by]))\n rnd_data = rnd_data[sorted_indexes]\n return rnd_data\n\n\n\nif __name__ == '__main__':\n import doctest\n doctest.testmod()\n", "Have not tested this but if you sort your array along x then y then z this should get you the list of duplicates. You then need to choose which to keep.\ndef find_dup_xyz(anarray, x, y, z): #for example in an data = array([id,x,y,z,energy]) x=1 y=2 z=3\n dup_xyz=[]\n for i, row in enumerated(sortedArray):\n nx=1\n while (abs(row[x] - sortedArray[i+nx[x])<0.1) and (abs(row[z] and sortedArray[i+nx[y])<0.1) and (abs(row[z] - sortedArray[i+nx[z])<0.1):\n nx=+1\n dup_xyz.append(row)\nreturn dup_xyz\n\nAlso just found this\nhttp://mail.scipy.org/pipermail/scipy-user/2008-April/016504.html\n" ]
[ 2, 1, 0 ]
[]
[]
[ "numpy", "python", "sorting" ]
stackoverflow_0002433882_numpy_python_sorting.txt
Q: Python's Popen cleanup I wanted to use a python equivalent to piping some shell commands in perl. Something like the python version of open(PIPE, "command |"). I go to the subprocess module and try this: p = subprocess.Popen("zgrep thingiwant largefile", shell=True, stdout=subprocess.PIPE) This works for reading the output the same way I would in perl, but it doesn't clean itself up. When I exit the interpreter, I get grep: writing output: Broken pipe spewed all over stderr a few million times. I guess I had naively hoped all this would be taken care of for me, but that's not true. Calling terminate or kill on p doesn't seem to help. Look at the process table, I see that this kills the /bin/sh process, but leaves the child gzip in place to complain about the broken pipe. What's the right way to do this? A: The issue is that the pipe is full. The subprocess stops, waiting for the pipe to empty out, but then your process (the Python interpreter) quits, breaking its end of the pipe (hence the error message). p.wait() will not help you: Warning This will deadlock if the child process generates enough output to a stdout or stderr pipe such that it blocks waiting for the OS pipe buffer to accept more data. Use communicate() to avoid that. http://docs.python.org/library/subprocess.html#subprocess.Popen.wait p.communicate() will not help you: Note The data read is buffered in memory, so do not use this method if the data size is large or unlimited. http://docs.python.org/library/subprocess.html#subprocess.Popen.communicate p.stdout.read(num_bytes) will not help you: Warning Use communicate() rather than .stdin.write, .stdout.read or .stderr.read to avoid deadlocks due to any of the other OS pipe buffers filling up and blocking the child process. http://docs.python.org/library/subprocess.html#subprocess.Popen.stdout The moral of the story is, for large output, subprocess.PIPE will doom you to certain failure if your program is trying to read the data (it seems to me that you should be able to put p.stdout.read(bytes) into a while p.returncode is None: loop, but the above warning suggests that this could deadlock). The docs suggest replacing a shell pipe with this: p1 = Popen(["zgrep", "thingiwant", "largefile"], stdout=PIPE) p2 = Popen(["processreceivingdata"], stdin=p1.stdout, stdout=PIPE) output = p2.communicate()[0] Notice that p2 is taking its standard input directly from p1. This should avoid deadlocks, but given the contradictory warnings above, who knows. Anyway, if that last part doesn't work for you (it should, though), you could try creating a temporary file, writing all data from the first call to that, and then using the temporary file as input to the next process. A: After you open the pipe, you can work with the command output: p.stdout: for line in p.stdout: # do stuff p.stdout.close() A: How did you executed this process? Proper way is to use p.communicate() See docs for more details. A: You need to wait for the process to finish: import subprocess p = subprocess.Popen("cat /mach_kernel", shell=True) p.wait() Alternatively, you can capture the program's standard output (as you have), and perhaps its standard error, and then call communicate: import subprocess p = subprocess.Popen("cat /mach_kernel", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = p.communicate()
Python's Popen cleanup
I wanted to use a python equivalent to piping some shell commands in perl. Something like the python version of open(PIPE, "command |"). I go to the subprocess module and try this: p = subprocess.Popen("zgrep thingiwant largefile", shell=True, stdout=subprocess.PIPE) This works for reading the output the same way I would in perl, but it doesn't clean itself up. When I exit the interpreter, I get grep: writing output: Broken pipe spewed all over stderr a few million times. I guess I had naively hoped all this would be taken care of for me, but that's not true. Calling terminate or kill on p doesn't seem to help. Look at the process table, I see that this kills the /bin/sh process, but leaves the child gzip in place to complain about the broken pipe. What's the right way to do this?
[ "The issue is that the pipe is full. The subprocess stops, waiting for the pipe to empty out, but then your process (the Python interpreter) quits, breaking its end of the pipe (hence the error message).\np.wait() will not help you:\n\nWarning This will deadlock if the child process generates enough output to a stdout or stderr pipe such that it blocks waiting for the OS pipe buffer to accept more data. Use communicate() to avoid that.\nhttp://docs.python.org/library/subprocess.html#subprocess.Popen.wait\n\np.communicate() will not help you:\n\nNote The data read is buffered in memory, so do not use this method if the data size is large or unlimited.\nhttp://docs.python.org/library/subprocess.html#subprocess.Popen.communicate\n\np.stdout.read(num_bytes) will not help you:\n\nWarning Use communicate() rather than .stdin.write, .stdout.read or .stderr.read to avoid deadlocks due to any of the other OS pipe buffers filling up and blocking the child process.\nhttp://docs.python.org/library/subprocess.html#subprocess.Popen.stdout\n\nThe moral of the story is, for large output, subprocess.PIPE will doom you to certain failure if your program is trying to read the data (it seems to me that you should be able to put p.stdout.read(bytes) into a while p.returncode is None: loop, but the above warning suggests that this could deadlock).\nThe docs suggest replacing a shell pipe with this:\np1 = Popen([\"zgrep\", \"thingiwant\", \"largefile\"], stdout=PIPE)\np2 = Popen([\"processreceivingdata\"], stdin=p1.stdout, stdout=PIPE)\noutput = p2.communicate()[0]\n\nNotice that p2 is taking its standard input directly from p1. This should avoid deadlocks, but given the contradictory warnings above, who knows.\nAnyway, if that last part doesn't work for you (it should, though), you could try creating a temporary file, writing all data from the first call to that, and then using the temporary file as input to the next process.\n", "After you open the pipe, you can work with the command output: p.stdout:\nfor line in p.stdout:\n # do stuff\np.stdout.close()\n\n", "How did you executed this process?\nProper way is to use\np.communicate()\n\nSee docs for more details. \n", "You need to wait for the process to finish:\nimport subprocess\np = subprocess.Popen(\"cat /mach_kernel\", shell=True)\np.wait()\n\nAlternatively, you can capture the program's standard output (as you have), and perhaps its standard error, and then call communicate:\nimport subprocess\np = subprocess.Popen(\"cat /mach_kernel\", shell=True,\n stdout=subprocess.PIPE, stderr=subprocess.PIPE)\nstdout, stderr = p.communicate()\n\n" ]
[ 11, 3, 0, 0 ]
[]
[]
[ "popen", "python", "resource_cleanup" ]
stackoverflow_0002595602_popen_python_resource_cleanup.txt
Q: Problem with VIM - "f" calling the "fold" command instead of "find" This is happening in python files. For example, I want to do type "fC" in normal mode, and instead of finding the first "C" character, it is just doing code fold toggling. A: Real answer: Are you using this plugin? Under 4, it says that pressing "f" toggles the fold (in certain conditions). Original answer: I'm not sure what fC does, because it doesn't do anything in my version of vim, but normally to use find "C," you can use "/C" followed by enter.
Problem with VIM - "f" calling the "fold" command instead of "find"
This is happening in python files. For example, I want to do type "fC" in normal mode, and instead of finding the first "C" character, it is just doing code fold toggling.
[ "Real answer:\nAre you using this plugin? Under 4, it says that pressing \"f\" toggles the fold (in certain conditions).\nOriginal answer:\nI'm not sure what fC does, because it doesn't do anything in my version of vim, but normally to use find \"C,\" you can use \"/C\" followed by enter.\n" ]
[ 3 ]
[]
[]
[ "python", "vim" ]
stackoverflow_0002603389_python_vim.txt
Q: Python lxml screen scraping? I need to do some HTML parsing with python. After some research lxml seems to be my best choice but I am having a hard time finding examples that help me with what I am trying to do. this is why i am hear. I need to scrape a page for all of its viewable text.. strip out all tags and javascript.. I need it to leave me with what text is viewable. sounds simple enough.. i did it with the HTMLParser but its not handling javascript well class HTML2Text(HTMLParser.HTMLParser): def __init__(self): HTMLParser.HTMLParser.__init__(self) self.output = cStringIO.StringIO() def get_text(self): return self.output.getvalue() def handle_data(self, data): self.output.write(data) def ParseHTML(source): p = HTML2Text() p.feed(source) text = p.get_text() return text Any Ideas for a way to do this with lxml or a better way to do it HTMLParser.. HTMLParser would be best because no additional libs are needed.. thanks everyone Scott F. A: No screen-scraping library I know "does well with Javascript" -- it's just too hard to anticipate all ways in which JS could alter the HTML DOM dynamically, conditionally &c. A: scrape.py can do this for you. It's as simple as: import scrape s = scrape.Session() s.go('yoursite.com') print s.doc.text Jump to about 2:40 in this video for an awesome overview from the creator of scrape.py: pycon.blip.tv/file/3261277 A: BeautifulSoup (http://www.crummy.com/software/BeautifulSoup/) is often the right answer to python html scraping questions. A: I know of no Python HTML parsing libraries that handle running javascript in the page being parsed. It's not "simple enough" for the reasons given by Alex Martelli and more. For this task you may need to think about going to a higher level than just parsing HTML and look at web application testing frameworks. Two that can execute javascript and are either Python based or can interface with Python: PAMIE Selenium Unfortunately I'm not sure if the "unit testing" orientation of these frameworks will actually let you scrape out visible text. So the only other solution would be to do it yourself, say by integrating python-spidermonkey into your app. A: Your code is smart and very flexible to extent, I think. How about simply adding handle_starttag() and handle_endtag() to supress the <script> blocks? class HTML2Text(HTMLParser.HTMLParser): def __init__(self): HTMLParser.HTMLParser.__init__(self) self.output = cStringIO.StringIO() self.is_in_script = False def get_text(self): return self.output.getvalue() def handle_data(self, data): if not self.is_in_script: self.output.write(data) def handle_starttag(self, tag, attrs): if tag == "script": self.is_in_script = True def handle_endtag(self, tag): if tag == "script": self.is_in_script = False def ParseHTML(source): p = HTML2Text() p.feed(source) text = p.get_text() return text
Python lxml screen scraping?
I need to do some HTML parsing with python. After some research lxml seems to be my best choice but I am having a hard time finding examples that help me with what I am trying to do. this is why i am hear. I need to scrape a page for all of its viewable text.. strip out all tags and javascript.. I need it to leave me with what text is viewable. sounds simple enough.. i did it with the HTMLParser but its not handling javascript well class HTML2Text(HTMLParser.HTMLParser): def __init__(self): HTMLParser.HTMLParser.__init__(self) self.output = cStringIO.StringIO() def get_text(self): return self.output.getvalue() def handle_data(self, data): self.output.write(data) def ParseHTML(source): p = HTML2Text() p.feed(source) text = p.get_text() return text Any Ideas for a way to do this with lxml or a better way to do it HTMLParser.. HTMLParser would be best because no additional libs are needed.. thanks everyone Scott F.
[ "No screen-scraping library I know \"does well with Javascript\" -- it's just too hard to anticipate all ways in which JS could alter the HTML DOM dynamically, conditionally &c.\n", "scrape.py can do this for you.\nIt's as simple as:\nimport scrape\ns = scrape.Session()\ns.go('yoursite.com')\nprint s.doc.text\n\nJump to about 2:40 in this video for an awesome overview from the creator of scrape.py:\npycon.blip.tv/file/3261277\n", "BeautifulSoup (http://www.crummy.com/software/BeautifulSoup/) is often the right answer to python html scraping questions.\n", "I know of no Python HTML parsing libraries that handle running javascript in the page being parsed. It's not \"simple enough\" for the reasons given by Alex Martelli and more.\nFor this task you may need to think about going to a higher level than just parsing HTML and look at web application testing frameworks.\nTwo that can execute javascript and are either Python based or can interface with Python:\n\nPAMIE\nSelenium\n\nUnfortunately I'm not sure if the \"unit testing\" orientation of these frameworks will actually let you scrape out visible text.\nSo the only other solution would be to do it yourself, say by integrating python-spidermonkey into your app.\n", "Your code is smart and very flexible to extent, I think.\nHow about simply adding handle_starttag() and handle_endtag() to supress the <script> blocks?\nclass HTML2Text(HTMLParser.HTMLParser):\n def __init__(self):\n HTMLParser.HTMLParser.__init__(self)\n self.output = cStringIO.StringIO()\n self.is_in_script = False\n def get_text(self):\n return self.output.getvalue()\n def handle_data(self, data):\n if not self.is_in_script:\n self.output.write(data)\n def handle_starttag(self, tag, attrs):\n if tag == \"script\":\n self.is_in_script = True\n def handle_endtag(self, tag):\n if tag == \"script\":\n self.is_in_script = False\n\ndef ParseHTML(source):\n p = HTML2Text()\n p.feed(source)\n text = p.get_text()\n return text\n\n" ]
[ 4, 2, 0, 0, 0 ]
[]
[]
[ "html", "lxml", "parsing", "python", "screen_scraping" ]
stackoverflow_0000814227_html_lxml_parsing_python_screen_scraping.txt
Q: Mako templates use old version until I manually update template files I periodically get this problem where all of a sudden mako is using old versions of templates, and it's not until I manually go and update the template files that they'll use the current version. I'm using ./manage.py runserver I think it's usually after I update using source control, but it's intermittent, and I can't reliably reproduce the problem. A: It kinda feels like there some caching going on. You don't give a very specific description of the process, so it's hard to go any deeper than that. A: In your settings.py file you can use the MAKO_TEMPLATE_OPTS setting to specify where the temporary compiled templates go. import os import tempfile MAKO_TEMPLATE_OPTS=dict(input_encoding='utf-8', module_directory=os.path.join( tempfile.gettempdir(), os.environ.get('LOGNAME', 'unknown_user'), 'mako')) This will put them somewhere like /tmp/dsmith/mako You can use different folders for different projects to make sure they don't overlap. Also, if you notice the problem after a source control update or something you can just clear out the cached folder.
Mako templates use old version until I manually update template files
I periodically get this problem where all of a sudden mako is using old versions of templates, and it's not until I manually go and update the template files that they'll use the current version. I'm using ./manage.py runserver I think it's usually after I update using source control, but it's intermittent, and I can't reliably reproduce the problem.
[ "It kinda feels like there some caching going on. You don't give a very specific description of the process, so it's hard to go any deeper than that.\n", "In your settings.py file you can use the MAKO_TEMPLATE_OPTS setting to specify where the temporary compiled templates go.\nimport os\nimport tempfile\nMAKO_TEMPLATE_OPTS=dict(input_encoding='utf-8',\n module_directory=os.path.join(\n tempfile.gettempdir(),\n os.environ.get('LOGNAME', 'unknown_user'),\n 'mako'))\n\nThis will put them somewhere like /tmp/dsmith/mako\nYou can use different folders for different projects to make sure they don't overlap. Also, if you notice the problem after a source control update or something you can just clear out the cached folder.\n" ]
[ 0, 0 ]
[]
[]
[ "django", "mako", "python" ]
stackoverflow_0001949516_django_mako_python.txt
Q: Django repeating vars/cache issue? I'm trying to build a better/more powerful form class for Django. It's working well, except for these sub-forms. Actually, it works perfectly right after I re-start apache, but after I refresh the page a few times, my HTML output starts to look like this: <input class="text" type="text" id="pickup_addr-pickup_addr-pickup_addr-id-pickup_addr-venue" value="" name="pickup_addr-pickup_addr-pickup_addr-pickup_addr-venue" /> The pickup_addr- part starts repeating many times. I was looking for loops around the prefix code that might have cause this to happen, but the output isn't even consistent when I refresh the page, so I think something is getting cached somewhere, but I can't even imagine how that's possible. The prefix var should be reset when the class is initialized, no? Unless it's somehow not initializing something? class Form(object): count = 0 def __init__(self, data={}, prefix='', action='', id=None, multiple=False): self.fields = {} self.subforms = {} self.data = {} self.action = action self.id = fnn(id, 'form%d' % Form.count) self.errors = [] self.valid = True if not empty(prefix) and prefix[-1:] not in ('-','_'): prefix += '-' for name, field in inspect.getmembers(self, lambda m: isinstance(m, Field)): if name[:2] == '__': continue field_name = fnn(field.name, name) field.label = fnn(field.label, humanize(field_name)) field.name = field.widget.name = prefix + field_name + ife(multiple, '[]') field.id = field.auto_id = field.widget.id = ife(field.id==None, 'id-') + prefix + fnn(field.id, field_name) + ife(multiple, Form.count) field.errors = [] val = fnn(field.widget.get_value(data), field.default) if isinstance(val, basestring): try: val = field.coerce(field.format(val)) except Exception, err: self.valid = False field.errors.append(escape_html(err)) field.val = self.data[name] = field.widget.val = val for rule in field.rules: rule.fields = self.fields rule.val = field.val rule.name = field.name self.fields[name] = field for name, form in inspect.getmembers(self, lambda m: ispropersubclass(m, Form)): if name[:2] == '__': continue self.subforms[name] = self.__dict__[name] = form(data=data, prefix='%s%s-' % (prefix, name)) Form.count += 1 Let me know if you need more code... I know it's a lot, but I just can't figure out what's causing this! I'm not even using any cache middleware. Copying/cloning the fields first gives me this output instead: <label for="None">None</label> <input class="text" type="text" id="id-pickup_address-venue" value="" name="pickup_address-venue" /> field.name and field.label are set in exactly the same way... in fact, field.id is correctly displayed on the <input> but that same value is suddenly gone when I try to print the label.... the difference is that the <input> bit is printed by the Widget class, whereas the label is printed directly from my template... which I guess is.... oh I get it, that one is still referring to the unset class-level/static field, rather than the instance field... A: You're probably declaring your forms like this: class SomeForm(Form): someField = Field(....) ... Now, this means that one instance of someField will actually be shared among all your SomeForm instances. In your __init__ you're changing the attributes of the field, which will affect all forms, not just the current one, including ones created in the future. To fix this, you can make a copy of the field for each instance: field = copy(field) #maybe you need deepcopy instead setattr(self, name, field) And then change the attributes of the copy.
Django repeating vars/cache issue?
I'm trying to build a better/more powerful form class for Django. It's working well, except for these sub-forms. Actually, it works perfectly right after I re-start apache, but after I refresh the page a few times, my HTML output starts to look like this: <input class="text" type="text" id="pickup_addr-pickup_addr-pickup_addr-id-pickup_addr-venue" value="" name="pickup_addr-pickup_addr-pickup_addr-pickup_addr-venue" /> The pickup_addr- part starts repeating many times. I was looking for loops around the prefix code that might have cause this to happen, but the output isn't even consistent when I refresh the page, so I think something is getting cached somewhere, but I can't even imagine how that's possible. The prefix var should be reset when the class is initialized, no? Unless it's somehow not initializing something? class Form(object): count = 0 def __init__(self, data={}, prefix='', action='', id=None, multiple=False): self.fields = {} self.subforms = {} self.data = {} self.action = action self.id = fnn(id, 'form%d' % Form.count) self.errors = [] self.valid = True if not empty(prefix) and prefix[-1:] not in ('-','_'): prefix += '-' for name, field in inspect.getmembers(self, lambda m: isinstance(m, Field)): if name[:2] == '__': continue field_name = fnn(field.name, name) field.label = fnn(field.label, humanize(field_name)) field.name = field.widget.name = prefix + field_name + ife(multiple, '[]') field.id = field.auto_id = field.widget.id = ife(field.id==None, 'id-') + prefix + fnn(field.id, field_name) + ife(multiple, Form.count) field.errors = [] val = fnn(field.widget.get_value(data), field.default) if isinstance(val, basestring): try: val = field.coerce(field.format(val)) except Exception, err: self.valid = False field.errors.append(escape_html(err)) field.val = self.data[name] = field.widget.val = val for rule in field.rules: rule.fields = self.fields rule.val = field.val rule.name = field.name self.fields[name] = field for name, form in inspect.getmembers(self, lambda m: ispropersubclass(m, Form)): if name[:2] == '__': continue self.subforms[name] = self.__dict__[name] = form(data=data, prefix='%s%s-' % (prefix, name)) Form.count += 1 Let me know if you need more code... I know it's a lot, but I just can't figure out what's causing this! I'm not even using any cache middleware. Copying/cloning the fields first gives me this output instead: <label for="None">None</label> <input class="text" type="text" id="id-pickup_address-venue" value="" name="pickup_address-venue" /> field.name and field.label are set in exactly the same way... in fact, field.id is correctly displayed on the <input> but that same value is suddenly gone when I try to print the label.... the difference is that the <input> bit is printed by the Widget class, whereas the label is printed directly from my template... which I guess is.... oh I get it, that one is still referring to the unset class-level/static field, rather than the instance field...
[ "You're probably declaring your forms like this:\nclass SomeForm(Form):\n someField = Field(....)\n ...\n\nNow, this means that one instance of someField will actually be shared among all your SomeForm instances. In your __init__ you're changing the attributes of the field, which will affect all forms, not just the current one, including ones created in the future.\nTo fix this, you can make a copy of the field for each instance:\nfield = copy(field) #maybe you need deepcopy instead\nsetattr(self, name, field) \n\nAnd then change the attributes of the copy.\n" ]
[ 1 ]
[]
[]
[ "django", "python", "wsgi" ]
stackoverflow_0002603937_django_python_wsgi.txt
Q: Pre-generating GUIDs for use in python? I have a python program that needs to generate several guids and hand them back with some other data to a client over the network. It may be hit with a lot of requests in a short time period and I would like the latency to be as low as reasonably possible. Ideally, rather than generating new guids on the fly as the client waits for a response, I would rather be bulk-generating a list of guids in the background that is continually replenished so that I always have pre-generated ones ready to hand out. I am using the uuid module in python on linux. I understand that this is using the uuidd daemon to get uuids. Does uuidd already take care of pre-genreating uuids so that it always has some ready? From the documentation it appears that it does not. Is there some setting in python or with uuidd to get it to do this automatically? Is there a more elegant approach then manually creating a background thread in my program that maintains a list of uuids? A: Are you certain that the uuid module would in fact be too slow to handle the requests you expect in a timely manner? I would be very surprised if UUID generation accounted for a bottleneck in your application. I would first build the application to simply use the uuid module and then if you find that this module is in fact slowing things down you should investigate a way to keep a pre-generated list of UUIDs around. A: I have tested the performance of the uuid module for generating uuids: >>> import timeit >>> timer=timeit.Timer('uuid.uuid1()','import uuid') >>> timer.repeat(3, 10000) [0.84600019454956055, 0.8469998836517334, 0.84400010108947754] How many do you need? Is 10000 per second not enough? A: Suppose you have a thread to keep topping up a pool of uuid's. Here is a very simple version import uuid,threading,time class UUID_Pool(threading.Thread): pool_size=10000 def __init__(self): super(UUID_Pool,self).__init__() self.daemon=True self.uuid_pool=set(uuid.uuid1() for x in range(self.pool_size)) def run(self): while True: while len(self.uuid_pool) < self.pool_size: self.uuid_pool.add(uuid.uuid1()) time.sleep(0.01) # top up the pool 100 times/sec uuid_pool = UUID_Pool() uuid_pool.start() get_uuid = uuid_pool.uuid_pool.pop # make a local binding uuid=get_uuid() # ~60x faster than uuid.uuid1() on my computer You'd also need to handle the case where your burst empties the pool by using uuid's faster than the thread can generate them.
Pre-generating GUIDs for use in python?
I have a python program that needs to generate several guids and hand them back with some other data to a client over the network. It may be hit with a lot of requests in a short time period and I would like the latency to be as low as reasonably possible. Ideally, rather than generating new guids on the fly as the client waits for a response, I would rather be bulk-generating a list of guids in the background that is continually replenished so that I always have pre-generated ones ready to hand out. I am using the uuid module in python on linux. I understand that this is using the uuidd daemon to get uuids. Does uuidd already take care of pre-genreating uuids so that it always has some ready? From the documentation it appears that it does not. Is there some setting in python or with uuidd to get it to do this automatically? Is there a more elegant approach then manually creating a background thread in my program that maintains a list of uuids?
[ "Are you certain that the uuid module would in fact be too slow to handle the requests you expect in a timely manner? I would be very surprised if UUID generation accounted for a bottleneck in your application.\nI would first build the application to simply use the uuid module and then if you find that this module is in fact slowing things down you should investigate a way to keep a pre-generated list of UUIDs around.\n", "I have tested the performance of the uuid module for generating uuids:\n>>> import timeit\n>>> timer=timeit.Timer('uuid.uuid1()','import uuid')\n>>> timer.repeat(3, 10000)\n[0.84600019454956055, 0.8469998836517334, 0.84400010108947754]\n\nHow many do you need? Is 10000 per second not enough?\n", "Suppose you have a thread to keep topping up a pool of uuid's.\nHere is a very simple version\nimport uuid,threading,time\n\nclass UUID_Pool(threading.Thread):\n pool_size=10000\n def __init__(self):\n super(UUID_Pool,self).__init__()\n self.daemon=True\n self.uuid_pool=set(uuid.uuid1() for x in range(self.pool_size))\n\n def run(self):\n while True:\n while len(self.uuid_pool) < self.pool_size:\n self.uuid_pool.add(uuid.uuid1())\n time.sleep(0.01) # top up the pool 100 times/sec\n\nuuid_pool = UUID_Pool()\nuuid_pool.start()\nget_uuid = uuid_pool.uuid_pool.pop # make a local binding\nuuid=get_uuid() # ~60x faster than uuid.uuid1() on my computer\n\nYou'd also need to handle the case where your burst empties the pool by using uuid's faster than the thread can generate them.\n" ]
[ 6, 4, 0 ]
[]
[]
[ "guid", "linux", "performance", "python", "uuid" ]
stackoverflow_0002603951_guid_linux_performance_python_uuid.txt
Q: Obtaining IP addresses in Bittorrent I am trying to get a list of IP addresses serving or downloading a file. What I did was to contact a tracker like openbittorrent.com to get the following (as part of the scrape file): B%00%00%0C%5F%B1%B1l%CAGa%84S%CB%B0%9BG%84%3BE:0:1 Now, the long string in the beginning is the info hash. As a next step, I did this: http://tracker.sometracker.com/announce?info_hash=B%00%00%0C%5F%B1%B1l%CAGa%84S%CB%B0%9BG%84%3BE It gave me back the following. So far so good. The message contained this: d8:completei0e10:downloadedi0e10:incompletei2e8:intervali1931e12:min intervali965e5:peers12:U���ٿ��ӣǣ^@^@e Can someone tell me what should I be doing after this to get the IP addresses currently serving the file or downloading it? A: That's not a torrent file, that's an announce response. They're both bencode (use bencode to decode them), but the announce response contains only peer information. That's not enough information to be able to download the contents of the torrent: to do that you will need the torrent file itself. The peers member of the bencoded dictionary contains groups of 6 bytes which you can unpack with struct. First four bytes are the IP address, followed by two bytes for the port. This is a compact announce response, which is common (but IPv4 only, obviously). You may also see non-compact responses which give you a transparent dictionary. Many trackers today won't talk to you with the non-specific scrape announce you're sending, or the initial announce request that doesn't include compact, port or event. You should probably read over the protocol a bit before going further.
Obtaining IP addresses in Bittorrent
I am trying to get a list of IP addresses serving or downloading a file. What I did was to contact a tracker like openbittorrent.com to get the following (as part of the scrape file): B%00%00%0C%5F%B1%B1l%CAGa%84S%CB%B0%9BG%84%3BE:0:1 Now, the long string in the beginning is the info hash. As a next step, I did this: http://tracker.sometracker.com/announce?info_hash=B%00%00%0C%5F%B1%B1l%CAGa%84S%CB%B0%9BG%84%3BE It gave me back the following. So far so good. The message contained this: d8:completei0e10:downloadedi0e10:incompletei2e8:intervali1931e12:min intervali965e5:peers12:U���ٿ��ӣǣ^@^@e Can someone tell me what should I be doing after this to get the IP addresses currently serving the file or downloading it?
[ "That's not a torrent file, that's an announce response. They're both bencode (use bencode to decode them), but the announce response contains only peer information. That's not enough information to be able to download the contents of the torrent: to do that you will need the torrent file itself.\nThe peers member of the bencoded dictionary contains groups of 6 bytes which you can unpack with struct. First four bytes are the IP address, followed by two bytes for the port. This is a compact announce response, which is common (but IPv4 only, obviously). You may also see non-compact responses which give you a transparent dictionary.\nMany trackers today won't talk to you with the non-specific scrape announce you're sending, or the initial announce request that doesn't include compact, port or event. You should probably read over the protocol a bit before going further.\n" ]
[ 3 ]
[]
[]
[ "bittorrent", "language_agnostic", "p2p", "prototype", "python" ]
stackoverflow_0002604153_bittorrent_language_agnostic_p2p_prototype_python.txt
Q: Why don't these class attributes register? I have a factory method that generates django form classes like so: def get_indicator_form(indicator, patient): class IndicatorForm(forms.Form): #These don't work! indicator_id = forms.IntegerField(initial=indicator.id, widget=forms.HiddenInput()) patient_id = forms.IntegerField(initial=patient.id, widget=forms.HiddenInput()) def __init__(self, *args, **kwargs): forms.Form.__init__(self, *args, **kwargs) self.indicator = indicator self.patient = patient #These do! setattr(IndicatorForm, 'indicator_id', forms.IntegerField(initial=indicator.id, widget=forms.HiddenInput())) setattr(IndicatorForm, 'patient_id', forms.IntegerField(initial=patient.id, widget=forms.HiddenInput())) for field in indicator.indicatorfield_set.all(): setattr(IndicatorForm, field.name, copy(field.get_field_type())) return type('IndicatorForm', (forms.Form,), dict(IndicatorForm.__dict__)) I'm trying to understand why the top form field declarations don't work, but the setattr method below does work. I'm fairly new to python, so I suspect it's some language feature that I'm misunderstanding. Can you help me understand why the field declarations at the top of the class don't add the fields to the class? In a possibly related note, when these classes are instantiated, instance.media returns nothing even though some fields have widgets with associated media. Thanks, Pete A: Try this: def get_indicator_form(indicator, patient): class IndicatorForm(forms.Form): indicator_id = forms.IntegerField(initial=indicator.id, widget=forms.HiddenInput()) patient_id = forms.IntegerField(initial=patient.id, widget=forms.HiddenInput()) def __init__(self, *args, **kwargs): forms.Form.__init__(self, *args, **kwargs) self.indicator = indicator self.patient = patient for field in indicator.indicatorfield_set.all(): IndicatorForm.base_fields[field.name] = field.get_field_type() return IndicatorForm
Why don't these class attributes register?
I have a factory method that generates django form classes like so: def get_indicator_form(indicator, patient): class IndicatorForm(forms.Form): #These don't work! indicator_id = forms.IntegerField(initial=indicator.id, widget=forms.HiddenInput()) patient_id = forms.IntegerField(initial=patient.id, widget=forms.HiddenInput()) def __init__(self, *args, **kwargs): forms.Form.__init__(self, *args, **kwargs) self.indicator = indicator self.patient = patient #These do! setattr(IndicatorForm, 'indicator_id', forms.IntegerField(initial=indicator.id, widget=forms.HiddenInput())) setattr(IndicatorForm, 'patient_id', forms.IntegerField(initial=patient.id, widget=forms.HiddenInput())) for field in indicator.indicatorfield_set.all(): setattr(IndicatorForm, field.name, copy(field.get_field_type())) return type('IndicatorForm', (forms.Form,), dict(IndicatorForm.__dict__)) I'm trying to understand why the top form field declarations don't work, but the setattr method below does work. I'm fairly new to python, so I suspect it's some language feature that I'm misunderstanding. Can you help me understand why the field declarations at the top of the class don't add the fields to the class? In a possibly related note, when these classes are instantiated, instance.media returns nothing even though some fields have widgets with associated media. Thanks, Pete
[ "Try this:\ndef get_indicator_form(indicator, patient):\n class IndicatorForm(forms.Form):\n indicator_id = forms.IntegerField(initial=indicator.id, widget=forms.HiddenInput())\n patient_id = forms.IntegerField(initial=patient.id, widget=forms.HiddenInput())\n\n def __init__(self, *args, **kwargs):\n forms.Form.__init__(self, *args, **kwargs)\n self.indicator = indicator\n self.patient = patient\n\n for field in indicator.indicatorfield_set.all():\n IndicatorForm.base_fields[field.name] = field.get_field_type()\n\n return IndicatorForm\n\n" ]
[ 1 ]
[]
[]
[ "django", "django_forms", "python" ]
stackoverflow_0002604230_django_django_forms_python.txt
Q: Why does easy_install extract some python eggs and not others? Looking in my /usr/local/lib/python.../dist-package directory, I have .egg directories and .egg files. Why does the installer choose to extra packages to the .egg directory, yet leave other files with .egg extensions? A: If the package contains only pure-Python code, it can stay as just an egg file. The Python interpreter can load the Python modules directly from the egg. If the package contains modules written in C or other data, then egg needs to be extracted so the C modules and/or data can be accessed. That's the default behavior of packages, I believe. Newer versions of Python might be able to load C modules from egg files; I'm not sure about that part. The creator of the package can also specifically instruct the installer to unzip the package, by passing zip_safe = False to setup() in their setup.py. Finally, the person doing the installing can tell easy_install explicitly to unpack eggs by passing it the -Z option or by setting zip_ok = False in the pydistutils.cfg. A: I can't explain why some eggs are zipped (the files) and some are directories, but I can offer this: if you hate zipped eggs (like I do) put this in the [easy_install] section of your ~/.pydistutils.cfg: zip_ok = false
Why does easy_install extract some python eggs and not others?
Looking in my /usr/local/lib/python.../dist-package directory, I have .egg directories and .egg files. Why does the installer choose to extra packages to the .egg directory, yet leave other files with .egg extensions?
[ "If the package contains only pure-Python code, it can stay as just an egg file. The Python interpreter can load the Python modules directly from the egg. If the package contains modules written in C or other data, then egg needs to be extracted so the C modules and/or data can be accessed. That's the default behavior of packages, I believe. Newer versions of Python might be able to load C modules from egg files; I'm not sure about that part.\nThe creator of the package can also specifically instruct the installer to unzip the package, by passing zip_safe = False to setup() in their setup.py.\nFinally, the person doing the installing can tell easy_install explicitly to unpack eggs by passing it the -Z option or by setting zip_ok = False in the pydistutils.cfg.\n", "I can't explain why some eggs are zipped (the files) and some are directories, but I can offer this: if you hate zipped eggs (like I do) put this in the [easy_install] section of your ~/.pydistutils.cfg:\n\nzip_ok = false\n\n" ]
[ 32, 5 ]
[]
[]
[ "egg", "python" ]
stackoverflow_0002604600_egg_python.txt
Q: Enable PyGTK Eventbox motion-notify-event while is a Layout child I noticed when a Eventbox is added into a Layout some events are missed, this does not happend for example adding it to a Fixed (very similar widget), I tried to restore the event mask in this way with no sucess: import pygtk import gtk def foo(widget, event): print event pygtk.require('2.0') window = gtk.Window(gtk.WINDOW_TOPLEVEL) window.connect('destroy', lambda x: gtk.main_quit()) eventbox = gtk.EventBox() eventbox.connect('button-press-event', foo) # works eventbox.connect('motion-notify-event', foo) # fail eventbox.set_events( gtk.gdk.BUTTON_MOTION_MASK| # restoring missed masks gtk.gdk.BUTTON1_MOTION_MASK| gtk.gdk.BUTTON2_MOTION_MASK| gtk.gdk.BUTTON3_MOTION_MASK) layout = gtk.Layout() image = gtk.image_new_from_file('/home/me/picture.jpg') layout.add(image) eventbox.add(layout) window.add(eventbox) window.show_all() gtk.main() How should I restore the missed event/mask? A: The code you pasted works fine for me. When I press button 1 on the mouse and drag on the window, it generates and prints motion events to the terminal. I've even removed the eventbox.set_events(...) call and it still works. So what's the problem?
Enable PyGTK Eventbox motion-notify-event while is a Layout child
I noticed when a Eventbox is added into a Layout some events are missed, this does not happend for example adding it to a Fixed (very similar widget), I tried to restore the event mask in this way with no sucess: import pygtk import gtk def foo(widget, event): print event pygtk.require('2.0') window = gtk.Window(gtk.WINDOW_TOPLEVEL) window.connect('destroy', lambda x: gtk.main_quit()) eventbox = gtk.EventBox() eventbox.connect('button-press-event', foo) # works eventbox.connect('motion-notify-event', foo) # fail eventbox.set_events( gtk.gdk.BUTTON_MOTION_MASK| # restoring missed masks gtk.gdk.BUTTON1_MOTION_MASK| gtk.gdk.BUTTON2_MOTION_MASK| gtk.gdk.BUTTON3_MOTION_MASK) layout = gtk.Layout() image = gtk.image_new_from_file('/home/me/picture.jpg') layout.add(image) eventbox.add(layout) window.add(eventbox) window.show_all() gtk.main() How should I restore the missed event/mask?
[ "The code you pasted works fine for me. When I press button 1 on the mouse and drag on the window, it generates and prints motion events to the terminal.\nI've even removed the eventbox.set_events(...) call and it still works.\nSo what's the problem?\n" ]
[ 1 ]
[]
[]
[ "gnome", "gtk", "pygtk", "python" ]
stackoverflow_0002604846_gnome_gtk_pygtk_python.txt
Q: How do I do this loop in Django template? {% for d in mydata %} {{ d.title }} {% endfor %} However, I would like the first one to be bolded. How can I use the loop to say...if the d is the first one, then bold it? A: Check out http://docs.djangoproject.com/en/dev/ref/templates/builtins/#for. Looks like: {% for d in mydata %} {% if forloop.first %} <strong>{{ d.title }}</strong> {% else %} {{ d.title }} {% endif %} {% endfor %} A: Check if forloop.first is true.
How do I do this loop in Django template?
{% for d in mydata %} {{ d.title }} {% endfor %} However, I would like the first one to be bolded. How can I use the loop to say...if the d is the first one, then bold it?
[ "Check out http://docs.djangoproject.com/en/dev/ref/templates/builtins/#for. Looks like:\n{% for d in mydata %}\n {% if forloop.first %}\n <strong>{{ d.title }}</strong>\n {% else %}\n {{ d.title }}\n {% endif %}\n{% endfor %}\n\n", "Check if forloop.first is true.\n" ]
[ 8, 2 ]
[]
[]
[ "django", "loops", "python", "templates" ]
stackoverflow_0002604979_django_loops_python_templates.txt
Q: Issue with making python program executable I'm trying to make a program so that I can run it through the command line with the following format: ./myProgram I made it executable and put #!/usr/bin/env python in the header, but it's giving me the following error. env: python\r: No such file or directory However, when I run "python myProgram", it runs fine. Can someone tell me what I'm doing wrong? A: Your line endings are wrong. Use dos2unix to fix them. A: +1 on ignacio's suggestion. however, to answer the 1st part of your question more directly, each OS/system uses a different line termination character: POSIX (any Unix-flavor like Linux, *BSD, Mac OS X, etc.) uses \n (NEWLINE) while DOS/Win uses the combo \r\n (CR/carriage return + NEWLINE) and old Mac OS 8 or 9 uses just CR or \r. to solve this problem, you can run a utility like ignacio has suggested, or you should be able to do it from your text editor (may not be very apparent however). to answer the other part of your question, the reason why $ python myProgram works is because Python treats all three different line endings the same... the shebang line at the top is ignored because you told Python to load and run that script, and "#" means the first line is a comment and thus ignored. when you tell your OS shell to run it, it needs to parse that line and execute whatever interpreter you requested, but if it can't, it pukes on you like it did. hope this helps! ps. on a side note, you can find out what line-termination character is being used on your operating system, just check out the os.linesep (data) attribute. for example, on my Mac (OS X), i get this: >>> import os >>> os.linesep '\n' here's a quick summary of the other related attributes that i plagiarized from my hardcore Python intro course notes: A: dos2unix filename.py or inside vim issue the command :set fileformat=unix and save.
Issue with making python program executable
I'm trying to make a program so that I can run it through the command line with the following format: ./myProgram I made it executable and put #!/usr/bin/env python in the header, but it's giving me the following error. env: python\r: No such file or directory However, when I run "python myProgram", it runs fine. Can someone tell me what I'm doing wrong?
[ "Your line endings are wrong. Use dos2unix to fix them.\n", "+1 on ignacio's suggestion.\nhowever, to answer the 1st part of your question more directly, each OS/system uses a different line termination character:\nPOSIX (any Unix-flavor like Linux, *BSD, Mac OS X, etc.) uses \\n (NEWLINE) while\nDOS/Win uses the combo \\r\\n (CR/carriage return + NEWLINE) and old Mac OS 8 or 9 uses just CR or \\r.\nto solve this problem, you can run a utility like ignacio has suggested, or you should be able to do it from your text editor (may not be very apparent however).\nto answer the other part of your question, the reason why $ python myProgram works is because Python treats all three different line endings the same... the shebang line at the top is ignored because you told Python to load and run that script, and \"#\" means the first line is a comment and thus ignored.\nwhen you tell your OS shell to run it, it needs to parse that line and execute whatever interpreter you requested, but if it can't, it pukes on you like it did.\nhope this helps!\nps. on a side note, you can find out what line-termination character is being used on your operating system, just check out the os.linesep (data) attribute. for example, on my Mac (OS X), i get this:\n>>> import os\n>>> os.linesep\n'\\n'\n\nhere's a quick summary of the other related attributes that i plagiarized from my hardcore Python intro course notes:\n\n", "dos2unix filename.py or inside vim issue the command :set fileformat=unix and save.\n" ]
[ 17, 11, 3 ]
[]
[]
[ "python" ]
stackoverflow_0002604917_python.txt
Q: Google appengine datastore tree structure I need to be able to make a tree like structure in the appengine database. I have try to make an object reference itself but have not gotten it to work. class Item(db.Model): children = db.ListProperty(db.ReferenceProperty(Item)) A: Alternatively, you can store references to children in the parent with: class Node(db.Model): children = db.ListProperty(db.Key) This answer shamelessly stolen (with credit!) from Nick Johnson's answer to this related question A: Here is a related topic from the google-appengine group. You can store a reference to the parent node in each child, instead of references to the child nodes in the parent. Here's some code: class Node(db.Model): pass ...snip... root = Node() db.put(root) for i in xrange(10): child = Node(parent=root) db.put(child) for i in xrange(5): grandchild = Node(parent=child) db.put(grandchild) parent is a special field on a Model which tells the datastore that an entity has a parent-child relationship with its parent. From the docs: When the application creates an entity, it can assign another entity as the parent of the new entity, using the parent argument in the Model constructor. Assigning a parent to a new entity puts the new entity in the same entity group as the parent entity. An entity without a parent is a root entity. An entity that is a parent for another entity can also have a parent. A chain of parent entities from an entity up to the root is the path for the entity, and members of the path are the entity's ancestors. The parent of an entity is defined when the entity is created, and cannot be changed later.
Google appengine datastore tree structure
I need to be able to make a tree like structure in the appengine database. I have try to make an object reference itself but have not gotten it to work. class Item(db.Model): children = db.ListProperty(db.ReferenceProperty(Item))
[ "Alternatively, you can store references to children in the parent with:\nclass Node(db.Model):\n children = db.ListProperty(db.Key)\n\nThis answer shamelessly stolen (with credit!) from Nick Johnson's answer to this related question\n", "Here is a related topic from the google-appengine group.\nYou can store a reference to the parent node in each child, instead of references to the child nodes in the parent.\nHere's some code:\nclass Node(db.Model):\n pass\n\n...snip...\n\nroot = Node()\ndb.put(root)\n\nfor i in xrange(10):\n child = Node(parent=root)\n db.put(child)\n \n for i in xrange(5):\n grandchild = Node(parent=child)\n db.put(grandchild)\n\nparent is a special field on a Model which tells the datastore that an entity has a parent-child relationship with its parent.\nFrom the docs:\n\nWhen the application creates an\nentity, it can assign another entity\nas the parent of the new entity, using\nthe parent argument in the Model\nconstructor. Assigning a parent to a\nnew entity puts the new entity in the\nsame entity group as the parent\nentity.\nAn entity without a parent is a root entity. An entity that is a parent for another entity can also have a parent. A chain of parent entities from an entity up to the root is the path for the entity, and members of the path are the entity's ancestors. The parent of an entity is defined when the entity is created, and cannot be changed later.\n\n" ]
[ 3, 1 ]
[]
[]
[ "database", "google_app_engine", "python" ]
stackoverflow_0002604966_database_google_app_engine_python.txt
Q: Silence loggers and printing to screen - Python I'm having a problem with my python script. It's printing massive amounts of data on the screen, and I would like to prevent all sorts of printing to screen. Edit: The library I'm using is mechanize, and it's printing a LOT of data on screen. I have set these to false with no luck! br.set_debug_redirects(False) br.set_debug_responses(False) br.set_debug_http(False) Any ideas? Help would be amazing and very much appreciated! A: (Based on your 2nd edit) If you don't want to disable all output, you can try to be specific to mechanize itself. http://wwwsearch.sourceforge.net/mechanize/ provides a snippet, which I've modified (though I'm not sure if it will work): import logging logger = logging.getLogger("mechanize") # only log really bad events logger.setLevel(logging.ERROR) When you print something it goes to the screen through the sys.stdout file. You can change this file to any other file (eg, a log file you open) so that nothing is printed to the screen: import sys # save the old stdout so you can print later (do sys.stdout = OLD_STDOUT) OLD_STDOUT = sys.stdout sys.stdout = open("logfile.txt", 'w') Of course, if you're talking about some library that you're calling, it may be printing to sys.stderr. Luckily, you can do the exact same thing for this one (continuing from above): OLD_STDERR = sys.stderr sys.stderr = open("errorLog.txt", 'w') Now if, for some reason, you want to completely ignore stdout (or stderr) and never see it again, you can define your own file-like classes that simply discard the objects: class Discarder(object): def write(self, text): pass # do nothing # now discard everything coming out of stdout sys.stdout = Discarder() And, to add to the din of possible solutions, here is a solution that works in Unix shells: # discards all input (change /dev/null to a file name to keep track of output) python yourScript.py > /dev/null A: You may redirect sys.stdout and sys.stderr to a file or any file like object of yours e.g. class EatLog(object): def write(self): pass sys.stdout = EatLog() but i would not recommend that, simpler option is to use OS level redirection e.g. python myscript.py > out.log A: you can use the StringIO module, too, instead of rolling your own stdout stream. Occasionally, the stdout needs more than a write method (flush is another common one), which StringIO will handle. import StringIO import sys sys.stdout = StringIO.StringIO()
Silence loggers and printing to screen - Python
I'm having a problem with my python script. It's printing massive amounts of data on the screen, and I would like to prevent all sorts of printing to screen. Edit: The library I'm using is mechanize, and it's printing a LOT of data on screen. I have set these to false with no luck! br.set_debug_redirects(False) br.set_debug_responses(False) br.set_debug_http(False) Any ideas? Help would be amazing and very much appreciated!
[ "(Based on your 2nd edit)\nIf you don't want to disable all output, you can try to be specific to mechanize itself. http://wwwsearch.sourceforge.net/mechanize/ provides a snippet, which I've modified (though I'm not sure if it will work):\nimport logging\nlogger = logging.getLogger(\"mechanize\")\n# only log really bad events\nlogger.setLevel(logging.ERROR)\n\n\nWhen you print something it goes to the screen through the sys.stdout file. You can change this file to any other file (eg, a log file you open) so that nothing is printed to the screen:\nimport sys\n# save the old stdout so you can print later (do sys.stdout = OLD_STDOUT)\nOLD_STDOUT = sys.stdout\nsys.stdout = open(\"logfile.txt\", 'w')\n\nOf course, if you're talking about some library that you're calling, it may be printing to sys.stderr. Luckily, you can do the exact same thing for this one (continuing from above):\nOLD_STDERR = sys.stderr\nsys.stderr = open(\"errorLog.txt\", 'w')\n\nNow if, for some reason, you want to completely ignore stdout (or stderr) and never see it again, you can define your own file-like classes that simply discard the objects:\nclass Discarder(object):\n def write(self, text):\n pass # do nothing\n# now discard everything coming out of stdout\nsys.stdout = Discarder()\n\nAnd, to add to the din of possible solutions, here is a solution that works in Unix shells:\n# discards all input (change /dev/null to a file name to keep track of output)\npython yourScript.py > /dev/null\n\n", "You may redirect sys.stdout and sys.stderr to a file or any file like object of yours e.g.\nclass EatLog(object):\n def write(self):\n pass\n\nsys.stdout = EatLog()\n\nbut i would not recommend that, simpler option is to use OS level redirection e.g.\npython myscript.py > out.log\n\n", "you can use the StringIO module, too, instead of rolling your own stdout stream. Occasionally, the stdout needs more than a write method (flush is another common one), which StringIO will handle.\nimport StringIO\nimport sys\n\nsys.stdout = StringIO.StringIO()\n\n" ]
[ 16, 2, 0 ]
[]
[]
[ "logging", "mechanize", "printing", "python" ]
stackoverflow_0002605117_logging_mechanize_printing_python.txt
Q: Django: reverse lookup URL of feeds? I am having trouble doing a reverse URL lookup for Django-generated feeds. I have the following setup in urls.py: feeds = { 'latest': LatestEntries, } urlpatterns = patterns('', # ... # enable feeds (RSS) url(r'^feeds/(?P<url>.*)/$', 'django.contrib.syndication.views.feed', {'feed_dict': feeds}, name='feeds_view'), ) I have tried using the following template tag: <a href="{% url feeds_view latest %}">RSS feeds</a> But the resulting link is not what want (http://my.domain.com/feeds//). It should be http://my.domain.com/feeds/latest/. For now, I am using a hack to generate the URL for the template: <a href="http://{{ request.META.HTTP_HOST }}/feeds/latest">RSS feeds</a> But, as you can see, it clearly is not DRY. Is there something I am missing? A: Unfortunately, URL reversing is not really possible with the current feed framework. The good news is that the feed framework has been completely refactored and can seamlessly integrate with Django's URL resolving mechanisms. This refactored feed framework will be delivered with Django 1.2, which should arrive at the end of April. You can read up on it in the docs or in a great article by Rob Hudson on DjangoAdvent. A: You're using keyword arguments so you should pass them as such :) Try this: <a href="{% url feeds_view url="latest" %}">RSS feeds</a>
Django: reverse lookup URL of feeds?
I am having trouble doing a reverse URL lookup for Django-generated feeds. I have the following setup in urls.py: feeds = { 'latest': LatestEntries, } urlpatterns = patterns('', # ... # enable feeds (RSS) url(r'^feeds/(?P<url>.*)/$', 'django.contrib.syndication.views.feed', {'feed_dict': feeds}, name='feeds_view'), ) I have tried using the following template tag: <a href="{% url feeds_view latest %}">RSS feeds</a> But the resulting link is not what want (http://my.domain.com/feeds//). It should be http://my.domain.com/feeds/latest/. For now, I am using a hack to generate the URL for the template: <a href="http://{{ request.META.HTTP_HOST }}/feeds/latest">RSS feeds</a> But, as you can see, it clearly is not DRY. Is there something I am missing?
[ "Unfortunately, URL reversing is not really possible with the current feed framework. The good news is that the feed framework has been completely refactored and can seamlessly integrate with Django's URL resolving mechanisms. This refactored feed framework will be delivered with Django 1.2, which should arrive at the end of April. You can read up on it in the docs or in a great article by Rob Hudson on DjangoAdvent.\n", "You're using keyword arguments so you should pass them as such :)\nTry this:\n<a href=\"{% url feeds_view url=\"latest\" %}\">RSS feeds</a>\n\n" ]
[ 3, 1 ]
[]
[]
[ "django", "django_templates", "django_urls", "python" ]
stackoverflow_0002604823_django_django_templates_django_urls_python.txt