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: Mysterious logging.basicConfig problem (Python) I'm writing a Python script to retrieve data from Flickr. For logging purposes, I have the following setup function: def init_log(logfile): format = '%(asctime)s - %(levelname)s - %(message)s' logging.basicConfig(filename=logfile,level=logging.DEBUG,format=format) I've tested this using the python shell and it works as expected, creating a file if one doesn't already exist. But calling it from within my program is where it stops working. The function is definitely being called, and the logfile parameter is working properly – logging.basicConfig just isn't creating any file. I'm not even getting any errors or warnings. My use of the Python Flickr API may be the culprit, but I doubt it. Any ideas? A: The logging.basicConfig function only does anything if the root logger has no handlers configured. If called when there are already some handlers attached to the root, it's basically a no-op (as is documented). Possibly the Python Flickr API does some logging, in which case you may find that basicConfig should be called earlier in your code.
Mysterious logging.basicConfig problem (Python)
I'm writing a Python script to retrieve data from Flickr. For logging purposes, I have the following setup function: def init_log(logfile): format = '%(asctime)s - %(levelname)s - %(message)s' logging.basicConfig(filename=logfile,level=logging.DEBUG,format=format) I've tested this using the python shell and it works as expected, creating a file if one doesn't already exist. But calling it from within my program is where it stops working. The function is definitely being called, and the logfile parameter is working properly – logging.basicConfig just isn't creating any file. I'm not even getting any errors or warnings. My use of the Python Flickr API may be the culprit, but I doubt it. Any ideas?
[ "The logging.basicConfig function only does anything if the root logger has no handlers configured. If called when there are already some handlers attached to the root, it's basically a no-op (as is documented).\nPossibly the Python Flickr API does some logging, in which case you may find that basicConfig should be called earlier in your code.\n" ]
[ 6 ]
[]
[]
[ "logging", "python" ]
stackoverflow_0002833186_logging_python.txt
Q: Parsing specific numeric data from csv file using python Good morning. I have series of data in cvs file like below, 1,,, 1,137.1,1198,1.6 2,159,300,0.4 3,176,253,0.3 4,197,231,0.3 5,198,525,0.7 6,199,326,0.4 7,215,183,0.2 8,217.1,178,0.2 9,244.2,416,0.5 10,245.1,316,0.4 I want to extract specific data from second column for example 217.1 and 245.1 and have them concatenated into a new file like, 8,217.1,178,0.2 10,245.1,316,0.4 I use cvs module to read my cvs file, but, I can't extract specific data as I desire. Could anyone kindly please help me. Thank you. A: results = [] reader = csv.reader(open('file.csv')) for line in reader: # iterate over the lines in the csv if line[1] in ['217.1','245.1']: # check if the 2nd element is one you're looking for results.append(line) # if so, add this line the the results list or if you want to convert to numbers, replace the last line with results.append([float(x) for x in line]) # append a list of floats instead of strings A: Edit: Misunderstood what the question was about, sorry. I'm not sure where the problem is, You mean row not column? As you can see in the docs for csv module You can easily access each row: >>> import csv >>> spamReader = csv.reader(open('eggs.csv'), delimiter=',', quotechar='|') >>> for row in spamReader: ... print ', '.join(row) Spam, Spam, Spam, Spam, Spam, Baked Beans Spam, Lovely Spam, Wonderful Spam And (ok my python days are some years old) for the columns you could e.g just do result += row[0] + "," + row[4] A: I hope this helps: import csv r = csv.reader(file(r'orig.csv')) w = csv.writer(file(r'new.csv', 'w')) for line in r: if line[0] in ['8','10']: # look for the data in lines 8 and 10 w.writerow(line)
Parsing specific numeric data from csv file using python
Good morning. I have series of data in cvs file like below, 1,,, 1,137.1,1198,1.6 2,159,300,0.4 3,176,253,0.3 4,197,231,0.3 5,198,525,0.7 6,199,326,0.4 7,215,183,0.2 8,217.1,178,0.2 9,244.2,416,0.5 10,245.1,316,0.4 I want to extract specific data from second column for example 217.1 and 245.1 and have them concatenated into a new file like, 8,217.1,178,0.2 10,245.1,316,0.4 I use cvs module to read my cvs file, but, I can't extract specific data as I desire. Could anyone kindly please help me. Thank you.
[ "results = []\nreader = csv.reader(open('file.csv'))\nfor line in reader: # iterate over the lines in the csv\n if line[1] in ['217.1','245.1']: # check if the 2nd element is one you're looking for\n results.append(line) # if so, add this line the the results list\n\nor if you want to convert to numbers, replace the last line with\n results.append([float(x) for x in line]) # append a list of floats instead of strings\n\n", "Edit: Misunderstood what the question was about, sorry.\nI'm not sure where the problem is, You mean row not column?\nAs you can see in the docs for csv module\nYou can easily access each row:\n>>> import csv \n>>> spamReader = csv.reader(open('eggs.csv'), delimiter=',', quotechar='|') \n>>> for row in spamReader: \n... print ', '.join(row) \nSpam, Spam, Spam, Spam, Spam, Baked Beans \nSpam, Lovely Spam, Wonderful Spam \n\nAnd (ok my python days are some years old) for the columns you could e.g just do\nresult += row[0] + \",\" + row[4]\n\n", "I hope this helps:\nimport csv\nr = csv.reader(file(r'orig.csv'))\nw = csv.writer(file(r'new.csv', 'w'))\nfor line in r:\n if line[0] in ['8','10']: # look for the data in lines 8 and 10\n w.writerow(line)\n\n" ]
[ 2, 0, 0 ]
[]
[]
[ "csv", "python" ]
stackoverflow_0002832944_csv_python.txt
Q: Calculating probability that a string has been randomized? - Python this is correlated to a question I asked earlier (question) I have a list of manually created strings such as: lucy87 gordan_king fancy_unicorn77 joplucky_kanga90 base_belong_to_narwhals and a list of randomized strings: johnkdf pancake90kgjd fancy_jagookfk manhattanljg What gives away that the last set of strings are randomized is that sequences such as 'kjg', 'jgf', 'lkd', ... . Any clever way I could separate strings that contain these apparently randomized strings from the crowd? I guess that this plays a lot on the fact that certain characters are more likely to be placed next to others (e.g. 'co', 'ka', 'ja', ...). Any ideas on this one? Kylotan mentioned Reverend, but I am not sure if it can be used fr such purpose. Help would be much appreciated! A: This is just a thought. I've never tried it myself... Build a bloom filter from hashing every (overlapping) 4-letter sequence found in a dictionary. Test a string by counting how many 4-letter sequences in the string don't hit the filter. The more misses, the more likely it is that the word contains random junk. Try tuning the size of the bloom filter and the number of letters per sequence. Also note (thanks @MihaiD) that you should include a dictionary of names, preferably from multiple languages, in the bloom filter to minimise false positives. A: What scores do you get if you run the strings through something like textcat? (I've seen a few different implementations of TextCat; maybe there's a Python one already out there; if not it's not a hard algorithm -- it's the data that's important.) I'm thinking that if you strip the numbers out, the first set of strings will be closer to the "English" result in TextCat than the ones with random stuff in them. How much closer and whether you might be able to use the TextCat data -- which is fundamentally based on which letters tend to be next to each other in particular languages -- to "pass" or "fail" a string is going to need some experimentation, though... A: Try using a vanilla bayes classifier. Should be enough for the general case. A: It seems to me like you are trying to write code to recognize a certian particular set of tiny stuff some spammer does to a string to get past your filters. What I don't see is what is stopping them from, after all your hard work, making a 10-second tweak to their algorithm and defeating your new filter. A: Some time ago I read a short article about random name generation, where they did the following: They built up a table that contains the information you already pointed at: "I guess that this plays a lot on the fact that certain characters are more likely to be placed next to others". So what they did was they read a whole dictionary and determined which letters were placed more likely to each others. I do not know, how much letters in a row they considered. Maybe you should try more than just two consecutive letters, let's say something between 3 and 6. Now I suggest you bild up such a table (maybe in a better data structural representation), that contains all "valid" consecutive letter combinations (and maybe their likelihood) and look if your name to be checked contains (almost) only such "valid" consecutive letters.
Calculating probability that a string has been randomized? - Python
this is correlated to a question I asked earlier (question) I have a list of manually created strings such as: lucy87 gordan_king fancy_unicorn77 joplucky_kanga90 base_belong_to_narwhals and a list of randomized strings: johnkdf pancake90kgjd fancy_jagookfk manhattanljg What gives away that the last set of strings are randomized is that sequences such as 'kjg', 'jgf', 'lkd', ... . Any clever way I could separate strings that contain these apparently randomized strings from the crowd? I guess that this plays a lot on the fact that certain characters are more likely to be placed next to others (e.g. 'co', 'ka', 'ja', ...). Any ideas on this one? Kylotan mentioned Reverend, but I am not sure if it can be used fr such purpose. Help would be much appreciated!
[ "This is just a thought. I've never tried it myself...\nBuild a bloom filter from hashing every (overlapping) 4-letter sequence found in a dictionary. Test a string by counting how many 4-letter sequences in the string don't hit the filter. The more misses, the more likely it is that the word contains random junk.\nTry tuning the size of the bloom filter and the number of letters per sequence.\nAlso note (thanks @MihaiD) that you should include a dictionary of names, preferably from multiple languages, in the bloom filter to minimise false positives.\n", "What scores do you get if you run the strings through something like textcat? (I've seen a few different implementations of TextCat; maybe there's a Python one already out there; if not it's not a hard algorithm -- it's the data that's important.)\nI'm thinking that if you strip the numbers out, the first set of strings will be closer to the \"English\" result in TextCat than the ones with random stuff in them.\nHow much closer and whether you might be able to use the TextCat data -- which is fundamentally based on which letters tend to be next to each other in particular languages -- to \"pass\" or \"fail\" a string is going to need some experimentation, though...\n", "Try using a vanilla bayes classifier. Should be enough for the general case.\n", "It seems to me like you are trying to write code to recognize a certian particular set of tiny stuff some spammer does to a string to get past your filters. What I don't see is what is stopping them from, after all your hard work, making a 10-second tweak to their algorithm and defeating your new filter.\n", "Some time ago I read a short article about random name generation, where they did the following: They built up a table that contains the information you already pointed at: \"I guess that this plays a lot on the fact that certain characters are more likely to be placed next to others\".\nSo what they did was they read a whole dictionary and determined which letters were placed more likely to each others. I do not know, how much letters in a row they considered. Maybe you should try more than just two consecutive letters, let's say something between 3 and 6.\nNow I suggest you bild up such a table (maybe in a better data structural representation), that contains all \"valid\" consecutive letter combinations (and maybe their likelihood) and look if your name to be checked contains (almost) only such \"valid\" consecutive letters.\n" ]
[ 4, 2, 1, 1, 1 ]
[]
[]
[ "pattern_recognition", "python", "spam_prevention", "string" ]
stackoverflow_0002833531_pattern_recognition_python_spam_prevention_string.txt
Q: Can't overload python socket.send As we can see, send method is not overloaded. from socket import socket class PolySocket(socket): def __init__(self,*p): print "PolySocket init" socket.__init__(self,*p) def sendall(self,*p): print "PolySocket sendall" return socket.sendall(self,*p) def send(self,*p): print "PolySocket send" return socket.send(self,*p) def connect(self,*p): print "connecting..." socket.connect(self,*p) print "connected" HOST="stackoverflow.com" PORT=80 readbuffer="" s=PolySocket() s.connect((HOST, PORT)) s.send("a") s.sendall("a") Output: PolySocket init connecting... connected PolySocket sendall A: I am sure you don't actually need it and there are other ways to solve your task (not subclassing but the real task). If you really need to mock object, go with proxy object: from socket import socket class PolySocket(object): def __init__(self, *p): print "PolySocket init" self._sock = socket(*p) def __getattr__(self, name): return getattr(self._sock, name) def sendall(self, *p): print "PolySocket sendall" return self._sock.sendall(*p) def send(self, *p): print "PolySocket send" return self._sock.send(*p) def connect(self, *p): print "connecting..." self._sock.connect(*p) print "connected" HOST = "stackoverflow.com" PORT = 80 readbuffer = "" s = PolySocket() s.connect((HOST, PORT)) s.send("a") s.sendall("a") Here's the output: % python foo.py PolySocket init connecting... connected PolySocket send PolySocket sendall
Can't overload python socket.send
As we can see, send method is not overloaded. from socket import socket class PolySocket(socket): def __init__(self,*p): print "PolySocket init" socket.__init__(self,*p) def sendall(self,*p): print "PolySocket sendall" return socket.sendall(self,*p) def send(self,*p): print "PolySocket send" return socket.send(self,*p) def connect(self,*p): print "connecting..." socket.connect(self,*p) print "connected" HOST="stackoverflow.com" PORT=80 readbuffer="" s=PolySocket() s.connect((HOST, PORT)) s.send("a") s.sendall("a") Output: PolySocket init connecting... connected PolySocket sendall
[ "I am sure you don't actually need it and there are other ways to solve your task (not subclassing but the real task).\nIf you really need to mock object, go with proxy object:\nfrom socket import socket\n\n\nclass PolySocket(object):\n def __init__(self, *p):\n print \"PolySocket init\"\n self._sock = socket(*p)\n\n def __getattr__(self, name):\n return getattr(self._sock, name)\n\n def sendall(self, *p):\n print \"PolySocket sendall\"\n return self._sock.sendall(*p)\n\n def send(self, *p):\n print \"PolySocket send\"\n return self._sock.send(*p)\n\n def connect(self, *p):\n print \"connecting...\"\n self._sock.connect(*p)\n print \"connected\"\n\nHOST = \"stackoverflow.com\"\nPORT = 80\nreadbuffer = \"\"\n\ns = PolySocket()\ns.connect((HOST, PORT))\ns.send(\"a\")\ns.sendall(\"a\")\n\nHere's the output:\n% python foo.py\nPolySocket init\nconnecting...\nconnected\nPolySocket send\nPolySocket sendall\n\n" ]
[ 9 ]
[]
[]
[ "inheritance", "overloading", "python" ]
stackoverflow_0002833022_inheritance_overloading_python.txt
Q: Data munging and data import scripting I need to write some scripts to carry out some tasks on my server (running Ubuntu server 8.04 TLS). The tasks are to be run periodically, so I will be running the scripts as cron jobs. I have divided the tasks into "group A" and "group B" - because (in my mind at least), they are a bit different. Task Group A import data from a file and possibly reformat it - by reformatting, I mean doing things like santizing the data, possibly normalizing it and or running calculations on 'columns' of the data Import the munged data into a database. For now, I am mostly using mySQL for the vast majority of imports - although some files will be imported into a sqlLite database. Note: The files will be mostly text files, although some of the files are in a binary format (my own proprietary format, written by a C++ application I developed). Task Group B Extract data from the database Perform calculations on the data and either insert or update tables in the database. My coding experience is is primarily as a C/C++ developer, although I have been using PHP as well for the last 2 years or so (+ a few other languages which are not relevant for the purpose of this question). I am from a Windows background, so I am still finding my feet in the Linux environment. My question is this - I need to write scripts to perform the tasks I described above. Although I suppose I could write a few C++ applications to be used in the shell scripts, I think it may be better to write them in a scripting language, but this may be a flawed assumption. My thinking is that it would be easier to modify things in a script - no need to rebuild etc for changes to functionality. Additionally, C++ data munging in C++ tends to involve more lines of code than "natural" scripting languages such as Perl, Python etc. Assuming that the majority of people on here agree that scripting is the way to go, herein lies my dilemma. Which scripting language do I use to perform the tasks above (giving my background)? My gut instinct tells me that Perl (shudder) would be the most obvious choice for performing all of the above tasks. BUT (and that is a big BUT). The mere mention of Perl makes my toes curl, as I had a very, very bad experience with it a while back (bought the Perl Camel book + 'data munging with Perl' many years ago, but could still not 'grok' it just felt too alien. The syntax seems quite unnatural to me - despite how many times I have tried to learn it - so if possible, I would really like to give it a miss. PHP (which I already know), also am not sure is a good candidate for scripting on the CLI (I have not seen many examples on how to do this etc - so I may be wrong). The last thing I must mention is that IF I have to learn a new language in order to do this, I cannot afford (time constraint) to spend more than a day, in learning the key commands/features required in order to do this (I can always learn the details of the language later, once I have actually deployed the scripts). So, which scripting language would you recommend (PHP, Python, Perl, [insert your favorite here]) - and most importantly WHY? Or, should I just stick to writing little C++ applications that I call in a shell script? Lastly, if you have suggested a scripting language, can you please show with a FEW lines (Perl mongers - I'm looking in your direction [nothing too cryptic!]) how I can use the language you suggested to do what I am trying to do i.e. load a CSV file into some kind of data structure where you can access data columns easily for data manipulation dump the columnar data into a mySQL table load data from mySQL table into a data structure that allows columns/rows to be accessed in the scripting language Hopefully, the snippets will allow me to quickly spot the languages that will pose the steepest learning curve for me - as well as those that simple, elegant and efficient (hopefully those two criteria [elegance and shallow learning curve] are not orthogonal - though I suspect they might be). A: Well, I was you a few years back. Didn't like Perl at all and would re-write any scripts my peers wrote in Perl back to Python - because I could not stand Perl. Long story short - let's just say I am fairly conversant with Perl now. I would recommend a book called "Impatient Perl" which explains the really important stuff quite nicely and which converted me to Perl. :) Another thing, is to install the Perl documentation on your computer - this was really important for me - easy and quick access to sample code, etc. Teaser Script for Task A - to read a file, format it and then write to the database. use autodie qw(:all); use Text::CSV_XS (); use DBI (); my $csv = Text::CSV_XS->new({binary => 1}) or die 'Cannot use CSV: ' . Text::CSV->error_diag; { my $database_handle = DBI->connect( 'dbi:SQLite:dbname=some_database_file.sqlite', undef, undef, { RaiseError => 1, AutoCommit => 1, }, ); $database_handle->do( q{CREATE TABLE something_table_or_other ('foo' CHAR(10), 'bar' CHAR(10), 'baz' CHAR(10), 'quux' CHAR(10), 'blah' CHAR(10))} ); my $statement_handle = $database_handle->prepare( q{INSERT INTO something_table_or_other ('foo', 'bar', 'baz', 'quux', 'blah') VALUES (?, ?, ?, ?, ?)} ); { open my $file_handle, '<:encoding(utf8)', 'data.csv'; while (my $columns_aref = $csv->getline($file_handle)) { my @columns = @{ $columns_aref }; # sanitize the columns - maybe substitute commas, numbers, etc. for (@columns) { s{,}{}; # substitutes commas with nothing } # insert columns into database now, using placeholders $statement_handle->execute(@columns); } } } Note: Given your current distaste for Perl, I would well recommend you do the above "tasks" in any programming language you are comfortable in. The above is only an attempt to show you that it might not be so cryptic after all. You get to be cryptic when you don't want to repeat yourself! :) A: import data from a file and possibly reformat it Python excels at this. Be sure to read up on the csv module so you don't waste time inventing it yourself. For binary data, you may have to use the struct module. [If you wrote the C++ program that produces the binary data, consider rewriting that program to stop using binary data. Your life will be simpler in the long run. Disk storage is cheaper than your time; highly compressed binary formats are more cost than value.] Import the munged data into a database. Extract data from the database Perform calculations on the data and either insert or update tables in the database. Use the mysqldb module for MySQL. SQLite is built-in to Python. Often, you'll want to use Object-Relational mapping rather than write your own SQL. Look at sqlobject and sqlalchemy for this. Also, before doing too much of this, buy a good book on data warehousing. Your two "task groups" sound like you're starting down the data warehousing road. It's easy to get this all fouled up through poor database design. Learn what a "Star Schema" is before you do anything else. A: I'd go with Python or Ruby. You will most likely find them much faster/easier to pick up than Perl, and they are still very powerful/efficient languages in their own right for "data munging". You should be able to pick up either of them in a day or less, not counting looking up random library functions every so often. To pick up Python quick: http://diveintopython3.ep.io/ I personally can't recommend a Ruby tutorial myself, but I'm sure others can chime in with good options. If you want to play around with either, http://www.trypython.org and http://www.tryruby.org each host online interactive-shell versions of the interpreters for their respective languages.
Data munging and data import scripting
I need to write some scripts to carry out some tasks on my server (running Ubuntu server 8.04 TLS). The tasks are to be run periodically, so I will be running the scripts as cron jobs. I have divided the tasks into "group A" and "group B" - because (in my mind at least), they are a bit different. Task Group A import data from a file and possibly reformat it - by reformatting, I mean doing things like santizing the data, possibly normalizing it and or running calculations on 'columns' of the data Import the munged data into a database. For now, I am mostly using mySQL for the vast majority of imports - although some files will be imported into a sqlLite database. Note: The files will be mostly text files, although some of the files are in a binary format (my own proprietary format, written by a C++ application I developed). Task Group B Extract data from the database Perform calculations on the data and either insert or update tables in the database. My coding experience is is primarily as a C/C++ developer, although I have been using PHP as well for the last 2 years or so (+ a few other languages which are not relevant for the purpose of this question). I am from a Windows background, so I am still finding my feet in the Linux environment. My question is this - I need to write scripts to perform the tasks I described above. Although I suppose I could write a few C++ applications to be used in the shell scripts, I think it may be better to write them in a scripting language, but this may be a flawed assumption. My thinking is that it would be easier to modify things in a script - no need to rebuild etc for changes to functionality. Additionally, C++ data munging in C++ tends to involve more lines of code than "natural" scripting languages such as Perl, Python etc. Assuming that the majority of people on here agree that scripting is the way to go, herein lies my dilemma. Which scripting language do I use to perform the tasks above (giving my background)? My gut instinct tells me that Perl (shudder) would be the most obvious choice for performing all of the above tasks. BUT (and that is a big BUT). The mere mention of Perl makes my toes curl, as I had a very, very bad experience with it a while back (bought the Perl Camel book + 'data munging with Perl' many years ago, but could still not 'grok' it just felt too alien. The syntax seems quite unnatural to me - despite how many times I have tried to learn it - so if possible, I would really like to give it a miss. PHP (which I already know), also am not sure is a good candidate for scripting on the CLI (I have not seen many examples on how to do this etc - so I may be wrong). The last thing I must mention is that IF I have to learn a new language in order to do this, I cannot afford (time constraint) to spend more than a day, in learning the key commands/features required in order to do this (I can always learn the details of the language later, once I have actually deployed the scripts). So, which scripting language would you recommend (PHP, Python, Perl, [insert your favorite here]) - and most importantly WHY? Or, should I just stick to writing little C++ applications that I call in a shell script? Lastly, if you have suggested a scripting language, can you please show with a FEW lines (Perl mongers - I'm looking in your direction [nothing too cryptic!]) how I can use the language you suggested to do what I am trying to do i.e. load a CSV file into some kind of data structure where you can access data columns easily for data manipulation dump the columnar data into a mySQL table load data from mySQL table into a data structure that allows columns/rows to be accessed in the scripting language Hopefully, the snippets will allow me to quickly spot the languages that will pose the steepest learning curve for me - as well as those that simple, elegant and efficient (hopefully those two criteria [elegance and shallow learning curve] are not orthogonal - though I suspect they might be).
[ "Well, I was you a few years back. Didn't like Perl at all and would re-write\nany scripts my peers wrote in Perl back to Python - because I could not stand Perl.\nLong story short - let's just say I am fairly conversant with Perl now.\nI would recommend a book called \"Impatient Perl\" which explains the really important\nstuff quite nicely and which converted me to Perl. :)\nAnother thing, is to install the Perl documentation on your computer - this was really important for me - easy and quick access to sample code, etc.\nTeaser Script for Task A - to read a file, format it and then write to the database.\nuse autodie qw(:all);\nuse Text::CSV_XS ();\nuse DBI ();\n\nmy $csv = Text::CSV_XS->new({binary => 1}) \n or die 'Cannot use CSV: ' . Text::CSV->error_diag;\n\n{\n my $database_handle = DBI->connect(\n 'dbi:SQLite:dbname=some_database_file.sqlite', undef, undef, {\n RaiseError => 1,\n AutoCommit => 1,\n },\n );\n $database_handle->do(\n q{CREATE TABLE something_table_or_other ('foo' CHAR(10), 'bar' CHAR(10), 'baz' CHAR(10), 'quux' CHAR(10), 'blah' CHAR(10))}\n );\n\n my $statement_handle = $database_handle->prepare(\n q{INSERT INTO something_table_or_other ('foo', 'bar', 'baz', 'quux', 'blah') VALUES (?, ?, ?, ?, ?)}\n );\n\n {\n open my $file_handle, '<:encoding(utf8)', 'data.csv';\n while (my $columns_aref = $csv->getline($file_handle)) {\n my @columns = @{ $columns_aref };\n\n # sanitize the columns - maybe substitute commas, numbers, etc.\n for (@columns) {\n s{,}{}; # substitutes commas with nothing\n }\n\n # insert columns into database now, using placeholders\n $statement_handle->execute(@columns);\n }\n }\n}\n\nNote: Given your current distaste for Perl, I would well recommend you do the above \"tasks\" in any programming language you are comfortable in. The above is only an attempt to show you that it might not be so cryptic after all. You get to be cryptic when you don't want to repeat yourself! :)\n", "\nimport data from a file and possibly reformat it \n\nPython excels at this. Be sure to read up on the csv module so you don't waste time inventing it yourself.\nFor binary data, you may have to use the struct module. [If you wrote the C++ program that produces the binary data, consider rewriting that program to stop using binary data. Your life will be simpler in the long run. Disk storage is cheaper than your time; highly compressed binary formats are more cost than value.]\n\nImport the munged data into a database. \n Extract data from the database\n Perform calculations on the data and either insert or update tables in the database.\n\nUse the mysqldb module for MySQL. SQLite is built-in to Python.\nOften, you'll want to use Object-Relational mapping rather than write your own SQL. Look at sqlobject and sqlalchemy for this.\nAlso, before doing too much of this, buy a good book on data warehousing. Your two \"task groups\" sound like you're starting down the data warehousing road. It's easy to get this all fouled up through poor database design. Learn what a \"Star Schema\" is before you do anything else.\n", "I'd go with Python or Ruby. You will most likely find them much faster/easier to pick up than Perl, and they are still very powerful/efficient languages in their own right for \"data munging\". You should be able to pick up either of them in a day or less, not counting looking up random library functions every so often.\nTo pick up Python quick: http://diveintopython3.ep.io/\nI personally can't recommend a Ruby tutorial myself, but I'm sure others can chime in with good options.\nIf you want to play around with either, http://www.trypython.org and http://www.tryruby.org each host online interactive-shell versions of the interpreters for their respective languages.\n" ]
[ 4, 3, 1 ]
[]
[]
[ "data_munging", "perl", "php", "python", "shell" ]
stackoverflow_0002833312_data_munging_perl_php_python_shell.txt
Q: Sending HTTP requests from App Engine Is it possible to send HTTP requests from my AppEngine application? I need to make some requests and pull some data from the other sites. A: Yes. More info here: http://code.google.com/appengine/docs/python/urlfetch/overview.html You can use the Python standard libraries urllib, urllib2 or httplib to make HTTP requests. When running in App Engine, these libraries perform HTTP requests using App Engine's URL fetch service, which runs on Google's scalable HTTP request infrastructure. Here's an example: import urllib from xml.dom import minidom from google.appengine.api import urlfetch params = urllib.urlencode({'p': loc_param, 'u': units,}) full_uri = '?'.join([url, params,]) result = urlfetch.fetch(full_uri) if result.status_code == 200: return minidom.parseString(result.content)
Sending HTTP requests from App Engine
Is it possible to send HTTP requests from my AppEngine application? I need to make some requests and pull some data from the other sites.
[ "Yes. More info here: http://code.google.com/appengine/docs/python/urlfetch/overview.html\n\nYou can use the Python standard\n libraries urllib, urllib2 or httplib\n to make HTTP requests. When running in\n App Engine, these libraries perform\n HTTP requests using App Engine's URL\n fetch service, which runs on Google's\n scalable HTTP request infrastructure.\n\nHere's an example:\nimport urllib\nfrom xml.dom import minidom\nfrom google.appengine.api import urlfetch\n\nparams = urllib.urlencode({'p': loc_param, 'u': units,})\nfull_uri = '?'.join([url, params,])\n\nresult = urlfetch.fetch(full_uri)\nif result.status_code == 200:\n return minidom.parseString(result.content)\n\n" ]
[ 4 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0002834687_google_app_engine_python.txt
Q: Trouble with encoding and urllib I'm loading web-page using urllib. Ther eis russian symbols, but page encoding is 'utf-8' 1 pageData = unicode(requestHandler.read()).decode('utf-8') UnicodeDecodeError: 'ascii' codec can't decode byte 0xd0 in position 262: ordinal not in range(128) 2 pageData = requestHandler.read() soupHandler = BeautifulSoup(pageData) print soupHandler.findAll(...) UnicodeEncodeError: 'ascii' codec can't encode characters in position 340-345: ordinal not in range(128) A: In your first snippet, the call unicode(requestHandler.read()) tells Python to convert the bytestring returned by read into unicode: since no code is specified for the conversion, ascii gets tried (and fails). It never gets to the point where you're going to call .decode (which would make no sense to call on that unicode object anyway). Either use unicode(requestHandler.read(), 'utf-8'), or requestHandler.read().decode('utf-8'): either of these should produce a correct unicode object if the encoding is indeed utf-8 (the presence of that D0 byte suggests it may not be, but it's impossible to guess from being shown a single non-ascii character out of context). printing Unicode data is a different issue and requires a well configured and cooperative terminal emulator -- one that lets Python set sys.stdout.encoding on startup. For example, on a Mac, using Apple's Terminal.App: >>> sys.stdout.encoding 'UTF-8' so the printing of Unicode objects works fine here: >>> print u'\xabutf8\xbb' «utf8» as does the printing of utf8-encoded byte strings: >>> print u'\xabutf8\xbb'.encode('utf8') «utf8» but on other machines only the latter will work (using the terminal emulator's own encoding, which you need to discover on your own because the terminal emulator isn't telling Python;-). A: If requestHandler.read() delivers a UTF-8 encoded stream, then pageData = requestHandler.read().decode('utf-8') will decode this into a Unicode string (at which point, as Dietrich Epp noted correctly), the unicode() call is not necessary anymore. If it throws an exception, then the input is obviously not UTF-8-encoded.
Trouble with encoding and urllib
I'm loading web-page using urllib. Ther eis russian symbols, but page encoding is 'utf-8' 1 pageData = unicode(requestHandler.read()).decode('utf-8') UnicodeDecodeError: 'ascii' codec can't decode byte 0xd0 in position 262: ordinal not in range(128) 2 pageData = requestHandler.read() soupHandler = BeautifulSoup(pageData) print soupHandler.findAll(...) UnicodeEncodeError: 'ascii' codec can't encode characters in position 340-345: ordinal not in range(128)
[ "In your first snippet, the call unicode(requestHandler.read()) tells Python to convert the bytestring returned by read into unicode: since no code is specified for the conversion, ascii gets tried (and fails). It never gets to the point where you're going to call .decode (which would make no sense to call on that unicode object anyway).\nEither use unicode(requestHandler.read(), 'utf-8'), or requestHandler.read().decode('utf-8'): either of these should produce a correct unicode object if the encoding is indeed utf-8 (the presence of that D0 byte suggests it may not be, but it's impossible to guess from being shown a single non-ascii character out of context).\nprinting Unicode data is a different issue and requires a well configured and cooperative terminal emulator -- one that lets Python set sys.stdout.encoding on startup. For example, on a Mac, using Apple's Terminal.App:\n>>> sys.stdout.encoding\n'UTF-8'\n\nso the printing of Unicode objects works fine here:\n>>> print u'\\xabutf8\\xbb'\n«utf8»\n\nas does the printing of utf8-encoded byte strings:\n>>> print u'\\xabutf8\\xbb'.encode('utf8')\n«utf8»\n\nbut on other machines only the latter will work (using the terminal emulator's own encoding, which you need to discover on your own because the terminal emulator isn't telling Python;-).\n", "If requestHandler.read() delivers a UTF-8 encoded stream, then\npageData = requestHandler.read().decode('utf-8')\n\nwill decode this into a Unicode string (at which point, as Dietrich Epp noted correctly), the unicode() call is not necessary anymore.\nIf it throws an exception, then the input is obviously not UTF-8-encoded.\n" ]
[ 2, 1 ]
[]
[]
[ "encoding", "python", "urllib" ]
stackoverflow_0002834714_encoding_python_urllib.txt
Q: Python's behavior for rich comparison (Or, when Decimal('100.0') < .01) So I have a one liner: import decimal; h = decimal.Decimal('100.0'); (h > .01, h < .01, h.__gt__(.01), h.__lt__(.01)) All it does is make a Decimal object holding 100.0, and compares it to .01 (the float) in various ways. My result is: >>> import decimal; h = decimal.Decimal('100.0'); (h > .01, h < .01, h.__gt__(.01), h.__lt__(.01)) (False, True, NotImplemented, NotImplemented) From the docs: "A rich comparison method may return the singleton NotImplemented if it does not implement the operation for a given pair of arguments." So really there are three questions here. When a rich comparison method returns NotImplemented, what happens? Why doesn't it raise an Exception? When it gets NotImplemented, why does it return False in the first case, and True in the second? bool(NotImplemented) should be a constant. Does it simply fall back to id() checking? It seems no (or yes, but backwards): (ignore this line, formatting is screwed up and this fixes it) from decimal import Decimal h = Decimal('100.0') f = .01 print h < f, id(h) < id(f) print h > f, id(h) > id(f) My results were tested on: Python 2.6.4 (r264:75708, Oct 26 2009, 08:23:19) [MSC v.1500 32 bit (Intel)] on win32 Python 2.6.5 (r265:79096, Mar 19 2010, 21:48:26) [MSC v.1500 32 bit (Intel)] on win32 Edit: Documentation about ordering: http://docs.python.org/library/stdtypes.html#comparisons A: When a rich comparison method returns NotImplemented, what happens? Why doesn't it raise an Exception? it delegates to the converse method (e.g., __lt__ when the operator is >) RHS in the comparison (the float) -- which in this case also returns NotImplemented -- and finally falls back to Python 2's silly old rules for heterogeneous comparisons. When it gets NotImplemented, why does it return False in the first case, and True in the second? bool(NotImplemented) should be a constant. No bool involved -- since both sides of the comparison return NotImplemented (due to a deliberate design decision to NOT support any operation between decimals and floats), the silly old rules are used as a fallback (and in a recent-enough version will be comparing the types, not the instances -- id has nothing to do with it, therefore). In Python 3, such an unsupported heterogeneous comparison would fail, and raise a clear exception, but in Python 2, for backwards compatibility, that just can't happen -- it must keep behaving in the silly way it's behaved throughout Python 2's lifetime. Introducing backwards incompatibilities to fix what are now considered design errors, like this part about het comparisons, was the core reason to introduce Python 3. As long as you're sticking to Python 2 (e.g. because it has more third party extensions, etc), you need to grin and bear with these imperfections that are fixed in Python 3 only. A: I have Python 2.6.4 and your example works fine, i.e., I find (True, False, NotImplemented, NotImplemented) which is expected. I don't know why you obtain different results. About id: id has nothing to do with comparisons, so under no circumstances should you compare a and b by id(a) < id(b), that does not make any sense. id is a bit like an adress in memory, so comparing them makes no sense at all.
Python's behavior for rich comparison (Or, when Decimal('100.0') < .01)
So I have a one liner: import decimal; h = decimal.Decimal('100.0'); (h > .01, h < .01, h.__gt__(.01), h.__lt__(.01)) All it does is make a Decimal object holding 100.0, and compares it to .01 (the float) in various ways. My result is: >>> import decimal; h = decimal.Decimal('100.0'); (h > .01, h < .01, h.__gt__(.01), h.__lt__(.01)) (False, True, NotImplemented, NotImplemented) From the docs: "A rich comparison method may return the singleton NotImplemented if it does not implement the operation for a given pair of arguments." So really there are three questions here. When a rich comparison method returns NotImplemented, what happens? Why doesn't it raise an Exception? When it gets NotImplemented, why does it return False in the first case, and True in the second? bool(NotImplemented) should be a constant. Does it simply fall back to id() checking? It seems no (or yes, but backwards): (ignore this line, formatting is screwed up and this fixes it) from decimal import Decimal h = Decimal('100.0') f = .01 print h < f, id(h) < id(f) print h > f, id(h) > id(f) My results were tested on: Python 2.6.4 (r264:75708, Oct 26 2009, 08:23:19) [MSC v.1500 32 bit (Intel)] on win32 Python 2.6.5 (r265:79096, Mar 19 2010, 21:48:26) [MSC v.1500 32 bit (Intel)] on win32 Edit: Documentation about ordering: http://docs.python.org/library/stdtypes.html#comparisons
[ "\nWhen a rich comparison method returns\n NotImplemented, what happens? Why\n doesn't it raise an Exception?\n\nit delegates to the converse method (e.g., __lt__ when the operator is >) RHS in the comparison (the float) -- which in this case also returns NotImplemented -- and finally falls back to Python 2's silly old rules for heterogeneous comparisons.\n\nWhen it gets NotImplemented, why does\n it return False in the first case, and\n True in the second?\n bool(NotImplemented) should be a\n constant.\n\nNo bool involved -- since both sides of the comparison return NotImplemented (due to a deliberate design decision to NOT support any operation between decimals and floats), the silly old rules are used as a fallback (and in a recent-enough version will be comparing the types, not the instances -- id has nothing to do with it, therefore). In Python 3, such an unsupported heterogeneous comparison would fail, and raise a clear exception, but in Python 2, for backwards compatibility, that just can't happen -- it must keep behaving in the silly way it's behaved throughout Python 2's lifetime.\nIntroducing backwards incompatibilities to fix what are now considered design errors, like this part about het comparisons, was the core reason to introduce Python 3. As long as you're sticking to Python 2 (e.g. because it has more third party extensions, etc), you need to grin and bear with these imperfections that are fixed in Python 3 only.\n", "I have Python 2.6.4 and your example works fine, i.e., I find \n(True, False, NotImplemented, NotImplemented)\n\nwhich is expected. I don't know why you obtain different results.\nAbout id: id has nothing to do with comparisons, so under no circumstances should you compare a and b by id(a) < id(b), that does not make any sense. id is a bit like an adress in memory, so comparing them makes no sense at all.\n" ]
[ 6, 0 ]
[]
[]
[ "compare", "decimal", "floating_point", "python" ]
stackoverflow_0002834953_compare_decimal_floating_point_python.txt
Q: Python - problem in importing new module - libgmail I downloaded Python module libgmail from sourceforge and extracted all the files in the archive. The archive had setup.py, so I went to that directory in command prompt and did setup.py install I am getting the following error message I:\libgmail-0.1.11>setup.py install Traceback (most recent call last): File "I:\libgmail-0.1.11\setup.py", line 7, in ? import libgmail File "I:\libgmail-0.1.11\libgmail.py", line 36, in ? import mechanize as ClientCookie ImportError: No module named mechanize This may be trivial, but I am new to python. So plz guide what to do. please note, I am using python 2.4 and using Windows-XP. Thank you MicroKernel A: I think this lib depends on this one: http://wwwsearch.sourceforge.net/mechanize/ Try installing it first. A: You need to download and install the module called mechanize. Depending on your operating system (ie. Linux), your package manager probably has something for this, otherwise you will need to google it, and follow it's installation instructions. A: easy_install mechanize If this doesn't work, you need to fix your PATH environment variable to include path to your python installation directory\scripts. easy_install will save you a lot of time in future. P.S.: Python 2.4 is 6 years old, you should really consider at least 2.6.
Python - problem in importing new module - libgmail
I downloaded Python module libgmail from sourceforge and extracted all the files in the archive. The archive had setup.py, so I went to that directory in command prompt and did setup.py install I am getting the following error message I:\libgmail-0.1.11>setup.py install Traceback (most recent call last): File "I:\libgmail-0.1.11\setup.py", line 7, in ? import libgmail File "I:\libgmail-0.1.11\libgmail.py", line 36, in ? import mechanize as ClientCookie ImportError: No module named mechanize This may be trivial, but I am new to python. So plz guide what to do. please note, I am using python 2.4 and using Windows-XP. Thank you MicroKernel
[ "I think this lib depends on this one:\nhttp://wwwsearch.sourceforge.net/mechanize/\nTry installing it first.\n", "You need to download and install the module called mechanize. Depending on your operating system (ie. Linux), your package manager probably has something for this, otherwise you will need to google it, and follow it's installation instructions.\n", "easy_install mechanize\nIf this doesn't work, you need to fix your PATH environment variable to include path to your python installation directory\\scripts. easy_install will save you a lot of time in future.\nP.S.: Python 2.4 is 6 years old, you should really consider at least 2.6.\n" ]
[ 4, 2, 0 ]
[]
[]
[ "importerror", "libgmail", "python", "python_module" ]
stackoverflow_0002834143_importerror_libgmail_python_python_module.txt
Q: lxml unicode entity parse problems I'm using lxml as follows to parse an exported XML file from another system: xmldoc = open(filename) etree.parse(xmldoc) But im getting: lxml.etree.XMLSyntaxError: Entity 'eacute' not defined, line 4495, column 46 Obviously it's having problems with unicode entity names - but how would i get round this? Via open() or parse()? Edit: I had forgotten to include my DTD in the same folder - it's there now and has the following declaration: <!ENTITY eacute "&#233;"> and is referred to (and always was) in xmldoc as so: <?xml version="1.0" encoding="ISO-8859-1" ?> <!DOCTYPE DScribeDatabase SYSTEM "foo.dtd"> Yet I still get the same problem ... does the DTD need to be declared in Python too? A: eacute is not a predefined entity in XML. To include an &eacute; entity reference in an XML file, it must have a <!DOCTYPE> declaration pointing to a DTD (such as an XHTML 1.0 DTD) that defines the entity. If the XML uses &eacute; but doesn't have a <!DOCTYPE>, it is not well-formed and the system that exported it needs to be fixed. (There isn't a good reason to use an entity reference to represent é in an XML file. The character reference &#233; is understood everywhere without entity definitions, if the file can't simply include a raw UTF-8 é for some reason.)
lxml unicode entity parse problems
I'm using lxml as follows to parse an exported XML file from another system: xmldoc = open(filename) etree.parse(xmldoc) But im getting: lxml.etree.XMLSyntaxError: Entity 'eacute' not defined, line 4495, column 46 Obviously it's having problems with unicode entity names - but how would i get round this? Via open() or parse()? Edit: I had forgotten to include my DTD in the same folder - it's there now and has the following declaration: <!ENTITY eacute "&#233;"> and is referred to (and always was) in xmldoc as so: <?xml version="1.0" encoding="ISO-8859-1" ?> <!DOCTYPE DScribeDatabase SYSTEM "foo.dtd"> Yet I still get the same problem ... does the DTD need to be declared in Python too?
[ "eacute is not a predefined entity in XML. To include an &eacute; entity reference in an XML file, it must have a <!DOCTYPE> declaration pointing to a DTD (such as an XHTML 1.0 DTD) that defines the entity.\nIf the XML uses &eacute; but doesn't have a <!DOCTYPE>, it is not well-formed and the system that exported it needs to be fixed.\n(There isn't a good reason to use an entity reference to represent é in an XML file. The character reference &#233; is understood everywhere without entity definitions, if the file can't simply include a raw UTF-8 é for some reason.)\n" ]
[ 6 ]
[]
[]
[ "lxml", "python", "unicode", "xml" ]
stackoverflow_0002835077_lxml_python_unicode_xml.txt
Q: Reset selection of wx.lib.calendar.Calendar control? I have a wx.lib.calendar.Calendar control (not wx.lib.calendar.CalendarCtrl!). I am selecting a number of days using the following function call: self.cal.AddSelect([days], 'green', 'white') This works, and draws the days highlighted. However, I cannot work out how to reverse this (i.e., clear the selection so the days go back to their normal colouring). Any hints, please? A: Couldn't you just do it manually? self.cal.AddSelect([days], 'black', 'white')
Reset selection of wx.lib.calendar.Calendar control?
I have a wx.lib.calendar.Calendar control (not wx.lib.calendar.CalendarCtrl!). I am selecting a number of days using the following function call: self.cal.AddSelect([days], 'green', 'white') This works, and draws the days highlighted. However, I cannot work out how to reverse this (i.e., clear the selection so the days go back to their normal colouring). Any hints, please?
[ "Couldn't you just do it manually?\nself.cal.AddSelect([days], 'black', 'white')\n\n" ]
[ 0 ]
[]
[]
[ "calendar", "python", "wxpython", "wxwidgets" ]
stackoverflow_0002834770_calendar_python_wxpython_wxwidgets.txt
Q: IDN aware tools to encode/decode human readable IRI to/from valid URI Let's assume a user enter address of some resource and we need to translate it to: <a href="valid URI here">human readable form</a> HTML4 specification refers to RFC 3986 which allows only ASCII alphanumeric characters and dash in host part and all non-ASCII character in other parts should be percent-encoded. That's what I want to put in href attribute to make link working properly in all browsers. IDN should be encoded with Punycode. HTML5 draft refers to RFC 3987 which also allows percent-encoded unicode characters in host part and a large subset of unicode in both host and other parts without encoding them. User may enter address in any of these forms. To provide human readable form of it I need to decode all printable characters. Note that some parts of address might not correspond to valid UTF-8 sequences, usually when target site uses some other character encoding. An example of what I'd like to get: <a href="http://xn--80aswg.xn--p1ai/%D0%BF%D1%83%D1%82%D1%8C?%D0%B7%D0%B0%D0%BF%D1%80%D0%BE%D1%81"> http://сайт.рф/путь?запрос</a> Are there any tools to solve these tasks? I'm especially interested in libraries for Python and JavaScript. Update: I know there is a way to do percent and Punycode (without proper normalization, but I can live with it) encoding/decoding in Python and JavaScript. The whole task needs much more work and there are some pitfalls (some characters should be always encoded or never encoded depending on context). I wonder if there are ready to use libraries for the whole problem, since it seems to be quite common and modern browsers already do such conversions (try typing http://%D1%81%D0%B0%D0%B9%D1%82.%D1%80%D1%84/ in Google Chrome and it will be replaced with http://сайт.рф/, but use Host: xn--80aswg.xn--p1ai in HTTP request). Update2: Vinay Sajip pointed that Werkzeug has iri_to_uri and uri_to_iri functions that handles most cases correctly. I've found only 2 cases where it fails so far: percent-encoded host (quite easy to fix) and invalid utf-8 sequences (it's a bit tricky to do nicely, but shouldn't be a problem). I'm still looking for library in JavaScript. It's not hard to write, but I'd prefer to avoid inventing the wheel. A: If I understand you correctly, then you can use the batteries included in Python: # -*- coding: utf-8 -*- import urllib import urlparse URL1 = u'http://сайт.рф/путь?запрос' URL2 = 'http://%D1%81%D0%B0%D0%B9%D1%82.%D1%80%D1%84/' def to_idn(url): parts = list(urlparse.urlparse(url)) parts[1] = parts[1].encode('idna') parts[2:] = [urllib.quote(s.encode('utf-8')) for s in parts[2:]] return urlparse.urlunparse(parts) def from_idn(url): return urllib.unquote(url) print to_idn(URL1) print from_idn(URL2) print to_idn(from_idn(URL2).decode('utf-8')) which prints http://xn--80aswg.xn--p1ai/%D0%BF%D1%83%D1%82%D1%8C?%D0%B7%D0%B0%D0%BF%D1%80%D0%BE%D1%81 http://сайт.рф/ http://xn--80aswg.xn--p1ai/ which looks like what you want. I'm not sure what special cases you mean - perhaps you could give some examples of the pitfalls you're referring to? Update: I just remembered, Werkzeug has iri_to_uri and uri_to_iri functions in versions 0.6 and later (links are to the relevant part of the docs). Further update: Sorry, I hadn't noticed that you're looking for a JavaScript implementation as well as a Python one. An existing public domain Javascript implementation of punycode is here. I can't vouch for it, though. And of course you can use the built-in JavaScript encodeURI/decodeURI APIs.
IDN aware tools to encode/decode human readable IRI to/from valid URI
Let's assume a user enter address of some resource and we need to translate it to: <a href="valid URI here">human readable form</a> HTML4 specification refers to RFC 3986 which allows only ASCII alphanumeric characters and dash in host part and all non-ASCII character in other parts should be percent-encoded. That's what I want to put in href attribute to make link working properly in all browsers. IDN should be encoded with Punycode. HTML5 draft refers to RFC 3987 which also allows percent-encoded unicode characters in host part and a large subset of unicode in both host and other parts without encoding them. User may enter address in any of these forms. To provide human readable form of it I need to decode all printable characters. Note that some parts of address might not correspond to valid UTF-8 sequences, usually when target site uses some other character encoding. An example of what I'd like to get: <a href="http://xn--80aswg.xn--p1ai/%D0%BF%D1%83%D1%82%D1%8C?%D0%B7%D0%B0%D0%BF%D1%80%D0%BE%D1%81"> http://сайт.рф/путь?запрос</a> Are there any tools to solve these tasks? I'm especially interested in libraries for Python and JavaScript. Update: I know there is a way to do percent and Punycode (without proper normalization, but I can live with it) encoding/decoding in Python and JavaScript. The whole task needs much more work and there are some pitfalls (some characters should be always encoded or never encoded depending on context). I wonder if there are ready to use libraries for the whole problem, since it seems to be quite common and modern browsers already do such conversions (try typing http://%D1%81%D0%B0%D0%B9%D1%82.%D1%80%D1%84/ in Google Chrome and it will be replaced with http://сайт.рф/, but use Host: xn--80aswg.xn--p1ai in HTTP request). Update2: Vinay Sajip pointed that Werkzeug has iri_to_uri and uri_to_iri functions that handles most cases correctly. I've found only 2 cases where it fails so far: percent-encoded host (quite easy to fix) and invalid utf-8 sequences (it's a bit tricky to do nicely, but shouldn't be a problem). I'm still looking for library in JavaScript. It's not hard to write, but I'd prefer to avoid inventing the wheel.
[ "If I understand you correctly, then you can use the batteries included in Python:\n# -*- coding: utf-8 -*-\n\nimport urllib\nimport urlparse\n\nURL1 = u'http://сайт.рф/путь?запрос'\nURL2 = 'http://%D1%81%D0%B0%D0%B9%D1%82.%D1%80%D1%84/'\n\ndef to_idn(url):\n parts = list(urlparse.urlparse(url))\n parts[1] = parts[1].encode('idna')\n parts[2:] = [urllib.quote(s.encode('utf-8')) for s in parts[2:]]\n return urlparse.urlunparse(parts)\n\ndef from_idn(url):\n return urllib.unquote(url)\n\nprint to_idn(URL1)\nprint from_idn(URL2)\nprint to_idn(from_idn(URL2).decode('utf-8'))\n\nwhich prints\nhttp://xn--80aswg.xn--p1ai/%D0%BF%D1%83%D1%82%D1%8C?%D0%B7%D0%B0%D0%BF%D1%80%D0%BE%D1%81\nhttp://сайт.рф/\nhttp://xn--80aswg.xn--p1ai/\n\nwhich looks like what you want. I'm not sure what special cases you mean - perhaps you could give some examples of the pitfalls you're referring to?\nUpdate: I just remembered, Werkzeug has iri_to_uri and uri_to_iri functions in versions 0.6 and later (links are to the relevant part of the docs).\nFurther update: Sorry, I hadn't noticed that you're looking for a JavaScript implementation as well as a Python one. An existing public domain Javascript implementation of punycode is here. I can't vouch for it, though. And of course you can use the built-in JavaScript encodeURI/decodeURI APIs.\n" ]
[ 2 ]
[]
[]
[ "html", "idn", "iri", "javascript", "python" ]
stackoverflow_0002833013_html_idn_iri_javascript_python.txt
Q: How to extract longest of overlapping groups? How can I extract the longest of groups which start the same way For example, from a given string, I want to extract the longest match to either CS or CSI. I tried this "(CS|CSI).*" and it it will return CS rather than CSI even if CSI is available. If I do "(CSI|CS).*" then I do get CSI if it's a match, so I gues the solution is to always place the shorter of the overlaping groups after the longer one. Is there a clearer way to express this with re's? somehow it feels confusing that the result depends on the order you link the groups. A: No, that's just how it works, at least in Perl-derived regex flavors like Python, JavaScript, .NET, etc. http://www.regular-expressions.info/alternation.html A: As Alan says, the patterns will be matched in the order you specified them. If you want to match on the longest of overlapping literal strings, you need the longest one to appear first. But you can organize your strings longest-to-shortest automatically, if you like: >>> '|'.join(sorted('cs csi miami vice'.split(), key=len, reverse=True)) 'miami|vice|csi|cs' A: Intrigued to know the right way of doing this, if it helps any you can always build up your regex like: import re string_to_look_in = "AUHDASOHDCSIAAOSLINDASOI" string_to_match = "CSIABC" re_to_use = "(" + "|".join([string_to_match[0:i] for i in range(len(string_to_match),0,-1)]) + ")" re_result = re.search(re_to_use,string_to_look_in) print string_to_look_in[re_result.start():re_result.end()]
How to extract longest of overlapping groups?
How can I extract the longest of groups which start the same way For example, from a given string, I want to extract the longest match to either CS or CSI. I tried this "(CS|CSI).*" and it it will return CS rather than CSI even if CSI is available. If I do "(CSI|CS).*" then I do get CSI if it's a match, so I gues the solution is to always place the shorter of the overlaping groups after the longer one. Is there a clearer way to express this with re's? somehow it feels confusing that the result depends on the order you link the groups.
[ "No, that's just how it works, at least in Perl-derived regex flavors like Python, JavaScript, .NET, etc.\nhttp://www.regular-expressions.info/alternation.html\n", "As Alan says, the patterns will be matched in the order you specified them.\nIf you want to match on the longest of overlapping literal strings, you need the longest one to appear first. But you can organize your strings longest-to-shortest automatically, if you like:\n>>> '|'.join(sorted('cs csi miami vice'.split(), key=len, reverse=True))\n'miami|vice|csi|cs'\n\n", "Intrigued to know the right way of doing this, if it helps any you can always build up your regex like:\nimport re\n\nstring_to_look_in = \"AUHDASOHDCSIAAOSLINDASOI\"\nstring_to_match = \"CSIABC\"\n\nre_to_use = \"(\" + \"|\".join([string_to_match[0:i] for i in range(len(string_to_match),0,-1)]) + \")\"\n\nre_result = re.search(re_to_use,string_to_look_in)\n\nprint string_to_look_in[re_result.start():re_result.end()]\n\n" ]
[ 5, 2, 0 ]
[ "similar functionality is present in vim editor (\"sequence of optionally matched atoms\"), where e.g. col\\%[umn] matches col in color, colum in columbus and full column.\ni am not aware if similar functionality in python re,\nyou can use nested anonymous groups, each one followed by ? quantifier, for that:\n>>> import re\n>>> words = ['color', 'columbus', 'column']\n>>> rex = re.compile(r'col(?:u(?:m(?:n)?)?)?')\n>>> for w in words: print rex.findall(w)\n['col']\n['colum']\n['column']\n\n" ]
[ -1 ]
[ "python", "regex" ]
stackoverflow_0002835206_python_regex.txt
Q: Why can't I access the instance.__class__ attribute in Python? I'm new to Python, and I know I must be missing something pretty simple, but why doesn't this very, very simple code work? class myClass: pass testObject = myClass print testObject.__class__ I get the following error: AttributeError: class myClass has no attribute '__class__' Doesn't every object in Python have a __class__ attribute? A: I think I realized my mistake. I thought that the code testObject = myClass was creating a new instance/object of the class, but it was actually assigning a reference to the class itself. I changed the code to: class myClass: pass testObject = myClass() print testObject.__class__ and it now works as I was expecting A: Most, but not all, objects in Python have a __class__ attribute. You can usually access it to determine an object's class. You can get the class of any object by calling type on it. >>> class myClass: ... pass ... >>> testObject = myClass >>> type(testObject) <type 'classobj'> A: Old-style classes don't have a __class__ attribute. class myClass(object): pass
Why can't I access the instance.__class__ attribute in Python?
I'm new to Python, and I know I must be missing something pretty simple, but why doesn't this very, very simple code work? class myClass: pass testObject = myClass print testObject.__class__ I get the following error: AttributeError: class myClass has no attribute '__class__' Doesn't every object in Python have a __class__ attribute?
[ "I think I realized my mistake. I thought that the code testObject = myClass was creating a new instance/object of the class, but it was actually assigning a reference to the class itself. I changed the code to:\nclass myClass: \n pass \n\ntestObject = myClass() \nprint testObject.__class__ \n\nand it now works as I was expecting\n", "Most, but not all, objects in Python have a __class__ attribute. You can usually access it to determine an object's class.\nYou can get the class of any object by calling type on it.\n>>> class myClass:\n... pass\n... \n>>> testObject = myClass\n>>> type(testObject)\n<type 'classobj'>\n\n", "Old-style classes don't have a __class__ attribute.\nclass myClass(object):\n pass\n\n" ]
[ 3, 2, 1 ]
[]
[]
[ "class_attribute", "python" ]
stackoverflow_0002835558_class_attribute_python.txt
Q: getting global name not defined error i have the following class class notify(): def __init__(self,server="localhost", port=23053): self.host = server self.port = port register = gntp.GNTPRegister() register.add_header('Application-Name',"SVN Monitor") register.add_notification("svnupdate",True) growl(register) def svn_update(self, author="Unknown", files=0): notice = gntp.GNTPNotice() notice.add_header('Application-Name',"SVN Monitor") notice.add_header('Notification-Name', "svnupdate") notice.add_header('Notification-Title',"SVN Commit") # notice.add_header('Notification-Icon',"") notice.add_header('Notification-Text',Msg) growl(notice) def growl(data): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((self.host,self.port)) s.send(data) response = gntp.parse_gntp(s.recv(1024)) print response s.close() but when ever i try to use this class via the follwoing code i get NameError: global name 'growl' is not defined from growlnotify import * n = notify() n.svn_update() any one has an idea what is going on here ? cheers nash A: The instance scope is not searched as part of scope resolution in Python. If you want to call a method on self then you must prefix it with a reference to self. self.growl(register) A: growl is not a global symbol, it's a member of the notify class. Inside the notify class, call the growl method as follows: self.growl(notice)
getting global name not defined error
i have the following class class notify(): def __init__(self,server="localhost", port=23053): self.host = server self.port = port register = gntp.GNTPRegister() register.add_header('Application-Name',"SVN Monitor") register.add_notification("svnupdate",True) growl(register) def svn_update(self, author="Unknown", files=0): notice = gntp.GNTPNotice() notice.add_header('Application-Name',"SVN Monitor") notice.add_header('Notification-Name', "svnupdate") notice.add_header('Notification-Title',"SVN Commit") # notice.add_header('Notification-Icon',"") notice.add_header('Notification-Text',Msg) growl(notice) def growl(data): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((self.host,self.port)) s.send(data) response = gntp.parse_gntp(s.recv(1024)) print response s.close() but when ever i try to use this class via the follwoing code i get NameError: global name 'growl' is not defined from growlnotify import * n = notify() n.svn_update() any one has an idea what is going on here ? cheers nash
[ "The instance scope is not searched as part of scope resolution in Python. If you want to call a method on self then you must prefix it with a reference to self.\nself.growl(register)\n\n", "growl is not a global symbol, it's a member of the notify class.\nInside the notify class, call the growl method as follows: \nself.growl(notice)\n\n" ]
[ 3, 1 ]
[]
[]
[ "growlnotify", "python" ]
stackoverflow_0002835684_growlnotify_python.txt
Q: Using xAuth from python using tweepy I am trying to write a twitter client application in python. I would like to use xAuth for authentication. My choice on the library is tweepy, because it seems that it knows everything I need. Here is my problem: >>> import tweepy >>> auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) >>> auth.get_xauth_access_token('username', 'password') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "tweepy/auth.py", line 152, in get_xauth_access_token raise TweepError(e) tweepy.error.TweepError: HTTP Error 401: Unauthorized The username and the password is correct, I can log in with them. The CONSUMER_{KEY,SECRET} also valid, I copypasted them from the page of my application. Do you have any idea why the code above fails? A: Have you emailed Twitter support to get them to turn on xAuth for your application? Twitter only want xAuth to be used by desktop and mobile applications, so registered applications have xAuth disabled by default, and you need someone at Twitter to turn it on for you. If you application doesn't have xAuth enabled, you get a 401. To get xAuth enabled, send an email to api@twitter.com with the name of your application and the reason it needs xAuth instead of plain old OAuth (eg. it's not appropriate to pop up a web browser in my desktop application).
Using xAuth from python using tweepy
I am trying to write a twitter client application in python. I would like to use xAuth for authentication. My choice on the library is tweepy, because it seems that it knows everything I need. Here is my problem: >>> import tweepy >>> auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) >>> auth.get_xauth_access_token('username', 'password') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "tweepy/auth.py", line 152, in get_xauth_access_token raise TweepError(e) tweepy.error.TweepError: HTTP Error 401: Unauthorized The username and the password is correct, I can log in with them. The CONSUMER_{KEY,SECRET} also valid, I copypasted them from the page of my application. Do you have any idea why the code above fails?
[ "Have you emailed Twitter support to get them to turn on xAuth for your application?\nTwitter only want xAuth to be used by desktop and mobile applications, so registered applications have xAuth disabled by default, and you need someone at Twitter to turn it on for you. If you application doesn't have xAuth enabled, you get a 401.\nTo get xAuth enabled, send an email to api@twitter.com with the name of your application and the reason it needs xAuth instead of plain old OAuth (eg. it's not appropriate to pop up a web browser in my desktop application).\n" ]
[ 2 ]
[]
[]
[ "python", "tweepy", "xauth" ]
stackoverflow_0002834654_python_tweepy_xauth.txt
Q: Simulating Pointers in Python for arithmetic The question at Simulating Pointers in Python asking how to simulate pointers in Python had a nice suggestion in the solutions, namely to do class ref: def __init__(self, obj): self.obj = obj def get(self): return self.obj def set(self, obj): self.obj = obj which can then be used to do e.g. a = ref(1.22) b = ref(a) print a # prints 1.22 print b.get() # prints 1.22 The class can be modified to avoid the use of get for the print statement by adding def __str__(self): return self.obj.__str__() Then, print b # prints out 1.22 Now I would like to be able to do arithmetic with b in the same way as a, which I guess would be equivelent to saying that I want a and b to behave exactly like obj. Is there anyway to do this? I tried adding methods such as def __getattribute__(self, attribute): return self.obj.__getattribute__(attribute) def __call__(self): return self.obj.__call__() But regardless of this, the output of print a + b is always Traceback (most recent call last): File "test.py", line 13, in <module> print a + b TypeError: unsupported operand type(s) for +: 'instance' and 'instance' Does anyone have any ideas on how to modify the ref class to allow this? Thanks for any advice! A: The + operator is implemented via the __add__() method on the left operand, or the __radd__() method on the right operand. Here. A: There are two potential issues. First, you seem to be relying on your __getattribute__ implementation to let the interpreter find the right __add__ method. Unfortunately, I have noticed that the Python interpreter often has trouble finding special functions, like __add__ or __call__ if they are created on the fly (that is, not made an explicit part of the class when the class is defined). The manuals explicitly acknowledge this, at least for new-style classes: For new-style classes, implicit invocations of special methods are only guaranteed to work correctly if defined on an object’s type, not in the object’s instance dictionary. although it seems to me that I have had problems with similar tricks even with old-style classes. Second, just redirecting __add__ won't be enough. Even if the interpreter successfully reduces a + b to float.__add__( 1.22, b ) the float class still doesn't know how to add a float to a ref. So your __add__ will have to explicitly dereference the target (and dereference that if it's an indirect reference (and dereference that...) Like so: class ref: def __init__(self, obj): self.obj = obj def get(self): return self.obj def set(self, obj): self.obj = obj def __str__(self): return self.obj.__str__() def __add__( self, other ): while isinstance( other, ref ): other = other.obj return self.obj.__add__( other ) a = ref(1.22) b = ref(a) print a print b print a + b The while loop in __add__makes sure that you've unpacked all of the nested refs all the way to the base object. If I were doing this, and I have used similar constructs to implement proxy patterns, I would refactor so that the while loop is in its own method, say getBaseObject(), and then is called from every time we need the object that is at the actual base of the chain of refs.
Simulating Pointers in Python for arithmetic
The question at Simulating Pointers in Python asking how to simulate pointers in Python had a nice suggestion in the solutions, namely to do class ref: def __init__(self, obj): self.obj = obj def get(self): return self.obj def set(self, obj): self.obj = obj which can then be used to do e.g. a = ref(1.22) b = ref(a) print a # prints 1.22 print b.get() # prints 1.22 The class can be modified to avoid the use of get for the print statement by adding def __str__(self): return self.obj.__str__() Then, print b # prints out 1.22 Now I would like to be able to do arithmetic with b in the same way as a, which I guess would be equivelent to saying that I want a and b to behave exactly like obj. Is there anyway to do this? I tried adding methods such as def __getattribute__(self, attribute): return self.obj.__getattribute__(attribute) def __call__(self): return self.obj.__call__() But regardless of this, the output of print a + b is always Traceback (most recent call last): File "test.py", line 13, in <module> print a + b TypeError: unsupported operand type(s) for +: 'instance' and 'instance' Does anyone have any ideas on how to modify the ref class to allow this? Thanks for any advice!
[ "The + operator is implemented via the __add__() method on the left operand, or the __radd__() method on the right operand.\nHere.\n", "There are two potential issues.\nFirst, you seem to be relying on your __getattribute__ implementation to let the interpreter find the right __add__ method. Unfortunately, I have noticed that the Python interpreter often has trouble finding special functions, like __add__ or __call__ if they are created on the fly (that is, not made an explicit part of the class when the class is defined). The manuals explicitly acknowledge this, at least for new-style classes:\n\nFor new-style classes, implicit\n invocations of special methods are\n only guaranteed to work correctly if\n defined on an object’s type, not in\n the object’s instance dictionary.\n\nalthough it seems to me that I have had problems with similar tricks even with old-style classes.\nSecond, just redirecting __add__ won't be enough. Even if the interpreter successfully reduces\na + b\n\nto\nfloat.__add__( 1.22, b )\n\nthe float class still doesn't know how to add a float to a ref. So your __add__ will have to explicitly dereference the target (and dereference that if it's an indirect reference (and dereference that...) Like so:\nclass ref:\n def __init__(self, obj):\n self.obj = obj\n def get(self): return self.obj\n def set(self, obj): self.obj = obj\n def __str__(self): return self.obj.__str__()\n def __add__( self, other ):\n while isinstance( other, ref ):\n other = other.obj\n return self.obj.__add__( other )\n\na = ref(1.22)\nb = ref(a)\n\nprint a\nprint b\n\nprint a + b\n\nThe while loop in __add__makes sure that you've unpacked all of the nested refs all the way to the base object.\nIf I were doing this, and I have used similar constructs to implement proxy patterns, I would refactor so that the while loop is in its own method, say getBaseObject(), and then is called from every time we need the object that is at the actual base of the chain of refs.\n" ]
[ 3, 0 ]
[]
[]
[ "pointers", "python" ]
stackoverflow_0002835639_pointers_python.txt
Q: Shared value in parallel python I'm using ParallelPython to develop a performance-critical script. I'd like to share one value between the 8 processes running on the system. Please excuse the trivial example but this illustrates my question. def findMin(listOfElements): for el in listOfElements: if el < min: min = el import pp min = 0 myList = range(100000) job_server = pp.Server() f1 = job_server.submit(findMin, myList[0:25000]) f2 = job_server.submit(findMin, myList[25000:50000]) f3 = job_server.submit(findMin, myList[50000:75000]) f4 = job_server.submit(findMin, myList[75000:100000]) The pp docs don't seem to describe a way to share data across processes. Is it possible? If so, is there a standard locking mechanism (like in the threading module) to confirm that only one update is done at a time? l = Lock() if(el < min): l.acquire if(el < min): min = el l.release I understand I could keep a local min and compare the 4 in the main thread once returned, but by sharing the value I can do some better pruning of my BFS binary tree and potentially save a lot of loop iterations. Thanks- Jonathan A: Actually, there is an example at http://www.parallelpython.com/content/view/17/31/#CALLBACK and they simply use the locks from the thread module. Like JudoWill pointed out, make sure to experiment with how often you should sync the global min in your jobs. If you do it every time you may end up close to serializing your whole calculation. A: Parallel Python runs the sub-functions on different processes, so there is no shared memory which means you should not be using a shared value. The callback example mentioned by clackle takes the results of each function and combines them in a callback function which is operating in the original process. To use it properly you should do something similar; in the example given you would calculate local minimums and use a callback function to find the minimum of all the subresults. Hopefully in your real case you can do something similar. A: I'm not sure about the PP module but you could always store the lowest value in a scratch file. My only worry would be that you would spend the majority of your time acquiring and releasing the lock. The only exception would be if your el < min operation is time-consuming. I would actually say that your "merging" technique is probably the way to go. And btw, I understand you're giving a simple example of your code for brevity, but don't use min as a variable name ... it'll cause you a lot of head-aches while debugging. A: You won't save any iterations by sharing the value, you need to read at least once every element from the list. Moreover, it will be slower, as you need to lock everytime you use the shared value. In your case, if you want more performance, you should compute a min for each part separately and the compare these results in the main thread. On the other hand, passing the list to other processes might be more ressource consumming than finding the minimum value of the list in a single pass.
Shared value in parallel python
I'm using ParallelPython to develop a performance-critical script. I'd like to share one value between the 8 processes running on the system. Please excuse the trivial example but this illustrates my question. def findMin(listOfElements): for el in listOfElements: if el < min: min = el import pp min = 0 myList = range(100000) job_server = pp.Server() f1 = job_server.submit(findMin, myList[0:25000]) f2 = job_server.submit(findMin, myList[25000:50000]) f3 = job_server.submit(findMin, myList[50000:75000]) f4 = job_server.submit(findMin, myList[75000:100000]) The pp docs don't seem to describe a way to share data across processes. Is it possible? If so, is there a standard locking mechanism (like in the threading module) to confirm that only one update is done at a time? l = Lock() if(el < min): l.acquire if(el < min): min = el l.release I understand I could keep a local min and compare the 4 in the main thread once returned, but by sharing the value I can do some better pruning of my BFS binary tree and potentially save a lot of loop iterations. Thanks- Jonathan
[ "Actually, there is an example at http://www.parallelpython.com/content/view/17/31/#CALLBACK and they simply use the locks from the thread module.\nLike JudoWill pointed out, make sure to experiment with how often you should sync the global min in your jobs. If you do it every time you may end up close to serializing your whole calculation.\n", "Parallel Python runs the sub-functions on different processes, so there is no shared memory which means you should not be using a shared value. The callback example mentioned by clackle takes the results of each function and combines them in a callback function which is operating in the original process. To use it properly you should do something similar; in the example given you would calculate local minimums and use a callback function to find the minimum of all the subresults. Hopefully in your real case you can do something similar.\n", "I'm not sure about the PP module but you could always store the lowest value in a scratch file. My only worry would be that you would spend the majority of your time acquiring and releasing the lock. The only exception would be if your el < min operation is time-consuming.\nI would actually say that your \"merging\" technique is probably the way to go.\nAnd btw, I understand you're giving a simple example of your code for brevity, but don't use min as a variable name ... it'll cause you a lot of head-aches while debugging. \n", "You won't save any iterations by sharing the value, you need to read at least once every element from the list. Moreover, it will be slower, as you need to lock everytime you use the shared value.\nIn your case, if you want more performance, you should compute a min for each part separately and the compare these results in the main thread.\nOn the other hand, passing the list to other processes might be more ressource consumming than finding the minimum value of the list in a single pass.\n" ]
[ 1, 1, 0, 0 ]
[]
[]
[ "parallel_processing", "python" ]
stackoverflow_0002770157_parallel_processing_python.txt
Q: Group Chat XMPP with Google App Engine Google App Engine has a great XMPP service built in. One of the few limitations it has is that it doesn't support receiving messages from a group chat. That's the one thing I want to do with it. :( Can I run a 3rd party XMPP/Jabber server on App Engine that supports group chat? If so, which one? A: No. App Engine apps can only directly handle HTTP requests - you can't run arbitrary servers on App Engine.
Group Chat XMPP with Google App Engine
Google App Engine has a great XMPP service built in. One of the few limitations it has is that it doesn't support receiving messages from a group chat. That's the one thing I want to do with it. :( Can I run a 3rd party XMPP/Jabber server on App Engine that supports group chat? If so, which one?
[ "No. App Engine apps can only directly handle HTTP requests - you can't run arbitrary servers on App Engine.\n" ]
[ 3 ]
[]
[]
[ "google_app_engine", "java", "python", "xmpp" ]
stackoverflow_0002835472_google_app_engine_java_python_xmpp.txt
Q: pythonic way of selecing a random value that satisfies a certain predicate Suppose I have a list of elements and I want to randomly select an element from the list that satisfies a predicate. What is the pythonic way of doing this? I currently do a comprehension followed by a random.choice() but that is unnecessarily inefficient : intlist = [1,2,3,4,5,6,7,8,9] evenlist = [ i for i in intlist if i % 2 == 0 ] randomeven = random.choice(evenlist) Thanks! A: The way you've written it above is actually good idiomatic python. If we analyze the algorithm we'll find it's essentially doing this: Making a list of elements that satisfy the predicate. (Grows linearly with n) Choosing a random element from that list. (Constant time) The only other way to go about it would be to choose an element at random, decide if it satisfies the predicate, and choose again if it does not. This algorithm is a little more complex. In the case where 90% of the list satisfies the predicate, this will run much faster than your solution. In the case where only 10% of the list satisfies the predicate, it will actually run much slower, because there's a good chance it will randomly select a given element and check if the predicate is satisfied on that element more than once. Now you could consider memoizing your predicate, but you're still going to select a lot of random data. It comes down to this: Unless your solution is particularly unsuited for your data, stick with it, because it's great. Personally, I'd rewrite it like this: intlist = range(1,10) randomeven = random.choice([i for i in intlist if i % 2 == 0]) This is a little more concise, but it's going to run exactly the same as your existing code. A: I could not find a function sort of random.selectspecific(list, predicate) in the documentation, so I would try something like the following: import random def selectspecific(l, predicate): result = random.choice(l) while (not predicate(result)): result = random.choice(l) return result A: import random intlist = [1,2,3,4,5,6,7,8,9] randomeven = random.choice(filter(lambda x: x % 2 == 0, intlist)) A: How pythonic is this? from itertools import ifilterfalse from random import choice print choice([ i for i in ifilterfalse(lambda x: x%2, range(10)) ]) A: If you would like to encapsulate more you could create a method to handle the selection, that would accept a predicate method. You can then use this predicate method with filter(). import random def selectSpecific(intlist, predicate): filteredList = filter(predicate, intlist) result = random.choice(filteredList) return result You can pass a predicate to selectSpecific() as a lambda or any other method. Example: intlist = range(1,10) selectSpecific(intlist, lambda x: x % 2 == 0) def makeEven(n): if n % 2 == 0: return n selectSpecific(intlist, makeEven)
pythonic way of selecing a random value that satisfies a certain predicate
Suppose I have a list of elements and I want to randomly select an element from the list that satisfies a predicate. What is the pythonic way of doing this? I currently do a comprehension followed by a random.choice() but that is unnecessarily inefficient : intlist = [1,2,3,4,5,6,7,8,9] evenlist = [ i for i in intlist if i % 2 == 0 ] randomeven = random.choice(evenlist) Thanks!
[ "The way you've written it above is actually good idiomatic python. If we analyze the algorithm we'll find it's essentially doing this:\n\nMaking a list of elements that satisfy the predicate. (Grows linearly with n)\nChoosing a random element from that list. (Constant time)\n\nThe only other way to go about it would be to choose an element at random, decide if it satisfies the predicate, and choose again if it does not. This algorithm is a little more complex. In the case where 90% of the list satisfies the predicate, this will run much faster than your solution. In the case where only 10% of the list satisfies the predicate, it will actually run much slower, because there's a good chance it will randomly select a given element and check if the predicate is satisfied on that element more than once. Now you could consider memoizing your predicate, but you're still going to select a lot of random data. It comes down to this: Unless your solution is particularly unsuited for your data, stick with it, because it's great. Personally, I'd rewrite it like this: \nintlist = range(1,10)\nrandomeven = random.choice([i for i in intlist if i % 2 == 0])\n\nThis is a little more concise, but it's going to run exactly the same as your existing code. \n", "I could not find a function sort of random.selectspecific(list, predicate) in the documentation, so I would try something like the following:\nimport random\ndef selectspecific(l, predicate):\n result = random.choice(l)\n while (not predicate(result)):\n result = random.choice(l)\n return result\n\n", "import random\n\nintlist = [1,2,3,4,5,6,7,8,9]\nrandomeven = random.choice(filter(lambda x: x % 2 == 0, intlist)) \n\n", "How pythonic is this?\nfrom itertools import ifilterfalse\nfrom random import choice\nprint choice([ i for i in ifilterfalse(lambda x: x%2, range(10)) ])\n\n", "If you would like to encapsulate more you could create a method to handle the selection, that would accept a predicate method. You can then use this predicate method with filter().\nimport random\ndef selectSpecific(intlist, predicate):\n filteredList = filter(predicate, intlist)\n result = random.choice(filteredList)\n return result\n\nYou can pass a predicate to selectSpecific() as a lambda or any other method. Example:\nintlist = range(1,10)\nselectSpecific(intlist, lambda x: x % 2 == 0)\n\ndef makeEven(n):\n if n % 2 == 0:\n return n\n\nselectSpecific(intlist, makeEven)\n\n" ]
[ 2, 1, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002835754_python.txt
Q: Python modify an xml file I have this xml model. link text So I have to add some node (see the text commented) to this file. How I can do it? I have writed this partial code but it doesn't work: xmldoc=minidom.parse(directory) child = xmldoc.createElement("map") for node in xmldoc.getElementsByTagName("Environment"): node.appendChild(child) Thanks in advance. A: I downloaded your sample xml file and your code works fine. Your problem is most likely with the line: xmldoc=minidom.parse(directory), should this not be the path to the file you are trying to parse not to a directory? The parse() function parses an XML file it does not automatically parse all the XML files in a given directory. If you change your code to something like below this should work fine: xmldoc=minidom.parse("directory/model_template.xml") child = xmldoc.createElement("map") for node in xmldoc.getElementsByTagName("Environment"): node.appendChild(child) If you then execute the statement: print xmldoc.toxml() you will see that the map element has indeed been added to the Environment element: <Environment><map/></Environment>.
Python modify an xml file
I have this xml model. link text So I have to add some node (see the text commented) to this file. How I can do it? I have writed this partial code but it doesn't work: xmldoc=minidom.parse(directory) child = xmldoc.createElement("map") for node in xmldoc.getElementsByTagName("Environment"): node.appendChild(child) Thanks in advance.
[ "I downloaded your sample xml file and your code works fine. Your problem is most likely with the line: xmldoc=minidom.parse(directory), should this not be the path to the file you are trying to parse not to a directory? The parse() function parses an XML file it does not automatically parse all the XML files in a given directory. \nIf you change your code to something like below this should work fine:\nxmldoc=minidom.parse(\"directory/model_template.xml\")\nchild = xmldoc.createElement(\"map\")\n for node in xmldoc.getElementsByTagName(\"Environment\"):\n node.appendChild(child)\n\nIf you then execute the statement: print xmldoc.toxml() you will see that the map element has indeed been added to the Environment element: <Environment><map/></Environment>.\n" ]
[ 1 ]
[]
[]
[ "add", "python", "xml" ]
stackoverflow_0002836132_add_python_xml.txt
Q: Working with html generated from javascript I have some html-page. There is a javascript which generates some content. I have to parse this content from python-script. I have saved copy of file on the computer. Are there any ways to work with 'already generated' html? Like I can see in the browser after opening page-file. As I understand, I have to work with DOM (maybe, xml2dom lib). A: Have you saved "the file" (web page, I imagine) before or after Javascript has altered it? If "after", then it doesn't matter any more that some of the HTML was done via Javascript -- you can just use popular parsers like lxml or BeautifulSoup to handle the HTML you have. If "before", then first you need to let Javascript do its work by automating a real browser; for that task, I would recommend SeleniumRC -- which brings you back to the "after" case;-). A: I think you may have a fundamental misunderstanding in regards to what runs where: At the time JavaScript generates the content (on client side), the server side processing of the document has already taken place. There is no direct way for a server side Python script to access HTML created by JavaScript. Basically, that HTML lives only "virtually" in the browser's DOM. You would have to find a way to transmit that HTML to your Python script. Most likely using Ajax. You would take the HTML, and add it as a parameter to your Ajax call (Remember to use POST as the request method so you don't get size limitation problems.) An example using jQuery's AJAX functions: $.ajax({ url: "myscript.py", type: "POST", data: { html: your_html_content_here }, success: function(){ alert("sent HTML to python script!"); }});
Working with html generated from javascript
I have some html-page. There is a javascript which generates some content. I have to parse this content from python-script. I have saved copy of file on the computer. Are there any ways to work with 'already generated' html? Like I can see in the browser after opening page-file. As I understand, I have to work with DOM (maybe, xml2dom lib).
[ "Have you saved \"the file\" (web page, I imagine) before or after Javascript has altered it?\nIf \"after\", then it doesn't matter any more that some of the HTML was done via Javascript -- you can just use popular parsers like lxml or BeautifulSoup to handle the HTML you have.\nIf \"before\", then first you need to let Javascript do its work by automating a real browser; for that task, I would recommend SeleniumRC -- which brings you back to the \"after\" case;-).\n", "I think you may have a fundamental misunderstanding in regards to what runs where: At the time JavaScript generates the content (on client side), the server side processing of the document has already taken place. There is no direct way for a server side Python script to access HTML created by JavaScript. Basically, that HTML lives only \"virtually\" in the browser's DOM.\nYou would have to find a way to transmit that HTML to your Python script. Most likely using Ajax. You would take the HTML, and add it as a parameter to your Ajax call (Remember to use POST as the request method so you don't get size limitation problems.)\nAn example using jQuery's AJAX functions:\n$.ajax({ \n url: \"myscript.py\", \n type: \"POST\",\n data: { html: your_html_content_here },\n success: function(){\n alert(\"sent HTML to python script!\");\n }});\n\n" ]
[ 2, 0 ]
[]
[]
[ "dom", "html", "python" ]
stackoverflow_0002836745_dom_html_python.txt
Q: PIL to pyvision conversion How can a PIL image be converted to a Pyvision image? A: Based on the documentation, http://sourceforge.net/apps/mediawiki/pyvision/index.php?title=Quick_Start_1, Pvvision image itself is PIL image. The Image constructor accepts filenames as an argument and will then load that file from the disk as a PIL image. The Image constructor will also accept other python image objects. For example, if you pass a numpy matrix, PIL image, or an OpenCV image to the constructor it will crate a pyvision image based on that data.
PIL to pyvision conversion
How can a PIL image be converted to a Pyvision image?
[ "Based on the documentation, http://sourceforge.net/apps/mediawiki/pyvision/index.php?title=Quick_Start_1, Pvvision image itself is PIL image. \n\nThe Image constructor accepts\n filenames as an argument and will then\n load that file from the disk as a PIL image. The Image constructor\n will also accept other python image objects. For example, if you\n pass a numpy matrix, PIL image, or an OpenCV image to the constructor \n it will crate a pyvision image based on that data.\n\n" ]
[ 1 ]
[]
[]
[ "image", "image_manipulation", "python", "python_imaging_library" ]
stackoverflow_0002835200_image_image_manipulation_python_python_imaging_library.txt
Q: Permission to access network drives when running Python CGI? I have a Python script running on the default OSX webserver, stored in /Library/WebServer/CGI-Executables. That script spits out a list of files on a network drive using os.listdir. If I just execute this from the terminal, it works as expected, but when I try to access it through a browser (computer.local/cgi-bin/test.py), I get a permissions error: <type 'exceptions.OSError'>: [Errno 13] Permission denied: '/Volumes/code/code/_sendrender/queue/waiting' Is there any way to give the script permission to access the network when accessed via CGI? A: I don't know much about the default osx webserver, but the webserver process is probably being run as some user, that user needs to be able to access those files. To find out who the user is you can use the ps command. Then depending on the configuration of the network shared drive, you can add this user to the users allowed to access this data.
Permission to access network drives when running Python CGI?
I have a Python script running on the default OSX webserver, stored in /Library/WebServer/CGI-Executables. That script spits out a list of files on a network drive using os.listdir. If I just execute this from the terminal, it works as expected, but when I try to access it through a browser (computer.local/cgi-bin/test.py), I get a permissions error: <type 'exceptions.OSError'>: [Errno 13] Permission denied: '/Volumes/code/code/_sendrender/queue/waiting' Is there any way to give the script permission to access the network when accessed via CGI?
[ "I don't know much about the default osx webserver, but the webserver process is probably being run as some user, that user needs to be able to access those files. To find out who the user is you can use the ps command. Then depending on the configuration of the network shared drive, you can add this user to the users allowed to access this data.\n" ]
[ 1 ]
[]
[]
[ "cgi", "python" ]
stackoverflow_0002837181_cgi_python.txt
Q: Turbogears 2.0 with Python 2.6 I've tried to install TurboGears 2.0 with Python 2.6 on both Windows 7 and Windows XP, but both give the same error: File "D:\PythonProjects\tg2env\Scripts\paster-script.py", line 8, in <module> load_entry_point('pastescript==1.7.3', 'console_scripts', 'paster')() File "D:\PythonProjects\tg2env\lib\site-packages\pastescript-1.7.3-py2.6.egg\paste\script\command.py", line 73, in run commands = get_commands() File "D:\PythonProjects\tg2env\lib\site-packages\pastescript-1.7.3-py2.6.egg\paste\script\command.py", line 115, in get_ plugins = pluginlib.resolve_plugins(plugins) File "D:\PythonProjects\tg2env\lib\site-packages\pastescript-1.7.3-py2.6.egg\paste\script\pluginlib.py", line 81, in res pkg_resources.require(plugin) File "D:\PythonProjects\tg2env\lib\site-packages\setuptools-0.6c9-py2.6.egg\pkg_resources.py", line 626, in require File "D:\PythonProjects\tg2env\lib\site-packages\setuptools-0.6c9-py2.6.egg\pkg_resources.py", line 524, in resolve pkg_resources.DistributionNotFound: zope.sqlalchemy>=0.4: Not Found for: City_Guide (did you run python setup.py develop?) Now, according to the documentation on the main site, TurboGears 2.0 supports Python 2.6 in this page: TurboGears works with any version of python between 2.4 and 2.6. The most widely deployed version of python at the moment of this writing is version 2.5. Both python 2.4 and python 2.6 require additional steps which will be covered in the appropriate sections. But they never mention those steps in the documentation. A: did you run python setup.py develop? (as the error message says) I was using virtualenv as recommended in the documentation, but the develop command installs the packages in the original python folder. Okay, that is the cause of your problems. I'm wondering about your comment "but the develop command installs..." The develop command of your web app shouldn't install anything. It's just meant to set up the database. Are you running this command inside the directory of your web app? A: I had the same problem. I was finally able to get it to work. I closed the command window. i opened a new commandwindow and activated the virtualenv by executing the appropriate activate.bat. Afterwards I reexecuted "setup.py develop" and finally i was able to start paster serve as documented in the Turbogears wiki. A: The key is to run python setup.py development.ini. If you just run setup.py development.ini, it will use the installed python, and will not litter to your virtualenv
Turbogears 2.0 with Python 2.6
I've tried to install TurboGears 2.0 with Python 2.6 on both Windows 7 and Windows XP, but both give the same error: File "D:\PythonProjects\tg2env\Scripts\paster-script.py", line 8, in <module> load_entry_point('pastescript==1.7.3', 'console_scripts', 'paster')() File "D:\PythonProjects\tg2env\lib\site-packages\pastescript-1.7.3-py2.6.egg\paste\script\command.py", line 73, in run commands = get_commands() File "D:\PythonProjects\tg2env\lib\site-packages\pastescript-1.7.3-py2.6.egg\paste\script\command.py", line 115, in get_ plugins = pluginlib.resolve_plugins(plugins) File "D:\PythonProjects\tg2env\lib\site-packages\pastescript-1.7.3-py2.6.egg\paste\script\pluginlib.py", line 81, in res pkg_resources.require(plugin) File "D:\PythonProjects\tg2env\lib\site-packages\setuptools-0.6c9-py2.6.egg\pkg_resources.py", line 626, in require File "D:\PythonProjects\tg2env\lib\site-packages\setuptools-0.6c9-py2.6.egg\pkg_resources.py", line 524, in resolve pkg_resources.DistributionNotFound: zope.sqlalchemy>=0.4: Not Found for: City_Guide (did you run python setup.py develop?) Now, according to the documentation on the main site, TurboGears 2.0 supports Python 2.6 in this page: TurboGears works with any version of python between 2.4 and 2.6. The most widely deployed version of python at the moment of this writing is version 2.5. Both python 2.4 and python 2.6 require additional steps which will be covered in the appropriate sections. But they never mention those steps in the documentation.
[ "did you run python setup.py develop? (as the error message says)\n\nI was using virtualenv as recommended in the documentation, but the develop command installs the packages in the original python folder.\n\nOkay, that is the cause of your problems. I'm wondering about your comment \"but the develop command installs...\" The develop command of your web app shouldn't install anything. It's just meant to set up the database.\nAre you running this command inside the directory of your web app?\n", "I had the same problem. I was finally able to get it to work. I closed the command window. i opened a new commandwindow and activated the virtualenv by executing the appropriate activate.bat. Afterwards I reexecuted \"setup.py develop\" and finally i was able to start paster serve as documented in the Turbogears wiki.\n", "The key is to run python setup.py development.ini. If you just run setup.py development.ini, it will use the installed python, and will not litter to your virtualenv\n" ]
[ 1, 0, 0 ]
[]
[]
[ "python", "turbogears" ]
stackoverflow_0001536437_python_turbogears.txt
Q: What could cause xmlrpclib.ResponseError: ResponseError()? I am experimenting with XML-RPC. I have the following server script (Python): from SimpleXMLRPCServer import SimpleXMLRPCServer server = SimpleXMLRPCServer(('localhost', 9000)) def return_input(someinput): return someinput server.register_function(return_input) try: print 'ctrl-c to stop server' server.serve_forever() except KeyboardInterrupt: print 'stopping' and the following client script: import xmlrpclib server = xmlrpclib.ServerProxy('http://www.example.com/pathto/xmlrpcTester2.py') print server.return_input('some input') I have tested this locally and it works fine. All it does it spit out the input from the client script, which is right. However, when I try to do it on a remote server I get the following error: Traceback (most recent call last): File "client.py", line 4, in <module> print server.return_input('some input') File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/xmlrpclib.py", line 1199, in __call__ return self.__send(self.__name, args) File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/xmlrpclib.py", line 1489, in __request verbose=self.__verbose File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/xmlrpclib.py", line 1253, in request return self._parse_response(h.getfile(), sock) File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/xmlrpclib.py", line 1392, in _parse_response return u.close() File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/xmlrpclib.py", line 836, in close raise ResponseError() xmlrpclib.ResponseError: ResponseError() Any ideas what could cause this? UPDATE: when verbose=True: send: 'POST /pythonScripts/xmlrpcTester2.py HTTP/1.0\r\nHost: www.example.com\r\nUser-Agent: xmlrpclib.py/1.0.1 (by www.pythonware.com)\r\nContent- Type: text/xml\r\nContent-Length: 166\r\n\r\n' send: "<?xml version='1.0'? >\n<methodCall>\n<methodName>return_input</methodName>\n<params>\n<param>\n<value><string>so me input</string></value>\n</param>\n</params>\n</methodCall>\n" reply: 'HTTP/1.1 200 OK\r\n' header: Date: Fri, 14 May 2010 20:52:25 GMT header: Server: Apache/2.2.9 (Fedora) header: Last-Modified: Fri, 14 May 2010 20:52:03 GMT header: ETag: "7e206-13d-486940c17a2c0" header: Accept-Ranges: bytes header: Content-Length: 317 header: Connection: close header: Content-Type: text/plain; charset=UTF-8 body: "from SimpleXMLRPCServer import SimpleXMLRPCServer\r\n\r\nserver = SimpleXMLRPCServer(('localhost', 8000))\r\n\r\ndef return_input(someinput):\r\n\treturn someinput\r\n\r\nserver.register_function(return_input)\r\n\r\ntry:\r\n print 'ctrl-c to stop server'\r\n server.serve_forever()\r\nexcept KeyboardInterrupt:\r\n print 'stopping'" Traceback (most recent call last): File "client.py", line 4, in <module> print server.return_input('some input') File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/xmlrpclib.py", line 1199, in __call__ return self.__send(self.__name, args) File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/xmlrpclib.py", line 1489, in __request verbose=self.__verbose File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/xmlrpclib.py", line 1253, in request return self._parse_response(h.getfile(), sock) File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/xmlrpclib.py", line 1392, in _parse_response return u.close() File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/xmlrpclib.py", line 836, in close raise ResponseError() xmlrpclib.ResponseError: ResponseError() A: It looks like something else is running on that port on the remote machine. And sending back an unexpected answer. I would check the server is starting correctly. Then check if there is anything in the firewall setup that might be affecting things. You could also turn on the verbose flag in the client to see if that sheds any light on the problem. EDIT: So the verbose output makes clear the problem: you aren't running the server, you are sharing it out over a normal webserver! You need to run the server on the remote machine.
What could cause xmlrpclib.ResponseError: ResponseError()?
I am experimenting with XML-RPC. I have the following server script (Python): from SimpleXMLRPCServer import SimpleXMLRPCServer server = SimpleXMLRPCServer(('localhost', 9000)) def return_input(someinput): return someinput server.register_function(return_input) try: print 'ctrl-c to stop server' server.serve_forever() except KeyboardInterrupt: print 'stopping' and the following client script: import xmlrpclib server = xmlrpclib.ServerProxy('http://www.example.com/pathto/xmlrpcTester2.py') print server.return_input('some input') I have tested this locally and it works fine. All it does it spit out the input from the client script, which is right. However, when I try to do it on a remote server I get the following error: Traceback (most recent call last): File "client.py", line 4, in <module> print server.return_input('some input') File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/xmlrpclib.py", line 1199, in __call__ return self.__send(self.__name, args) File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/xmlrpclib.py", line 1489, in __request verbose=self.__verbose File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/xmlrpclib.py", line 1253, in request return self._parse_response(h.getfile(), sock) File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/xmlrpclib.py", line 1392, in _parse_response return u.close() File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/xmlrpclib.py", line 836, in close raise ResponseError() xmlrpclib.ResponseError: ResponseError() Any ideas what could cause this? UPDATE: when verbose=True: send: 'POST /pythonScripts/xmlrpcTester2.py HTTP/1.0\r\nHost: www.example.com\r\nUser-Agent: xmlrpclib.py/1.0.1 (by www.pythonware.com)\r\nContent- Type: text/xml\r\nContent-Length: 166\r\n\r\n' send: "<?xml version='1.0'? >\n<methodCall>\n<methodName>return_input</methodName>\n<params>\n<param>\n<value><string>so me input</string></value>\n</param>\n</params>\n</methodCall>\n" reply: 'HTTP/1.1 200 OK\r\n' header: Date: Fri, 14 May 2010 20:52:25 GMT header: Server: Apache/2.2.9 (Fedora) header: Last-Modified: Fri, 14 May 2010 20:52:03 GMT header: ETag: "7e206-13d-486940c17a2c0" header: Accept-Ranges: bytes header: Content-Length: 317 header: Connection: close header: Content-Type: text/plain; charset=UTF-8 body: "from SimpleXMLRPCServer import SimpleXMLRPCServer\r\n\r\nserver = SimpleXMLRPCServer(('localhost', 8000))\r\n\r\ndef return_input(someinput):\r\n\treturn someinput\r\n\r\nserver.register_function(return_input)\r\n\r\ntry:\r\n print 'ctrl-c to stop server'\r\n server.serve_forever()\r\nexcept KeyboardInterrupt:\r\n print 'stopping'" Traceback (most recent call last): File "client.py", line 4, in <module> print server.return_input('some input') File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/xmlrpclib.py", line 1199, in __call__ return self.__send(self.__name, args) File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/xmlrpclib.py", line 1489, in __request verbose=self.__verbose File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/xmlrpclib.py", line 1253, in request return self._parse_response(h.getfile(), sock) File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/xmlrpclib.py", line 1392, in _parse_response return u.close() File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/xmlrpclib.py", line 836, in close raise ResponseError() xmlrpclib.ResponseError: ResponseError()
[ "It looks like something else is running on that port on the remote machine. And sending back an unexpected answer.\nI would check the server is starting correctly. Then check if there is anything in the firewall setup that might be affecting things.\nYou could also turn on the verbose flag in the client to see if that sheds any light on the problem.\nEDIT:\nSo the verbose output makes clear the problem: you aren't running the server, you are sharing it out over a normal webserver!\nYou need to run the server on the remote machine.\n" ]
[ 3 ]
[]
[]
[ "python", "simplexmlrpcserver", "xml_rpc" ]
stackoverflow_0002837414_python_simplexmlrpcserver_xml_rpc.txt
Q: Help with parsing lxml To implement a college project, I need to handle XML files. For this I choose lxml after doing some research. However I can't seem to find some nice tutorial to help me get started. I can't choose most specifically which type of parsing I need to use. My XML files don't have that much data but speed is main concern, not memory. Can anyone point me to some tutorial that would help me or some book that I can lookup? I have already tried the tutorial on lxml site but that didn't help me much. Is there some small application I can look up to get a hang of parsing XML with lxml A: No applications but examples: http://www.ibm.com/developerworks/xml/library/x-hiperfparse/ http://infohost.nmt.edu/tcc/help/pubs/pylxml/pylxml.pdf
Help with parsing lxml
To implement a college project, I need to handle XML files. For this I choose lxml after doing some research. However I can't seem to find some nice tutorial to help me get started. I can't choose most specifically which type of parsing I need to use. My XML files don't have that much data but speed is main concern, not memory. Can anyone point me to some tutorial that would help me or some book that I can lookup? I have already tried the tutorial on lxml site but that didn't help me much. Is there some small application I can look up to get a hang of parsing XML with lxml
[ "No applications but examples:\n\nhttp://www.ibm.com/developerworks/xml/library/x-hiperfparse/\nhttp://infohost.nmt.edu/tcc/help/pubs/pylxml/pylxml.pdf\n\n" ]
[ 3 ]
[]
[]
[ "lxml", "python" ]
stackoverflow_0002837513_lxml_python.txt
Q: Animate pygame sprite in elliptical path This is pygame 1.9 on python 2.6.. Here is a screenshot of what is currently being drawn in my "game" to give some context. Here is the code. It's supposed to be the moon orbiting around the earth (I'm not trying to make a real simulation or anything, I'm just using the setting to play around and learn pygame). It's 2 circles, and the moons elliptical orbit around the earth. My end game is to have the moon follow it's orbit around the earth, but I want to later use keyboard controls to adjust the shape of the moons orbit. I really just need help with figuring out how to make the moon follow the path, I could probably figure the rest out. A: Well here is how you generate points along an ellipse: for degree in range(360): x = cos(degree * 2 * pi / 360) * radius * xToYratio y = sin(degree * 2 * pi / 360) * radius (x,y) will follow an ellipse centered at (0,0), with the y radius being radius and the x radius being xToYratio. In your case, you probably want degree to be related to time passing somehow. EDIT: you can also do this: for degree in range(360): x = cos(degree * 2 * pi / 360) * xRadius y = sin(degree * 2 * pi / 360) * yRadius where xRadius is half of your rect's width, and yRadius is half of your rects height. Visualize it intuitively - you have a circle, and you're stretching it out (i.e. scaling it, i.e. multiplying it) so that it's as big as the rect horizontally and vertically.
Animate pygame sprite in elliptical path
This is pygame 1.9 on python 2.6.. Here is a screenshot of what is currently being drawn in my "game" to give some context. Here is the code. It's supposed to be the moon orbiting around the earth (I'm not trying to make a real simulation or anything, I'm just using the setting to play around and learn pygame). It's 2 circles, and the moons elliptical orbit around the earth. My end game is to have the moon follow it's orbit around the earth, but I want to later use keyboard controls to adjust the shape of the moons orbit. I really just need help with figuring out how to make the moon follow the path, I could probably figure the rest out.
[ "Well here is how you generate points along an ellipse:\nfor degree in range(360):\n x = cos(degree * 2 * pi / 360) * radius * xToYratio\n y = sin(degree * 2 * pi / 360) * radius\n\n(x,y) will follow an ellipse centered at (0,0), with the y radius being radius and the x radius being xToYratio. In your case, you probably want degree to be related to time passing somehow.\nEDIT: you can also do this:\nfor degree in range(360):\n x = cos(degree * 2 * pi / 360) * xRadius\n y = sin(degree * 2 * pi / 360) * yRadius\n\nwhere xRadius is half of your rect's width, and yRadius is half of your rects height. Visualize it intuitively - you have a circle, and you're stretching it out (i.e. scaling it, i.e. multiplying it) so that it's as big as the rect horizontally and vertically. \n" ]
[ 5 ]
[]
[]
[ "animation", "pygame", "python" ]
stackoverflow_0002837615_animation_pygame_python.txt
Q: Downloading a web page and all of its resource files in Python I want to be able to download a page and all of its associated resources (images, style sheets, script files, etc) using Python. I am (somewhat) familiar with urllib2 and know how to download individual urls, but before I go and start hacking at BeautifulSoup + urllib2 I wanted to be sure that there wasn't already a Python equivalent to "wget --page-requisites http://www.google.com". Specifically I am interested in gathering statistical information about how long it takes to download an entire web page, including all resources. Thanks Mark A: Websucker? See http://effbot.org/zone/websucker.htm A: websucker.py doesn't import css links. HTTrack.com is not python, it's C/C++, but it's a good, maintained, utility for downloading a website for offline browsing. http://www.mail-archive.com/python-bugs-list@python.org/msg13523.html [issue1124] Webchecker not parsing css "@import url" Guido> This is essentially unsupported and unmaintaned example code. Feel free to submit a patch though!
Downloading a web page and all of its resource files in Python
I want to be able to download a page and all of its associated resources (images, style sheets, script files, etc) using Python. I am (somewhat) familiar with urllib2 and know how to download individual urls, but before I go and start hacking at BeautifulSoup + urllib2 I wanted to be sure that there wasn't already a Python equivalent to "wget --page-requisites http://www.google.com". Specifically I am interested in gathering statistical information about how long it takes to download an entire web page, including all resources. Thanks Mark
[ "Websucker? See http://effbot.org/zone/websucker.htm\n", "websucker.py doesn't import css links. HTTrack.com is not python, it's C/C++, but it's a good, maintained, utility for downloading a website for offline browsing.\nhttp://www.mail-archive.com/python-bugs-list@python.org/msg13523.html\n[issue1124] Webchecker not parsing css \"@import url\"\nGuido> This is essentially unsupported and unmaintaned example code. Feel free\nto submit a patch though!\n" ]
[ 3, 2 ]
[]
[]
[ "python", "urllib2", "wget" ]
stackoverflow_0000844115_python_urllib2_wget.txt
Q: In Python, how to make sure database connection will always close before leaving a code block? I want to prevent database connection being open as much as possible, because this code will run on an intensive used server and people here already told me database connections should always be closed as soon as possible. def do_something_that_needs_database (): dbConnection = MySQLdb.connect(host=args['database_host'], user=args['database_user'], passwd=args['database_pass'], db=args['database_tabl'], cursorclass=MySQLdb.cursors.DictCursor) dbCursor = dbConnection.cursor() dbCursor.execute('SELECT COUNT(*) total FROM table') row = dbCursor.fetchone() if row['total'] == 0: print 'error: table have no records' dbCursor.execute('UPDATE table SET field="%s"', whatever_value) return None print 'table is ok' dbCursor.execute('UPDATE table SET field="%s"', another_value) # a lot more of workflow done here dbConnection.close() # even more stuff would come below I believe that leaves a database connection open when there is no row on the table, tho I'm still really not sure how it works. Anyway, maybe that is bad design in the sense that I could open and close a DB connection after each small block of execute. And sure, I could just add a close right before the return in that case... But how could I always properly close the DB without having to worry if I have that return, or a raise, or continue, or whatever in the middle? I'm thinking in something like a code block, similar to using try, like in the following suggestion, which obviously doesn't work: def do_something_that_needs_database (): dbConnection = MySQLdb.connect(host=args['database_host'], user=args['database_user'], passwd=args['database_pass'], db=args['database_tabl'], cursorclass=MySQLdb.cursors.DictCursor) try: dbCursor = dbConnection.cursor() dbCursor.execute('SELECT COUNT(*) total FROM table') row = dbCursor.fetchone() if row['total'] == 0: print 'error: table have no records' dbCursor.execute('UPDATE table SET field="%s"', whatever_value) return None print 'table is ok' dbCursor.execute('UPDATE table SET field="%s"', another_value) # again, that same lot of line codes done here except ExitingCodeBlock: closeDb(dbConnection) # still, that "even more stuff" from before would come below I don't think there is anything similar to ExitingCodeBlock for an exception, tho I know there is the try else, but I hope Python already have a similar feature... Or maybe someone can suggest me a paradigm move and tell me this is awful and highly advise me to never do that. Maybe this is just something to not worry about and let MySQLdb handle it, or is it? A: The traditional approach is the try/finally statement: def do_something_that_needs_database (): dbConnection = MySQLdb.connect(host=args['database_host'], user=args['database_user'], passwd=args['database_pass'], db=args['database_tabl'], cursorclass=MySQLdb.cursors.DictCursor) try: # as much work as you want, including return, raising exceptions, _whatever_ finally: closeDb(dbConnection) Since Python 2.6 (and 2.5 with a from __future__ import with_statement), there is an alternative (although try/finally still works perfectly well!): the with statement. with somecontext as whatever: # the work goes here A context has an __enter__ method, executed on entry (to return the whatever above, if you want) and an __exit__ method, executed on exit. Despite the elegance, since there is no existing context that works the way you want, the work needed to build one (although reduced in 2.6 with contextlib) should probably suggest that good old try/finally is best. If you have 2.6 and want to try contextlib, this is one way you could do it to "hide" the try/finally...: import contextlib @contextlib.contextmanager def dbconnect(**kwds): dbConnection = MySQLdb.connect(**kwds) try: yield dbConnection finally: closeDb(dbConnection) to be used as: def do_something_that_needs_database (): with dbconnect(host=args['database_host'], user=args['database_user'], passwd=args['database_pass'], db=args['database_tabl'], cursorclass=MySQLdb.cursors.DictCursor) as dbConnection: # as much work as you want, including return, raising exceptions, _whatever_ It may be worth it if you are going to use this many, many times, just to avoid repeating the try/finally over and over for each of those many uses. A: If MySQLdb supports it, then you could use the "with" statement. The "with" statement exists for just that reason. However, it requires that the object define __enter__ and __exit__ for that to work. As an example of the with statement... for reading/writing files, you might have: with open('filename','r') as file: for line in file: # processing.... # File automatically closed afterwards or if there was an exception thrown If it doesn't support it, then you can always use try...finally as in: try: # Do some processing finally: # Cleanup The finally clause is executed no matter how the try finishes (whether it completed successfull, or an exception was propagated but caught, or an exception was thrown and will continue to propagate). A: Why not just wrap it in a try: finally: block? http://docs.python.org/tutorial/errors.html#defining-clean-up-actions This is what finally blocks are for. A: Assuming that the DB driver you're using doesn't support with out of the box, try the closing method from contextlib.
In Python, how to make sure database connection will always close before leaving a code block?
I want to prevent database connection being open as much as possible, because this code will run on an intensive used server and people here already told me database connections should always be closed as soon as possible. def do_something_that_needs_database (): dbConnection = MySQLdb.connect(host=args['database_host'], user=args['database_user'], passwd=args['database_pass'], db=args['database_tabl'], cursorclass=MySQLdb.cursors.DictCursor) dbCursor = dbConnection.cursor() dbCursor.execute('SELECT COUNT(*) total FROM table') row = dbCursor.fetchone() if row['total'] == 0: print 'error: table have no records' dbCursor.execute('UPDATE table SET field="%s"', whatever_value) return None print 'table is ok' dbCursor.execute('UPDATE table SET field="%s"', another_value) # a lot more of workflow done here dbConnection.close() # even more stuff would come below I believe that leaves a database connection open when there is no row on the table, tho I'm still really not sure how it works. Anyway, maybe that is bad design in the sense that I could open and close a DB connection after each small block of execute. And sure, I could just add a close right before the return in that case... But how could I always properly close the DB without having to worry if I have that return, or a raise, or continue, or whatever in the middle? I'm thinking in something like a code block, similar to using try, like in the following suggestion, which obviously doesn't work: def do_something_that_needs_database (): dbConnection = MySQLdb.connect(host=args['database_host'], user=args['database_user'], passwd=args['database_pass'], db=args['database_tabl'], cursorclass=MySQLdb.cursors.DictCursor) try: dbCursor = dbConnection.cursor() dbCursor.execute('SELECT COUNT(*) total FROM table') row = dbCursor.fetchone() if row['total'] == 0: print 'error: table have no records' dbCursor.execute('UPDATE table SET field="%s"', whatever_value) return None print 'table is ok' dbCursor.execute('UPDATE table SET field="%s"', another_value) # again, that same lot of line codes done here except ExitingCodeBlock: closeDb(dbConnection) # still, that "even more stuff" from before would come below I don't think there is anything similar to ExitingCodeBlock for an exception, tho I know there is the try else, but I hope Python already have a similar feature... Or maybe someone can suggest me a paradigm move and tell me this is awful and highly advise me to never do that. Maybe this is just something to not worry about and let MySQLdb handle it, or is it?
[ "The traditional approach is the try/finally statement:\ndef do_something_that_needs_database ():\n dbConnection = MySQLdb.connect(host=args['database_host'], user=args['database_user'], passwd=args['database_pass'], db=args['database_tabl'], cursorclass=MySQLdb.cursors.DictCursor)\n try:\n # as much work as you want, including return, raising exceptions, _whatever_\n finally:\n closeDb(dbConnection)\n\nSince Python 2.6 (and 2.5 with a from __future__ import with_statement), there is an alternative (although try/finally still works perfectly well!): the with statement.\nwith somecontext as whatever:\n # the work goes here\n\nA context has an __enter__ method, executed on entry (to return the whatever above, if you want) and an __exit__ method, executed on exit. Despite the elegance, since there is no existing context that works the way you want, the work needed to build one (although reduced in 2.6 with contextlib) should probably suggest that good old try/finally is best.\nIf you have 2.6 and want to try contextlib, this is one way you could do it to \"hide\" the try/finally...:\nimport contextlib\n\n@contextlib.contextmanager\ndef dbconnect(**kwds):\n dbConnection = MySQLdb.connect(**kwds)\n try:\n yield dbConnection\n finally:\n closeDb(dbConnection)\n\nto be used as:\ndef do_something_that_needs_database ():\n with dbconnect(host=args['database_host'], user=args['database_user'], \n passwd=args['database_pass'], db=args['database_tabl'], \n cursorclass=MySQLdb.cursors.DictCursor) as dbConnection:\n # as much work as you want, including return, raising exceptions, _whatever_\n\nIt may be worth it if you are going to use this many, many times, just to avoid repeating the try/finally over and over for each of those many uses.\n", "If MySQLdb supports it, then you could use the \"with\" statement. The \"with\" statement exists for just that reason. However, it requires that the object define __enter__ and __exit__ for that to work.\nAs an example of the with statement... for reading/writing files, you might have:\nwith open('filename','r') as file:\n for line in file:\n # processing....\n# File automatically closed afterwards or if there was an exception thrown\n\nIf it doesn't support it, then you can always use try...finally as in:\ntry:\n # Do some processing\nfinally:\n # Cleanup\n\nThe finally clause is executed no matter how the try finishes (whether it completed successfull, or an exception was propagated but caught, or an exception was thrown and will continue to propagate).\n", "Why not just wrap it in a try: finally: block?\nhttp://docs.python.org/tutorial/errors.html#defining-clean-up-actions\nThis is what finally blocks are for.\n", "Assuming that the DB driver you're using doesn't support with out of the box, try the closing method from contextlib.\n" ]
[ 33, 6, 4, 4 ]
[]
[]
[ "database_connection", "nested", "python" ]
stackoverflow_0002837822_database_connection_nested_python.txt
Q: Huge amount of time sending data with suds and proxy I have the following code to send data through a proxy using suds: import suds t = suds.transport.http.HttpTransport() proxy = urllib2.ProxyHandler({'http': 'http://192.168.3.217:3128'}) opener = urllib2.build_opener(proxy) t.urlopener = opener ws = suds.client.Client('http://xxxxxxx/web.asmx?WSDL', transport=t) req = ws.factory.create('ActionRequest.request') req.SerialNumber = 'asdf' req.HostName = 'hola' res = ws.service.ActionRequest(req) I don't know why, but it can be sending data above 2 or 3 minutes, or even more and it raises a "Gateway timeout" exception sometimes. If I don't use the proxy, the amount of time used is above 2 seconds or less. Here is the SOAP reply: (ActionResponse){ Id = None Action = "Action.None" Objects = "" } The proxy is running right with other requests through urllib2, or using normal web browsers like firefox. Does anyone have any idea what's happening here with suds? Thanks a lot in advance!!! A: A sniffer output (e.g. from wireshark) could be very helpful to understand this one.
Huge amount of time sending data with suds and proxy
I have the following code to send data through a proxy using suds: import suds t = suds.transport.http.HttpTransport() proxy = urllib2.ProxyHandler({'http': 'http://192.168.3.217:3128'}) opener = urllib2.build_opener(proxy) t.urlopener = opener ws = suds.client.Client('http://xxxxxxx/web.asmx?WSDL', transport=t) req = ws.factory.create('ActionRequest.request') req.SerialNumber = 'asdf' req.HostName = 'hola' res = ws.service.ActionRequest(req) I don't know why, but it can be sending data above 2 or 3 minutes, or even more and it raises a "Gateway timeout" exception sometimes. If I don't use the proxy, the amount of time used is above 2 seconds or less. Here is the SOAP reply: (ActionResponse){ Id = None Action = "Action.None" Objects = "" } The proxy is running right with other requests through urllib2, or using normal web browsers like firefox. Does anyone have any idea what's happening here with suds? Thanks a lot in advance!!!
[ "A sniffer output (e.g. from wireshark) could be very helpful to understand this one.\n" ]
[ 0 ]
[]
[]
[ "proxy", "python", "suds" ]
stackoverflow_0001922538_proxy_python_suds.txt
Q: Django & custom auth backend (web service) + no database. How to save stuff in session? I've been searching here and there, and based on this answer I've put together what you see below. It works, but I need to put some stuff in the user's session, right there inside authenticate. How would I store acme_token in the user's session, so that it will get cleared if they logged out? The request object is not available in this context class AcmeUserBackend(object): # Create a User object if not already in the database? create_unknown_user = False def get_user(self, username): return AcmeUser(id=username) def authenticate(self, username=None, password=None): """ Check the username/password and return an AcmeUser. """ acme_token = ask_another_site_about_creds(username, password) if acme_token: return AcmeUser(id=username) return None A: Shove it onto the returned user, then handle it in middleware.
Django & custom auth backend (web service) + no database. How to save stuff in session?
I've been searching here and there, and based on this answer I've put together what you see below. It works, but I need to put some stuff in the user's session, right there inside authenticate. How would I store acme_token in the user's session, so that it will get cleared if they logged out? The request object is not available in this context class AcmeUserBackend(object): # Create a User object if not already in the database? create_unknown_user = False def get_user(self, username): return AcmeUser(id=username) def authenticate(self, username=None, password=None): """ Check the username/password and return an AcmeUser. """ acme_token = ask_another_site_about_creds(username, password) if acme_token: return AcmeUser(id=username) return None
[ "Shove it onto the returned user, then handle it in middleware.\n" ]
[ 2 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0002836969_django_django_models_python.txt
Q: Python subprocess.Popen hangs in 'for l in p.stdout' until p terminates, why? I have that code: #!/usr/bin/python -u localport = 9876 import sys, re, os from subprocess import * tun = Popen(["./newtunnel", "22", str(localport)], stdout=PIPE, stderr=STDOUT) print "** Started tunnel, waiting to be ready ..." for l in tun.stdout: sys.stdout.write(l) if re.search("Waiting for connection", l): print "** Ready for SSH !" break The "./newtunnel" will not exit, it will constantly output more and more data to stdout. However, that code will not give any output and just keeps waiting in the tun.stdout. When I kill the newtunnel process externally, it flushes all the data to tun.stdout. So it seems that I can't get any data from the tun.stdout while it is still running. Why is that? How can I get the information? Note that the default bufsize for Popen is 0 (unbuffered). I can also specify bufsize=0 but that doesn't change anything. A: Ok, it seems that it is a bug in Python: http://bugs.python.org/issue3907 If I replace the line for l in tun.stdout: by while True: l = tun.stdout.readline() then it works exactly the way I want.
Python subprocess.Popen hangs in 'for l in p.stdout' until p terminates, why?
I have that code: #!/usr/bin/python -u localport = 9876 import sys, re, os from subprocess import * tun = Popen(["./newtunnel", "22", str(localport)], stdout=PIPE, stderr=STDOUT) print "** Started tunnel, waiting to be ready ..." for l in tun.stdout: sys.stdout.write(l) if re.search("Waiting for connection", l): print "** Ready for SSH !" break The "./newtunnel" will not exit, it will constantly output more and more data to stdout. However, that code will not give any output and just keeps waiting in the tun.stdout. When I kill the newtunnel process externally, it flushes all the data to tun.stdout. So it seems that I can't get any data from the tun.stdout while it is still running. Why is that? How can I get the information? Note that the default bufsize for Popen is 0 (unbuffered). I can also specify bufsize=0 but that doesn't change anything.
[ "Ok, it seems that it is a bug in Python: http://bugs.python.org/issue3907\nIf I replace the line\nfor l in tun.stdout:\n\nby\nwhile True:\n l = tun.stdout.readline()\n\nthen it works exactly the way I want.\n" ]
[ 2 ]
[]
[]
[ "popen", "python", "subprocess" ]
stackoverflow_0002838035_popen_python_subprocess.txt
Q: Python msn hook - possible? Is it possible to hook msn via a python application to send messages to your contacts etc? A: You can use twisted.words.protocols.msn or use libpurple through its DBus bindings or Python bindings.
Python msn hook - possible?
Is it possible to hook msn via a python application to send messages to your contacts etc?
[ "You can use twisted.words.protocols.msn or use libpurple through its DBus bindings or Python bindings. \n" ]
[ 3 ]
[]
[]
[ "hook", "msn", "python" ]
stackoverflow_0002838458_hook_msn_python.txt
Q: import problem with twisted.web server I'm just getting started with twisted.web, and I'm having trouble importing a Python module into a .rpy script. in C:\py\twisted\mysite.py, I have this: from twisted.web.resource import Resource from twisted.web import server class MySite(Resource): def render_GET(self, request): request.write("<!DOCTYPE html>") request.write("<html><head>") request.write("<title>Twisted Driven Site</title>") request.write("</head><body>") request.write("<h1>Twisted Driven Website</h1>") request.write("<p>Prepath: <pre>{0}</pre></p>".format(request.prepath)) request.write("</body></html>") request.finish() return server.NOT_DONE_YET and in C:\py\twisted\index.rpy, I have this: import mysite reload(mysite) resource = mysite.MySite() I ran twistd -n web --port 8888 --path C:\py\twisted in command prompt and the server started successfully. But when I requested localhost:8888 I got a (huge) stack trace originating from an ImportError: <type 'exceptions.ImportError'>: No module named mysite I can import the module from the interpreter, and if i just execute index.rpy as a python script, I don't get the import error. The documentation on this subject is a bit vague, it just says "However, it is often a better idea to define Resource subclasses in Python modules. In order for changes in modules to be visible, you must either restart the Python process, or reload the module:" (from here). Does anyone know the proper way to do this? A: Short answer: you need to set PYTHONPATH to include C:\py\twisted. Long answer... An rpy script is basically just some Python code, like any other Python code. So an import in a rpy script works just like an import in any other Python code. For the most common case, this means that the directories in sys.path are visited one by one, in order, and if a .py file matching the imported name is found, that file is used to define the module. sys.path is mostly populated from a static definition including things like C:\Python26\Lib\ and from the PYTHONPATH environment variable. However, there's one extra thing worth knowing about. When you run "python", the current working directory is added to the front of sys.path. When you run "python C:\foo\bar\baz.py", C:\foo\bar\' is added to the front ofsys.path. But when you run "twistd ...", nothing useful is added tosys.path`. This last behavior probably explains why your tests work if you run the rpy script directly, or if you run python and try to import the module interactively, but fail when you use twistd. Adding C:\py\twisted to the PYTHONPATH environment variable should make the module importable when the rpy script is run from the server you start with twistd.
import problem with twisted.web server
I'm just getting started with twisted.web, and I'm having trouble importing a Python module into a .rpy script. in C:\py\twisted\mysite.py, I have this: from twisted.web.resource import Resource from twisted.web import server class MySite(Resource): def render_GET(self, request): request.write("<!DOCTYPE html>") request.write("<html><head>") request.write("<title>Twisted Driven Site</title>") request.write("</head><body>") request.write("<h1>Twisted Driven Website</h1>") request.write("<p>Prepath: <pre>{0}</pre></p>".format(request.prepath)) request.write("</body></html>") request.finish() return server.NOT_DONE_YET and in C:\py\twisted\index.rpy, I have this: import mysite reload(mysite) resource = mysite.MySite() I ran twistd -n web --port 8888 --path C:\py\twisted in command prompt and the server started successfully. But when I requested localhost:8888 I got a (huge) stack trace originating from an ImportError: <type 'exceptions.ImportError'>: No module named mysite I can import the module from the interpreter, and if i just execute index.rpy as a python script, I don't get the import error. The documentation on this subject is a bit vague, it just says "However, it is often a better idea to define Resource subclasses in Python modules. In order for changes in modules to be visible, you must either restart the Python process, or reload the module:" (from here). Does anyone know the proper way to do this?
[ "Short answer: you need to set PYTHONPATH to include C:\\py\\twisted.\nLong answer...\nAn rpy script is basically just some Python code, like any other Python code. So an import in a rpy script works just like an import in any other Python code. For the most common case, this means that the directories in sys.path are visited one by one, in order, and if a .py file matching the imported name is found, that file is used to define the module.\nsys.path is mostly populated from a static definition including things like C:\\Python26\\Lib\\ and from the PYTHONPATH environment variable. However, there's one extra thing worth knowing about. When you run \"python\", the current working directory is added to the front of sys.path. When you run \"python C:\\foo\\bar\\baz.py\", C:\\foo\\bar\\' is added to the front ofsys.path. But when you run \"twistd ...\", nothing useful is added tosys.path`.\nThis last behavior probably explains why your tests work if you run the rpy script directly, or if you run python and try to import the module interactively, but fail when you use twistd. Adding C:\\py\\twisted to the PYTHONPATH environment variable should make the module importable when the rpy script is run from the server you start with twistd.\n" ]
[ 5 ]
[]
[]
[ "python", "twisted", "twisted.web" ]
stackoverflow_0002838145_python_twisted_twisted.web.txt
Q: How can I get sessions to work if I'm using Google App Engine + Django 1.1? Is there a way for me to get sessions working? I know Django has built in session management, and GAE has some tools for it if you're using their watered down version of Django 0.96, but is there a way to get sessions to work if you're trying to use GAE w/ Django 1.1 (i.e. use_library() call). I assume using a db-backed session doesn't work, and a file system backed one won't work b/c we don't have access to the filesystem if we deploy to the Google production servers. This kinda worked (as in didn't crap out) when I used SessionMiddleware backed by a local-memory backed cache and a non-persistent cache (i.e. setting SESSION_ENGINE to django.contrib.sessions.backends.cache). But the session never seems to persist in this case, no matter how I set the timeouts. A new session key is generated on every page reload. Maybe this is b/c the GAE assumes complete statelessness with each request and blows away my local cache? Apologies in advance, I'm pretty new to Python. Any suggestions would be greatly appreciated. A: If you want to use the django sessions, you need to use the google django helper here: http://code.google.com/p/google-app-engine-django/ Which says: Support for the db and cache session backed modules when using Django 1.0 alpha Even though it says 1.0 alpha, it means 1.0 and above.
How can I get sessions to work if I'm using Google App Engine + Django 1.1?
Is there a way for me to get sessions working? I know Django has built in session management, and GAE has some tools for it if you're using their watered down version of Django 0.96, but is there a way to get sessions to work if you're trying to use GAE w/ Django 1.1 (i.e. use_library() call). I assume using a db-backed session doesn't work, and a file system backed one won't work b/c we don't have access to the filesystem if we deploy to the Google production servers. This kinda worked (as in didn't crap out) when I used SessionMiddleware backed by a local-memory backed cache and a non-persistent cache (i.e. setting SESSION_ENGINE to django.contrib.sessions.backends.cache). But the session never seems to persist in this case, no matter how I set the timeouts. A new session key is generated on every page reload. Maybe this is b/c the GAE assumes complete statelessness with each request and blows away my local cache? Apologies in advance, I'm pretty new to Python. Any suggestions would be greatly appreciated.
[ "If you want to use the django sessions, you need to use the google django helper here: http://code.google.com/p/google-app-engine-django/\nWhich says: \n\nSupport for the db and cache session backed modules when using Django 1.0 alpha\n\nEven though it says 1.0 alpha, it means 1.0 and above.\n" ]
[ 1 ]
[]
[]
[ "django", "google_app_engine", "python", "session" ]
stackoverflow_0002837802_django_google_app_engine_python_session.txt
Q: Efficient update of SQLite table with many records I am trying to use sqlite (sqlite3) for a project to store hundreds of thousands of records (would like sqlite so users of the program don't have to run a [my]sql server). I have to update hundreds of thousands of records sometimes to enter left right values (they are hierarchical), but have found the standard update table set left_value = 4, right_value = 5 where id = 12340; to be very slow. I have tried surrounding every thousand or so with begin; .... update... update table set left_value = 4, right_value = 5 where id = 12340; update... .... commit; but again, very slow. Odd, because when I populate it with a few hundred thousand (with inserts), it finishes in seconds. I am currently trying to test the speed in python (the slowness is at the command line and python) before I move it to the C++ implementation, but right now this is way to slow and I need to find a new solution unless I am doing something wrong. Thoughts? (would take open source alternative to SQLite that is portable as well) A: Create an index on table.id create index table_id_index on table(id) A: Other than making sure you have an index in place, you can checkout the SQLite Optimization FAQ. Using transactions can give you a very big speed increase as you mentioned and you can also try to turn off journaling. Example 1: 2.2 PRAGMA synchronous The Boolean synchronous value controls whether or not the library will wait for disk writes to be fully written to disk before continuing. This setting can be different from the default_synchronous value loaded from the database. In typical use the library may spend a lot of time just waiting on the file system. Setting "PRAGMA synchronous=OFF" can make a major speed difference. Example 2: 2.3 PRAGMA count_changes When the count_changes setting is ON, the callback function is invoked once for each DELETE, INSERT, or UPDATE operation. The argument is the number of rows that were changed. If you don't use this feature, there is a small speed increase from turning this off.
Efficient update of SQLite table with many records
I am trying to use sqlite (sqlite3) for a project to store hundreds of thousands of records (would like sqlite so users of the program don't have to run a [my]sql server). I have to update hundreds of thousands of records sometimes to enter left right values (they are hierarchical), but have found the standard update table set left_value = 4, right_value = 5 where id = 12340; to be very slow. I have tried surrounding every thousand or so with begin; .... update... update table set left_value = 4, right_value = 5 where id = 12340; update... .... commit; but again, very slow. Odd, because when I populate it with a few hundred thousand (with inserts), it finishes in seconds. I am currently trying to test the speed in python (the slowness is at the command line and python) before I move it to the C++ implementation, but right now this is way to slow and I need to find a new solution unless I am doing something wrong. Thoughts? (would take open source alternative to SQLite that is portable as well)
[ "Create an index on table.id\ncreate index table_id_index on table(id)\n\n", "Other than making sure you have an index in place, you can checkout the SQLite Optimization FAQ.\nUsing transactions can give you a very big speed increase as you mentioned and you can also try to turn off journaling.\nExample 1:\n\n2.2 PRAGMA synchronous\nThe Boolean synchronous value controls\n whether or not the library will wait\n for disk writes to be fully written to\n disk before continuing. This setting\n can be different from the\n default_synchronous value loaded from\n the database. In typical use the\n library may spend a lot of time just\n waiting on the file system. Setting\n \"PRAGMA synchronous=OFF\" can make a\n major speed difference.\n\nExample 2:\n\n2.3 PRAGMA count_changes\nWhen the count_changes setting is ON,\n the callback function is invoked once\n for each DELETE, INSERT, or UPDATE\n operation. The argument is the number\n of rows that were changed. If you\n don't use this feature, there is a\n small speed increase from turning this\n off.\n\n" ]
[ 13, 3 ]
[]
[]
[ "c++", "database", "python", "sql", "sqlite" ]
stackoverflow_0002838790_c++_database_python_sql_sqlite.txt
Q: Why doesn't negative values for the second index in a jagged array work in Python? For example, if I have the following (data from Project Euler): s = [[75], [95, 64], [17, 47, 82], [18, 35, 87, 10], [20, 4, 82, 47, 65], [19, 1, 23, 75, 3, 34], [88, 2, 77, 73, 7, 63, 67], [99, 65, 4, 28, 6, 16, 70, 92], [41, 41, 26, 56, 83, 40, 80, 70, 33], [41, 48, 72, 33, 47, 32, 37, 16, 94, 29], [53, 71, 44, 65, 25, 43, 91, 52, 97, 51, 14], [70, 11, 33, 28, 77, 73, 17, 78, 39, 68, 17, 57], [91, 71, 52, 38, 17, 14, 91, 43, 58, 50, 27, 29, 48], [63, 66, 4, 68,89, 53, 67, 30, 73, 16, 69, 87, 40, 31], [4, 62, 98, 27, 23, 9, 70, 98, 73, 93, 38, 53, 60, 4, 23]] Why does s[1:][:-1] give me the same thing as s[1:] instead of (what I want) [s[i][:-1] for i in range(1,len(s))]. In other words, why does Python ignore my second index? A: Python doesn't have 2-dimensional lists, it has lists of lists. I think the first [1:] gives everything but the first contained list, and the second [:-1] takes that result and removes the last contained list. What you want is: [r[:-1] for r in s[1:]] A: You're misdescribing the results: s[1:][:-1] is definitely not the same as s[:1], as you erroneously say -- it is, rather, the same as s[1:-1]. Check it out! This must necessarily hold true of any list s, no matter what its contents may be (other lists, dicts, strings, floats, unicorns, ...): s[1:] means "all but the first", then [:-1] means "all but the last", so obviously their combined effects are the same as [1:-1] which means "all but the first and last". The indexing-like syntax with a colon in the brackets is also known as slicing, and when applied to a list (of whatevers) it returns another (typically shorter) list (also of whatevers). Thinking of s as a "jagged array" rather than what it actually is (just a list, whose items happen to also be lists -- but the type of some or all of the items obviously can't and shouldn't affect the semantics of operations on the list itself, like slicing) may be what's throwing you off; perhaps because, if the first indexing is actually an indexing and not a slicing, its results is an item of the original list -- a "whatever" (a list of ints in your case), not a list of whatevers. So if you then apply a further indexing or slicing you're doing that on one of the original sublists -- a very different matter. @Mark's answer has already shown the canonical list-comprehension solution to do what you actually want. I think that other approaches, if you have matlab code and want the Python equivalent, might include OMPC (but I haven't tried that myself).
Why doesn't negative values for the second index in a jagged array work in Python?
For example, if I have the following (data from Project Euler): s = [[75], [95, 64], [17, 47, 82], [18, 35, 87, 10], [20, 4, 82, 47, 65], [19, 1, 23, 75, 3, 34], [88, 2, 77, 73, 7, 63, 67], [99, 65, 4, 28, 6, 16, 70, 92], [41, 41, 26, 56, 83, 40, 80, 70, 33], [41, 48, 72, 33, 47, 32, 37, 16, 94, 29], [53, 71, 44, 65, 25, 43, 91, 52, 97, 51, 14], [70, 11, 33, 28, 77, 73, 17, 78, 39, 68, 17, 57], [91, 71, 52, 38, 17, 14, 91, 43, 58, 50, 27, 29, 48], [63, 66, 4, 68,89, 53, 67, 30, 73, 16, 69, 87, 40, 31], [4, 62, 98, 27, 23, 9, 70, 98, 73, 93, 38, 53, 60, 4, 23]] Why does s[1:][:-1] give me the same thing as s[1:] instead of (what I want) [s[i][:-1] for i in range(1,len(s))]. In other words, why does Python ignore my second index?
[ "Python doesn't have 2-dimensional lists, it has lists of lists. I think the first [1:] gives everything but the first contained list, and the second [:-1] takes that result and removes the last contained list.\nWhat you want is:\n[r[:-1] for r in s[1:]]\n\n", "You're misdescribing the results: s[1:][:-1] is definitely not the same as s[:1], as you erroneously say -- it is, rather, the same as s[1:-1]. Check it out!\nThis must necessarily hold true of any list s, no matter what its contents may be (other lists, dicts, strings, floats, unicorns, ...): s[1:] means \"all but the first\", then [:-1] means \"all but the last\", so obviously their combined effects are the same as [1:-1] which means \"all but the first and last\". The indexing-like syntax with a colon in the brackets is also known as slicing, and when applied to a list (of whatevers) it returns another (typically shorter) list (also of whatevers).\nThinking of s as a \"jagged array\" rather than what it actually is (just a list, whose items happen to also be lists -- but the type of some or all of the items obviously can't and shouldn't affect the semantics of operations on the list itself, like slicing) may be what's throwing you off; perhaps because, if the first indexing is actually an indexing and not a slicing, its results is an item of the original list -- a \"whatever\" (a list of ints in your case), not a list of whatevers. So if you then apply a further indexing or slicing you're doing that on one of the original sublists -- a very different matter.\n@Mark's answer has already shown the canonical list-comprehension solution to do what you actually want. I think that other approaches, if you have matlab code and want the Python equivalent, might include OMPC (but I haven't tried that myself).\n" ]
[ 4, 2 ]
[]
[]
[ "jagged_arrays", "python" ]
stackoverflow_0002838712_jagged_arrays_python.txt
Q: pywinauto: taking more than one app windows I have a GUI application which can create many similar windows on desktop. All windows have same title. I have to enumerate all dialogs with same title and make some tests against each of such dialogs. If I call: dialog = app['Window Name'] pywinauto returns a WindowSpecification object which is useful along with accessing controls by name. When I call: dialogs = app.windows_(title='Window Name') pywinauto returns me a list of HwndWrapper instances which are not so useful. How to obtain a list of windows with specified title but as WindowSpecification objects? A: You can't really. WindowSpecification is a single specification for all windows that match the criteria supplied. When you work with a WindowSpecification instance you are often interacting with an HwndWrapper instance that WindowSpecification is finding and accessing for you. So I think the answer is to work with the HwndWrapper's returned by app.windows_() (similar to the single HwndWrapper returned by WindowSpecification.WrapperObject() Note - if you are always trying to narrow down the list of windows by looking at particular controls within a window - then using app['Window Name']['Unique Control Name'].Parent() should return the window. The main difference between WindowSpecification and HwndWrapper is that a WindowSpecification does not have to exist yet, while a HwndWrapper instance reflects a particular underlying windows handle. This allows WindowSpecification to implement code that waits for windows or checks if they exist.
pywinauto: taking more than one app windows
I have a GUI application which can create many similar windows on desktop. All windows have same title. I have to enumerate all dialogs with same title and make some tests against each of such dialogs. If I call: dialog = app['Window Name'] pywinauto returns a WindowSpecification object which is useful along with accessing controls by name. When I call: dialogs = app.windows_(title='Window Name') pywinauto returns me a list of HwndWrapper instances which are not so useful. How to obtain a list of windows with specified title but as WindowSpecification objects?
[ "You can't really. WindowSpecification is a single specification for all windows that match the criteria supplied. \nWhen you work with a WindowSpecification instance you are often interacting with an HwndWrapper instance that WindowSpecification is finding and accessing for you.\nSo I think the answer is to work with the HwndWrapper's returned by app.windows_() (similar to the single HwndWrapper returned by WindowSpecification.WrapperObject()\nNote - if you are always trying to narrow down the list of windows by looking at particular controls within a window - then using app['Window Name']['Unique Control Name'].Parent() should return the window.\nThe main difference between WindowSpecification and HwndWrapper is that a WindowSpecification does not have to exist yet, while a HwndWrapper instance reflects a particular underlying windows handle. This allows WindowSpecification to implement code that waits for windows or checks if they exist.\n" ]
[ 4 ]
[]
[]
[ "matching", "python", "pywinauto", "window" ]
stackoverflow_0002829925_matching_python_pywinauto_window.txt
Q: increasing string size through loop what's a simple way to increase the length of a string to an arbitrary integer x? like 'a' goes to 'z' and then goes to 'aa' to 'zz' to 'aaa', etc. A: That should do the trick: def iterate_strings(n): if n <= 0: yield '' return for c in string.ascii_lowercase: for s in iterate_strings(n - 1): yield c + s It returns a generator. You can iterate it with a for loop: for s in iterate_strings(5) Or get a list of the strings: list(iterate_strings(5)) If you want to iterate over shorter strings too, you can use this function: def iterate_strings(n): yield '' if n <= 0: return for c in string.ascii_lowercase: for s in iterate_strings(n - 1): yield c + s A: Here's my solution, similar to Adam's, except it's not recursive. :]. from itertools import product from string import lowercase def letter_generator(limit): for length in range(1, limit+1): for letters in product(lowercase, repeat=length): yield ''.join(letters) And it returns a generator, so you can use a for loop to iterate over it: for letters in letter_generator(5): # ... Have fun! (This is the second time today I found itertools.product() useful. Woot.) A: You can multiply the string in the integer. For example >>> 'a' * 2 'aa' >>> 'a' * 4 'aaaa' >>> 'z' * 3 'zzz' >>> 'az' * 3 'azazaz' A: Define x. I am using x = 5 for this example. x = 5 import string for n in range(1,x+1): for letter in string.ascii_lowercase: print letter*n
increasing string size through loop
what's a simple way to increase the length of a string to an arbitrary integer x? like 'a' goes to 'z' and then goes to 'aa' to 'zz' to 'aaa', etc.
[ "That should do the trick:\ndef iterate_strings(n):\n if n <= 0:\n yield ''\n return\n for c in string.ascii_lowercase:\n for s in iterate_strings(n - 1):\n yield c + s\n\nIt returns a generator.\nYou can iterate it with a for loop:\nfor s in iterate_strings(5)\n\nOr get a list of the strings:\nlist(iterate_strings(5))\n\nIf you want to iterate over shorter strings too, you can use this function:\ndef iterate_strings(n):\n yield ''\n if n <= 0:\n return\n for c in string.ascii_lowercase:\n for s in iterate_strings(n - 1):\n yield c + s\n\n", "Here's my solution, similar to Adam's, except it's not recursive. :].\nfrom itertools import product\nfrom string import lowercase\n\ndef letter_generator(limit):\n for length in range(1, limit+1):\n for letters in product(lowercase, repeat=length):\n yield ''.join(letters)\n\nAnd it returns a generator, so you can use a for loop to iterate over it:\nfor letters in letter_generator(5):\n # ...\n\nHave fun!\n(This is the second time today I found itertools.product() useful. Woot.)\n", "You can multiply the string in the integer.\nFor example\n>>> 'a' * 2\n'aa'\n>>> 'a' * 4\n'aaaa'\n>>> 'z' * 3\n'zzz'\n>>> 'az' * 3\n'azazaz'\n\n", "Define x. I am using x = 5 for this example.\nx = 5\nimport string\nfor n in range(1,x+1):\n for letter in string.ascii_lowercase:\n print letter*n\n\n" ]
[ 7, 3, 0, 0 ]
[]
[]
[ "python", "string" ]
stackoverflow_0002838261_python_string.txt
Q: How to find/replace text in html while preserving html tags/structure I use regexps to transform text as I want, but I want to preserve the HTML tags. e.g. if I want to replace "stack overflow" with "stack underflow", this should work as expected: if the input is stack <sometag>overflow</sometag>, I must obtain stack <sometag>underflow</sometag> (i.e. the string substitution is done, but the tags are still there... A: Use a DOM library, not regular expressions, when dealing with manipulating HTML: lxml: a parser, document, and HTML serializer. Also can use BeautifulSoup and html5lib for parsing. BeautifulSoup: a parser, document, and HTML serializer. html5lib: a parser. It has a serializer. ElementTree: a document object, and XML serializer cElementTree: a document object implemented as a C extension. HTMLParser: a parser. Genshi: includes a parser, document, and HTML serializer. xml.dom.minidom: a document model built into the standard library, which html5lib can parse to. Stolen from http://blog.ianbicking.org/2008/03/30/python-html-parser-performance/. Out of these I would recommend lxml, html5lib, and BeautifulSoup. A: Beautiful Soup or HTMLParser is your answer. A: Note that arbitrary replacements can't be done unambiguously. Consider the following examples: 1) HTML: A<tag>B</tag> Pattern -> replacement: AB -> AXB Possible results: AX<tag>B</tag> A<tag>XB</tag> 2) HTML: A<tag>A</tag>A Pattern -> replacement: A+ -> WXYZ Possible results: W<tag />XYZ W<tag>X</tag>YZ W<tag>XY</tag>Z W<tag>XYZ</tag> WX<tag />YZ WX<tag>Y</tag>Z WX<tag>YZ</tag> WXY<tag />Z WXY<tag>Z</tag> WXYZ What kind of algorithms work for your case depends highly on the nature of possible search patterns and desired rules for handling ambiguity. A: Use html parser such as provided by lxml or BeautifulSoup. Another option is to use XSLT transformations (XSLT in Jython). A: I don't think that the DOM / HTML parser library recommendations posted so far address the specific problem in the given example: overflow should replaced with underflow only when preceded by stack in the rendered document, whether or not there are tags between them. Such a library is a necessary part the solution, though. Assuming that tags never appear in the middle of words, one solution would be to process the DOM, tokenize all text nodes and insert a unique identifier at the beginning of each token (e.g. word) render the document as plain text search and replace the plain text with regexes which use groups to match, preserve and mark unique identifiers at the beginning of each token extract all tokens with marked unique identifiers from the plain text process the DOM by removing unique identifiers and replacing tokens matching marked unique identifiers with corresponding changed tokens render the processed DOM back to HTML Example: In 1. the HTML DOM, stack <sometag>overflow</sometag> becomes the DOM #1;stack <sometag>#2;overflow</sometag> and in 2. the plain text is produced: #1;stack #2;overflow The regex needed in 3. is #(\d+);stack\s+#(\d+);overflow\b and the replacement #\1;stack %\2;underflow. Note that only the second word is marked by changing # to % in the unique identifier, since the first word isn't altered. In 4., the word underflow with the unique identifier numbered 2 is extracted from the resulting plain text since it was marked by changing the # to a %. In 5., all #(\d+); identifiers are removed from text nodes of the DOM while looking up their numbers among extracted words. The number 1 is not found, so #1;stack is replaced with simply stack. The number 2 is found with the changed word underflow, so #2;overflow is replaced by underflow. Finally in 6. the DOM is rendered back to the HTML document `stack underflow.
How to find/replace text in html while preserving html tags/structure
I use regexps to transform text as I want, but I want to preserve the HTML tags. e.g. if I want to replace "stack overflow" with "stack underflow", this should work as expected: if the input is stack <sometag>overflow</sometag>, I must obtain stack <sometag>underflow</sometag> (i.e. the string substitution is done, but the tags are still there...
[ "Use a DOM library, not regular expressions, when dealing with manipulating HTML:\n\nlxml: a parser, document, and HTML serializer. Also can use BeautifulSoup and html5lib for parsing.\nBeautifulSoup: a parser, document, and HTML serializer.\nhtml5lib: a parser. It has a serializer.\nElementTree: a document object, and XML serializer \ncElementTree: a document object implemented as a C extension. \nHTMLParser: a parser. \nGenshi: includes a parser, document, and HTML serializer.\nxml.dom.minidom: a document model built into the standard library, which html5lib can parse to. \n\nStolen from http://blog.ianbicking.org/2008/03/30/python-html-parser-performance/.\nOut of these I would recommend lxml, html5lib, and BeautifulSoup.\n", "Beautiful Soup or HTMLParser is your answer.\n", "Note that arbitrary replacements can't be done unambiguously. Consider the following examples:\n1)\nHTML:\nA<tag>B</tag>\n\nPattern -> replacement:\nAB -> AXB\n\nPossible results:\nAX<tag>B</tag>\nA<tag>XB</tag>\n\n2)\nHTML:\nA<tag>A</tag>A\n\nPattern -> replacement:\nA+ -> WXYZ\n\nPossible results:\nW<tag />XYZ\nW<tag>X</tag>YZ\nW<tag>XY</tag>Z\nW<tag>XYZ</tag>\nWX<tag />YZ\nWX<tag>Y</tag>Z\nWX<tag>YZ</tag>\nWXY<tag />Z\nWXY<tag>Z</tag>\nWXYZ\n\nWhat kind of algorithms work for your case depends highly on the nature of possible search patterns and desired rules for handling ambiguity.\n", "Use html parser such as provided by lxml or BeautifulSoup. Another option is to use XSLT transformations (XSLT in Jython).\n", "I don't think that the DOM / HTML parser library recommendations posted so far address the specific problem in the given example: overflow should replaced with underflow only when preceded by stack in the rendered document, whether or not there are tags between them. Such a library is a necessary part the solution, though.\nAssuming that tags never appear in the middle of words, one solution would be to\n\nprocess the DOM, tokenize all text nodes and insert a unique identifier\nat the beginning of each token (e.g. word)\nrender the document as plain text\nsearch and replace the plain text with regexes which use groups to match, preserve and\nmark unique identifiers at the beginning of each token\nextract all tokens with marked unique identifiers from the plain text\nprocess the DOM by removing unique identifiers and replacing tokens matching\nmarked unique identifiers with corresponding changed tokens\nrender the processed DOM back to HTML\n\nExample:\nIn 1. the HTML DOM,\nstack <sometag>overflow</sometag>\n\nbecomes the DOM\n#1;stack <sometag>#2;overflow</sometag>\n\nand in 2. the plain text is produced:\n#1;stack #2;overflow\n\nThe regex needed in 3. is #(\\d+);stack\\s+#(\\d+);overflow\\b and the replacement #\\1;stack %\\2;underflow. Note that only the second word is marked by changing # to % in the unique identifier, since the first word isn't altered.\nIn 4., the word underflow with the unique identifier numbered 2 is extracted from the resulting plain text since it was marked by changing the # to a %.\nIn 5., all #(\\d+); identifiers are removed from text nodes of the DOM while looking up their numbers among extracted words. The number 1 is not found, so #1;stack is replaced with simply stack. The number 2 is found with the changed word underflow, so #2;overflow is replaced by underflow.\nFinally in 6. the DOM is rendered back to the HTML document `stack underflow.\n" ]
[ 9, 3, 3, 1, 0 ]
[ "Fun stuff to try. It sorta works. My friends like it when I attach this script to a textarea and let them \"translate\" things. I guess you could use it for anything really. Meh. Check the code over a few times if you're going to use it, it works but I'm new to all this. I think it's been 2 or three weeks since I started studying the php.\n\n<?php\n\n$html = ('<div style=\"border: groove 2px;\"><p>Dear so and so, after reviewing your application I. . .</p><p>More of the same...</p><p>sincerely,</p><p>Important Dude</p></div>');\n\n$oldWords = array('important', 'sincerely');\n\n$newWords = array('arrogant', 'ya sure');\n\n// function for oldWords\nfunction regex_oldWords_word_list(&$item1, $key)\n{\n\n $item1 = \"/>([^<>]+)?\\b$item1(tionally|istic|tion|ance|ence|less|ally|able|ness|ing|ity|ful|ant|est|ist|ic|al|ed|er|et|ly|y|s|d|'s|'d|'ve|'ll)?\\b([^<>]+)?/\";\n\n}\n\n// function for newWords\nfunction format_newWords_results(&$item1, $key)\n{\n\n $item1 = \">$1<span style=\\\"color: red;\\\"><em> $item1$2</em></span>$3\";\n\n}\n\n// apply regex to oldWords\narray_walk($oldWords, 'regex_oldWords_word_list');\n\n// apply formatting to newWords\narray_walk($newWords, 'format_newWords_results');\n\n//HTML is not always as perfect as we want it\n$poo = array('/ /', '/>([a-zA-Z\\']+)/', '/’/', '/;([a-zA-Z\\']+)/', '/\"([a-zA-Z\\']+)/', '/([a-zA-Z\\']+)</', '/\\.\\.+/', '/\\. \\.+/');\n\n$unpoo = array(' ', '> $1', '\\'', '; $1', '\" $1', '$1 <', '. crap taco.', '. crap taco with cheese.');\n\n//and maybe things will go back to normal sort of\n$repoo = array('/> /', '/; /', '/\" /', '/ </');\n\n$muck = array('> ', ';', '\"',' <');\n\n//before\necho ($html);\n\n//I don't know what was happening on the free host but I had to keep stripping slashes\n//This is where the work is done anyway.\n$html = stripslashes(preg_replace($repoo , $muck , (ucwords(preg_replace($oldWords , $newWords , (preg_replace($poo , $unpoo , (stripslashes(strtolower(stripslashes($html)))))))))));\n\n//after\necho ('<hr/> ' . $html);\n\n//now if only there were a way to keep it out of the area between\n//<style>here</style> and <script>here</script> and tell it that english isn't math.\n\n?>\n\n" ]
[ -1 ]
[ "html", "html_parsing", "python" ]
stackoverflow_0001856014_html_html_parsing_python.txt
Q: How to include a dynamic page contents into a template? I have to include a dynamic page content into my template, Say I have a left panel which gets the data dynamically through a view. Now, I have to include this left panel into all my pages but I do not want to duplicate the code for all the pages. Is there any way, I can write a single script and include it in all my templates to display the left panel in all my pages? Thanks in advance. A: What you trying to achieve is directly supported in pretty much all template languages I know of. I would strongly recommend using one the many good choices for Python: Genshi Kid Jinja Mako If you were using Genshi for example (the default template language in TurboGears web application framework) what you want to do would look something like this: <html xmlns="http://www.w3.org/1999/xhtml" xmlns:py="http://genshi.edgewall.org/" xmlns:xi="http://www.w3.org/2001/XInclude" py:strip=""> <xi:include href="header.html" /> <xi:include href="sidebar.html" /> <xi:include href="footer.html" /> <!-- The rest of your page goes here --> <html> header.html, sidebar.html and footer.html need only be defined once and reused in any other page.
How to include a dynamic page contents into a template?
I have to include a dynamic page content into my template, Say I have a left panel which gets the data dynamically through a view. Now, I have to include this left panel into all my pages but I do not want to duplicate the code for all the pages. Is there any way, I can write a single script and include it in all my templates to display the left panel in all my pages? Thanks in advance.
[ "What you trying to achieve is directly supported in pretty much all template languages I know of. I would strongly recommend using one the many good choices for Python:\n\nGenshi\nKid\nJinja\nMako\n\nIf you were using Genshi for example (the default template language in TurboGears web application framework) what you want to do would look something like this:\n<html xmlns=\"http://www.w3.org/1999/xhtml\"\n xmlns:py=\"http://genshi.edgewall.org/\"\n xmlns:xi=\"http://www.w3.org/2001/XInclude\"\n py:strip=\"\">\n <xi:include href=\"header.html\" />\n <xi:include href=\"sidebar.html\" />\n <xi:include href=\"footer.html\" />\n\n <!-- The rest of your page goes here -->\n<html>\n\nheader.html, sidebar.html and footer.html need only be defined once and reused in any other page.\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0002839513_python.txt
Q: How to delete sentences starting with a lower case letter? In the example below the following regex (".*?") was used to remove all dialogue first. The next step is to remove all remaining sentences starting with a lower case letter. Only sentences starting with an upper case letter should remain. Example: exclaimed Wade. Indeed, below them were villages, of crude huts made of timber and stone and mud. Rubble work walls, for they needed little shelter here, and the people were but savages. asked Arcot, his voice a bit unsteady with suppressed excitement. replied Morey without turning from his station at the window. Below them now, less than half a mile down on the patchwork of the Nile valley, men were standing, staring up, collecting in little groups, gesticulating toward the strange thing that had materialized in the air above them. In the example above the following should be deleted only: exclaimed Wade. asked Arcot, his voice a bit unsteady with suppressed excitement. replied Morey without turning from his station at the window. A useful regex or simple Perl or python code is appreciated. I'm using version 7 of Textpipe. Thanks. A: This should work for the example you posted: text = re.sub(r'(^|(?<=[.!?])\s+)[a-z].*?[.!?](?=\s|$)', r'\1', text) A: This works for me in Perl on your example: $s = "exclaimed Wade. Indeed, ..."; do { $prev = $s; $s =~ s/(^\s*|[.!?]\s+)[a-z][^.!?]*[.!?]\s*/$1/gs; } until ($s eq $prev); Without the do loop it had trouble with removing multiple consecutive sentences. Note that doing this perfectly is pretty much AI-complete. See this question for examples of the kind of sentences that you'll never get right: LaTeX sometimes puts too much or too little space after periods. Of course you could use LaTeX's heuristic for what's a sentence-ending period and get it right most of the time. A: Why not use a module like Lingua::EN::Sentence? It makes it very easy to get pretty good sentences from arbitrary English text. #!perl use strict; use warnings; use Lingua::EN::Sentence qw( get_sentences ); my $text = <<END; exclaimed Wade. Indeed, below them were villages, of crude huts made of timber and stone and mud. Rubble work walls, for they needed little shelter here, and the people were but savages. asked Arcot, his voice a bit unsteady with suppressed excitement. replied Morey without turning from his station at the window. Below them now, less than half a mile down on the patchwork of the Nile valley, men were standing, staring up, collecting in little groups, gesticulating toward the strange thing that had materialized in the air above them. END my $sentences = matching_sentences( qr/^[^a-z]/, $text ); print map "$_\n", @$sentences; sub matching_sentences { my $re = shift; my $text = shift; my $s = get_sentences( $text ); @$s = grep /$re/, @$s; return $s; } Results: Indeed, below them were villages, of crude huts made of timber and stone and mud. Rubble work walls, for they needed little shelter here, and the people were but savages. Below them now, less than half a mile down on the patchwork of the Nile valley, men were standing, staring up, collecting in little groups, gesticulating toward the strange thing that had materialized in the air above them.
How to delete sentences starting with a lower case letter?
In the example below the following regex (".*?") was used to remove all dialogue first. The next step is to remove all remaining sentences starting with a lower case letter. Only sentences starting with an upper case letter should remain. Example: exclaimed Wade. Indeed, below them were villages, of crude huts made of timber and stone and mud. Rubble work walls, for they needed little shelter here, and the people were but savages. asked Arcot, his voice a bit unsteady with suppressed excitement. replied Morey without turning from his station at the window. Below them now, less than half a mile down on the patchwork of the Nile valley, men were standing, staring up, collecting in little groups, gesticulating toward the strange thing that had materialized in the air above them. In the example above the following should be deleted only: exclaimed Wade. asked Arcot, his voice a bit unsteady with suppressed excitement. replied Morey without turning from his station at the window. A useful regex or simple Perl or python code is appreciated. I'm using version 7 of Textpipe. Thanks.
[ "This should work for the example you posted:\ntext = re.sub(r'(^|(?<=[.!?])\\s+)[a-z].*?[.!?](?=\\s|$)', r'\\1', text)\n\n", "This works for me in Perl on your example:\n$s = \"exclaimed Wade. Indeed, ...\";\n\ndo {\n $prev = $s;\n $s =~ s/(^\\s*|[.!?]\\s+)[a-z][^.!?]*[.!?]\\s*/$1/gs;\n} until ($s eq $prev);\n\nWithout the do loop it had trouble with removing multiple consecutive sentences.\nNote that doing this perfectly is pretty much AI-complete.\nSee this question for examples of the kind of sentences that you'll never get right:\nLaTeX sometimes puts too much or too little space after periods.\nOf course you could use LaTeX's heuristic for what's a sentence-ending period and get it right most of the time.\n", "Why not use a module like Lingua::EN::Sentence? It makes it very easy to get pretty good sentences from arbitrary English text.\n#!perl\n\nuse strict;\nuse warnings;\n\nuse Lingua::EN::Sentence qw( get_sentences );\n\nmy $text = <<END;\n\nexclaimed Wade. Indeed, below them were villages, of crude huts made of timber and stone and mud. Rubble work walls, for they needed little shelter here, and the people were but savages.\n\nasked Arcot, his voice a bit unsteady with suppressed excitement.\n\nreplied Morey without turning from his station at the window. Below them now, less than half a mile down on the patchwork of the Nile valley, men were standing, staring up, collecting in little groups, gesticulating toward the strange thing that had materialized in the air above them.\nEND\n\n\nmy $sentences = matching_sentences( qr/^[^a-z]/, $text );\n\nprint map \"$_\\n\", @$sentences;\n\nsub matching_sentences {\n my $re = shift;\n my $text = shift;\n\n my $s = get_sentences( $text );\n\n @$s = grep /$re/, @$s;\n\n return $s;\n}\n\nResults:\nIndeed, below them were villages, of crude huts made of timber and stone and mud.\nRubble work walls, for they needed little shelter here, and the people were but savages.\nBelow them now, less than half a mile down on the patchwork of the Nile valley, men were standing, staring up, collecting in little groups, gesticulating toward the strange thing that had materialized in the air above them.\n\n" ]
[ 3, 0, 0 ]
[]
[]
[ "perl", "python", "regex", "text" ]
stackoverflow_0002664626_perl_python_regex_text.txt
Q: What are the most valuable certification available for Programming? I would like to know what are the certificates available for programming, like Zend for PHP SUN Certification for java What are the others? Javascript? C++? Python? etc... Please give me some suggestion for other available certifications. A: Most valuable thing for a developer: being able to show you can convert requirements into working and maintainable software. Certifications generally are worth very little, except in a few niches that demand them (or at least ask, until they give up and get someone who puts practice before pieces of paper). A: Let me be bold and say that your Experience is your best certificate. A: I second the opinion voiced here that the only valid certifications are experience and the work done by you so far. However you might want to check out these two link - prominent programming certifications and a discussion on slashdot on a similar subject. A: For ASP.NET the most valuable certificates are MCP certificates. Some of them are good for C++ too. http://en.wikipedia.org/wiki/Microsoft_Certified_Professional In PHP for there is the W3C certification (it exists js, and other programming languages to) http://www.w3schools.com/cert/cert_php.asp I think these certifications are very valuable. A: For linux (implies perl/bash) Comptia+ Red Hat Certified Engineer
What are the most valuable certification available for Programming?
I would like to know what are the certificates available for programming, like Zend for PHP SUN Certification for java What are the others? Javascript? C++? Python? etc... Please give me some suggestion for other available certifications.
[ "Most valuable thing for a developer: being able to show you can convert requirements into working and maintainable software.\nCertifications generally are worth very little, except in a few niches that demand them (or at least ask, until they give up and get someone who puts practice before pieces of paper).\n", "Let me be bold and say that your Experience is your best certificate.\n", "I second the opinion voiced here that the only valid certifications are experience and the work done by you so far. However you might want to check out these two link - prominent programming certifications and a discussion on slashdot on a similar subject.\n", "For ASP.NET the most valuable certificates are MCP certificates. Some of them are good for C++ too.\nhttp://en.wikipedia.org/wiki/Microsoft_Certified_Professional\nIn PHP for there is the W3C certification (it exists js, and other programming languages to) http://www.w3schools.com/cert/cert_php.asp\nI think these certifications are very valuable.\n", "For linux (implies perl/bash)\nComptia+ \nRed Hat Certified Engineer\n" ]
[ 16, 7, 2, 0, 0 ]
[]
[]
[ "certificate", "javascript", "php", "programming_languages", "python" ]
stackoverflow_0002839663_certificate_javascript_php_programming_languages_python.txt
Q: symbols in command line argument.. python, bash I am writing a python script on Linux for twitter post using API, Is it possible to pass symbols like "(" ")" etc in clear text without apostrophes.... % ./twitterupdate this is me #works fine % ./twitterupdate this is bad :(( #this leaves a error on bash. Is the only alternative is to enclose the text into --> "" ?? like.. % ./twitterupdate "this is bad :((" #this will reduce the ease of use for the script Is there any workaround? A: Yes, quoting the string is the only way. Bash has its syntax and and some characters have special meaning. Btw, using "" is not enough, use apostrophes instead. Some characters will still get interpretted with normal quotation marks: $ echo "lots of $$" lots of 15570 $ echo 'lots of $$' lots of $$ A: http://www.gnu.org/software/bash/manual/bashref.html#Quoting
symbols in command line argument.. python, bash
I am writing a python script on Linux for twitter post using API, Is it possible to pass symbols like "(" ")" etc in clear text without apostrophes.... % ./twitterupdate this is me #works fine % ./twitterupdate this is bad :(( #this leaves a error on bash. Is the only alternative is to enclose the text into --> "" ?? like.. % ./twitterupdate "this is bad :((" #this will reduce the ease of use for the script Is there any workaround?
[ "Yes, quoting the string is the only way. Bash has its syntax and and some characters have special meaning. Btw, using \"\" is not enough, use apostrophes instead. Some characters will still get interpretted with normal quotation marks:\n$ echo \"lots of $$\"\nlots of 15570\n$ echo 'lots of $$'\nlots of $$\n\n", "http://www.gnu.org/software/bash/manual/bashref.html#Quoting\n" ]
[ 10, 1 ]
[]
[]
[ "bash", "command_line_arguments", "python" ]
stackoverflow_0002840076_bash_command_line_arguments_python.txt
Q: How to have localized style when writing cell with xlwt I'm writing an Excel spreadsheet with Python's xlwt and I need numbers to be formatted using "." as thousands separator, as it is in brazilian portuguese language. I have tried: style.num_format_str = r'#,##0' And it sets the thousands separator as ','. If I try setting num_format_str to '#.##0', I'll get number formatted as 1234.000 instead of 1.234. And if I open n document in OpenOffice and format cells, I can set the language of the cell to "Portuguese (Brazil)" and then OpenOffice will show the format code as being "#.##0", but I don't find a way to set the cell's language to brazilian portuguese. Any ideas? A: The thousands separator (and the decimal "point" etc) are recorded in the XLS file in a locale-independent fashion. The recorded thousands separator is a comma. How it is displayed depends on the user's locale. OpenOffice calc allows the user to override the default locale (Tools / Options / Languages / Locale setting). With xlwt, write your num_format_str as "#,###.00" and your data as float("1234567.89"), like this: import xlwt b = xlwt.Workbook() s = b.add_sheet('x') style = xlwt.easyxf("", "#,###.00") s.write(0, 0, 1234567.89, style) b.save("locale_fmt_demo.xls") Open the output file with OO Calc and try various locale settings. I got these results: English (Australia): 1,234,567.89 Portuguese (Brazil): 1.234.567,89 French (France): 1 234 567,89
How to have localized style when writing cell with xlwt
I'm writing an Excel spreadsheet with Python's xlwt and I need numbers to be formatted using "." as thousands separator, as it is in brazilian portuguese language. I have tried: style.num_format_str = r'#,##0' And it sets the thousands separator as ','. If I try setting num_format_str to '#.##0', I'll get number formatted as 1234.000 instead of 1.234. And if I open n document in OpenOffice and format cells, I can set the language of the cell to "Portuguese (Brazil)" and then OpenOffice will show the format code as being "#.##0", but I don't find a way to set the cell's language to brazilian portuguese. Any ideas?
[ "The thousands separator (and the decimal \"point\" etc) are recorded in the XLS file in a locale-independent fashion. The recorded thousands separator is a comma. How it is displayed depends on the user's locale. OpenOffice calc allows the user to override the default locale (Tools / Options / Languages / Locale setting).\nWith xlwt, write your num_format_str as \"#,###.00\" and your data as float(\"1234567.89\"), like this:\nimport xlwt\nb = xlwt.Workbook()\ns = b.add_sheet('x')\nstyle = xlwt.easyxf(\"\", \"#,###.00\")\ns.write(0, 0, 1234567.89, style)\nb.save(\"locale_fmt_demo.xls\")\n\nOpen the output file with OO Calc and try various locale settings. I got these results:\nEnglish (Australia): 1,234,567.89 \nPortuguese (Brazil): 1.234.567,89\nFrench (France): 1 234 567,89\n\n" ]
[ 6 ]
[]
[]
[ "excel", "localization", "python", "xlwt" ]
stackoverflow_0002836358_excel_localization_python_xlwt.txt
Q: Django throws 404 at generic views I'm trying to get the generic views for a date-based archive working in django. I defined the urls as described in a tutorial, but django returns a 404 error whenever I want to access an url with a variable (such as month or year) in it. It don't even produces a TemplateDoesNotExist-execption. Normal urls without variables work fine. Here's my updated urlconf: from django.conf.urls.defaults import * from zurichlive.zhl.models import Event info_dict = { 'queryset': Event.objects.all(), 'date_field': 'date', 'allow_future': 'True', } urlpatterns += patterns('django.views.generic.date_based', (r'events/(?P<year>\d{4})/(?P<month>[a-z]{3})/(?P<day>\w{1,2})/(?P<slug>[-\w]+)/$', 'object_detail', dict(info_dict, slug_field='slug', template_name='archive/detail.html')), (r'^events/(?P<year>\d{4})/(?P<month>[a-z]{3})/(?P<day>\w{1,2})/(?P<slug>[-\w]+)/$', 'object_detail', dict(info_dict, template_name='archive/list.html')), (r'^events/(?P<year>\d{4})/(?P<month>[a-z]{3})/(?P<day>\w{1,2})/$','archive_day',dict(info_dict,template_name='archive/list.html')), (r'^events/(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month', dict(info_dict, template_name='archive/list.html')), (r'^events/(?P<year>)/$','archive_year', dict(info_dict, template_name='archive/list.html')), (r'^events/$','archive_index', dict(info_dict, template_name='archive/list.html')), ) When I access /events/2010/may/12/this-is-a-slug/ I should get to the detail.html template, but instead I get a 404. What am I doing wrong? And I'm using Django 1.1.2 A: You forgot the backslashes in your regexes: (r'events/(?P<year>\d{4})/(?P<month>[a-z]{3})/(?P<day>\w{1,2})/(?P<slug>[-\w]+)/$' Also you've (correctly) got the URL regex ending with a slash, so your URL should be /events/2010/may/12/this-is-a-slug/. A: Check the template_name once again.
Django throws 404 at generic views
I'm trying to get the generic views for a date-based archive working in django. I defined the urls as described in a tutorial, but django returns a 404 error whenever I want to access an url with a variable (such as month or year) in it. It don't even produces a TemplateDoesNotExist-execption. Normal urls without variables work fine. Here's my updated urlconf: from django.conf.urls.defaults import * from zurichlive.zhl.models import Event info_dict = { 'queryset': Event.objects.all(), 'date_field': 'date', 'allow_future': 'True', } urlpatterns += patterns('django.views.generic.date_based', (r'events/(?P<year>\d{4})/(?P<month>[a-z]{3})/(?P<day>\w{1,2})/(?P<slug>[-\w]+)/$', 'object_detail', dict(info_dict, slug_field='slug', template_name='archive/detail.html')), (r'^events/(?P<year>\d{4})/(?P<month>[a-z]{3})/(?P<day>\w{1,2})/(?P<slug>[-\w]+)/$', 'object_detail', dict(info_dict, template_name='archive/list.html')), (r'^events/(?P<year>\d{4})/(?P<month>[a-z]{3})/(?P<day>\w{1,2})/$','archive_day',dict(info_dict,template_name='archive/list.html')), (r'^events/(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month', dict(info_dict, template_name='archive/list.html')), (r'^events/(?P<year>)/$','archive_year', dict(info_dict, template_name='archive/list.html')), (r'^events/$','archive_index', dict(info_dict, template_name='archive/list.html')), ) When I access /events/2010/may/12/this-is-a-slug/ I should get to the detail.html template, but instead I get a 404. What am I doing wrong? And I'm using Django 1.1.2
[ "You forgot the backslashes in your regexes:\n(r'events/(?P<year>\\d{4})/(?P<month>[a-z]{3})/(?P<day>\\w{1,2})/(?P<slug>[-\\w]+)/$'\n\nAlso you've (correctly) got the URL regex ending with a slash, so your URL should be /events/2010/may/12/this-is-a-slug/.\n", "Check the template_name once again.\n" ]
[ 2, 0 ]
[]
[]
[ "django", "django_generic_views", "http_status_code_404", "python" ]
stackoverflow_0002818073_django_django_generic_views_http_status_code_404_python.txt
Q: Converting a bash script to python (small script) I’ve a bash script I’ve been using for a Linux environment but now I have to use it on a Windows platform and want to convert the bash script to a python script which I can run. The bash script is rather simple (I think) and I’ve tried to convert it by google by way around but can’t convert it successfully. The bash script looks like this: runs=5 queries=50 outfile=outputfile.txt date >> $outfile echo -e "\n---------------------------------" echo -e "\n----------- Normal --------------" echo -e "\n---------------------------------" echo -e "\n----------- Normal --------------" >> $outfile for ((r = 1; r < ($runs + 1); r++)) do echo -e "Run $r of $runs\n" db2 FLUSH PACKAGE CACHE DYNAMIC python reads.py -r1 -pquery1.sql -q$queries -shotelspec -k6 -a5 >> $outfile done The main command, the python read.py … etc. is another python file I’ve been given and have the arguments as you see. I know it is a lot to ask for, but it would really help me out if someone could convert this to a python script I can use or at least give me some hints and directions. Sincerely Mestika Added per request: This is what I've written but without success: runs=5 queries=50 outfile=ReadsAgain.txt file = open("results.txt", "ab") print "\n---------------------------------" print "\n----------- Normal --------------" print "\n---------------------------------" file.write("\n----------- Normal --------------\n") print "\n------------- Query without Index --------------" file.write("\n------------- Query without Index --------------\n") for r = 1; r < (%s + 1); r++ % runs print "Run %s of %s \n" % r % runs db2 FLUSH PACKAGE CACHE DYNAMIC output = python reads.py -r1 -pquery1.sql -q$queries -shotelspec -k6 -a5 file.write(output) file.close() A: Answer Let's break it down into pieces. Especially the pieces you got wrong. :) Assignment outfile=ReadsAgain.txt It should come to little surprise that you need to put quotes around strings. On the other hand, you have the luxury of putting spaces around the = for readability. outfilename = "ReadsAgain.txt" Variable expansion → str.format (or, the % operation) python reads.py <snip/> -q$queries <snip/> So you know how to do the redirection already, but how do you do the variable expansion? You can use the format method (v2.6+): command = "python reads.py -r1 -pquery1.sql -q{0} -shotelspec -k6 -a5".format(queries) You can alternatively use the % operator: #since queries is a number, use %d as a placeholder command = "python reads.py -r1 -pquery1.sql -q%d -shotelspec -k6 -a5" % queries C-style loop → Object-oriented-style loop for ((r = 1; r < ($runs + 1); r++)) do done Looping in Python is different from C-style iteration. What happens in Python is you iterate over an iterable object, like for example a list. Here, you are trying to do something runs times, so you would do this: for r in range(runs): #loop body here range(runs) is equivalent to [0,1,...,runs-1], a list of runs = 5 integer elements. So you'll be repeating the body runs times. At every cicle, r is assigned the next item of the list. This is thus completely equivalent to what you are doing in Bash. If you're feeling daring, use xrange instead. It's completely equivalent but uses more advanced language features (so it is harder to explain in layman's terms) but consumes less resources. Output redirection → the subprocess module The "tougher" part, if you will: executing a program and getting its output. Google to the rescue! Obviously, the top hit is a stackoverflow question: this one. You can hide all the complexity behind it with a simple function: import subprocess, shlex def get_output_of(command): args = shlex.split(command) return subprocess.Popen(args, stdout=subprocess.PIPE).communicate()[0] # this only returns stdout So: python reads.py -r1 -pquery1.sql -q$queries -shotelspec -k6 -a5 >> $outfile becomes: command = "python reads.py -r1 -pquery1.sql -q%s -shotelspec -k6 -a5" % queries read_result = get_output_of(command) Don't over-subprocess, batteries are included Optionally, consider that you can get pretty much the same output of date with the following: import time time_now = time.strftime("%c", time.localtime()) # Sat May 15 15:42:47 2010 (Note the absence of the time zone information. This should be the subject of another question, if it is important to you.) How your program should look like The final result should then look like this: import subprocess, shlex, time def get_output_of(command): #... body of get_output_of #... more functions ... if __name__ = "__main__": #only execute the following if you are calling this .py file directly, #and not, say, importing it #... initialization ... with file("outputfile.txt", "a") as output_file: #alternative way to open files, v2.5+ #... write date and other stuff ... for r in range(runs): #... loop body here ... Post scriptum That must look pretty horrible when compared to the relatively simple and short Bash script, right? Python is not a specialized language: it aims to do everything reasonably well, but isn't built directly for running programs and getting the output of those. Still, you wouldn't normally write a database engine in Bash, right? It's different tools for different jobs. Here, unless you're planning to make some changes that would be non-trivial to write with that language, [Ba]sh was definitely the right choice. A: It should be fairly simple to port your program. The only tricky part will be running the db2 command and (maybe) refactoring reads.py so that it can be called as a library function. The basic idea is the same: Setting local variables is the same. Replace echo with print. Replace your loop with for r in range(runs):. Get the date with the datetime module. Replace write to file with the file objects module. Replace the call to db2 with the subprocess module. You'll need to import reads.py to use as a library (or you can use subprocess). But, as Marcelo says, if you want more help- you're best off putting in some effort of your own to ask direct questions. A: As much as I am in favor of writing in Python rather than bash, if the only reason to convert it to Python is so that you can run it on Windows, keep in mind that you can install bash on Windows and run it as is. Cygwin.com has a complete implementation of many Unix commands.
Converting a bash script to python (small script)
I’ve a bash script I’ve been using for a Linux environment but now I have to use it on a Windows platform and want to convert the bash script to a python script which I can run. The bash script is rather simple (I think) and I’ve tried to convert it by google by way around but can’t convert it successfully. The bash script looks like this: runs=5 queries=50 outfile=outputfile.txt date >> $outfile echo -e "\n---------------------------------" echo -e "\n----------- Normal --------------" echo -e "\n---------------------------------" echo -e "\n----------- Normal --------------" >> $outfile for ((r = 1; r < ($runs + 1); r++)) do echo -e "Run $r of $runs\n" db2 FLUSH PACKAGE CACHE DYNAMIC python reads.py -r1 -pquery1.sql -q$queries -shotelspec -k6 -a5 >> $outfile done The main command, the python read.py … etc. is another python file I’ve been given and have the arguments as you see. I know it is a lot to ask for, but it would really help me out if someone could convert this to a python script I can use or at least give me some hints and directions. Sincerely Mestika Added per request: This is what I've written but without success: runs=5 queries=50 outfile=ReadsAgain.txt file = open("results.txt", "ab") print "\n---------------------------------" print "\n----------- Normal --------------" print "\n---------------------------------" file.write("\n----------- Normal --------------\n") print "\n------------- Query without Index --------------" file.write("\n------------- Query without Index --------------\n") for r = 1; r < (%s + 1); r++ % runs print "Run %s of %s \n" % r % runs db2 FLUSH PACKAGE CACHE DYNAMIC output = python reads.py -r1 -pquery1.sql -q$queries -shotelspec -k6 -a5 file.write(output) file.close()
[ "Answer\nLet's break it down into pieces. Especially the pieces you got wrong. :)\n\nAssignment\n\noutfile=ReadsAgain.txt\n\n\nIt should come to little surprise that you need to put quotes around strings. On the other hand, you have the luxury of putting spaces around the = for readability.\noutfilename = \"ReadsAgain.txt\"\n\n\nVariable expansion → str.format (or, the % operation)\n\npython reads.py <snip/> -q$queries <snip/>\n\n\nSo you know how to do the redirection already, but how do you do the variable expansion? You can use the format method (v2.6+):\ncommand = \"python reads.py -r1 -pquery1.sql -q{0} -shotelspec -k6 -a5\".format(queries)\n\nYou can alternatively use the % operator:\n#since queries is a number, use %d as a placeholder\ncommand = \"python reads.py -r1 -pquery1.sql -q%d -shotelspec -k6 -a5\" % queries\n\n\nC-style loop → Object-oriented-style loop\n\nfor ((r = 1; r < ($runs + 1); r++)) do done\n\n\nLooping in Python is different from C-style iteration. What happens in Python is you iterate over an iterable object, like for example a list. Here, you are trying to do something runs times, so you would do this:\nfor r in range(runs):\n #loop body here\n\nrange(runs) is equivalent to [0,1,...,runs-1], a list of runs = 5 integer elements. So you'll be repeating the body runs times. At every cicle, r is assigned the next item of the list. This is thus completely equivalent to what you are doing in Bash.\nIf you're feeling daring, use xrange instead. It's completely equivalent but uses more advanced language features (so it is harder to explain in layman's terms) but consumes less resources.\n\nOutput redirection → the subprocess module\nThe \"tougher\" part, if you will: executing a program and getting its output. Google to the rescue! Obviously, the top hit is a stackoverflow question: this one. You can hide all the complexity behind it with a simple function:\nimport subprocess, shlex\ndef get_output_of(command):\n args = shlex.split(command)\n return subprocess.Popen(args,\n stdout=subprocess.PIPE).communicate()[0]\n # this only returns stdout\n\nSo:\n\npython reads.py -r1 -pquery1.sql -q$queries -shotelspec -k6 -a5 >> $outfile\n\n\nbecomes:\ncommand = \"python reads.py -r1 -pquery1.sql -q%s -shotelspec -k6 -a5\" % queries\nread_result = get_output_of(command)\n\n\nDon't over-subprocess, batteries are included\nOptionally, consider that you can get pretty much the same output of date with the following:\nimport time\ntime_now = time.strftime(\"%c\", time.localtime()) # Sat May 15 15:42:47 2010\n\n(Note the absence of the time zone information. This should be the subject of another question, if it is important to you.)\n\nHow your program should look like\nThe final result should then look like this:\nimport subprocess, shlex, time\ndef get_output_of(command):\n #... body of get_output_of\n#... more functions ...\nif __name__ = \"__main__\":\n #only execute the following if you are calling this .py file directly,\n #and not, say, importing it\n #... initialization ...\n with file(\"outputfile.txt\", \"a\") as output_file: #alternative way to open files, v2.5+\n #... write date and other stuff ...\n for r in range(runs):\n #... loop body here ...\n\n\nPost scriptum\nThat must look pretty horrible when compared to the relatively simple and short Bash script, right? Python is not a specialized language: it aims to do everything reasonably well, but isn't built directly for running programs and getting the output of those.\nStill, you wouldn't normally write a database engine in Bash, right? It's different tools for different jobs. Here, unless you're planning to make some changes that would be non-trivial to write with that language, [Ba]sh was definitely the right choice.\n", "It should be fairly simple to port your program. The only tricky part will be running the db2 command and (maybe) refactoring reads.py so that it can be called as a library function.\nThe basic idea is the same:\n\nSetting local variables is the same.\nReplace echo with print.\nReplace your loop with for r in range(runs):.\nGet the date with the datetime module.\nReplace write to file with the file objects module.\nReplace the call to db2 with the subprocess module.\nYou'll need to import reads.py to use as a library (or you can use subprocess).\n\nBut, as Marcelo says, if you want more help- you're best off putting in some effort of your own to ask direct questions.\n", "As much as I am in favor of writing in Python rather than bash, if the only reason to convert it to Python is so that you can run it on Windows, keep in mind that you can install bash on Windows and run it as is. Cygwin.com has a complete implementation of many Unix commands.\n" ]
[ 36, 10, 2 ]
[]
[]
[ "bash", "python" ]
stackoverflow_0002839810_bash_python.txt
Q: Is there a method to convert PyUnicodeObject variable to PyObject type? A value which is a PyUnicodeObject need to be passed to PyObject variable. Is there any conversion method for that? thanks karnol A: You can just use a cast in your C code for this purpose: PyUnicodeObject *p = ...whatever...; callsomefun((PyObject*)p); All the various specific, concrete types PyWhateverObject can be thought of as being "derived from" PyObject. Now C doesn't have the concept of inheritance so there's no "derived" in it, but the Python VM synthesizes it very simply, by ensuring every such object's first struct member (or first member's first member, or...) is a PyObject struct (there's a macro for that). This guarantees that normal C casting of pointers (although technically "risky" as the compiler cannot check that correctness -- if you cast the wrong thing you'll just crash during runtime;-) works as intended when used correctly between a pointer to PyObject and any pointer to a specific, concrete Python type struct. A: PyUnicodeObject is a subset of PyObject so there shouldn't be any problem passing it.
Is there a method to convert PyUnicodeObject variable to PyObject type?
A value which is a PyUnicodeObject need to be passed to PyObject variable. Is there any conversion method for that? thanks karnol
[ "You can just use a cast in your C code for this purpose:\nPyUnicodeObject *p = ...whatever...;\ncallsomefun((PyObject*)p);\n\nAll the various specific, concrete types PyWhateverObject can be thought of as being \"derived from\" PyObject. Now C doesn't have the concept of inheritance so there's no \"derived\" in it, but the Python VM synthesizes it very simply, by ensuring every such object's first struct member (or first member's first member, or...) is a PyObject struct (there's a macro for that). This guarantees that normal C casting of pointers (although technically \"risky\" as the compiler cannot check that correctness -- if you cast the wrong thing you'll just crash during runtime;-) works as intended when used correctly between a pointer to PyObject and any pointer to a specific, concrete Python type struct.\n", "PyUnicodeObject is a subset of PyObject so there shouldn't be any problem passing it.\n" ]
[ 3, 2 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0002840144_python_python_3.x.txt
Q: setting url in yaml file for google app engin (page not found) problem I am new to python and I am super excited to learn. I am building my first app on app engin and I am not totally understanding why my yaml file is not resolving to the url that I set up. here is the code handlers: - url: .* script: main.py - url: /letmein/.* script: letmein.py so if I go to http://localhost:8080/letmein/ I get a link is brooken or page not found error. here is the python code that I have in letmein.py from google.appengine.ext import webapp from google.appengine.ext.webapp import util class LetMeInHandler(webapp.RequestHandler): def get(self): self.response.out.write('letmein!') def main(): application = webapp.WSGIApplication([('/letmein/', LetMeInHandler)], debug=True) util.run_wsgi_app(application) if __name__ == '__main__': main() thanks in advance for the help! A: Your handlers are in the wrong order as they must always be less general first. Change to: handlers: - url: /letmein/.* script: letmein.py - url: .* script: main.py and it works.
setting url in yaml file for google app engin (page not found) problem
I am new to python and I am super excited to learn. I am building my first app on app engin and I am not totally understanding why my yaml file is not resolving to the url that I set up. here is the code handlers: - url: .* script: main.py - url: /letmein/.* script: letmein.py so if I go to http://localhost:8080/letmein/ I get a link is brooken or page not found error. here is the python code that I have in letmein.py from google.appengine.ext import webapp from google.appengine.ext.webapp import util class LetMeInHandler(webapp.RequestHandler): def get(self): self.response.out.write('letmein!') def main(): application = webapp.WSGIApplication([('/letmein/', LetMeInHandler)], debug=True) util.run_wsgi_app(application) if __name__ == '__main__': main() thanks in advance for the help!
[ "Your handlers are in the wrong order as they must always be less general first. Change to:\nhandlers:\n- url: /letmein/.*\n script: letmein.py\n\n- url: .*\n script: main.py\n\nand it works.\n" ]
[ 7 ]
[]
[]
[ "google_app_engine", "http_status_code_404", "python", "yaml" ]
stackoverflow_0002840483_google_app_engine_http_status_code_404_python_yaml.txt
Q: Decorator that can take both init args and call args? Is it possible to create a decorator which can be __init__'d with a set of arguments, then later have methods called with other arguments? For instance: from foo import MyDecorator bar = MyDecorator(debug=True) @bar.myfunc(a=100) def spam(): pass @bar.myotherfunc(x=False) def eggs(): pass If this is possible, can you provide a working example? A: You need another level of wrapping for this, using closures for example: import functools def say_when_called(what_to_say): def decorator(fn): @functools.wraps(fn) def wrapper(*args, **kw): print what_to_say return fn(*args, **kw) return wrapper return decorator @say_when_called("spam") def my_func(v): print v my_func("eggs") Output: spam eggs (see http://codepad.org/uyJV56gk) Note that I've used the functools.wraps here to make the decorated function look like the original. It's not functionally required, but a nice thing to do in case code reads the __name__ or __doc__ attributes of your function. A class-based example: class SayWhenCalledWrapper(object): def __init__(self, fn, what_to_say): self.fn = fn self.what_to_say = what_to_say def __call__(self, *args, **kw): print self.what_to_say return self.fn(*args, **kw) class SayWhenCalled(object): def __init__(self, what_to_say): self.what_to_say = what_to_say def __call__(self, fn): return SayWhenCalledWrapper(fn, self.what_to_say) @SayWhenCalled("spam") def my_func(v): print v my_func("eggs") Output: spam eggs (see http://codepad.org/6Y2XffDN) A: Sure, a decorator is just a function which accepts a function and returns a function. There's no reason that function can't be (or, if you have arguments, can't be returned by) an instance method. Here's a really trivial example (because I'm not sure what exactly you'd be trying to do with this): class MyDecorator(object): def __init__(self, debug): self.debug = debug def myfunc(self, a): def decorator(fn): def new_fn(): if self.debug: print a fn() return new_fn return decorator def myotherfunc(self, x): def decorator(fn): def new_fn(): if self.debug: print x fn() return new_fn return decorator Like I said, I can't think of a use case for this off the top of my head. But I'm sure they're out there. A: The property decorator is kind of like this. @property decorates a function and replaces it with an object that has getter, setter and deleter functions, which are also decorators. This is a little more complex than the OP's example because there are two levels of decoration, but the principle is the same. A: huin's answer is very good. His two options execute decorator code only when the decorated function is defined (that's not a criticism, as often that's exactly what you want). Here's an extension of his class-based approach, which also executes some code each time you call the function. This is the sort of thing you do, for example, when you are using decorators to ensure thread safety. class MyInnerDecorator: def __init__( self, outer_decorator, *args, **kwargs ): self._outerDecorator = outer_decorator self._args = args self._kwargs = kwargs def __call__( self, f ): print "Decorating function\n" self._f = f return self.wrap def wrap( self, *args, **kwargs ): print "Calling decorated function" print "Debug is ", self._outerDecorator._debug print "Positional args to decorator: ", self._args print "Keyword args to decorator: ", self._kwargs print "Positional args to function call: ", args print "Keyword args to function call: ", kwargs return self._f( *args, **kwargs ) print "\n" class MyDecorator: def __init__( self, debug ): self._debug = debug def myFunc( self, *args, **kwargs ): return MyInnerDecorator( self, "Wrapped by myFunc", *args, **kwargs ) def myOtherFunc( self, *args, **kwargs ): return MyInnerDecorator( self, "Wrapped by myOtherFunc", *args, **kwargs ) bar = MyDecorator( debug=True ) @bar.myFunc( a=100 ) def spam( *args, **kwargs ): print "\nIn spam\n" @bar.myOtherFunc( x=False ) def eggs( *args, **kwargs ): print "\nIn eggs\n" spam( "penguin" ) eggs( "lumberjack" ) Which outputs this: Decorating function Decorating function Calling decorated function Debug is True Positional args to decorator: ('Wrapped by myFunc',) Keyword args to decorator: {'a': 100} Positional args to function call: ('penguin',) Keyword args to function call: {} In spam Calling decorated function Debug is True Positional args to decorator: ('Wrapped by myOtherFunc',) Keyword args to decorator: {'x': False} Positional args to function call: ('lumberjack',) Keyword args to function call: {} In eggs
Decorator that can take both init args and call args?
Is it possible to create a decorator which can be __init__'d with a set of arguments, then later have methods called with other arguments? For instance: from foo import MyDecorator bar = MyDecorator(debug=True) @bar.myfunc(a=100) def spam(): pass @bar.myotherfunc(x=False) def eggs(): pass If this is possible, can you provide a working example?
[ "You need another level of wrapping for this, using closures for example:\nimport functools\n\ndef say_when_called(what_to_say):\n def decorator(fn):\n @functools.wraps(fn)\n def wrapper(*args, **kw):\n print what_to_say\n return fn(*args, **kw)\n return wrapper\n return decorator\n\n@say_when_called(\"spam\")\ndef my_func(v):\n print v\n\nmy_func(\"eggs\")\n\nOutput:\nspam\neggs\n\n(see http://codepad.org/uyJV56gk)\nNote that I've used the functools.wraps here to make the decorated function look like the original. It's not functionally required, but a nice thing to do in case code reads the __name__ or __doc__ attributes of your function.\nA class-based example:\nclass SayWhenCalledWrapper(object):\n\n def __init__(self, fn, what_to_say):\n self.fn = fn\n self.what_to_say = what_to_say\n\n def __call__(self, *args, **kw):\n print self.what_to_say\n return self.fn(*args, **kw)\n\n\nclass SayWhenCalled(object):\n\n def __init__(self, what_to_say):\n self.what_to_say = what_to_say\n\n def __call__(self, fn):\n return SayWhenCalledWrapper(fn, self.what_to_say)\n\n\n@SayWhenCalled(\"spam\")\ndef my_func(v):\n print v\n\nmy_func(\"eggs\")\n\nOutput:\nspam\neggs\n\n(see http://codepad.org/6Y2XffDN)\n", "Sure, a decorator is just a function which accepts a function and returns a function. There's no reason that function can't be (or, if you have arguments, can't be returned by) an instance method. Here's a really trivial example (because I'm not sure what exactly you'd be trying to do with this):\nclass MyDecorator(object):\n def __init__(self, debug):\n self.debug = debug\n def myfunc(self, a):\n def decorator(fn):\n def new_fn():\n if self.debug:\n print a\n fn()\n return new_fn\n return decorator\n def myotherfunc(self, x):\n def decorator(fn):\n def new_fn():\n if self.debug:\n print x\n fn()\n return new_fn\n return decorator\n\nLike I said, I can't think of a use case for this off the top of my head. But I'm sure they're out there.\n", "The property decorator is kind of like this. @property decorates a function and replaces it with an object that has getter, setter and deleter functions, which are also decorators. \nThis is a little more complex than the OP's example because there are two levels of decoration, but the principle is the same.\n", "huin's answer is very good. His two options execute decorator code only when the decorated function is defined (that's not a criticism, as often that's exactly what you want). Here's an extension of his class-based approach, which also executes some code each time you call the function. This is the sort of thing you do, for example, when you are using decorators to ensure thread safety.\nclass MyInnerDecorator:\n def __init__( self, outer_decorator, *args, **kwargs ):\n self._outerDecorator = outer_decorator\n self._args = args\n self._kwargs = kwargs\n\n def __call__( self, f ):\n print \"Decorating function\\n\"\n self._f = f\n return self.wrap\n\n\n def wrap( self, *args, **kwargs ):\n print \"Calling decorated function\"\n print \"Debug is \", self._outerDecorator._debug\n print \"Positional args to decorator: \", self._args\n print \"Keyword args to decorator: \", self._kwargs\n print \"Positional args to function call: \", args\n print \"Keyword args to function call: \", kwargs\n return self._f( *args, **kwargs )\n print \"\\n\"\n\n\n\nclass MyDecorator:\n def __init__( self, debug ):\n self._debug = debug\n\n def myFunc( self, *args, **kwargs ):\n return MyInnerDecorator( self, \"Wrapped by myFunc\", *args, **kwargs )\n\n def myOtherFunc( self, *args, **kwargs ):\n return MyInnerDecorator( self, \"Wrapped by myOtherFunc\", *args, **kwargs )\n\n\nbar = MyDecorator( debug=True )\n@bar.myFunc( a=100 )\ndef spam( *args, **kwargs ):\n print \"\\nIn spam\\n\"\n\n@bar.myOtherFunc( x=False )\ndef eggs( *args, **kwargs ):\n print \"\\nIn eggs\\n\"\n\nspam( \"penguin\" )\n\neggs( \"lumberjack\" )\n\nWhich outputs this:\nDecorating function\n\nDecorating function\n\nCalling decorated function\nDebug is True\nPositional args to decorator: ('Wrapped by myFunc',)\nKeyword args to decorator: {'a': 100}\nPositional args to function call: ('penguin',)\nKeyword args to function call: {}\n\nIn spam\n\nCalling decorated function\nDebug is True\nPositional args to decorator: ('Wrapped by myOtherFunc',)\nKeyword args to decorator: {'x': False}\nPositional args to function call: ('lumberjack',)\nKeyword args to function call: {}\n\nIn eggs\n\n" ]
[ 4, 3, 0, 0 ]
[]
[]
[ "decorator", "design_patterns", "python" ]
stackoverflow_0002839363_decorator_design_patterns_python.txt
Q: How to write a Python lexical analyser? I'm trying to write a C module to lexically analyse Python code. How can I do it? A: The complete, detailed specification for doing lexical analysis of Python code is here. As you can see, there are a lot of cases you need to cover. One help is that you will always be able to check most easily if your C-implemented lexical analyzer is correct for a given Python fragment: it will have to return exactly what the Python-implemented module tokenize in Python's standard library does. As you can see in tokenize's sources, it's several hundred lines of Python, so you can easily extrapolate to needing thousands of lines of C -- definitely not a weekend project;-) Of course, as a starting point, you can fork Python's own Parser/tokenizer.c -- that's less than 2000 lines (amazingly short for what it does!), but in good part because it's relying on quite a few other bits and pieces from Python's runtime (if your implementation needs to be stand-alone you'll therefore need to reproduce those). If you're a very experienced programmer with strong understanding of the Python's codebase, and can just sprint on this for all your waking hours, you might make it in a week or so. Under normal circumstances, I'd say expecting a month of work would be a bit optimistic. What's your deadline?
How to write a Python lexical analyser?
I'm trying to write a C module to lexically analyse Python code. How can I do it?
[ "The complete, detailed specification for doing lexical analysis of Python code is here.\nAs you can see, there are a lot of cases you need to cover. One help is that you will always be able to check most easily if your C-implemented lexical analyzer is correct for a given Python fragment: it will have to return exactly what the Python-implemented module tokenize in Python's standard library does.\nAs you can see in tokenize's sources, it's several hundred lines of Python, so you can easily extrapolate to needing thousands of lines of C -- definitely not a weekend project;-)\nOf course, as a starting point, you can fork Python's own Parser/tokenizer.c -- that's less than 2000 lines (amazingly short for what it does!), but in good part because it's relying on quite a few other bits and pieces from Python's runtime (if your implementation needs to be stand-alone you'll therefore need to reproduce those).\nIf you're a very experienced programmer with strong understanding of the Python's codebase, and can just sprint on this for all your waking hours, you might make it in a week or so. Under normal circumstances, I'd say expecting a month of work would be a bit optimistic. What's your deadline?\n" ]
[ 10 ]
[]
[]
[ "c", "lexical_analysis", "python" ]
stackoverflow_0002840547_c_lexical_analysis_python.txt
Q: Prevent web2py from caching? I'm working with web2py and for some reason web2py seems to fail to notice when code has changed in certain cases. I can't really narrow it down, but from time to time changes in the code are not reflected, web2py obviously has the old version cached somewhere. The only thing that helps is quitting web2py and restarting it (i'm using the internal server). Any hints ? Thank you ! A: web2py does cache your code, except for Google App Engine (for speed). That is not the problem. If you you edit code in models, views or controllers, you see the effect immediately. The problem may be modules; if you edit code in modules you will not see the effect immediately, unless you import them with local_import('module', reload=True), or by restarting web2py. Is that is also not your problem, then your browser is caching something. Please bring up this question to the web2py mailing list as we can help more. P.S. If you are using the latest web2py it no longer comes with cherrypy. The built-in web server is called Rocket. A: web2py itself shouldn't "cache" your code, but whatever app server you're using it on surely might. But web2py can be deployed on such a huge variety of app servers that it's impossible to give completely general suggestions. If you're using the popular cherrypy WSGI server that I believe comes bundled with web2py, for example, see, in cherrypy's own docs, the AutoReload feature. Such features are not recommended in a production deployment (they can require very significant resources), but they sure come in handy when you're just developing!-)
Prevent web2py from caching?
I'm working with web2py and for some reason web2py seems to fail to notice when code has changed in certain cases. I can't really narrow it down, but from time to time changes in the code are not reflected, web2py obviously has the old version cached somewhere. The only thing that helps is quitting web2py and restarting it (i'm using the internal server). Any hints ? Thank you !
[ "web2py does cache your code, except for Google App Engine (for speed). That is not the problem. If you you edit code in models, views or controllers, you see the effect immediately.\nThe problem may be modules; if you edit code in modules you will not see the effect immediately, unless you import them with local_import('module', reload=True), or by restarting web2py.\nIs that is also not your problem, then your browser is caching something. Please bring up this question to the web2py mailing list as we can help more.\nP.S. If you are using the latest web2py it no longer comes with cherrypy. The built-in web server is called Rocket.\n", "web2py itself shouldn't \"cache\" your code, but whatever app server you're using it on surely might. But web2py can be deployed on such a huge variety of app servers that it's impossible to give completely general suggestions.\nIf you're using the popular cherrypy WSGI server that I believe comes bundled with web2py, for example, see, in cherrypy's own docs, the AutoReload feature. Such features are not recommended in a production deployment (they can require very significant resources), but they sure come in handy when you're just developing!-)\n" ]
[ 5, 0 ]
[]
[]
[ "caching", "python", "web2py" ]
stackoverflow_0002840201_caching_python_web2py.txt
Q: Adjective Nominalization in Python NLTK Is there a way to obtain Wordnet adjective nominalizations using NLTK? For example, for happy the desired output would be happiness. I tried to dig around, but couldn't find anything. A: The quick and dirty answer is that wordnet does this already: <adj.all>S: (adj) happy (enjoying or showing or marked by joy or pleasure) "a happy smile"; "spent many happy days on the beach"; "a happy marriage" attribute <noun.state>S: (n) happiness, felicity (state of well-being characterized by emotions ranging from contentment to intense joy) <noun.feeling>S: (n) happiness (emotions experienced when in a state of well-being) derivationally related form <noun.state> W: (n) happiness [Related to: happy] (state of well-being characterized by emotions ranging from contentment to intense joy) <noun.feeling> W: (n) happiness [Related to: happy] (emotions experienced when in a state of well-being) The remaining question is how to do this programmatically (without web-scraping). Added: The wordnet library wrapper tool is pretty powerful and demonstrates what appears to be the breadth of the C library interface: $ wn happy No information available for noun happy No information available for verb happy Information available for adj happy -antsa Antonyms -synsa Synonyms (ordered by estimated frequency) -attra Attributes -deria Derived Forms -famla Familiarity & Polysemy Count -grepa List of Compound Words -over Overview of Senses $ wn happy -deria -n1 Derived Forms of adj happy Sense 1 happy (vs. unhappy) RELATED TO->(noun) happiness#1 => happiness, felicity RELATED TO->(noun) happiness#2 => happiness So, Pythonically, you could either subprocess to the wn command which is kinda sloppy, or use the wordnet facilities already built into NLTK. On ubuntu (and presumably debian) the wordnet libraries and tools are conveniently available with: sudo apt-get install wordnet wordnet-dev Alas: $ wn pythonic No information available for pythonic
Adjective Nominalization in Python NLTK
Is there a way to obtain Wordnet adjective nominalizations using NLTK? For example, for happy the desired output would be happiness. I tried to dig around, but couldn't find anything.
[ "The quick and dirty answer is that wordnet does this already:\n\n\n<adj.all>S: (adj) happy (enjoying or showing or marked by joy or pleasure)\n \"a happy smile\"; \"spent many happy\n days on the beach\"; \"a happy marriage\"\n\nattribute\n \n \n<noun.state>S: (n) happiness, felicity (state of\n well-being characterized by emotions\n ranging from contentment to intense\n joy)\n<noun.feeling>S: (n) happiness (emotions experienced when\n in a state of well-being)\n\nderivationally related form\n \n \n<noun.state> W: (n) happiness [Related to: happy] (state\n of well-being characterized by\n emotions ranging from contentment to\n intense joy)\n<noun.feeling> W: (n) happiness [Related to: happy]\n (emotions experienced when in a state\n of well-being)\n\n\n\n\nThe remaining question is how to do this programmatically (without web-scraping).\nAdded:\nThe wordnet library wrapper tool is pretty powerful and demonstrates what appears to be the breadth of the C library interface:\n$ wn happy\nNo information available for noun happy\nNo information available for verb happy\nInformation available for adj happy\n -antsa Antonyms\n -synsa Synonyms (ordered by estimated frequency)\n -attra Attributes\n -deria Derived Forms\n -famla Familiarity & Polysemy Count\n -grepa List of Compound Words\n -over Overview of Senses\n$ wn happy -deria -n1\nDerived Forms of adj happy\nSense 1\nhappy (vs. unhappy)\n RELATED TO->(noun) happiness#1\n => happiness, felicity\n RELATED TO->(noun) happiness#2\n => happiness\n\nSo, Pythonically, you could either subprocess to the wn command which is kinda sloppy, or use the wordnet facilities already built into NLTK.\nOn ubuntu (and presumably debian) the wordnet libraries and tools are conveniently available with:\nsudo apt-get install wordnet wordnet-dev\n\nAlas:\n$ wn pythonic\nNo information available for pythonic\n\n" ]
[ 4 ]
[]
[]
[ "nlp", "nltk", "python", "wordnet" ]
stackoverflow_0002836959_nlp_nltk_python_wordnet.txt
Q: Purpose of Zope Interfaces? I have started using Zope interfaces in my code, and as of now, they are really only documentation. I use them to specify what attributes the class should possess, explicitly implement them in the appropriate classes and explicitly check for them where I expect one. This is fine, but I would like them to do more if possible, such as actually verify that the class has implemented the interface, instead of just verifying that I have said that the class implements the interface. I have read the zope wiki a couple of times, but still cannot see much more use for interfaces than what I am currently doing. So, my question is what else can you use these interfaces for, and how do you use them for more. A: Where I work, we use Interfaces so that we can use ZCA, or the Zope Component Architecture, which is a whole framework for making components that are swappable and pluggable using Interfaces. We use ZCA so that we can cope with all manner of per-client customisations without necessarily having to fork our software or have all of the many per-client bits messing up the main tree. The Zope wiki is often quite incomplete, unfortunately. There's a good-but-terse explanation of most of ZCA's features on its ZCA's pypi page. I don't use Interfaces for anything like checking that a class implements all the methods for a given Interface. In theory, that might be useful when you add another method to an interface, to check that you've remembered to add the new method to all of the classes that implement the interface. Personally I strongly prefer to create a new Interface over modifying an old one. Modifying old Interfaces is usually a very bad idea once they're in eggs that have been released to pypi or to the rest of your organisation. A quick note on terminology: classes implement Interfaces, and objects (instances of classes) provide Interfaces. If you want to check for an Interface, you would either write ISomething.implementedBy(SomeClass) or ISomething.providedBy(some_object). So, down to examples of where ZCA is useful. Let's pretend that we're writing a blog, using the ZCA to make it modular. We'll have a BlogPost object for each post, which will provide an IBlogPost interface, all defined in our handy-dandy my.blog egg. We'll also store the blog's configuration in BlogConfiguration objects which provide IBlogConfiguration. Using this as a starting point, we can implement new features without necessarily having to touch my.blog at all. The following is a list of examples of things that we can do by using ZCA, without having to alter the base my.blog egg. I or my co-workers have done all of these things (and found them useful) on real for-client projects, though we weren't implementing blogs at the time. :) Some of the use cases here could be better solved by other means, such as a print CSS file. Adding extra views (BrowserViews, usually registered in ZCML with the browser:page directive) to all objects which provide IBlogPost. I could make a my.blog.printable egg. That egg would register a BrowserView called print for IBlogPost, which renders the blog post through a Zope Page Template designed to produce HTML that prints nicely. That BrowserView would then appear at the URL /path/to/blogpost/@@print. The event subscription mechanism in Zope. Say I want to publish RSS feeds, and I want to generate them in advance rather than on request. I could create a my.blog.rss egg. In that egg, I'd register a subscriber for events that provide IObjectModified (zope.lifecycleevent.interfaces.IObjectModified), on objects that provide IBlogPost. That subscriber would get get called every time an attribute changed on anything providing IBlogPost, and I could use it to update all the RSS feeds that the blog post should appear in. In this case, it might be better to have an IBlogPostModified event that is sent at the end of each of the BrowserViews that modify blog posts, since IObjectModified gets sent once on every single attribute change - which might be too often for performance's sake. Adapters. Adapters are effectively "casts" from one Interface to another. For programming language geeks: Zope adapters implement "open" multiple-dispatch in Python (by "open" I mean "you can add more cases from any egg"), with more-specific interface matches taking priority over less-specific matches (Interface classes can be subclasses of one another, and this does exactly what you'd hope it would do.) Adapters from one Interface can be called with a very nice syntax, ISomething(object_to_adapt), or can be looked up via the function zope.component.getAdapter. Adapters from multiple Interfaces have to be looked up via the function zope.component.getMultiAdapter, which is slightly less pretty. You can have more than one adapter for a given set of Interfaces, differentiated by a string name that you provide when registering the adapter. The name defaults to "". For example, BrowserViews are actually adapters that adapt from the interface that they're registered on and an interface that the HTTPRequest class implements. You can also look up all of the adapters that are registered from one sequence of Interfaces to another Interface, using zope.component.getAdapters( (IAdaptFrom,), IAdaptTo ), which returns a sequence of (name, adapter) pairs. This can be used as a very nice way to provide hooks for plugins to attach themselves to. Say I wanted to save all my blog's posts and configuration as one big XML file. I create a my.blog.xmldump egg which defines an IXMLSegment, and registers an adapter from IBlogPost to IXMLSegment and an adapter from IBlogConfiguration to IXMLSegment. I can now call whichever adapter is appropriate for some object I want to serialize by writing IXMLSegment(object_to_serialize). I could even add more adapters from various other things to IXMLSegment from eggs other than my.blog.xmldump. ZCML has a feature where it can run a particular directive if and only if some egg is installed. I could use this to have my.blog.rss register an adapter from IRSSFeed to IXMLSegment iff my.blog.xmldump happens to be installed, without making my.blog.rss depend on my.blog.xmldump. Viewlets are like little BrowserViews that you can have 'subscribe' to a particular spot inside a page. I can't remember all the details right now but these are very good for things like plugins that you want to appear in a sidebar. I can't remember offhand whether they're part of base Zope or Plone. I would recommend against using Plone unless the problem that you are trying to solve actually needs a real CMS, since it's a big and complicated piece of software and it tends to be kinda slow. You don't necessarily actually need Viewlets anyway, since BrowserViews can call one another, either by using 'object/@@some_browser_view' in a TAL expression, or by using queryMultiAdapter( (ISomething, IHttpRequest), name='some_browser_view' ), but they're pretty nice regardless. Marker Interfaces. A marker Interface is an Interface that provides no methods and no attributes. You can add a marker Interface any object at runtime using ISomething.alsoProvidedBy. This allows you to, for example, alter which adapters will get used on a particular object and which BrowserViews will be defined on it. I apologise that I haven't gone into enough detail to be able to implement each of these examples straight away, but they'd take approximately a blog post each. A: You can actually test if your object or class implements your interface. For that you can use verify module (you would normally use it in your tests): >>> from zope.interface import Interface, Attribute, implements >>> class IFoo(Interface): ... x = Attribute("The X attribute") ... y = Attribute("The Y attribute") >>> class Foo(object): ... implements(IFoo) ... x = 1 ... def __init__(self): ... self.y = 2 >>> from zope.interface.verify import verifyObject >>> verifyObject(IFoo, Foo()) True >>> from zope.interface.verify import verifyClass >>> verifyClass(IFoo, Foo) True Interfaces can also be used for setting and testing invariants. You can find more information here: http://www.muthukadan.net/docs/zca.html#interfaces A: Zope interfaces can provide a useful way to decouple two pieces of code that shouldn't depend on each other. Say we have a component that knows how to print a greeting in module a.py: >>> class Greeter(object): ... def greet(self): ... print 'Hello' And some code that needs to print a greeting in module b.py: >>> Greeter().greet() 'Hello' This arrangement makes it hard to swap out the code that handles the greeting without touching b.py (which might be distributed in a separate package). Instead, we could introduce a third module c.py which defines an IGreeter interface: >>> from zope.interface import Interface >>> class IGreeter(Interface): ... def greet(): ... """ Gives a greeting. """ Now we can use this to decouple a.py and b.py. Instead of instantiating a Greeter class, b.py will now ask for a utility providing the IGreeter interface. And a.py will declare that the Greeter class implements that interface: (a.py) >>> from zope.interface import implementer >>> from zope.component import provideUtility >>> from c import IGreeter >>> @implementer(IGreeter) ... class Greeter(object): ... def greet(self): ... print 'Hello' >>> provideUtility(Greeter(), IGreeter) (b.py) >>> from zope.component import getUtility >>> from c import IGreeter >>> greeter = getUtility(IGreeter) >>> greeter.greet() 'Hello' A: I've never used Zope interfaces, but you might consider writing a metaclass, which on initialization checks the members of the class against the interface, and raises a runtime exception if a method isn't implemented. With Python you don't have other options. Either have a "compile" step that inspects your code, or dynamically inspect it at runtime.
Purpose of Zope Interfaces?
I have started using Zope interfaces in my code, and as of now, they are really only documentation. I use them to specify what attributes the class should possess, explicitly implement them in the appropriate classes and explicitly check for them where I expect one. This is fine, but I would like them to do more if possible, such as actually verify that the class has implemented the interface, instead of just verifying that I have said that the class implements the interface. I have read the zope wiki a couple of times, but still cannot see much more use for interfaces than what I am currently doing. So, my question is what else can you use these interfaces for, and how do you use them for more.
[ "Where I work, we use Interfaces so that we can use ZCA, or the Zope Component Architecture, which is a whole framework for making components that are swappable and pluggable using Interfaces. We use ZCA so that we can cope with all manner of per-client customisations without necessarily having to fork our software or have all of the many per-client bits messing up the main tree. The Zope wiki is often quite incomplete, unfortunately. There's a good-but-terse explanation of most of ZCA's features on its ZCA's pypi page.\nI don't use Interfaces for anything like checking that a class implements all the methods for a given Interface. In theory, that might be useful when you add another method to an interface, to check that you've remembered to add the new method to all of the classes that implement the interface. Personally I strongly prefer to create a new Interface over modifying an old one. Modifying old Interfaces is usually a very bad idea once they're in eggs that have been released to pypi or to the rest of your organisation.\nA quick note on terminology: classes implement Interfaces, and objects (instances of classes) provide Interfaces. If you want to check for an Interface, you would either write ISomething.implementedBy(SomeClass) or ISomething.providedBy(some_object).\nSo, down to examples of where ZCA is useful. Let's pretend that we're writing a blog, using the ZCA to make it modular. We'll have a BlogPost object for each post, which will provide an IBlogPost interface, all defined in our handy-dandy my.blog egg. We'll also store the blog's configuration in BlogConfiguration objects which provide IBlogConfiguration. Using this as a starting point, we can implement new features without necessarily having to touch my.blog at all.\nThe following is a list of examples of things that we can do by using ZCA, without having to alter the base my.blog egg. I or my co-workers have done all of these things (and found them useful) on real for-client projects, though we weren't implementing blogs at the time. :) Some of the use cases here could be better solved by other means, such as a print CSS file.\n\nAdding extra views (BrowserViews, usually registered in ZCML with the browser:page directive) to all objects which provide IBlogPost. I could make a my.blog.printable egg. That egg would register a BrowserView called print for IBlogPost, which renders the blog post through a Zope Page Template designed to produce HTML that prints nicely. That BrowserView would then appear at the URL /path/to/blogpost/@@print.\nThe event subscription mechanism in Zope. Say I want to publish RSS feeds, and I want to generate them in advance rather than on request. I could create a my.blog.rss egg. In that egg, I'd register a subscriber for events that provide IObjectModified (zope.lifecycleevent.interfaces.IObjectModified), on objects that provide IBlogPost. That subscriber would get get called every time an attribute changed on anything providing IBlogPost, and I could use it to update all the RSS feeds that the blog post should appear in.\nIn this case, it might be better to have an IBlogPostModified event that is sent at the end of each of the BrowserViews that modify blog posts, since IObjectModified gets sent once on every single attribute change - which might be too often for performance's sake.\nAdapters. Adapters are effectively \"casts\" from one Interface to another. For programming language geeks: Zope adapters implement \"open\" multiple-dispatch in Python (by \"open\" I mean \"you can add more cases from any egg\"), with more-specific interface matches taking priority over less-specific matches (Interface classes can be subclasses of one another, and this does exactly what you'd hope it would do.)\nAdapters from one Interface can be called with a very nice syntax, ISomething(object_to_adapt), or can be looked up via the function zope.component.getAdapter. Adapters from multiple Interfaces have to be looked up via the function zope.component.getMultiAdapter, which is slightly less pretty.\nYou can have more than one adapter for a given set of Interfaces, differentiated by a string name that you provide when registering the adapter. The name defaults to \"\". For example, BrowserViews are actually adapters that adapt from the interface that they're registered on and an interface that the HTTPRequest class implements. You can also look up all of the adapters that are registered from one sequence of Interfaces to another Interface, using zope.component.getAdapters( (IAdaptFrom,), IAdaptTo ), which returns a sequence of (name, adapter) pairs. This can be used as a very nice way to provide hooks for plugins to attach themselves to.\nSay I wanted to save all my blog's posts and configuration as one big XML file. I create a my.blog.xmldump egg which defines an IXMLSegment, and registers an adapter from IBlogPost to IXMLSegment and an adapter from IBlogConfiguration to IXMLSegment. I can now call whichever adapter is appropriate for some object I want to serialize by writing IXMLSegment(object_to_serialize).\nI could even add more adapters from various other things to IXMLSegment from eggs other than my.blog.xmldump. ZCML has a feature where it can run a particular directive if and only if some egg is installed. I could use this to have my.blog.rss register an adapter from IRSSFeed to IXMLSegment iff my.blog.xmldump happens to be installed, without making my.blog.rss depend on my.blog.xmldump.\nViewlets are like little BrowserViews that you can have 'subscribe' to a particular spot inside a page. I can't remember all the details right now but these are very good for things like plugins that you want to appear in a sidebar.\nI can't remember offhand whether they're part of base Zope or Plone. I would recommend against using Plone unless the problem that you are trying to solve actually needs a real CMS, since it's a big and complicated piece of software and it tends to be kinda slow.\nYou don't necessarily actually need Viewlets anyway, since BrowserViews can call one another, either by using 'object/@@some_browser_view' in a TAL expression, or by using queryMultiAdapter( (ISomething, IHttpRequest), name='some_browser_view' ), but they're pretty nice regardless.\nMarker Interfaces. A marker Interface is an Interface that provides no methods and no attributes. You can add a marker Interface any object at runtime using ISomething.alsoProvidedBy. This allows you to, for example, alter which adapters will get used on a particular object and which BrowserViews will be defined on it.\n\nI apologise that I haven't gone into enough detail to be able to implement each of these examples straight away, but they'd take approximately a blog post each.\n", "You can actually test if your object or class implements your interface. \nFor that you can use verify module (you would normally use it in your tests):\n>>> from zope.interface import Interface, Attribute, implements\n>>> class IFoo(Interface):\n... x = Attribute(\"The X attribute\")\n... y = Attribute(\"The Y attribute\")\n\n>>> class Foo(object):\n... implements(IFoo)\n... x = 1\n... def __init__(self):\n... self.y = 2\n\n>>> from zope.interface.verify import verifyObject\n>>> verifyObject(IFoo, Foo())\nTrue\n\n>>> from zope.interface.verify import verifyClass\n>>> verifyClass(IFoo, Foo)\nTrue\n\nInterfaces can also be used for setting and testing invariants.\nYou can find more information here:\nhttp://www.muthukadan.net/docs/zca.html#interfaces\n", "Zope interfaces can provide a useful way to decouple two pieces of code that shouldn't depend on each other.\nSay we have a component that knows how to print a greeting in module a.py:\n>>> class Greeter(object):\n... def greet(self):\n... print 'Hello'\n\nAnd some code that needs to print a greeting in module b.py:\n>>> Greeter().greet()\n'Hello'\n\nThis arrangement makes it hard to swap out the code that handles the greeting without touching b.py (which might be distributed in a separate package). Instead, we could introduce a third module c.py which defines an IGreeter interface:\n>>> from zope.interface import Interface\n>>> class IGreeter(Interface):\n... def greet():\n... \"\"\" Gives a greeting. \"\"\"\n\nNow we can use this to decouple a.py and b.py. Instead of instantiating a Greeter class, b.py will now ask for a utility providing the IGreeter interface. And a.py will declare that the Greeter class implements that interface:\n(a.py)\n>>> from zope.interface import implementer\n>>> from zope.component import provideUtility\n>>> from c import IGreeter\n\n>>> @implementer(IGreeter)\n... class Greeter(object):\n... def greet(self):\n... print 'Hello'\n>>> provideUtility(Greeter(), IGreeter)\n\n(b.py)\n>>> from zope.component import getUtility\n>>> from c import IGreeter\n\n>>> greeter = getUtility(IGreeter)\n>>> greeter.greet()\n'Hello'\n\n", "I've never used Zope interfaces, but you might consider writing a metaclass, which on initialization checks the members of the class against the interface, and raises a runtime exception if a method isn't implemented.\nWith Python you don't have other options. Either have a \"compile\" step that inspects your code, or dynamically inspect it at runtime.\n" ]
[ 52, 24, 19, 2 ]
[]
[]
[ "interface", "python", "zope", "zope.interface" ]
stackoverflow_0002521189_interface_python_zope_zope.interface.txt
Q: Django: What's the correct way to get the requesting IP address? I'm trying to develop an app using Django 1.1 on Webfaction. I'd like to get the IP address of the incoming request, but when I use request.META['REMOTE_ADDR'] it returns 127.0.0.1. There seems to be a number of different ways of getting the address, such as using HTTP_X_FORWARDED_FOR or plugging in some middleware called SetRemoteAddrFromForwardedFor. Just wondering what the best approach was? A: The remote proxy middleware was removed in Django 1.1.1 with a nod towards pointing out that trusting REMOTE_ADDR or HTTP_X_FORWARDED for isn't secure anyway (in case that also helps you decide what to do) A: I use the middleware because this way I don't have to change the app's code. If I want to migrate my app to other hosting servers, I only need to modify the middleware without affecting other parts. Security is not an issue because on WebFaction you can trust what comes in from the front end server.
Django: What's the correct way to get the requesting IP address?
I'm trying to develop an app using Django 1.1 on Webfaction. I'd like to get the IP address of the incoming request, but when I use request.META['REMOTE_ADDR'] it returns 127.0.0.1. There seems to be a number of different ways of getting the address, such as using HTTP_X_FORWARDED_FOR or plugging in some middleware called SetRemoteAddrFromForwardedFor. Just wondering what the best approach was?
[ "The remote proxy middleware was removed in Django 1.1.1 with a nod towards pointing out that trusting REMOTE_ADDR or HTTP_X_FORWARDED for isn't secure anyway (in case that also helps you decide what to do)\n", "I use the middleware because this way I don't have to change the app's code. \nIf I want to migrate my app to other hosting servers, I only need to modify the middleware without affecting other parts. \nSecurity is not an issue because on WebFaction you can trust what comes in from the front end server.\n" ]
[ 2, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002840329_django_python.txt
Q: Querying datetime.datetime on appengine acts different then dev server help! I'm having some trouble with stuff that work locally and dont work on the app engine python environment: Basically, i want to get a program from an epg between ranges of date and time. i know i cannot do two where > < so i saw a suggestion to save the dates as list as datetime.datetime which i did. [datetime.datetime(2010, 5, 10, 14, 25), datetime.datetime(2010, 5, 10, 15, 0)] This is ok. but when i try to compare to it: progranon = get_object(Programs2Channel, 'channel_id =', channelobj.key(), 'endstartdate >', programstart_minex, 'endstartdate <', programstart_minex ) This for some reason works locally, but fails to retrieve the data on the app engine. *Im using Google app engine django patch which uses the get_object to retrieve data in transactions. Please help. Here are more details: this is the LIST: [datetime.datetime(2010, 5, 13, 10, 45), datetime.datetime(2010, 5, 13, 11, 30)] #this is the query: programstart = ""+year+"-"+month+"-"+day+" "+hour+":"+minute programstart_minex = datetime.strptime(programstart, "%Y-%m-%d %H:%M") progranon = Programs2Channel.gql('WHERE channel_id = :channelid AND endstartdate > :programstartx AND endstartdate < :programstartx',channelid = channelobj.key(),programstartx=programstart_minex).get() A: could this be the issue? From: http://code.google.com/appengine/docs/python/datastore/gqlreference.html a datetime, date, or time literal, with either numeric values or a string representation, in the following forms: DATETIME(year, month, day, hour, minute, second) DATETIME('YYYY-MM-DD HH:MM:SS') my local server dev saves the datetime as numerical YYYY-MM-DD while the app engine saves datetime.datetime(2010, 5, 10, 14, 25), LOCAL datetime list: 2010-05-09 08:30:00,2010-05-09 09:00:00 APP ENGINE LIST: [datetime.datetime(2010, 5, 13, 10, 45), datetime.datetime(2010, 5, 13, 11, 30)] maybe this is the issue? A: Unfortunately, this is a known issue with the dev_appserver and querying on lists. However, the dev_appserver now includes an experimental sqlite stub, which doesn't have this issue. Try running it with --use_sqlite, and see if that helps - it should! A: How about querying just querying for programs that start after mindate (just the > query) and then filtering in memory? If its a TV Guide, we're not talking thousand of possible entities right? probably ~100 tops?
Querying datetime.datetime on appengine acts different then dev server help!
I'm having some trouble with stuff that work locally and dont work on the app engine python environment: Basically, i want to get a program from an epg between ranges of date and time. i know i cannot do two where > < so i saw a suggestion to save the dates as list as datetime.datetime which i did. [datetime.datetime(2010, 5, 10, 14, 25), datetime.datetime(2010, 5, 10, 15, 0)] This is ok. but when i try to compare to it: progranon = get_object(Programs2Channel, 'channel_id =', channelobj.key(), 'endstartdate >', programstart_minex, 'endstartdate <', programstart_minex ) This for some reason works locally, but fails to retrieve the data on the app engine. *Im using Google app engine django patch which uses the get_object to retrieve data in transactions. Please help. Here are more details: this is the LIST: [datetime.datetime(2010, 5, 13, 10, 45), datetime.datetime(2010, 5, 13, 11, 30)] #this is the query: programstart = ""+year+"-"+month+"-"+day+" "+hour+":"+minute programstart_minex = datetime.strptime(programstart, "%Y-%m-%d %H:%M") progranon = Programs2Channel.gql('WHERE channel_id = :channelid AND endstartdate > :programstartx AND endstartdate < :programstartx',channelid = channelobj.key(),programstartx=programstart_minex).get()
[ "could this be the issue?\nFrom:\nhttp://code.google.com/appengine/docs/python/datastore/gqlreference.html\n\na datetime, date, or time literal,\n with either numeric values or a string\n representation, in the following\n forms: DATETIME(year, month, day,\n hour, minute, second)\n DATETIME('YYYY-MM-DD HH:MM:SS')\n\nmy local server dev saves the datetime as numerical YYYY-MM-DD while the app engine saves datetime.datetime(2010, 5, 10, 14, 25),\nLOCAL datetime list:\n2010-05-09 08:30:00,2010-05-09 09:00:00\n\nAPP ENGINE LIST:\n[datetime.datetime(2010, 5, 13, 10, 45), datetime.datetime(2010, 5, 13, 11, 30)]\n\nmaybe this is the issue?\n", "Unfortunately, this is a known issue with the dev_appserver and querying on lists.\nHowever, the dev_appserver now includes an experimental sqlite stub, which doesn't have this issue. Try running it with --use_sqlite, and see if that helps - it should!\n", "How about querying just querying for programs that start after mindate (just the > query) and then filtering in memory?\nIf its a TV Guide, we're not talking thousand of possible entities right? probably ~100 tops?\n" ]
[ 1, 0, 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0002832711_google_app_engine_python.txt
Q: How does one pre-populate a Python Formish form? How does one pre-populate a Formish form? The obvious method as per the documentation doesn't seem right. Using one of the provided examples: import formish, schemaish structure = schemaish.Structure() structure.add( 'a', schemaish.String() ) structure.add( 'b', schemaish.Integer() ) schema = schemaish.Structure() schema.add( 'myStruct', structure ) form = formish.Form(schema, 'form') If we pass this a valid request object: form.validate(request) The output is a structure like this: {'myStruct': {'a': 'value', 'b': 0 }} However, pre-populating the form using defaults requires this: form.defaults = {'myStruct.a': 'value', 'myStruct.b': 0} The dottedish package has a DottedDict object that can convert a nested dict to a dotted dict, but this asymmetry doesn't seem right. Is there a better way to do this? A: No, don't require to use dotted dict, you can easily use the post-validate style dict to pre-populate the form: form.defaults={'myStruct': {'a': None, 'b': 'default_value'}} maybe have old version of formish, try update the libs.
How does one pre-populate a Python Formish form?
How does one pre-populate a Formish form? The obvious method as per the documentation doesn't seem right. Using one of the provided examples: import formish, schemaish structure = schemaish.Structure() structure.add( 'a', schemaish.String() ) structure.add( 'b', schemaish.Integer() ) schema = schemaish.Structure() schema.add( 'myStruct', structure ) form = formish.Form(schema, 'form') If we pass this a valid request object: form.validate(request) The output is a structure like this: {'myStruct': {'a': 'value', 'b': 0 }} However, pre-populating the form using defaults requires this: form.defaults = {'myStruct.a': 'value', 'myStruct.b': 0} The dottedish package has a DottedDict object that can convert a nested dict to a dotted dict, but this asymmetry doesn't seem right. Is there a better way to do this?
[ "No, don't require to use dotted dict, you can easily use the post-validate style dict to pre-populate the form:\nform.defaults={'myStruct': {'a': None, 'b': 'default_value'}}\n\nmaybe have old version of formish, try update the libs.\n" ]
[ 1 ]
[]
[]
[ "formish", "python" ]
stackoverflow_0002711083_formish_python.txt
Q: Combinatorial optimisation of a distance metric I have a set of trajectories, made up of points along the trajectory, and with the coordinates associated with each point. I store these in a 3d array ( trajectory, point, param). I want to find the set of r trajectories that have the maximum accumulated distance between the possible pairwise combinations of these trajectories. My first attempt, which I think is working looks like this: max_dist = 0 for h in itertools.combinations ( xrange(num_traj), r): for (m,l) in itertools.combinations (h, 2): accum = 0. for ( i, j ) in itertools.izip ( range(k), range(k) ): A = [ (my_mat[m, i, z] - my_mat[l, j, z])**2 \ for z in xrange(k) ] A = numpy.array( numpy.sqrt (A) ).sum() accum += A if max_dist < accum: selected_trajectories = h This takes forever, as num_traj can be around 500-1000, and r can be around 5-20. k is arbitrary, but can typically be up to 50. Trying to be super-clever, I have put everything into two nested list comprehensions, making heavy use of itertools: chunk = [[ numpy.sqrt((my_mat[m, i, :] - my_mat[l, j, :])**2).sum() \ for ((m,l),i,j) in \ itertools.product ( itertools.combinations(h,2), range(k), range(k)) ]\ for h in itertools.combinations(range(num_traj), r) ] Apart from being quite unreadable (!!!), it is also taking a long time. Can anyone suggest any ways to improve on this? A: Rather than recalculate the distance between each pair of trajectories on-demand, you can start by calculating the distance between all pairs of trajectories. You can store those in a dictionary and look them up as needed. This way your inner-loop for (i,j) ... will be replaced with a constant-time lookup. A: You can ditch the square root calculation on the distance calculation... the maximal sum will also have the maximal squared sum, although that only yields a constant speedup. A: Here are few points of interest and suggestions in addition to what everyone else has mentioned. (By the way, mathmike's suggestion of generating a look-up list all all pair distances is one that you should put in place immediately. It gets rid of a O(r^2) from your algorithm complexity.) First, the lines for ( i, j ) in itertools.izip ( range(k), range(k) ): A = [ (my_mat[m, i, z] - my_mat[l, j, z])**2 \ for z in xrange(k) ] can be replaced with for i in xrange(k): A = [ (my_mat[m, i, z] - my_mat[l, i, z])**2 \ for z in xrange(k) ] because i and j are always the same in every loop. There's no need to use izip at all here. Second, regarding the line A = numpy.array( numpy.sqrt (A) ).sum() Are you sure this is how you want to calculate it? Possibly so, but it just struck me as odd because if this was more of a Euclidean distance between vectors then the line would be: A = numpy.sqrt (numpy.array( A ).sum()) or just A = numpy.sqrt(sum(A)) because I would think that converting A to a numpy array to use numpy's sum function would be slower than just using the built-in Python sum function, but I could be wrong. Also, if it truly is a Euclidean distance that you want, then you will be doing less sqrt's this way. Third, do you realize how many potential combinations you may be trying to iterate over? For the worst case with num_traj = 1000 and r = 20, that is approximately 6.79E42 combinations by my estimate. That's quite intractable with your current method. Even for the best case of num_traj = 500 and r = 5, that's 1.28E12 combinations which is quite a few, but not impossible. This is the real problem you're having here because by taking mathmike's advice, the first two points that I have mentioned aren't very important. What can you do then? Well, you will need to be a little more clever. It isn't clear to me yet what would be a great method use for this. I'm guessing that you will need to make the algorithm heuristic in some way. One thought I had was to try a dynamic programming sort of approach with a heuristic. For each trajectory you could find the sum or mean of the distances for every pairing of it with another trajectory and use this as a fitness measure. Some of the trajectories with the lowest fitness measures could be dropped before moving on to trios. You could then do the same thing with trios: find the sum or mean of the accumulated distances for all trios (among remaining possible trajectories) that each trajectory is involved with and use that as the fitness measure to decide which ones to drop before moving on to foursomes. It doesn't guarantee the optimal solution, but it should be quite good and it will greatly lower the time complexity of the solution I believe. A: It's likely to take forever anyhow, as your algorithm takes about ~ O( C( N, r ) * r^2 ), where C( N, r ) is N choose r. For smaller r's (or N) this might be okay, but if you absolutely need to find the max, as opposed to using an approximation heuristic, you should try branch and bound with different strategies. This might work for smaller r's, and it saves you quite a bit on unnecessary recalculations. A: This sounds like a "weighted clique" problem: find e.g. r=5 people in a network with maximim compatibility / max sum of C(5,2) pair weights. Google "weighted clique" algorithm -"clique percolation" → 3k hits. BUT I would go with Justin Peel's method because it's understandable and controllable (take the n2 best pairs, from them the best n3 triples ... adjust n2 n3 ... to easily tradeoff runtime / quality of results.) Added 18may, a cut at an implementation follows. @Jose, it would be interesting to see what nbest[] sequence works for you. #!/usr/bin/env python """ cliq.py: grow high-weight 2 3 4 5-cliques, taking nbest at each stage weight ab = dist[a,b] -- a symmetric numpy array, diag << 0 weight abc, abcd ... = sum weight all pairs C[2] = [ (dist[j,k], (j,k)) ... ] nbest[2] pairs C[3] = [ (cliqwt(j,k,l), (j,k,l)) ... ] nbest[3] triples ... run time ~ N * (N + nbest[2] + nbest[3] ...) keywords: weighted-clique heuristic python """ # cf "graph clustering algorithm" from __future__ import division import numpy as np __version__ = "denis 18may 2010" me = __file__.split('/') [-1] def cliqdistances( cliq, dist ): return sorted( [dist[j,k] for j in cliq for k in cliq if j < k], reverse=True ) def maxarray2( a, n ): """ -> max n [ (a[j,k], (j,k)) ...] j <= k, a symmetric """ jkflat = np.argsort( a, axis=None )[:-2*n:-1] jks = [np.unravel_index( jk, a.shape ) for jk in jkflat] return [(a[j,k], (j,k)) for j,k in jks if j <= k] [:n] def _str( iter, fmt="%.2g" ): return " ".join( fmt % x for x in iter ) #............................................................................... def maxweightcliques( dist, nbest, r, verbose=10 ): def cliqwt( cliq, p ): return sum( dist[c,p] for c in cliq ) # << 0 if p in c def growcliqs( cliqs, nbest ): """ [(cliqweight, n-cliq) ...] -> nbest [(cliqweight, n+1 cliq) ...] """ # heapq the nbest ? here just gen all N * |cliqs|, sort all = [] dups = set() for w, c in cliqs: for p in xrange(N): # fast gen [sorted c+p ...] with small sorted c ? cp = c + [p] cp.sort() tup = tuple(cp) if tup in dups: continue dups.add( tup ) all.append( (w + cliqwt(c, p), cp )) all.sort( reverse=True ) if verbose: print "growcliqs: %s" % _str( w for w,c in all[:verbose] ) , print " best: %s" % _str( cliqdistances( all[0][1], dist )[:10]) return all[:nbest] np.fill_diagonal( dist, -1e10 ) # so cliqwt( c, p in c ) << 0 C = (r+1) * [(0, None)] # [(cliqweight, cliq-tuple) ...] # C[1] = [(0, (p,)) for p in xrange(N)] C[2] = [(w, list(pair)) for w, pair in maxarray2( dist, nbest[2] )] for j in range( 3, r+1 ): C[j] = growcliqs( C[j-1], nbest[j] ) return C #............................................................................... if __name__ == "__main__": import sys N = 100 r = 5 # max clique size nbest = 10 verbose = 0 seed = 1 exec "\n".join( sys.argv[1:] ) # N= ... np.random.seed(seed) nbest = [0, 0, N//2] + (r - 2) * [nbest] # ? print "%s N=%d r=%d nbest=%s" % (me, N, r, nbest) # random graphs w cluster parameters ? dist = np.random.exponential( 1, (N,N) ) dist = (dist + dist.T) / 2 for j in range( 0, N, r ): dist[j:j+r, j:j+r] += 2 # see if we get r in a row # dist = np.ones( (N,N) ) cliqs = maxweightcliques( dist, nbest, r, verbose )[-1] # [ (wt, cliq) ... ] print "Clique weight, clique, distances within clique" print 50 * "-" for w,c in cliqs: print "%5.3g %s %s" % ( w, _str( c, fmt="%d" ), _str( cliqdistances( c, dist )[:10]))
Combinatorial optimisation of a distance metric
I have a set of trajectories, made up of points along the trajectory, and with the coordinates associated with each point. I store these in a 3d array ( trajectory, point, param). I want to find the set of r trajectories that have the maximum accumulated distance between the possible pairwise combinations of these trajectories. My first attempt, which I think is working looks like this: max_dist = 0 for h in itertools.combinations ( xrange(num_traj), r): for (m,l) in itertools.combinations (h, 2): accum = 0. for ( i, j ) in itertools.izip ( range(k), range(k) ): A = [ (my_mat[m, i, z] - my_mat[l, j, z])**2 \ for z in xrange(k) ] A = numpy.array( numpy.sqrt (A) ).sum() accum += A if max_dist < accum: selected_trajectories = h This takes forever, as num_traj can be around 500-1000, and r can be around 5-20. k is arbitrary, but can typically be up to 50. Trying to be super-clever, I have put everything into two nested list comprehensions, making heavy use of itertools: chunk = [[ numpy.sqrt((my_mat[m, i, :] - my_mat[l, j, :])**2).sum() \ for ((m,l),i,j) in \ itertools.product ( itertools.combinations(h,2), range(k), range(k)) ]\ for h in itertools.combinations(range(num_traj), r) ] Apart from being quite unreadable (!!!), it is also taking a long time. Can anyone suggest any ways to improve on this?
[ "Rather than recalculate the distance between each pair of trajectories on-demand, you can start by calculating the distance between all pairs of trajectories. You can store those in a dictionary and look them up as needed.\nThis way your inner-loop for (i,j) ... will be replaced with a constant-time lookup.\n", "You can ditch the square root calculation on the distance calculation... the maximal sum will also have the maximal squared sum, although that only yields a constant speedup.\n", "Here are few points of interest and suggestions in addition to what everyone else has mentioned. (By the way, mathmike's suggestion of generating a look-up list all all pair distances is one that you should put in place immediately. It gets rid of a O(r^2) from your algorithm complexity.)\nFirst, the lines\nfor ( i, j ) in itertools.izip ( range(k), range(k) ):\n A = [ (my_mat[m, i, z] - my_mat[l, j, z])**2 \\\n for z in xrange(k) ]\n\ncan be replaced with\nfor i in xrange(k):\n A = [ (my_mat[m, i, z] - my_mat[l, i, z])**2 \\\n for z in xrange(k) ]\n\nbecause i and j are always the same in every loop. There's no need to use izip at all here.\nSecond, regarding the line\nA = numpy.array( numpy.sqrt (A) ).sum()\n\nAre you sure this is how you want to calculate it? Possibly so, but it just struck me as odd because if this was more of a Euclidean distance between vectors then the line would be:\nA = numpy.sqrt (numpy.array( A ).sum())\n\nor just\nA = numpy.sqrt(sum(A))\n\nbecause I would think that converting A to a numpy array to use numpy's sum function would be slower than just using the built-in Python sum function, but I could be wrong. Also, if it truly is a Euclidean distance that you want, then you will be doing less sqrt's this way.\nThird, do you realize how many potential combinations you may be trying to iterate over? For the worst case with num_traj = 1000 and r = 20, that is approximately 6.79E42 combinations by my estimate. That's quite intractable with your current method. Even for the best case of num_traj = 500 and r = 5, that's 1.28E12 combinations which is quite a few, but not impossible. This is the real problem you're having here because by taking mathmike's advice, the first two points that I have mentioned aren't very important.\nWhat can you do then? Well, you will need to be a little more clever. It isn't clear to me yet what would be a great method use for this. I'm guessing that you will need to make the algorithm heuristic in some way. One thought I had was to try a dynamic programming sort of approach with a heuristic. For each trajectory you could find the sum or mean of the distances for every pairing of it with another trajectory and use this as a fitness measure. Some of the trajectories with the lowest fitness measures could be dropped before moving on to trios. You could then do the same thing with trios: find the sum or mean of the accumulated distances for all trios (among remaining possible trajectories) that each trajectory is involved with and use that as the fitness measure to decide which ones to drop before moving on to foursomes. It doesn't guarantee the optimal solution, but it should be quite good and it will greatly lower the time complexity of the solution I believe.\n", "It's likely to take forever anyhow, as your algorithm takes about ~ O( C( N, r ) * r^2 ), where C( N, r ) is N choose r. For smaller r's (or N) this might be okay, but if you absolutely need to find the max, as opposed to using an approximation heuristic, you should try branch and bound with different strategies. This might work for smaller r's, and it saves you quite a bit on unnecessary recalculations.\n", "This sounds like a \"weighted clique\" problem: find e.g.\nr=5 people in a network with maximim compatibility / max sum of C(5,2) pair weights.\nGoogle \"weighted clique\" algorithm -\"clique percolation\" → 3k hits.\nBUT I would go with Justin Peel's method \nbecause it's understandable and controllable\n(take the n2 best pairs, from them the best n3 triples ...\nadjust n2 n3 ... to easily tradeoff runtime / quality of results.)\nAdded 18may, a cut at an implementation follows.\n@Jose, it would be interesting to see what nbest[] sequence works for you.\n#!/usr/bin/env python\n\"\"\" cliq.py: grow high-weight 2 3 4 5-cliques, taking nbest at each stage\n weight ab = dist[a,b] -- a symmetric numpy array, diag << 0\n weight abc, abcd ... = sum weight all pairs\n C[2] = [ (dist[j,k], (j,k)) ... ] nbest[2] pairs\n C[3] = [ (cliqwt(j,k,l), (j,k,l)) ... ] nbest[3] triples\n ...\n run time ~ N * (N + nbest[2] + nbest[3] ...)\n\nkeywords: weighted-clique heuristic python\n\"\"\"\n# cf \"graph clustering algorithm\"\n\nfrom __future__ import division\nimport numpy as np\n\n__version__ = \"denis 18may 2010\"\nme = __file__.split('/') [-1]\n\ndef cliqdistances( cliq, dist ):\n return sorted( [dist[j,k] for j in cliq for k in cliq if j < k], reverse=True )\n\ndef maxarray2( a, n ):\n \"\"\" -> max n [ (a[j,k], (j,k)) ...] j <= k, a symmetric \"\"\"\n jkflat = np.argsort( a, axis=None )[:-2*n:-1]\n jks = [np.unravel_index( jk, a.shape ) for jk in jkflat]\n return [(a[j,k], (j,k)) for j,k in jks if j <= k] [:n]\n\ndef _str( iter, fmt=\"%.2g\" ):\n return \" \".join( fmt % x for x in iter )\n\n#...............................................................................\n\ndef maxweightcliques( dist, nbest, r, verbose=10 ):\n\n def cliqwt( cliq, p ):\n return sum( dist[c,p] for c in cliq ) # << 0 if p in c\n\n def growcliqs( cliqs, nbest ):\n \"\"\" [(cliqweight, n-cliq) ...] -> nbest [(cliqweight, n+1 cliq) ...] \"\"\"\n # heapq the nbest ? here just gen all N * |cliqs|, sort\n all = []\n dups = set()\n for w, c in cliqs:\n for p in xrange(N):\n # fast gen [sorted c+p ...] with small sorted c ?\n cp = c + [p]\n cp.sort()\n tup = tuple(cp)\n if tup in dups: continue\n dups.add( tup )\n all.append( (w + cliqwt(c, p), cp ))\n all.sort( reverse=True )\n if verbose:\n print \"growcliqs: %s\" % _str( w for w,c in all[:verbose] ) ,\n print \" best: %s\" % _str( cliqdistances( all[0][1], dist )[:10])\n return all[:nbest]\n\n np.fill_diagonal( dist, -1e10 ) # so cliqwt( c, p in c ) << 0\n C = (r+1) * [(0, None)] # [(cliqweight, cliq-tuple) ...]\n # C[1] = [(0, (p,)) for p in xrange(N)]\n C[2] = [(w, list(pair)) for w, pair in maxarray2( dist, nbest[2] )]\n for j in range( 3, r+1 ):\n C[j] = growcliqs( C[j-1], nbest[j] )\n return C\n\n#...............................................................................\nif __name__ == \"__main__\":\n import sys\n\n N = 100\n r = 5 # max clique size\n nbest = 10\n verbose = 0\n seed = 1\n exec \"\\n\".join( sys.argv[1:] ) # N= ...\n np.random.seed(seed)\n nbest = [0, 0, N//2] + (r - 2) * [nbest] # ?\n\n print \"%s N=%d r=%d nbest=%s\" % (me, N, r, nbest)\n\n # random graphs w cluster parameters ?\n dist = np.random.exponential( 1, (N,N) )\n dist = (dist + dist.T) / 2\n for j in range( 0, N, r ):\n dist[j:j+r, j:j+r] += 2 # see if we get r in a row\n # dist = np.ones( (N,N) )\n\n cliqs = maxweightcliques( dist, nbest, r, verbose )[-1] # [ (wt, cliq) ... ]\n\n print \"Clique weight, clique, distances within clique\"\n print 50 * \"-\"\n for w,c in cliqs:\n print \"%5.3g %s %s\" % (\n w, _str( c, fmt=\"%d\" ), _str( cliqdistances( c, dist )[:10]))\n\n" ]
[ 3, 2, 2, 1, 1 ]
[]
[]
[ "algorithm", "combinatorics", "numpy", "python", "python_itertools" ]
stackoverflow_0002829772_algorithm_combinatorics_numpy_python_python_itertools.txt
Q: C# style properties in python I am looking for a way to define properties in Python similar to C#, with nested get/set definitions. This is how far I got: #### definition #### def Prop(fcn): f = fcn() return property(f['get'], f['set']) #### test #### class Example(object): @Prop def myattr(): def get(self): return self._value def set(self, value): self._value = value return locals() # <- how to get rid of this? e = Example() e.myattr = 'somevalue' print e.myattr The problem with this is, that it still needs the definition to 'return locals()'. Is there a way to get rid of it? Maybe with a nested decorator? A: You could return get, set (a much more elegant approach) and make your Prop into def Prop(fcn): g, s = fcn() return property(g, s) There is however no clean way to not require any return statement in the decorated function. A function with internal def statements, just like one with internal assignments, does not actually execute those statements until it gets called -- the objects and names said assignments and defs are supposed to build and bind are, literally, nowhere to be found. Once it is called, said names and objects are local to the function -- so, they go away unless external references to them exist... and there's really no more elegant way to ensure such external references to local names exist, besides returning them in some form. The problem comes from insisting that you want to decorate a function object (which keeps its local names very much to itself, by design). Everything would be fine and dandy if you agreed to use the correct keyword instead of def for the decorated thingy -- that correct keyword is class. (Note, you need Python 2.6 or better for this purpose)...: def Prop(cls): f = cls.__dict__ return property(f['get'], f['set']) #### test #### class Example(object): @Prop class myattr(): def get(self): print 'getting', self._value return self._value def set(self, value): print 'setting', value self._value = value e = Example() e.myattr = 'somevalue' print e.myattr Classes are much less secretive than functions wrt what's "inside" them, so a class decorator can easily accomplish what you're after. Note the tiny changes: __dict__ to access the dict of the class being decorated, s/def/class/ in the object being decorated, and removal of the return statement you dislike.
C# style properties in python
I am looking for a way to define properties in Python similar to C#, with nested get/set definitions. This is how far I got: #### definition #### def Prop(fcn): f = fcn() return property(f['get'], f['set']) #### test #### class Example(object): @Prop def myattr(): def get(self): return self._value def set(self, value): self._value = value return locals() # <- how to get rid of this? e = Example() e.myattr = 'somevalue' print e.myattr The problem with this is, that it still needs the definition to 'return locals()'. Is there a way to get rid of it? Maybe with a nested decorator?
[ "You could return get, set (a much more elegant approach) and make your Prop into\ndef Prop(fcn):\n g, s = fcn()\n return property(g, s)\n\nThere is however no clean way to not require any return statement in the decorated function. A function with internal def statements, just like one with internal assignments, does not actually execute those statements until it gets called -- the objects and names said assignments and defs are supposed to build and bind are, literally, nowhere to be found.\nOnce it is called, said names and objects are local to the function -- so, they go away unless external references to them exist... and there's really no more elegant way to ensure such external references to local names exist, besides returning them in some form.\nThe problem comes from insisting that you want to decorate a function object (which keeps its local names very much to itself, by design). Everything would be fine and dandy if you agreed to use the correct keyword instead of def for the decorated thingy -- that correct keyword is class. (Note, you need Python 2.6 or better for this purpose)...:\ndef Prop(cls):\n f = cls.__dict__\n return property(f['get'], f['set'])\n\n\n#### test ####\n\nclass Example(object):\n\n @Prop\n class myattr():\n\n def get(self):\n print 'getting', self._value\n return self._value\n\n def set(self, value):\n print 'setting', value\n self._value = value\n\n\ne = Example()\ne.myattr = 'somevalue' \nprint e.myattr\n\nClasses are much less secretive than functions wrt what's \"inside\" them, so a class decorator can easily accomplish what you're after. Note the tiny changes: __dict__ to access the dict of the class being decorated, s/def/class/ in the object being decorated, and removal of the return statement you dislike.\n" ]
[ 2 ]
[]
[]
[ "c#", "nested", "properties", "python" ]
stackoverflow_0002841432_c#_nested_properties_python.txt
Q: Best data-structure to use for two ended sorted list I need a collection data-structure that can do the following: Be sorted Allow me to quickly pop values off the front and back of the list O(log n) Remain sorted after I insert a new value Allow a user-specified comparison function, as I will be storing tuples and want to sort on a particular value Thread-safety is not required Optionally allow efficient haskey() lookups (I'm happy to maintain a separate hash-table for this though) My thoughts at this stage are that I need a priority queue and a hash table, although I don't know if I can quickly pop values off both ends of a priority queue. Another possibility is simply maintaining an OrderedDictionary and doing an insertion sort it every-time I add more data to it. Because I'm interested in performance for a moderate number of items (I would estimate less than 200,000), I am unsure about what asymptotic performance I require for these operations. n will not grow infinitely, so a low constant performance k in k * O(n) may be as important O(n). That said, I would prefer that both the insert and pop operations take O(log n) time. Furthermore, are there any particular implementations in Python? I would really like to avoid writing this code myself. A: You might get good performance for these kinds of operations using blist or a database (such as the sqlite which is in the stdlib). A: I suggest some sort of balanced binary tree such as a red-black tree. A search on PyPi throws up a couple of implementations. Searching on google will give you more. bintrees on PyPi looks very complete and has both Python and C/Cython implementations. I have not used it though, so caveat emptor. A red-black tree is kept sorted and most operations (insert, delete, find) are O(log2(N)), so finding an element in a tree of 200,000 entries will take on average 17-18 comparisons. A: Sounds like a skip list will fulfill all your requirements. It's basically a dynamically-sized sorted linked list, with O(log n) insertions and removals. I don't really know Python, but this link seems to be relevant: http://infohost.nmt.edu/tcc/help/lang/python/examples/pyskip/ A: I presume you need it sorted because you access element by rank in the sorted order? You can use any implementation of any balanced binary tree, with the additional information at each node which tells you the numbers of descendants of that node (usually called the Order Statistic Binary Tree). With this structure, given the rank of an element (even min/max), you can access/delete it in O(log n) time. This makes all operations (access/insert/delete by rank, pop front/back, insert/delete/search by value) O(logn) time, while allowing custom sort methods. Also, apparently python has an AVL tree (one of the first balanced tree structures) implementation which supports order statistics: http://www.python.org/ftp/python/contrib-09-Dec-1999/DataStructures/avl.README So you won't need a custom implementation. A: Except for the hashing, what you're looking for is a double-ended priority queue, aka a priority deque. If your need for sorting doesn't extend beyond managing the min and max of your data, another structure for you to look at might be an interval heap, which has the advantage of O(1) lookup of both min and max if you need to peek at values (though deleteMin and deleteMax are still O(log(N)) ). Unfortunately, I'm not aware of any implementations in Python, so I think you'd have to roll your own. Here's an addendum to an algorithms textbook that describes interval heaps if you're interested: http://www.mhhe.com/engcs/compsci/sahni/enrich/c9/interval.pdf A: If you can really allow O(log n) for pop, dequeue, and insert, then a simple balanced search tree like red-black tree is definitely sufficient. You can optimize this of course by maintaining a direct pointer to the smallest and largest element in the tree, and then updating it when you (1) insert elements into the tree or (2) pop or dequeue, which of course invalidate the resp. pointer. But because the tree is balanced, there's some shuffling going out anyway, and you can update the corr. pointer at the same time. There is also something called min-max heap (see the Wikipedia entry for Binary Heap), which implements exactly a "double-ended priority queue", i.e. a queue where you can pop both from front end and the rear end. However there you can't access the whole list of objects in order, whereas a search tree can be iterated efficiently through in O(n) time. The benefit of a min-max heap however is that the current min and max objects can be read in O(1) time, a search tree requires O(log(n)) just to read the min or max object unless you have the cached pointers as I mentioned above.
Best data-structure to use for two ended sorted list
I need a collection data-structure that can do the following: Be sorted Allow me to quickly pop values off the front and back of the list O(log n) Remain sorted after I insert a new value Allow a user-specified comparison function, as I will be storing tuples and want to sort on a particular value Thread-safety is not required Optionally allow efficient haskey() lookups (I'm happy to maintain a separate hash-table for this though) My thoughts at this stage are that I need a priority queue and a hash table, although I don't know if I can quickly pop values off both ends of a priority queue. Another possibility is simply maintaining an OrderedDictionary and doing an insertion sort it every-time I add more data to it. Because I'm interested in performance for a moderate number of items (I would estimate less than 200,000), I am unsure about what asymptotic performance I require for these operations. n will not grow infinitely, so a low constant performance k in k * O(n) may be as important O(n). That said, I would prefer that both the insert and pop operations take O(log n) time. Furthermore, are there any particular implementations in Python? I would really like to avoid writing this code myself.
[ "You might get good performance for these kinds of operations using blist or a database (such as the sqlite which is in the stdlib).\n", "I suggest some sort of balanced binary tree such as a red-black tree. \nA search on PyPi throws up a couple of implementations. Searching on google will give you more.\nbintrees on PyPi looks very complete and has both Python and C/Cython implementations. I have not used it though, so caveat emptor.\nA red-black tree is kept sorted and most operations (insert, delete, find) are O(log2(N)), so finding an element in a tree of 200,000 entries will take on average 17-18 comparisons.\n", "Sounds like a skip list will fulfill all your requirements. It's basically a dynamically-sized sorted linked list, with O(log n) insertions and removals.\nI don't really know Python, but this link seems to be relevant:\nhttp://infohost.nmt.edu/tcc/help/lang/python/examples/pyskip/\n", "I presume you need it sorted because you access element by rank in the sorted order? \nYou can use any implementation of any balanced binary tree, with the additional information at each node which tells you the numbers of descendants of that node (usually called the Order Statistic Binary Tree).\nWith this structure, given the rank of an element (even min/max), you can access/delete it in O(log n) time. \nThis makes all operations (access/insert/delete by rank, pop front/back, insert/delete/search by value) O(logn) time, while allowing custom sort methods.\nAlso, apparently python has an AVL tree (one of the first balanced tree structures) implementation which supports order statistics: http://www.python.org/ftp/python/contrib-09-Dec-1999/DataStructures/avl.README\nSo you won't need a custom implementation.\n", "Except for the hashing, what you're looking for is a double-ended priority queue, aka a priority deque.\nIf your need for sorting doesn't extend beyond managing the min and max of your data, another structure for you to look at might be an interval heap, which has the advantage of O(1) lookup of both min and max if you need to peek at values (though deleteMin and deleteMax are still O(log(N)) ). Unfortunately, I'm not aware of any implementations in Python, so I think you'd have to roll your own.\nHere's an addendum to an algorithms textbook that describes interval heaps if you're interested:\nhttp://www.mhhe.com/engcs/compsci/sahni/enrich/c9/interval.pdf\n", "If you can really allow O(log n) for pop, dequeue, and insert, then a simple balanced search tree like red-black tree is definitely sufficient.\nYou can optimize this of course by maintaining a direct pointer to the smallest and largest element in the tree, and then updating it when you (1) insert elements into the tree or (2) pop or dequeue, which of course invalidate the resp. pointer. But because the tree is balanced, there's some shuffling going out anyway, and you can update the corr. pointer at the same time.\nThere is also something called min-max heap (see the Wikipedia entry for Binary Heap), which implements exactly a \"double-ended priority queue\", i.e. a queue where you can pop both from front end and the rear end. However there you can't access the whole list of objects in order, whereas a search tree can be iterated efficiently through in O(n) time.\nThe benefit of a min-max heap however is that the current min and max objects can be read in O(1) time, a search tree requires O(log(n)) just to read the min or max object unless you have the cached pointers as I mentioned above.\n" ]
[ 2, 1, 1, 1, 1, 1 ]
[ "If this were Java I'd use a TreeSet with the NavigableSet interface.\nThis is implemented as a Red-Black-Tree.\n" ]
[ -1 ]
[ "algorithm", "collections", "data_structures", "performance", "python" ]
stackoverflow_0002839130_algorithm_collections_data_structures_performance_python.txt
Q: Is there a method to find out if a package is to be installed with distutils instead of setuptools? I can look inside setup.py I suppose to see if it's a distutils package. But in the process of familiarizing myself with python package management I have noticed that there seems to be more than one way to do it. So: How can I check an unzipped packages directory or setup.py to see how to build it? EDIT: When I say 'build' I mean is it going to use distutils or setuptools, or distribute. I am using buildout. A: Why do you need to know? What's wrong with just running /path/to/your/python setup.py install ?
Is there a method to find out if a package is to be installed with distutils instead of setuptools?
I can look inside setup.py I suppose to see if it's a distutils package. But in the process of familiarizing myself with python package management I have noticed that there seems to be more than one way to do it. So: How can I check an unzipped packages directory or setup.py to see how to build it? EDIT: When I say 'build' I mean is it going to use distutils or setuptools, or distribute. I am using buildout.
[ "Why do you need to know? What's wrong with just running \n/path/to/your/python setup.py install\n\n?\n" ]
[ 0 ]
[]
[]
[ "distribute", "distutils", "python" ]
stackoverflow_0002839902_distribute_distutils_python.txt
Q: Nested WHILE loops in Python I am a beginner with Python and trying few programs. I have something like the following WHILE loop construct in Python (not exact). IDLE 2.6.4 >>> a=0 >>> b=0 >>> while a < 4: a=a+1 while b < 4: b=b+1 print a, b 1 1 1 2 1 3 1 4 I am expecting the outer loop to loop through 1,2,3 and 4. And I know I can do this with FOR loop like this >>> for a in range(1,5): for b in range(1,5): print a,b 1 1 1 2 .. .. .. .. // Other lines omitted for brevity 4 4 But, what is wrong with WHILE loop? I guess I am missing some thing obvious, but could not make out. Answer: The corrected WHILE loop.. >>> a=0 >>> while a < 4: a=a+1 b=0 while b<4: b=b+1 print a,b 1 1 .. .. .. .. // Other lines omitted for brevity 4 4 P.S: Searched out SO, found few questions but none as close to this. Don't know whether this could classified as homework, the actual program was different, the problem is what puzzles me. A: You're not resetting b to 0 right inside your outer loop, so b stays at the value it had after the first leg of the outer loop -- 4 -- and the inner loop never executes again. The for loops work fine because they do reset their loop control variables correctly; with the less-structured while loops, such resetting is in your hands, and you're not doing it.
Nested WHILE loops in Python
I am a beginner with Python and trying few programs. I have something like the following WHILE loop construct in Python (not exact). IDLE 2.6.4 >>> a=0 >>> b=0 >>> while a < 4: a=a+1 while b < 4: b=b+1 print a, b 1 1 1 2 1 3 1 4 I am expecting the outer loop to loop through 1,2,3 and 4. And I know I can do this with FOR loop like this >>> for a in range(1,5): for b in range(1,5): print a,b 1 1 1 2 .. .. .. .. // Other lines omitted for brevity 4 4 But, what is wrong with WHILE loop? I guess I am missing some thing obvious, but could not make out. Answer: The corrected WHILE loop.. >>> a=0 >>> while a < 4: a=a+1 b=0 while b<4: b=b+1 print a,b 1 1 .. .. .. .. // Other lines omitted for brevity 4 4 P.S: Searched out SO, found few questions but none as close to this. Don't know whether this could classified as homework, the actual program was different, the problem is what puzzles me.
[ "You're not resetting b to 0 right inside your outer loop, so b stays at the value it had after the first leg of the outer loop -- 4 -- and the inner loop never executes again.\nThe for loops work fine because they do reset their loop control variables correctly; with the less-structured while loops, such resetting is in your hands, and you're not doing it.\n" ]
[ 7 ]
[]
[]
[ "for_loop", "nested_loops", "python", "while_loop" ]
stackoverflow_0002841489_for_loop_nested_loops_python_while_loop.txt
Q: How can I reshape and aggregate list of tuples in Python? I'm a newb to Python so apologies in advance if my question looks trivial. From a psycopg2 query i have a result in the form of a list of tuples looking like: [(1, 0), (1, 0), (1, 1), (2, 1), (2, 2), (2, 2), (2, 2)] Each tuple represents id of a location where event happened and hour of the day when event took place. I'd like to reshape and aggregate this list with subtotals for each hour in each location, to a form where it looks like: [(1, 0, 2), (1, 1, 1), (1, 2, 0), (2, 0, 0), (2, 1, 1), (2, 3, 3)] Where each touple will now tell me that, for example: in location 1, at hour 0 there were 2 events; in location 1, at hour 1 there was 1 event; and so on... If there were 0 events at certain hour, I still would like to see it, as for example 0 events at 0 hours in location 2: (2, 0, 0) How could I implement it in Python? EDIT: Thanks for help! A: Something like...: import collections raw_data = [(1, 0), (1, 0), (1, 1), (2, 1), (2, 2), (2, 2), (2, 2)] aux = collections.defaultdict(int) for x, y in raw_data: aux[x, y] += 1 locations = sorted(set(x for x, y in raw_data)) hours = sorted(set(y for x, y in raw_data)) result = [(x, y, aux[x, y]) for x in locations for y in hours] if you want locations and hours to reflect what's in the raw data. You might want to use range(some, thing) for each of locations and hours instead if you have independent information about the ranges that both locations and hours should span, quite separately from whatever hours and locations actually happen to be in raw_data. A: If you're getting this from the database, why not have the query do it in the first place? Something like: SELECT hour, location, COUNT(*) FROM events GROUP BY hour, location ORDER BY hour, location. In Python, maybe something like this: timed_events = {} # Count them up for event in events_from_database: timed_events[event] = timed_events.setdefault(event, 0) + 1 # Form a new list with the original data plus the count aggregate_list = [(evt[0], evt[1], count) for evt,count in events.items()]
How can I reshape and aggregate list of tuples in Python?
I'm a newb to Python so apologies in advance if my question looks trivial. From a psycopg2 query i have a result in the form of a list of tuples looking like: [(1, 0), (1, 0), (1, 1), (2, 1), (2, 2), (2, 2), (2, 2)] Each tuple represents id of a location where event happened and hour of the day when event took place. I'd like to reshape and aggregate this list with subtotals for each hour in each location, to a form where it looks like: [(1, 0, 2), (1, 1, 1), (1, 2, 0), (2, 0, 0), (2, 1, 1), (2, 3, 3)] Where each touple will now tell me that, for example: in location 1, at hour 0 there were 2 events; in location 1, at hour 1 there was 1 event; and so on... If there were 0 events at certain hour, I still would like to see it, as for example 0 events at 0 hours in location 2: (2, 0, 0) How could I implement it in Python? EDIT: Thanks for help!
[ "Something like...:\nimport collections\n\nraw_data = [(1, 0), (1, 0), (1, 1), (2, 1), (2, 2), (2, 2), (2, 2)]\naux = collections.defaultdict(int)\nfor x, y in raw_data:\n aux[x, y] += 1\n\nlocations = sorted(set(x for x, y in raw_data))\nhours = sorted(set(y for x, y in raw_data))\nresult = [(x, y, aux[x, y]) for x in locations for y in hours]\n\nif you want locations and hours to reflect what's in the raw data. You might want to use range(some, thing) for each of locations and hours instead if you have independent information about the ranges that both locations and hours should span, quite separately from whatever hours and locations actually happen to be in raw_data.\n", "If you're getting this from the database, why not have the query do it in the first place? Something like: SELECT hour, location, COUNT(*) FROM events GROUP BY hour, location ORDER BY hour, location.\nIn Python, maybe something like this:\ntimed_events = {}\n# Count them up\nfor event in events_from_database:\n timed_events[event] = timed_events.setdefault(event, 0) + 1\n\n# Form a new list with the original data plus the count\naggregate_list = [(evt[0], evt[1], count) for evt,count in events.items()]\n\n" ]
[ 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0002841442_python.txt
Q: Call function in views.py from command line (django) I'm trying to run a function defined in the views file of my django app, from the command line. Is there a way to do this? I understand view functions are supposed to be called from a request but I need this function to be called from a cron eventually. Thanks A: You can use custom management commands.
Call function in views.py from command line (django)
I'm trying to run a function defined in the views file of my django app, from the command line. Is there a way to do this? I understand view functions are supposed to be called from a request but I need this function to be called from a cron eventually. Thanks
[ "You can use custom management commands.\n" ]
[ 6 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002841628_django_python.txt
Q: Python optimization problem? Alright, i had this homework recently (don't worry, i've already done it, but in c++) but I got curious how i could do it in python. The problem is about 2 light sources that emit light. I won't get into details tho. Here's the code (that I've managed to optimize a bit in the latter part): import math, array import numpy as np from PIL import Image size = (800,800) width, height = size s1x = width * 1./8 s1y = height * 1./8 s2x = width * 7./8 s2y = height * 7./8 r,g,b = (255,255,255) arr = np.zeros((width,height,3)) hy = math.hypot print 'computing distances (%s by %s)'%size, for i in xrange(width): if i%(width/10)==0: print i, if i%20==0: print '.', for j in xrange(height): d1 = hy(i-s1x,j-s1y) d2 = hy(i-s2x,j-s2y) arr[i][j] = abs(d1-d2) print '' arr2 = np.zeros((width,height,3),dtype="uint8") for ld in [200,116,100,84,68,52,36,20,8,4,2]: print 'now computing image for ld = '+str(ld) arr2 *= 0 arr2 += abs(arr%ld-ld/2)*(r,g,b)/(ld/2) print 'saving image...' ar2img = Image.fromarray(arr2) ar2img.save('ld'+str(ld).rjust(4,'0')+'.png') print 'saved as ld'+str(ld).rjust(4,'0')+'.png' I have managed to optimize most of it, but there's still a huge performance gap in the part with the 2 for-s, and I can't seem to think of a way to bypass that using common array operations... I'm open to suggestions :D Edit: In response to Vlad's suggestion, I'll post the problem's details: There are 2 light sources, each emitting light as a sinusoidal wave: E1 = E0*sin(omega1*time+phi01) E2 = E0*sin(omega2*time+phi02) we consider omega1=omega2=omega=2*PI/T and phi01=phi02=phi0 for simplicity by considering x1 to be the distance from the first source of a point on the plane, the intensity of the light in that point is Ep1 = E0*sin(omega*time - 2*PI*x1/lambda + phi0) where lambda = speed of light * T (period of oscillation) Considering both light sources on the plane, the formula becomes Ep = 2*E0*cos(PI*(x2-x1)/lambda)sin(omegatime - PI*(x2-x1)/lambda + phi0) and from that we could make out that the intensity of the light is maximum when (x2-x1)/lambda = (2*k) * PI/2 and minimum when (x2-x1)/lambda = (2*k+1) * PI/2 and varies in between, where k is an integer For a given moment of time, given the coordinates of the light sources, and for a known lambda and E0, we had to make a program to draw how the light looks IMHO i think i optimized the problem as much as it could be done... A: Interference patterns are fun, aren't they? So, first off this is going to be minor because running this program as-is on my laptop takes a mere twelve and a half seconds. But let's see what can be done about doing the first bit through numpy array operations, shall we? We have basically that you want: arr[i][j] = abs(hypot(i-s1x,j-s1y) - hypot(i-s2x,j-s2y)) For all i and j. So, since numpy has a hypot function that works on numpy arrays, let's use that. Our first challenge is to get an array of the right size with every element equal to i and another with every element equal to j. But this isn't too hard; in fact, an answer below points my at the wonderful numpy.mgrid which I didn't know about before that does just this: array_i,array_j = np.mgrid[0:width,0:height] There is the slight matter of making your (width, height)-sized array into (width,height,3) to be compatible with your image-generation statements, but that's pretty easy to do: arr = (arr * np.ones((3,1,1))).transpose(1,2,0) Then we plug this into your program, and let things be done by array operations: import math, array import numpy as np from PIL import Image size = (800,800) width, height = size s1x = width * 1./8 s1y = height * 1./8 s2x = width * 7./8 s2y = height * 7./8 r,g,b = (255,255,255) array_i,array_j = np.mgrid[0:width,0:height] arr = np.abs(np.hypot(array_i-s1x, array_j-s1y) - np.hypot(array_i-s2x, array_j-s2y)) arr = (arr * np.ones((3,1,1))).transpose(1,2,0) arr2 = np.zeros((width,height,3),dtype="uint8") for ld in [200,116,100,84,68,52,36,20,8,4,2]: print 'now computing image for ld = '+str(ld) # Rest as before And the new time is... 8.2 seconds. So you save maybe four whole seconds. On the other hand, that's almost exclusively in the image generation stages now, so maybe you can tighten them up by only generating the images you want. A: If you use array operations instead of loops, it is much, much faster. For me, the image generation is now what takes so long time. Instead of your two i,j loops, I have this: I,J = np.mgrid[0:width,0:height] D1 = np.hypot(I - s1x, J - s1y) D2 = np.hypot(I - s2x, J - s2y) arr = np.abs(D1-D2) # triplicate into 3 layers arr = np.array((arr, arr, arr)).transpose(1,2,0) # .. continue program The basics that you want to remember for the future is: this is not about optimization; using array forms in numpy is just using it like it is supposed to be used. With experience, your future projects should not go the detour over python loops, the array forms should be the natural form. What we did here was really simple. Instead of math.hypot we found numpy.hypot and used it. Like all such numpy functions, it accepts ndarrays as arguments, and does exactly what we want. A: List comprehensions are much faster than loops. For example, instead of for j in xrange(height): d1 = hy(i-s1x,j-s1y) d2 = hy(i-s2x,j-s2y) arr[i][j] = abs(d1-d2) You'd write arr[i] = [abs(hy(i-s1x,j-s1y) - hy(i-s2x,j-s2y)) for j in xrange(height)] On the other hand, if you're really trying to "optimize", then you might want to reimplement this algorithm in C, and use SWIG or the like to call it from python. A: The only changes that come to my mind is to move some operations out of the loop: for i in xrange(width): if i%(width/10)==0: print i, if i%20==0: print '.', arri = arr[i] is1x = i - s1x is2x = i - s2x for j in xrange(height): d1 = hy(is1x,j-s1y) d2 = hy(is2x,j-s2y) arri[j] = abs(d1-d2) The improvement, if any, will probably be minor though.
Python optimization problem?
Alright, i had this homework recently (don't worry, i've already done it, but in c++) but I got curious how i could do it in python. The problem is about 2 light sources that emit light. I won't get into details tho. Here's the code (that I've managed to optimize a bit in the latter part): import math, array import numpy as np from PIL import Image size = (800,800) width, height = size s1x = width * 1./8 s1y = height * 1./8 s2x = width * 7./8 s2y = height * 7./8 r,g,b = (255,255,255) arr = np.zeros((width,height,3)) hy = math.hypot print 'computing distances (%s by %s)'%size, for i in xrange(width): if i%(width/10)==0: print i, if i%20==0: print '.', for j in xrange(height): d1 = hy(i-s1x,j-s1y) d2 = hy(i-s2x,j-s2y) arr[i][j] = abs(d1-d2) print '' arr2 = np.zeros((width,height,3),dtype="uint8") for ld in [200,116,100,84,68,52,36,20,8,4,2]: print 'now computing image for ld = '+str(ld) arr2 *= 0 arr2 += abs(arr%ld-ld/2)*(r,g,b)/(ld/2) print 'saving image...' ar2img = Image.fromarray(arr2) ar2img.save('ld'+str(ld).rjust(4,'0')+'.png') print 'saved as ld'+str(ld).rjust(4,'0')+'.png' I have managed to optimize most of it, but there's still a huge performance gap in the part with the 2 for-s, and I can't seem to think of a way to bypass that using common array operations... I'm open to suggestions :D Edit: In response to Vlad's suggestion, I'll post the problem's details: There are 2 light sources, each emitting light as a sinusoidal wave: E1 = E0*sin(omega1*time+phi01) E2 = E0*sin(omega2*time+phi02) we consider omega1=omega2=omega=2*PI/T and phi01=phi02=phi0 for simplicity by considering x1 to be the distance from the first source of a point on the plane, the intensity of the light in that point is Ep1 = E0*sin(omega*time - 2*PI*x1/lambda + phi0) where lambda = speed of light * T (period of oscillation) Considering both light sources on the plane, the formula becomes Ep = 2*E0*cos(PI*(x2-x1)/lambda)sin(omegatime - PI*(x2-x1)/lambda + phi0) and from that we could make out that the intensity of the light is maximum when (x2-x1)/lambda = (2*k) * PI/2 and minimum when (x2-x1)/lambda = (2*k+1) * PI/2 and varies in between, where k is an integer For a given moment of time, given the coordinates of the light sources, and for a known lambda and E0, we had to make a program to draw how the light looks IMHO i think i optimized the problem as much as it could be done...
[ "Interference patterns are fun, aren't they?\nSo, first off this is going to be minor because running this program as-is on my laptop takes a mere twelve and a half seconds.\nBut let's see what can be done about doing the first bit through numpy array operations, shall we? We have basically that you want:\narr[i][j] = abs(hypot(i-s1x,j-s1y) - hypot(i-s2x,j-s2y))\n\nFor all i and j.\nSo, since numpy has a hypot function that works on numpy arrays, let's use that. Our first challenge is to get an array of the right size with every element equal to i and another with every element equal to j. But this isn't too hard; in fact, an answer below points my at the wonderful numpy.mgrid which I didn't know about before that does just this:\narray_i,array_j = np.mgrid[0:width,0:height]\n\nThere is the slight matter of making your (width, height)-sized array into (width,height,3) to be compatible with your image-generation statements, but that's pretty easy to do:\narr = (arr * np.ones((3,1,1))).transpose(1,2,0)\n\nThen we plug this into your program, and let things be done by array operations:\nimport math, array\nimport numpy as np\nfrom PIL import Image\n\nsize = (800,800)\nwidth, height = size\n\ns1x = width * 1./8\ns1y = height * 1./8\ns2x = width * 7./8\ns2y = height * 7./8\n\nr,g,b = (255,255,255)\n\narray_i,array_j = np.mgrid[0:width,0:height]\n\narr = np.abs(np.hypot(array_i-s1x, array_j-s1y) -\n np.hypot(array_i-s2x, array_j-s2y))\n\narr = (arr * np.ones((3,1,1))).transpose(1,2,0)\n\narr2 = np.zeros((width,height,3),dtype=\"uint8\")\nfor ld in [200,116,100,84,68,52,36,20,8,4,2]:\n print 'now computing image for ld = '+str(ld)\n # Rest as before\n\nAnd the new time is... 8.2 seconds. So you save maybe four whole seconds. On the other hand, that's almost exclusively in the image generation stages now, so maybe you can tighten them up by only generating the images you want.\n", "If you use array operations instead of loops, it is much, much faster. For me, the image generation is now what takes so long time. Instead of your two i,j loops, I have this:\nI,J = np.mgrid[0:width,0:height]\nD1 = np.hypot(I - s1x, J - s1y)\nD2 = np.hypot(I - s2x, J - s2y)\n\narr = np.abs(D1-D2)\n# triplicate into 3 layers\narr = np.array((arr, arr, arr)).transpose(1,2,0)\n# .. continue program\n\nThe basics that you want to remember for the future is: this is not about optimization; using array forms in numpy is just using it like it is supposed to be used. With experience, your future projects should not go the detour over python loops, the array forms should be the natural form.\nWhat we did here was really simple. Instead of math.hypot we found numpy.hypot and used it. Like all such numpy functions, it accepts ndarrays as arguments, and does exactly what we want.\n", "List comprehensions are much faster than loops. For example, instead of\nfor j in xrange(height):\n d1 = hy(i-s1x,j-s1y)\n d2 = hy(i-s2x,j-s2y)\n arr[i][j] = abs(d1-d2)\n\nYou'd write\narr[i] = [abs(hy(i-s1x,j-s1y) - hy(i-s2x,j-s2y)) for j in xrange(height)]\n\nOn the other hand, if you're really trying to \"optimize\", then you might want to reimplement this algorithm in C, and use SWIG or the like to call it from python.\n", "The only changes that come to my mind is to move some operations out of the loop:\nfor i in xrange(width):\n if i%(width/10)==0:\n print i, \n if i%20==0:\n print '.',\n arri = arr[i]\n is1x = i - s1x\n is2x = i - s2x\n for j in xrange(height):\n d1 = hy(is1x,j-s1y)\n d2 = hy(is2x,j-s2y)\n arri[j] = abs(d1-d2)\n\nThe improvement, if any, will probably be minor though.\n" ]
[ 5, 3, 2, 1 ]
[]
[]
[ "for_loop", "numpy", "optimization", "physics", "python" ]
stackoverflow_0002841567_for_loop_numpy_optimization_physics_python.txt
Q: Python library to validate Excel data Is there any existing Python library that can validate data in Excel format? Or what kind of keyword should I use to search such an open source project? Thanks. A: [Disclosure: I'm the author of xlrd] xlrd allows you to extract data from XLS files. XLSX support is in alpha testing; e-mail me if you need it. You get told precisely what is in each cell (Excel cell type and value). It runs on Python 2.1 to 2.7 on any platform. You don't need Windows. You don't need Excel to be installed on your machine. Start with the tutorial found here. A: I`m not sure what are you looking for, but there are three libraries that, in combination, can read and write excel files: xlrd xlwt xlutils They read and save binary excel archives both in windows and linux. There are functions for formatting data and styles. If you want to check if some data column is in a given format you can do it with these libs (basically with xlrd).
Python library to validate Excel data
Is there any existing Python library that can validate data in Excel format? Or what kind of keyword should I use to search such an open source project? Thanks.
[ "[Disclosure: I'm the author of xlrd]\nxlrd allows you to extract data from XLS files. XLSX support is in alpha testing; e-mail me if you need it. You get told precisely what is in each cell (Excel cell type and value). It runs on Python 2.1 to 2.7 on any platform. You don't need Windows. You don't need Excel to be installed on your machine. Start with the tutorial found here.\n", "I`m not sure what are you looking for, but there are three libraries that, in combination, can read and write excel files:\nxlrd\nxlwt\nxlutils\nThey read and save binary excel archives both in windows and linux. There are functions for formatting data and styles.\nIf you want to check if some data column is in a given format you can do it with these libs (basically with xlrd). \n" ]
[ 2, 1 ]
[]
[]
[ "excel", "python", "validation" ]
stackoverflow_0002841451_excel_python_validation.txt
Q: have to invoke (Thread.__init__) in my overridden constructor, but why? i saw this phrase in python 2.6 man: class threading.Thread(group=None, target=None, name=None, args=(), kwargs={}) . . . If the subclass overrides the constructor, it must make sure to invoke the base class constructor (Thread.__init__()) before doing anything else to the thread. i just wanna know why? A: Because Thread.__init__ sets some internal variables which will be undefined if you omit the call. In general, it is a good practice to invoke super constructor in all cases unless there is a strong reason to not do it. A: If you want to know "exactly what, in detail, does the superclass's __init__ do for me", you can always study the sources and see, e.g., ...: self.__target = target self.__name = str(name or _newname()) self.__args = args self.__kwargs = kwargs self.__daemonic = self._set_daemon() self.__ident = None self.__started = Event() self.__stopped = False self.__block = Condition(Lock()) self.__initialized = True the exact set of super-private variables being initialized may of course vary from one revision of python to the next, but obviously there are always going to be some such variables and/or other initialization stuff performed in the base class's __init__. You only need to know all details for your own instruction (you should "respect" abstraction layers you choose to program on, but, if you're a wise and experienced developer, the better you understand what those abstraction layers are wisely hiding, the more you'll respect them;-). In general, the rule should always be for each __init__ to invoke the superclass's, except only very specific cases (such as "transparent mixin classes" -- and if you don't know what they are, you most likely don't need to know). The general rule will always be "that superclass initialization may or may not be important in this specific release, but it will never hurt and will often be necessary and/or helpful"!-)
have to invoke (Thread.__init__) in my overridden constructor, but why?
i saw this phrase in python 2.6 man: class threading.Thread(group=None, target=None, name=None, args=(), kwargs={}) . . . If the subclass overrides the constructor, it must make sure to invoke the base class constructor (Thread.__init__()) before doing anything else to the thread. i just wanna know why?
[ "Because Thread.__init__ sets some internal variables which will be undefined if you omit the call. In general, it is a good practice to invoke super constructor in all cases unless there is a strong reason to not do it.\n", "If you want to know \"exactly what, in detail, does the superclass's __init__ do for me\", you can always study the sources and see, e.g., ...:\n self.__target = target\n self.__name = str(name or _newname())\n self.__args = args\n self.__kwargs = kwargs\n self.__daemonic = self._set_daemon()\n self.__ident = None\n self.__started = Event()\n self.__stopped = False\n self.__block = Condition(Lock())\n self.__initialized = True\n\nthe exact set of super-private variables being initialized may of course vary from one revision of python to the next, but obviously there are always going to be some such variables and/or other initialization stuff performed in the base class's __init__. You only need to know all details for your own instruction (you should \"respect\" abstraction layers you choose to program on, but, if you're a wise and experienced developer, the better you understand what those abstraction layers are wisely hiding, the more you'll respect them;-).\nIn general, the rule should always be for each __init__ to invoke the superclass's, except only very specific cases (such as \"transparent mixin classes\" -- and if you don't know what they are, you most likely don't need to know). The general rule will always be \"that superclass initialization may or may not be important in this specific release, but it will never hurt and will often be necessary and/or helpful\"!-)\n" ]
[ 3, 2 ]
[]
[]
[ "python" ]
stackoverflow_0002841718_python.txt
Q: Best tools to create valid XML files from an Excel file I need to create a script that extracts some data from a complex Excel 2003 file (with multiple sheets and different tables inside a single sheet) and produces different XML files that need to be validated against a given XSD file. My preferred language is Python; to create and validate XML files i would go with lxml. What do you suggest for parsing XLS files? Is xlrd the right tool to use for complex Excel files? Or do i need to convert all the sheets in CSV manually, and read files line by line, splitting and getting data? I accept C#, VB6, VBA suggestions too. A: Xlrd is OK. We use it extensively to import XLS files full of references and formulas with multiple sheets and data presented in custom (not Latin-1) encoding. A: [disclaimer: I'm the author of xlrd] xlrd is quite suited for this kind of job. Get the latest version from PyPI. Get the flavour from the tutorial found here. XLSX support is in alpha test; e-mail me if you need it. The awkwardness and lossiness of the save-as-CSV approach was one of the things that prompted me to write xlrd. A: I am convinced the most simple solution for this task is using Excel VBA together with MSXML parser. Look here for some links how to use the MSXML parser in VBA for reading XML files; you can adopt this easily for writing XML files, I think. A: I cant answer whether xlrd/python is the right tool for the job - as I don't know python well enough. But there are many ways to access the excel data...in the main you have VBA built directly in to Excel. Then you have Ado.net See David Hayden's article here which allows you to access the data via any DotNet language...even IronPython
Best tools to create valid XML files from an Excel file
I need to create a script that extracts some data from a complex Excel 2003 file (with multiple sheets and different tables inside a single sheet) and produces different XML files that need to be validated against a given XSD file. My preferred language is Python; to create and validate XML files i would go with lxml. What do you suggest for parsing XLS files? Is xlrd the right tool to use for complex Excel files? Or do i need to convert all the sheets in CSV manually, and read files line by line, splitting and getting data? I accept C#, VB6, VBA suggestions too.
[ "Xlrd is OK. We use it extensively to import XLS files full of references and formulas with multiple sheets and data presented in custom (not Latin-1) encoding.\n", "[disclaimer: I'm the author of xlrd]\nxlrd is quite suited for this kind of job. Get the latest version from PyPI. Get the flavour from the tutorial found here. XLSX support is in alpha test; e-mail me if you need it. The awkwardness and lossiness of the save-as-CSV approach was one of the things that prompted me to write xlrd. \n", "I am convinced the most simple solution for this task is using Excel VBA together with MSXML parser. Look here for some links how to use the MSXML parser in VBA for reading XML files; you can adopt this easily for writing XML files, I think.\n", "I cant answer whether xlrd/python is the right tool for the job - as I don't know python well enough.\nBut there are many ways to access the excel data...in the main you have VBA built directly in to Excel.\nThen you have Ado.net See David Hayden's article here which allows you to access the data via any DotNet language...even IronPython\n" ]
[ 2, 2, 1, 0 ]
[]
[]
[ "c#", "excel", "python", "vb6", "xml" ]
stackoverflow_0002825006_c#_excel_python_vb6_xml.txt
Q: Excel Regex, or export to Python? ; "Vlookup" in Python? We have an Excel file with a worksheet containing people records. 1. Phone Number Sanitation One of the fields is a phone number field, which contains phone numbers in the format e.g.: +XX(Y)ZZZZ-ZZZZ (where X, Y and Z are integers). There are also some records which have less digits, e.g.: +XX(Y)ZZZ-ZZZZ And others with really screwed up formats: +XX(Y)ZZZZ-ZZZZ / ZZZZ or: ZZZZZZZZ We need to sanitise these all into the format: 0YZZZZZZZZ (or OYZZZZZZ with those with less digits). 2. Fill in Supervisor Details Each person also has a supervisor, given as an numeric ID. We need to do a lookup to get the name and email address of that supervisor, and add it to the line. This lookup will be firstly on the same worksheet (i.e. searching itself), and it can then fallback to another workbook with more people. 3. Approach? For the first issue, I was thinking of using regex in Excel/VBA somehow, to do the parsing. My Excel-fu isn't the best, but I suppose I can learn...lol. Any particular points on this one? However, would I be better off exporting the XLS to a CSV (e.g. using xlrd), then using Python to fix up the phone numbers? For the second approach, I was thinking of just using vlookups in Excel, to pull in the data, and somehow, having it fall through, first on searching itself, then on the external workbook, then just putting in error text. Not sure how to do that last part. However, if I do happen to choose to export to CSV and do it in Python, what's an efficient way of doing the vlookup? (Should I convert to a dict, or just iterate? Or is there a better, or more idiomatic way?) Cheers, Victor A: In general, avoid Excel formulas; use xlrd to extract the data that you need, then forget it came from Excel and manipulate the data using Python. E.g. addressing the xlrd / vlookup question: the best way would be to create a dictionary ONCE from the relevant parts of the 2 columns containing the keys and values. Using xlrd to export to CSV and then reading it back is a waste of time AND loses valuable information (like what is the actual type of the data in the Excel cell). If your data was in a database would you export it to CSV and read it back?? A: If you go the VBA route, it may pay to take a look at Tushar Mehta's documentation. If you go the Python route, you could try parsing to CSV or, alternatively, just manipulating things in memory and writing via XLWT (which would be my preferred technique). You may also consider just modifying the Excel data directly using COM calls, based on something like this. Finally, if you're committed to doing this outside of Excel, you might take a look at Jython and Apache POI. Not the most lightweight solution, but POI is the most feature-complete library I know of that does not depend on running on Windows. As other's have observed in comments, it's hard to be concrete with such a broad question. Hopefully something here gets you started...
Excel Regex, or export to Python? ; "Vlookup" in Python?
We have an Excel file with a worksheet containing people records. 1. Phone Number Sanitation One of the fields is a phone number field, which contains phone numbers in the format e.g.: +XX(Y)ZZZZ-ZZZZ (where X, Y and Z are integers). There are also some records which have less digits, e.g.: +XX(Y)ZZZ-ZZZZ And others with really screwed up formats: +XX(Y)ZZZZ-ZZZZ / ZZZZ or: ZZZZZZZZ We need to sanitise these all into the format: 0YZZZZZZZZ (or OYZZZZZZ with those with less digits). 2. Fill in Supervisor Details Each person also has a supervisor, given as an numeric ID. We need to do a lookup to get the name and email address of that supervisor, and add it to the line. This lookup will be firstly on the same worksheet (i.e. searching itself), and it can then fallback to another workbook with more people. 3. Approach? For the first issue, I was thinking of using regex in Excel/VBA somehow, to do the parsing. My Excel-fu isn't the best, but I suppose I can learn...lol. Any particular points on this one? However, would I be better off exporting the XLS to a CSV (e.g. using xlrd), then using Python to fix up the phone numbers? For the second approach, I was thinking of just using vlookups in Excel, to pull in the data, and somehow, having it fall through, first on searching itself, then on the external workbook, then just putting in error text. Not sure how to do that last part. However, if I do happen to choose to export to CSV and do it in Python, what's an efficient way of doing the vlookup? (Should I convert to a dict, or just iterate? Or is there a better, or more idiomatic way?) Cheers, Victor
[ "In general, avoid Excel formulas; use xlrd to extract the data that you need, then forget it came from Excel and manipulate the data using Python. E.g. addressing the xlrd / vlookup question: the best way would be to create a dictionary ONCE from the relevant parts of the 2 columns containing the keys and values. \nUsing xlrd to export to CSV and then reading it back is a waste of time AND loses valuable information (like what is the actual type of the data in the Excel cell). If your data was in a database would you export it to CSV and read it back??\n", "If you go the VBA route, it may pay to take a look at Tushar Mehta's documentation. If you go the Python route, you could try parsing to CSV or, alternatively, just manipulating things in memory and writing via XLWT (which would be my preferred technique). You may also consider just modifying the Excel data directly using COM calls, based on something like this. Finally, if you're committed to doing this outside of Excel, you might take a look at Jython and Apache POI. Not the most lightweight solution, but POI is the most feature-complete library I know of that does not depend on running on Windows.\nAs other's have observed in comments, it's hard to be concrete with such a broad question. Hopefully something here gets you started...\n" ]
[ 2, 0 ]
[]
[]
[ "excel", "python", "regex", "vba" ]
stackoverflow_0002770048_excel_python_regex_vba.txt
Q: Joining links together in a dictionary I have a dictionary links which holds a tuple mapped to a number. How can I join the second URL in the second tuple together with the urljoin() function? What I'm trying to do is get complete links so I can run a recursive function search() which takes a complete URL as an arguement, finds all the links in each URL and stores the number of links mapped to the links in a database. So far, I have: >>> links {('href', 'http://reed.cs.depaul.edu/lperkovic/csc242/test2.html'): 1, ('href', 'test3.html'): 1} I'm trying to turn this into "http://reed.cs.depaul.edu/lperkovic/csc242/test3.html". A: 1) There is no concept of "first" or "second" when considering the keys in a python dictionary; the keys have no defined order. 2) It's very unclear what you're actually trying to do. You'll get better help if you work harder on describing the problem you're trying to solve. On the other hand, if this is a homework assignment, then you shouldn't be looking for this kind of help here. You should instead be asking your TA. A: I think you should reconsider how you store the base URL and the URL fragments. Storing them in a dict like you're doing now makes things quite a lot harder than it has to be. One suggestion would be to generate the full URLs before you store it in a dict, drop the 'href' part from the tuples (and the tuples), and simply use the URLs themselves as keys. Something like this: from urlparse import urljoin links = {} urlbase = 'http://reed.cs.depaul.edu/lperkovic/csc242/test2.html' links[urljoin(urlbase, 'test3.html')] = 1 This would produce a dict looking like this: >>> links {'http://reed.cs.depaul.edu/lperkovic/csc242/test3.html': 1}
Joining links together in a dictionary
I have a dictionary links which holds a tuple mapped to a number. How can I join the second URL in the second tuple together with the urljoin() function? What I'm trying to do is get complete links so I can run a recursive function search() which takes a complete URL as an arguement, finds all the links in each URL and stores the number of links mapped to the links in a database. So far, I have: >>> links {('href', 'http://reed.cs.depaul.edu/lperkovic/csc242/test2.html'): 1, ('href', 'test3.html'): 1} I'm trying to turn this into "http://reed.cs.depaul.edu/lperkovic/csc242/test3.html".
[ "1) There is no concept of \"first\" or \"second\" when considering the keys in a python dictionary; the keys have no defined order.\n2) It's very unclear what you're actually trying to do. You'll get better help if you work harder on describing the problem you're trying to solve. On the other hand, if this is a homework assignment, then you shouldn't be looking for this kind of help here. You should instead be asking your TA.\n", "I think you should reconsider how you store the base URL and the URL fragments. Storing them in a dict like you're doing now makes things quite a lot harder than it has to be.\nOne suggestion would be to generate the full URLs before you store it in a dict, drop the 'href' part from the tuples (and the tuples), and simply use the URLs themselves as keys. Something like this:\nfrom urlparse import urljoin\nlinks = {}\nurlbase = 'http://reed.cs.depaul.edu/lperkovic/csc242/test2.html'\nlinks[urljoin(urlbase, 'test3.html')] = 1\n\nThis would produce a dict looking like this:\n>>> links\n{'http://reed.cs.depaul.edu/lperkovic/csc242/test3.html': 1}\n\n" ]
[ 0, 0 ]
[]
[]
[ "database", "python" ]
stackoverflow_0002841549_database_python.txt
Q: Compound dictionary keys I have a particular case where using compound dictionary keys would make a task easier. I have a working solution, but feel it is inelegant. How would you do it? context = { 'database': { 'port': 9990, 'users': ['number2', 'dr_evil'] }, 'admins': ['number2@virtucon.com', 'dr_evil@virtucon.com'], 'domain.name': 'virtucon.com' } def getitem(key, context): if hasattr(key, 'upper') and key in context: return context[key] keys = key if hasattr(key, 'pop') else key.split('.') k = keys.pop(0) if keys: try: return getitem(keys, context[k]) except KeyError, e: raise KeyError(key) if hasattr(context, 'count'): k = int(k) return context[k] if __name__ == "__main__": print getitem('database', context) print getitem('database.port', context) print getitem('database.users.0', context) print getitem('admins', context) print getitem('domain.name', context) try: getitem('database.nosuchkey', context) except KeyError, e: print "Error:", e Thanks. A: >>> def getitem(context, key): try: return context[key] except KeyError: pass cur, _, rest = key.partition('.') rest = int(rest) if rest.isdigit() else rest return getitem(context[cur], rest) >>> getitem(context, 'admins.0') 'number2@virtucon.com' >>> getitem(context, 'database.users.0') 'number2' >>> getitem(context, 'database.users.1') 'dr_evil' I've changed the order of the arguments, because that's how most Python's functions work, cf. getattr, operator.getitem, etc. A: The accepted solution (as well as my first attempt) failed due to the ambiguity inherent in the specs: '.' may be "just a separator" or a part of the actual key string. Consider, for example, that key may be 'a.b.c.d.e.f' and the actual key to use at the current level is 'a.b.c.d' with 'e.f' left over for the next-most-indented level. Also, the spec is ambiguous in another sense: if more than one dot-joined prefix of 'key' is present, which one to use? Assume the intention is to try every such feasible prefix: this would possibly produce multiple solutions but we can arbitrarily return the first solution found in this case. def getitem(key, context): stk = [(key.split('.'), context)] while stk: kl, ctx = stk.pop() if not kl: return ctx if kl[0].isdigit(): ik = int(kl[0]) try: stk.append((kl[1:], ctx[ik])) except LookupError: pass for i in range(1, len(kl) + 1): k = '.'.join(kl[:i]) if k in ctx: stk.append((kl[i:], ctx[k])) raise KeyError(key) I was originally trying to avoid all try/excepts (as well as recursion and introspection via hasattr, isinstance, etc), but one snuck back in: it's hard to check if an integer is an acceptable index/key into what might be either a dict or a list, without either some introspection to distinguish the cases, or (and it looks simpler here) a try/except, so I went fir te latter, simplicity being always near the top of my concerns. Anyway... I believe variants on this approach (where all the "possible continuation-context pairs" that might still be feasible at any point are kept around) are the only working way to deal with the ambiguities I've explained above (of course, one might choose to collect all possible solutions, arbitrarily pick one of them according to whatever heuristic criterion is desire, or maybe raise if the ambiguity is biting so there are multiple solutions, etc, etc, but these are minor variants of this general idea). A: I'm leaving my original solution for posterity: CONTEXT = { "database": { "port": 9990, "users": ["number2", "dr_evil"]}, "admins": ["number2@virtucon.com", "dr_evil@virtucon.com"], "domain": {"name": "virtucon.com"}} def getitem(context, *keys): node = context for key in keys: node = node[key] return node if __name__ == "__main__": print getitem(CONTEXT, "database") print getitem(CONTEXT, "database", "port") print getitem(CONTEXT, "database", "users", 0) print getitem(CONTEXT, "admins") print getitem(CONTEXT, "domain", "name") try: getitem(CONTEXT, "database", "nosuchkey") except KeyError, e: print "Error:", e But here's a version that implements an approach similar to the getitem interface suggested by doublep. I am specifically not handling dotted keys, but rather forcing the keys into separate nested structures because that seems cleaner to me: CONTEXT = { "database": { "port": 9990, "users": ["number2", "dr_evil"]}, "admins": ["number2@virtucon.com", "dr_evil@virtucon.com"], "domain": {"name": "virtucon.com"}} if __name__ == "__main__": print CONTEXT["database"] print CONTEXT["database"]["port"] print CONTEXT["database"]["users"][0] print CONTEXT["admins"] print CONTEXT["domain"]["name"] try: CONTEXT["database"]["nosuchkey"] except KeyError, e: print "Error:", e You might notice that what I've really done here is eliminate all ceremony regarding accessing the data structure. The output of this script is the same as the original except that it does not contain a dotted key. This seems like a more natural approach to me but if you really wanted to be able to handle dotted keys, you could do something like this I suppose: CONTEXT = { "database": { "port": 9990, "users": ["number2", "dr_evil"]}, "admins": ["number2@virtucon.com", "dr_evil@virtucon.com"], "domain": {"name": "virtucon.com"}} def getitem(context, dotted_key): keys = dotted_key.split(".") value = context for key in keys: try: value = value[key] except TypeError: value = value[int(key)] return value if __name__ == "__main__": print getitem(CONTEXT, "database") print getitem(CONTEXT, "database.port") print getitem(CONTEXT, "database.users.0") print getitem(CONTEXT, "admins") print getitem(CONTEXT, "domain.name") try: CONTEXT["database.nosuchkey"] except KeyError, e: print "Error:", e I'm not sure what the advantage of this type of approach would be though. A: The following code works. It checks for the special case of a single key having a period in it. Then, it splits the key apart. For each subkey, it tries to fetch the value from a list-like context, then it tries from a dictionary-type context, then it gives up. This code also shows how to use unittest/nose, which is highly recommended. Test with "nosetests mysource.py". Lastly, consder using Python's built-in ConfigParser class, which is really useful for this type of configuration task: http://docs.python.org/library/configparser.html #!/usr/bin/env python from nose.tools import eq_, raises context = { 'database': { 'port': 9990, 'users': ['number2', 'dr_evil'] }, 'admins': ['number2@virtucon.com', 'dr_evil@virtucon.com'], 'domain.name': 'virtucon.com' } def getitem(key, context): if isinstance(context, dict) and context.has_key(key): return context[key] for key in key.split('.'): try: context = context[int(key)] continue except ValueError: pass if isinstance(context, dict) and context.has_key(key): context = context[key] continue raise KeyError, key return context def test_getitem(): eq_( getitem('database', context), {'port': 9990, 'users': ['number2', 'dr_evil']} ) eq_( getitem('database.port', context), 9990 ) eq_( getitem('database.users.0', context), 'number2' ) eq_( getitem('admins', context), ['number2@virtucon.com', 'dr_evil@virtucon.com'] ) eq_( getitem('domain.name', context), 'virtucon.com' ) @raises(KeyError) def test_getitem_error(): getitem('database.nosuchkey', context) A: As the key to getitem must be a string (or a list which is passed in the recursive call) I've come up with the following: def getitem(key, context, first=True): if not isinstance(key, basestring) and not isinstance(key, list) and first: raise TypeError("Compound key must be a string.") if isinstance(key, basestring): if key in context: return context[key] else: keys = key.split('.') else: keys = key k = keys.pop(0) if key: try: return getitem(keys, context[k], False) except KeyError, e: raise KeyError(key) # is it a sequence type if hasattr(context, '__getitem__') and not hasattr(context, 'keys'): # then the index must be an integer k = int(k) return context[k] I am on the fence as to whether this is an improvement.
Compound dictionary keys
I have a particular case where using compound dictionary keys would make a task easier. I have a working solution, but feel it is inelegant. How would you do it? context = { 'database': { 'port': 9990, 'users': ['number2', 'dr_evil'] }, 'admins': ['number2@virtucon.com', 'dr_evil@virtucon.com'], 'domain.name': 'virtucon.com' } def getitem(key, context): if hasattr(key, 'upper') and key in context: return context[key] keys = key if hasattr(key, 'pop') else key.split('.') k = keys.pop(0) if keys: try: return getitem(keys, context[k]) except KeyError, e: raise KeyError(key) if hasattr(context, 'count'): k = int(k) return context[k] if __name__ == "__main__": print getitem('database', context) print getitem('database.port', context) print getitem('database.users.0', context) print getitem('admins', context) print getitem('domain.name', context) try: getitem('database.nosuchkey', context) except KeyError, e: print "Error:", e Thanks.
[ ">>> def getitem(context, key):\n try:\n return context[key]\n except KeyError:\n pass\n cur, _, rest = key.partition('.')\n rest = int(rest) if rest.isdigit() else rest\n return getitem(context[cur], rest)\n\n\n>>> getitem(context, 'admins.0')\n'number2@virtucon.com'\n>>> getitem(context, 'database.users.0')\n'number2'\n>>> getitem(context, 'database.users.1')\n'dr_evil'\n\nI've changed the order of the arguments, because that's how most Python's functions work, cf. getattr, operator.getitem, etc.\n", "The accepted solution (as well as my first attempt) failed due to the ambiguity inherent in the specs: '.' may be \"just a separator\" or a part of the actual key string. Consider, for example, that key may be 'a.b.c.d.e.f' and the actual key to use at the current level is 'a.b.c.d' with 'e.f' left over for the next-most-indented level. Also, the spec is ambiguous in another sense: if more than one dot-joined prefix of 'key' is present, which one to use?\nAssume the intention is to try every such feasible prefix: this would possibly produce multiple solutions but we can arbitrarily return the first solution found in this case.\ndef getitem(key, context):\n stk = [(key.split('.'), context)]\n while stk:\n kl, ctx = stk.pop()\n if not kl: return ctx\n if kl[0].isdigit():\n ik = int(kl[0])\n try: stk.append((kl[1:], ctx[ik]))\n except LookupError: pass\n for i in range(1, len(kl) + 1):\n k = '.'.join(kl[:i])\n if k in ctx: stk.append((kl[i:], ctx[k]))\n raise KeyError(key)\n\nI was originally trying to avoid all try/excepts (as well as recursion and introspection via hasattr, isinstance, etc), but one snuck back in: it's hard to check if an integer is an acceptable index/key into what might be either a dict or a list, without either some introspection to distinguish the cases, or (and it looks simpler here) a try/except, so I went fir te latter, simplicity being always near the top of my concerns. Anyway...\nI believe variants on this approach (where all the \"possible continuation-context pairs\" that might still be feasible at any point are kept around) are the only working way to deal with the ambiguities I've explained above (of course, one might choose to collect all possible solutions, arbitrarily pick one of them according to whatever heuristic criterion is desire, or maybe raise if the ambiguity is biting so there are multiple solutions, etc, etc, but these are minor variants of this general idea).\n", "I'm leaving my original solution for posterity:\nCONTEXT = {\n \"database\": {\n \"port\": 9990,\n \"users\": [\"number2\", \"dr_evil\"]},\n \"admins\": [\"number2@virtucon.com\", \"dr_evil@virtucon.com\"],\n \"domain\": {\"name\": \"virtucon.com\"}}\n\n\ndef getitem(context, *keys):\n node = context\n for key in keys:\n node = node[key]\n return node\n\n\nif __name__ == \"__main__\":\n print getitem(CONTEXT, \"database\")\n print getitem(CONTEXT, \"database\", \"port\")\n print getitem(CONTEXT, \"database\", \"users\", 0)\n print getitem(CONTEXT, \"admins\")\n print getitem(CONTEXT, \"domain\", \"name\")\n try:\n getitem(CONTEXT, \"database\", \"nosuchkey\")\n except KeyError, e:\n print \"Error:\", e\n\nBut here's a version that implements an approach similar to the getitem interface suggested by doublep. I am specifically not handling dotted keys, but rather forcing the keys into separate nested structures because that seems cleaner to me:\nCONTEXT = {\n \"database\": {\n \"port\": 9990,\n \"users\": [\"number2\", \"dr_evil\"]},\n \"admins\": [\"number2@virtucon.com\", \"dr_evil@virtucon.com\"],\n \"domain\": {\"name\": \"virtucon.com\"}}\n\n\nif __name__ == \"__main__\":\n print CONTEXT[\"database\"]\n print CONTEXT[\"database\"][\"port\"]\n print CONTEXT[\"database\"][\"users\"][0]\n print CONTEXT[\"admins\"]\n print CONTEXT[\"domain\"][\"name\"]\n try:\n CONTEXT[\"database\"][\"nosuchkey\"]\n except KeyError, e:\n print \"Error:\", e\n\nYou might notice that what I've really done here is eliminate all ceremony regarding accessing the data structure. The output of this script is the same as the original except that it does not contain a dotted key. This seems like a more natural approach to me but if you really wanted to be able to handle dotted keys, you could do something like this I suppose:\nCONTEXT = {\n \"database\": {\n \"port\": 9990,\n \"users\": [\"number2\", \"dr_evil\"]},\n \"admins\": [\"number2@virtucon.com\", \"dr_evil@virtucon.com\"],\n \"domain\": {\"name\": \"virtucon.com\"}}\n\n\ndef getitem(context, dotted_key):\n keys = dotted_key.split(\".\")\n value = context\n for key in keys:\n try:\n value = value[key]\n except TypeError:\n value = value[int(key)]\n return value\n\n\nif __name__ == \"__main__\":\n print getitem(CONTEXT, \"database\")\n print getitem(CONTEXT, \"database.port\")\n print getitem(CONTEXT, \"database.users.0\")\n print getitem(CONTEXT, \"admins\")\n print getitem(CONTEXT, \"domain.name\")\n try:\n CONTEXT[\"database.nosuchkey\"]\n except KeyError, e:\n print \"Error:\", e\n\nI'm not sure what the advantage of this type of approach would be though.\n", "The following code works. It checks for the special case of a single key having a period in it. Then, it splits the key apart. For each subkey, it tries to fetch the value from a list-like context, then it tries from a dictionary-type context, then it gives up.\nThis code also shows how to use unittest/nose, which is highly recommended. Test with \"nosetests mysource.py\".\nLastly, consder using Python's built-in ConfigParser class, which is really useful for this type of configuration task: http://docs.python.org/library/configparser.html\n#!/usr/bin/env python\n\nfrom nose.tools import eq_, raises\n\ncontext = {\n 'database': {\n 'port': 9990,\n 'users': ['number2', 'dr_evil']\n },\n 'admins': ['number2@virtucon.com', 'dr_evil@virtucon.com'],\n 'domain.name': 'virtucon.com'\n}\n\ndef getitem(key, context):\n if isinstance(context, dict) and context.has_key(key):\n return context[key]\n for key in key.split('.'):\n try:\n context = context[int(key)]\n continue\n except ValueError:\n pass\n if isinstance(context, dict) and context.has_key(key):\n context = context[key]\n continue\n raise KeyError, key\n return context\n\ndef test_getitem():\n eq_( getitem('database', context), {'port': 9990, 'users': ['number2', 'dr_evil']} )\n eq_( getitem('database.port', context), 9990 )\n eq_( getitem('database.users.0', context), 'number2' )\n eq_( getitem('admins', context), ['number2@virtucon.com', 'dr_evil@virtucon.com'] )\n eq_( getitem('domain.name', context), 'virtucon.com' )\n\n@raises(KeyError)\ndef test_getitem_error():\n getitem('database.nosuchkey', context)\n\n", "As the key to getitem must be a string (or a list which is passed in the recursive call) I've come up with the following: \ndef getitem(key, context, first=True):\n if not isinstance(key, basestring) and not isinstance(key, list) and first:\n raise TypeError(\"Compound key must be a string.\")\n\n if isinstance(key, basestring):\n if key in context:\n return context[key]\n else:\n keys = key.split('.')\n else:\n keys = key\n\n k = keys.pop(0)\n if key:\n try:\n return getitem(keys, context[k], False)\n except KeyError, e:\n raise KeyError(key)\n # is it a sequence type\n if hasattr(context, '__getitem__') and not hasattr(context, 'keys'):\n # then the index must be an integer\n k = int(k)\n return context[k]\n\nI am on the fence as to whether this is an improvement.\n" ]
[ 2, 2, 0, 0, 0 ]
[]
[]
[ "attributes", "dictionary", "python" ]
stackoverflow_0002841971_attributes_dictionary_python.txt
Q: How to enable a method in template of google-app-engine the method is: def printa(x): return x the response is: self.response.out.write(template.render(path, {'printa':printa})) the html is: {{ printa 'sss'}} I want to show 'sss' in my page , so how to do this , updated I create a templatetags folder, and 2 py file: templatetags |--------__init__.py |--------tags.py in tags.py is: #from django import template from google.appengine.ext.webapp import template register = template.Library() def printa(): return 'ssss' register.simple_tag(printa) the html is: {% load tags%} {% printa %} but it show error, and the error is: TemplateSyntaxError: 'tags' is not a valid tag library: Could not load template library from django.templatetags.tags, No module named tags why? what's wrong? answer is: tags.py: from google.appengine.ext import webapp register = webapp.template.create_template_register() @register.filter def printa(value,y): return 'url:%s' % y @register.tag def printb(x,y): return str(x.__dict__) +'dddddddddddddddddddddddddddddddd'+ str(y.__dict__) #return x #register.tag('printb',do_pagednav) and then in html (a is a variable i send to the template): {{a|printa:"dwqdq"}} {% printb %} woring: don't use load: {% load sometags %} A: Using the default webapp template system (which is actually Django 0.96), you can't do this. You're expected to put the program logic in the program files, not in your templates, so you can't pass arguments to your variables. You don't say what you're actually trying to do, though; I assume you don't literally want to print something, since you can just put that something in the template without a function and it prints. For whatever you're actually trying to do, registering a custom filter might be what you're looking for.
How to enable a method in template of google-app-engine
the method is: def printa(x): return x the response is: self.response.out.write(template.render(path, {'printa':printa})) the html is: {{ printa 'sss'}} I want to show 'sss' in my page , so how to do this , updated I create a templatetags folder, and 2 py file: templatetags |--------__init__.py |--------tags.py in tags.py is: #from django import template from google.appengine.ext.webapp import template register = template.Library() def printa(): return 'ssss' register.simple_tag(printa) the html is: {% load tags%} {% printa %} but it show error, and the error is: TemplateSyntaxError: 'tags' is not a valid tag library: Could not load template library from django.templatetags.tags, No module named tags why? what's wrong? answer is: tags.py: from google.appengine.ext import webapp register = webapp.template.create_template_register() @register.filter def printa(value,y): return 'url:%s' % y @register.tag def printb(x,y): return str(x.__dict__) +'dddddddddddddddddddddddddddddddd'+ str(y.__dict__) #return x #register.tag('printb',do_pagednav) and then in html (a is a variable i send to the template): {{a|printa:"dwqdq"}} {% printb %} woring: don't use load: {% load sometags %}
[ "Using the default webapp template system (which is actually Django 0.96), you can't do this. You're expected to put the program logic in the program files, not in your templates, so you can't pass arguments to your variables.\nYou don't say what you're actually trying to do, though; I assume you don't literally want to print something, since you can just put that something in the template without a function and it prints. For whatever you're actually trying to do, registering a custom filter might be what you're looking for.\n" ]
[ 1 ]
[]
[]
[ "google_app_engine", "methods", "python", "templates" ]
stackoverflow_0002842324_google_app_engine_methods_python_templates.txt
Q: How do you set the image attributes using PIL? I'm using PIL. I tried using : img.info = {'Buyer':'Text','Copyright':'Text2'} This is not working. Is there an alternate way to do it? A: I think you are looking for EXIF support which PIL is notoriously lacking. Other people have made their own modules to support it: here is one that claims to write EXIF data properly which I found in a recent survey article of the topic of EXIF and Python. A: pyexiv2 library @ http://tilloy.net/dev/pyexiv2
How do you set the image attributes using PIL?
I'm using PIL. I tried using : img.info = {'Buyer':'Text','Copyright':'Text2'} This is not working. Is there an alternate way to do it?
[ "I think you are looking for EXIF support which PIL is notoriously lacking. \nOther people have made their own modules to support it: here is one that claims to write EXIF data properly which I found in a recent survey article of the topic of EXIF and Python.\n", "pyexiv2 library @ http://tilloy.net/dev/pyexiv2\n" ]
[ 3, 2 ]
[]
[]
[ "python", "python_imaging_library" ]
stackoverflow_0002831497_python_python_imaging_library.txt
Q: Update Params in Python During Infinite Loop I was hoping to get some help on a question. I have an infinite loop that I need run and I need to update a set of variables (x in this case) at random times from the command-line. Is there any way to do this? For example: x = 0 while True: x = x + 1 if x < 30: do something and I need to update x's value from the command-line periodically A: To me it sounds like a better way to implement this would be to use a thread instead of an infinite loop and use the notify() method to instruct when to update with data from command line Here is a good reference to get you started: http://docs.python.org/library/threading.html A: This is rather hackish, but kinda cute: import code import signal import time def signal_handler(signal, frame): code.interact(local=globals()) signal.signal(signal.SIGINT, signal_handler) x=0 while True: x = x + 1 time.sleep(0.01) if x < 30: print(x,'do something') When you press Ctrl-C, you are dropped to the python interpreter. There you can type Python statements like x=10 Pressing Ctrl-D resumes execution. A: Once the program is running and inside that loop, theres no way externally to modify the parameters passed into that program. What you will do is have this program running, and run a seperate program to send a message into this one while its running to modify state. Inside your infinite loop you will need to have code to look for and receive that message and take effect. There are lots of methods to perform this communications. The most basic version would be to periodically poll a file every so many iterations in your infinite loop. If the file contents have changed, read them in and thats the new value of X. Then to change the variable from the command line you just run a command like echo "NewValue" > file.txt Files would work here, though something like pipes would be more appropriate. A: My Solution Using Threads and basic locking mechanism. from threading import Thread,Lock lock = Lock() def read(): global x x = 0 while True: lock.acquire() try: x = x + 1 finally: lock.release() if x < 30: #do something def update(): global x while True: cmd_input = int(raw_input()) lock.acquire() try: x = cmd_input finally: lock.release() if __name__=='__main__': update_t = Thread(target=update,args=()) read_t = Thread(target=read,args=()) update_t.start() read_t.start()
Update Params in Python During Infinite Loop
I was hoping to get some help on a question. I have an infinite loop that I need run and I need to update a set of variables (x in this case) at random times from the command-line. Is there any way to do this? For example: x = 0 while True: x = x + 1 if x < 30: do something and I need to update x's value from the command-line periodically
[ "To me it sounds like a better way to implement this would be to use a thread instead of an infinite loop and use the \nnotify()\n\nmethod to instruct when to update with data from command line\nHere is a good reference to get you started:\nhttp://docs.python.org/library/threading.html\n", "This is rather hackish, but kinda cute:\nimport code\nimport signal\nimport time\ndef signal_handler(signal, frame):\n code.interact(local=globals())\nsignal.signal(signal.SIGINT, signal_handler)\n\nx=0\nwhile True:\n x = x + 1\n time.sleep(0.01)\n if x < 30:\n print(x,'do something')\n\nWhen you press Ctrl-C, you are dropped to the python interpreter.\nThere you can type Python statements like\nx=10\n\nPressing Ctrl-D resumes execution.\n", "Once the program is running and inside that loop, theres no way externally to modify the parameters passed into that program. What you will do is have this program running, and run a seperate program to send a message into this one while its running to modify state. Inside your infinite loop you will need to have code to look for and receive that message and take effect. There are lots of methods to perform this communications. The most basic version would be to periodically poll a file every so many iterations in your infinite loop. If the file contents have changed, read them in and thats the new value of X. Then to change the variable from the command line you just run a command like\n echo \"NewValue\" > file.txt\n\nFiles would work here, though something like pipes would be more appropriate.\n", "My Solution Using Threads and basic locking mechanism.\nfrom threading import Thread,Lock\n\nlock = Lock()\n\ndef read():\n global x\n x = 0\n while True:\n lock.acquire()\n try:\n x = x + 1 \n finally:\n lock.release()\n if x < 30:\n #do something\n\n\ndef update():\n global x\n while True:\n cmd_input = int(raw_input())\n lock.acquire() \n try:\n x = cmd_input\n finally:\n lock.release()\n\nif __name__=='__main__':\n update_t = Thread(target=update,args=())\n read_t = Thread(target=read,args=())\n update_t.start()\n read_t.start()\n\n" ]
[ 2, 1, 0, 0 ]
[]
[]
[ "loops", "python" ]
stackoverflow_0002840745_loops_python.txt
Q: Using netbeans as IDE for Python I am about to embark on learning Python (largely for the purposes of using it as scripting glue between my applications). I use Netbeans (6.8) on Linux for both my C++ and PHP development work. Ideally, I would like to use the same IDE for Python - and there is a Python plugin for Netbeans (admittedly, its still in Beta). Does anyone have any experience using Python with Netbeans? Shall I use Netbeans (for the reasons stated above - i.e. already familiar environment), or is there a [GOOD] reason why I should use a different IDE? A: Although I've not been using it for long, I was in the same situation as yourself and just decided to bite the bullet. I haven't had any issues with it so far and found he most important thing to be that you are using an environment that you are both familiar and comfortable with. Any quirks you find along the way are probably more than made up for by the shallow learning curve given by not having to get used to an entirely new IDE. That said however, if you are only just picking the language up I can't recommend the "official" command interface, IDLE, enough as it just let's you get into the guts of the language giving instant feedback etc. Additionally, the following SO question has a comprehensive list of Python IDE's if you find that the Python plugin for Netbeans just doesn't work for you.
Using netbeans as IDE for Python
I am about to embark on learning Python (largely for the purposes of using it as scripting glue between my applications). I use Netbeans (6.8) on Linux for both my C++ and PHP development work. Ideally, I would like to use the same IDE for Python - and there is a Python plugin for Netbeans (admittedly, its still in Beta). Does anyone have any experience using Python with Netbeans? Shall I use Netbeans (for the reasons stated above - i.e. already familiar environment), or is there a [GOOD] reason why I should use a different IDE?
[ "Although I've not been using it for long, I was in the same situation as yourself and just decided to bite the bullet. I haven't had any issues with it so far and found he most important thing to be that you are using an environment that you are both familiar and comfortable with. Any quirks you find along the way are probably more than made up for by the shallow learning curve given by not having to get used to an entirely new IDE. \nThat said however, if you are only just picking the language up I can't recommend the \"official\" command interface, IDLE, enough as it just let's you get into the guts of the language giving instant feedback etc. \nAdditionally, the following SO question has a comprehensive list of Python IDE's if you find that the Python plugin for Netbeans just doesn't work for you.\n" ]
[ 0 ]
[]
[]
[ "netbeans", "netbeans6.8", "python" ]
stackoverflow_0002842867_netbeans_netbeans6.8_python.txt
Q: Django: How do I get logging working? I've added the following to my settings.py file: import logging ... logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)s %(message)s', filename=os.path.join(rootdir, 'django.log'), filemode='a+') And in views.py, I've added: import logging log = logging.getLogger(__name__) ... log.info("testing 123!") Unfortunately, no log file is being created. Any ideas what I am doing wrong? And also is their a better method I should be using for logging? I am doing this on Webfaction. A: Python logging for Django is fine on somewhere like Webfaction. If you were on a cloud-based provider (eg Amazon EC2) where you had a number of servers, it might be worth looking at either logging to key-value DB or using Python logging over the network. Your logging setup code in settings.py looks fine, but I'd check that you can write to rootdir -- your syslog might show errors, but it's more likely that Django would be throwing a 500 if it couldn't log properly. Which leads me to note that the only major difference in my logging (also on WebFaction) is that I do: import logging logging.info("Something here") instead of log.info
Django: How do I get logging working?
I've added the following to my settings.py file: import logging ... logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)s %(message)s', filename=os.path.join(rootdir, 'django.log'), filemode='a+') And in views.py, I've added: import logging log = logging.getLogger(__name__) ... log.info("testing 123!") Unfortunately, no log file is being created. Any ideas what I am doing wrong? And also is their a better method I should be using for logging? I am doing this on Webfaction.
[ "Python logging for Django is fine on somewhere like Webfaction. If you were on a cloud-based provider (eg Amazon EC2) where you had a number of servers, it might be worth looking at either logging to key-value DB or using Python logging over the network.\nYour logging setup code in settings.py looks fine, but I'd check that you can write to rootdir -- your syslog might show errors, but it's more likely that Django would be throwing a 500 if it couldn't log properly.\nWhich leads me to note that the only major difference in my logging (also on WebFaction) is that I do:\nimport logging\nlogging.info(\"Something here\") \n\ninstead of log.info \n" ]
[ 2 ]
[]
[]
[ "django", "logging", "python" ]
stackoverflow_0002843092_django_logging_python.txt
Q: How can I write to the previous line in a log file using Python's Logging module? long-time lurker here, finally emerging from the woodwork. Essentially, what I'm trying to do is have my logger write data like this to the logfile: Connecting to database . . . Done. I'd like the 'Connecting to database . . . ' to be written when the function is called, and the 'Done' written after the function has successfully executed. I'm using Python 2.6 and the logging module. Also, I'd really like to avoid using decorators for this. Any help would be most appreciated! A: Writing to a log is, and must be, an atomic action -- this is crucial, and a key feature of any logging package (including the one in Python's standard library) that distinguishes logging from the simple appending of information to files (where bits of things being written by different processes and threads might well "interleave" -- one of them writing some part of a line but not the line-end, just as you desire, and then maybe another one interposing something right afterwards, before the first task writes what it thinks will be the last part of the line but actually ends up on another line... utter confusion often results;-). It's not inevitable that the atomic unit be "a line" (logs can be recorded elsewhere than to a text file, of course, and some of the things that are acceptable "sinks" for logs won't even have the concept of "a line"!), but, for logging, atomic units there must be. If you want something entire non-atomic then you don't really want logging but simple appends to a file or other stream (and, watch out for the likely confusion mentioned in the first paragraph;-). For transient updates about what your task is doing (in the middle of X, X done, starting Y, etc), you could think of a specialized log-handler that (for example) interprets such streams of updates by taking the first word as a subtask-identifier (incrementally building up and displaying somewhere the composite message about the "current subtask", recognizing when the subtask identifier changes that the previous subtask is finished or taking an explicit "subtask finished" message, and only writing persistent log entries on subtask-finished events). It's a pretty specialized requirement so you're not likely to find a pre-made tool for this, but rather you'll have to roll your own. To help you with that, it's crucial to understand exactly what you're trying to accomplish (why would you want non-atomic logging entries, if such a concept even made any sense -- what deployment or system administration task are you trying to ameliorate by using such a hypothetical tool?) so that the specialized subsystem can be tailored to your actual needs. So, can you please expand on this? A: I don't believe Python's logger supports that. However, would it not be better to aggree on a Log format so that the log file can be easily parsed when you want analyse the data where ; is any deliminator you want: DateTime;LogType;string That could be parsed easiily by a script and then you could do analysis on the logs If you use: Connecting to database . . . Done. Then you won't be able to analyse how long the transaction took A: I don't think you should go down this route. A logging methodolgy with entry: Time;functionName()-> And exit logging is more useful for troubleshooting: Time;functionName()<-
How can I write to the previous line in a log file using Python's Logging module?
long-time lurker here, finally emerging from the woodwork. Essentially, what I'm trying to do is have my logger write data like this to the logfile: Connecting to database . . . Done. I'd like the 'Connecting to database . . . ' to be written when the function is called, and the 'Done' written after the function has successfully executed. I'm using Python 2.6 and the logging module. Also, I'd really like to avoid using decorators for this. Any help would be most appreciated!
[ "Writing to a log is, and must be, an atomic action -- this is crucial, and a key feature of any logging package (including the one in Python's standard library) that distinguishes logging from the simple appending of information to files (where bits of things being written by different processes and threads might well \"interleave\" -- one of them writing some part of a line but not the line-end, just as you desire, and then maybe another one interposing something right afterwards, before the first task writes what it thinks will be the last part of the line but actually ends up on another line... utter confusion often results;-).\nIt's not inevitable that the atomic unit be \"a line\" (logs can be recorded elsewhere than to a text file, of course, and some of the things that are acceptable \"sinks\" for logs won't even have the concept of \"a line\"!), but, for logging, atomic units there must be. If you want something entire non-atomic then you don't really want logging but simple appends to a file or other stream (and, watch out for the likely confusion mentioned in the first paragraph;-).\nFor transient updates about what your task is doing (in the middle of X, X done, starting Y, etc), you could think of a specialized log-handler that (for example) interprets such streams of updates by taking the first word as a subtask-identifier (incrementally building up and displaying somewhere the composite message about the \"current subtask\", recognizing when the subtask identifier changes that the previous subtask is finished or taking an explicit \"subtask finished\" message, and only writing persistent log entries on subtask-finished events).\nIt's a pretty specialized requirement so you're not likely to find a pre-made tool for this, but rather you'll have to roll your own. To help you with that, it's crucial to understand exactly what you're trying to accomplish (why would you want non-atomic logging entries, if such a concept even made any sense -- what deployment or system administration task are you trying to ameliorate by using such a hypothetical tool?) so that the specialized subsystem can be tailored to your actual needs. So, can you please expand on this?\n", "I don't believe Python's logger supports that.\nHowever, would it not be better to aggree on a Log format so that the log file can be easily parsed when you want analyse the data where ; is any deliminator you want:\nDateTime;LogType;string\n\nThat could be parsed easiily by a script and then you could do analysis on the logs\nIf you use:\n Connecting to database . . . Done.\n\nThen you won't be able to analyse how long the transaction took\n", "I don't think you should go down this route. A logging methodolgy with entry:\n Time;functionName()->\n\nAnd exit logging is more useful for troubleshooting:\n Time;functionName()<-\n\n" ]
[ 14, 8, 3 ]
[]
[]
[ "logging", "python" ]
stackoverflow_0002839928_logging_python.txt
Q: Can this Django query be improved? Given a model structure like this: class Book(models.Model): user = models.ForeignKey(User) class Readingdate(models.Model): book = models.ForeignKey(Book) date = models.DateField() One book may have several Readingdates. How do I list books having at least one Readingdate within a specific year? I can do this: from_date = datetime.date(2010,1,1) to_date = datetime.date(2010,12,31) book_ids = Readingdate.objects\ .filter(date__range=(from_date,to_date))\ .values_list('book_id', flat=True) books_read_2010 = Book.objects.filter(id__in=book_ids) Is it possible to do this with one queryset, or is this the best way? A: Book.objects.filter(readingdate__date__year=2010)
Can this Django query be improved?
Given a model structure like this: class Book(models.Model): user = models.ForeignKey(User) class Readingdate(models.Model): book = models.ForeignKey(Book) date = models.DateField() One book may have several Readingdates. How do I list books having at least one Readingdate within a specific year? I can do this: from_date = datetime.date(2010,1,1) to_date = datetime.date(2010,12,31) book_ids = Readingdate.objects\ .filter(date__range=(from_date,to_date))\ .values_list('book_id', flat=True) books_read_2010 = Book.objects.filter(id__in=book_ids) Is it possible to do this with one queryset, or is this the best way?
[ "Book.objects.filter(readingdate__date__year=2010)\n\n" ]
[ 5 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002843613_django_python.txt
Q: how to make my method running on the template of google-app-engine the model is : class someModel(db.Model): name = db.StringProperty() def name_is_sss(self): return self.name=='sss' the view is : a=someModel() a.name='sss' path = os.path.join(os.path.dirname(__file__), os.path.join('templates', 'blog/a.html')) self.response.out.write(template.render(path, {'a':a})) and the html is : {{ a.name_is_sss }} the page shows : True so i want to make it more useful, and like this: the model: class someModel(db.Model): name = db.StringProperty() def name_is_x(self,x): return self.name==x the html is : {% a.name_is_x 'www'%} or {{ a.name_is_x 'www'}} but the error is : TemplateSyntaxError: Invalid block tag: 'a.name_is_x' or TemplateSyntaxError: Could not parse the remainder: 'www' so how to make my method running thanks A: Did you try this already? {{ a.name_is_x('www') }}
how to make my method running on the template of google-app-engine
the model is : class someModel(db.Model): name = db.StringProperty() def name_is_sss(self): return self.name=='sss' the view is : a=someModel() a.name='sss' path = os.path.join(os.path.dirname(__file__), os.path.join('templates', 'blog/a.html')) self.response.out.write(template.render(path, {'a':a})) and the html is : {{ a.name_is_sss }} the page shows : True so i want to make it more useful, and like this: the model: class someModel(db.Model): name = db.StringProperty() def name_is_x(self,x): return self.name==x the html is : {% a.name_is_x 'www'%} or {{ a.name_is_x 'www'}} but the error is : TemplateSyntaxError: Invalid block tag: 'a.name_is_x' or TemplateSyntaxError: Could not parse the remainder: 'www' so how to make my method running thanks
[ "Did you try this already?\n{{ a.name_is_x('www') }}\n\n" ]
[ 0 ]
[]
[]
[ "google_app_engine", "methods", "python", "templates" ]
stackoverflow_0002842511_google_app_engine_methods_python_templates.txt
Q: How Can I Find a List of All Exceptions That a Given Library Function Throws in Python? Sorry for the long title, but it seems most descriptive for my question. Basically, I'm having a difficult time finding exception information in the official python documentation. For example, in one program I'm currently writing, I'm using the shutil libary's move function: from shutil import move move('somefile.txt', '/tmp/somefile.txt') That works fine, as long as I have write access to /tmp/, there is enough diskspace, and if all other requirements are satisfied. However, when writing generic code, it is often difficult to guarantee those factors, so one usually uses exceptions: from shutil import move try: move('somefile.txt', '/tmp/somefile.txt') except: print 'Move failed for some reason.' I'd like to actually catch the appropriate exceptions thrown instead of just catching everything, but I simply can't find a list of exceptions thrown for most python modules. Is there a way for me to see which exceptions a given function can throw, and why? This way I can make appropriate cases for each exception, eg: from shutil import move try: move('somefile.txt', '/tmp/somefile.txt') except PermissionDenied: print 'No permission.' except DestinationDoesNotExist: print "/tmp/ doesn't exist" except NoDiskSpace: print 'No diskspace available.' Answer points go to whoever can either link me to some relevant documentation that I've somehow overlooked in the official docs, or provide a sure-fire way to figure out exactly which exceptions are thrown by which functions, and why. Thanks! UPDATE: It seems from the answers given that there really isn't a 100% straight-forward way to figure out which errors are thrown by specific functions. With meta programming, it seems that I can figure out simple cases and list some exceptions, but this is not a particularly useful or convenient method. I'd like to think that eventually there will be some standard for defining which exceptions are raised by each python function, and that this information will be included in the official documentation. Until then I think I will just allow those exceptions to pass through and error out for my users as it seems like the most sane thing to do. A: To amplify Messa, catch what you expect are failure modes that you know how to recover from. Ian Bicking wrote an article that addresses some of the overarching principles as does Eli Bendersky's note. The problem with the sample code is that it is not handling errors, just prettifying them and discarding them. Your code does not "know" what to do with a NameError and there isn't much it should do other than pass it up, look at Bicking's re-raise if you feel you must add detail. IOError and OSError are reasonably "expectable" for a shutil.move but not necessarily handleable. And the caller of your function wanted it to move a file and may itself break if that "contract" that Eli writes of is broken. Catch what you can fix, adorn and re-raise what you expect but can't fix, and let the caller deal with what you didn't expect, even if the code that "deals" is seven levels up the stack in main. A: Python doesn't have a mechanism right now for declaring which exceptions are thrown, unlike (for example) Java. (In Java you have to define exactly which exceptions are thrown by what, and if one of your utility methods needs to throw another exception then you need to add it to all of the methods which call it which gets boring quickly!) So if you want to discover exactly which exceptions are thrown by any given bit of python then you need to examine the documentation and the source. However python has a really good exception hierarchy. If you study the exception hierarchy below you'll see that the error superclass you want to catch is called StandardError - this should catch all the errors that might be generated in normal operations. Turning the error into into a string will give a reasonable idea to the user as to what went wrong, so I'd suggest your code above should look like from shutil import move try: move('somefile.txt', '/tmp/somefile.txt') except StandardError, e: print 'Move failed: %s' % e Exception hierarchy BaseException |---Exception |---|---StandardError |---|---|---ArithmeticError |---|---|---|---FloatingPointError |---|---|---|---OverflowError |---|---|---|---ZeroDivisionError |---|---|---AssertionError |---|---|---AttributeError |---|---|---BufferError |---|---|---EOFError |---|---|---EnvironmentError |---|---|---|---IOError |---|---|---|---OSError |---|---|---ImportError |---|---|---LookupError |---|---|---|---IndexError |---|---|---|---KeyError |---|---|---MemoryError |---|---|---NameError |---|---|---|---UnboundLocalError |---|---|---ReferenceError |---|---|---RuntimeError |---|---|---|---NotImplementedError |---|---|---SyntaxError |---|---|---|---IndentationError |---|---|---|---|---TabError |---|---|---SystemError |---|---|---TypeError |---|---|---ValueError |---|---|---|---UnicodeError |---|---|---|---|---UnicodeDecodeError |---|---|---|---|---UnicodeEncodeError |---|---|---|---|---UnicodeTranslateError |---|---StopIteration |---|---Warning |---|---|---BytesWarning |---|---|---DeprecationWarning |---|---|---FutureWarning |---|---|---ImportWarning |---|---|---PendingDeprecationWarning |---|---|---RuntimeWarning |---|---|---SyntaxWarning |---|---|---UnicodeWarning |---|---|---UserWarning |---GeneratorExit |---KeyboardInterrupt |---SystemExit This also means that when defining your own exceptions you should base them off StandardError not Exception. Base class for all standard Python exceptions that do not represent interpreter exiting. A: Yes, you can (for simple cases), but you need a bit of meta-programming. Like the other answers have said, a function does not declare that it throws a particular error type, so you need to look at the module and see what exception types it defines, or what exception types it raises. You can either try to grok the documentation or leverage the Python API to do this. To first find which exception types a module defines, just write a simple script to go through each object in the module dictionary module.__dict__ and see if it ends in the word "Error" or if it is a subclass of Exception: def listexns(mod): """Saved as: http://gist.github.com/402861 """ module = __import__(mod) exns = [] for name in module.__dict__: if (issubclass(module.__dict__[name], Exception) or name.endswith('Error')): exns.append(name) for name in exns: print '%s.%s is an exception type' % (str(mod), name) return If I run this on your example of shutils I get this: $ python listexn.py shutil Looking for exception types in module: shutil shutil.Error is an exception type shutil.WindowsError is an exception type $ That tells you which error types are defined, but not which ones are thrown. To achieve the latter, we need to walk over the abstract syntax tree generated when the Python interpreter parses the module, and look for every raise statement, then save a list of names which are raised. The code for this is a little long, so first I'll state the output: $ python listexn-raised.py /usr/lib/python2.6/shutil.py Looking for exception types in: /usr/lib/python2.6/shutil.py /usr/lib/python2.6/shutil.py:OSError is an exception type /usr/lib/python2.6/shutil.py:Error is an exception type $ So, now we know that shutil.py defines the error types Error and WindowsError and raises the exception types OSError and Error. If we want to be a bit more complete, we could write another method to check every except clause to also see which exceptions shutil handles. Here's the code to walk over the AST, it just uses the compiler.visitor interface to create a walker which implements the "visitor pattern" from the Gang of Four book: class ExceptionFinder(visitor.ASTVisitor): """List all exceptions raised by a module. Saved as: http://gist.github.com/402869 """ def __init__(self, filename): visitor.ASTVisitor.__init__(self) self.filename = filename self.exns = set() return def __visitName(self, node): """Should not be called by generic visit, otherwise every name will be reported as an exception type. """ self.exns.add(node.name) return def __visitCallFunc(self, node): """Should not be called by generic visit, otherwise every name will be reported as an exception type. """ self.__visitName(node.node) return def visitRaise(self, node): """Visit a raise statement. Cheat the default dispatcher. """ if issubclass(node.expr1, compiler.ast.Name): self.__visitName(node.expr1) elif isinstance(node.expr1, compiler.ast.CallFunc): self.__visitCallFunc(node.expr1) return A: As these operations usually use libc functions and operating system calls, mostly you get IOError or OSError with an errno number; these errors are listed in man pages of that libc/OS calls. I know this is possibly not a complete answer, it would be good to have all exceptions listed in documentation...
How Can I Find a List of All Exceptions That a Given Library Function Throws in Python?
Sorry for the long title, but it seems most descriptive for my question. Basically, I'm having a difficult time finding exception information in the official python documentation. For example, in one program I'm currently writing, I'm using the shutil libary's move function: from shutil import move move('somefile.txt', '/tmp/somefile.txt') That works fine, as long as I have write access to /tmp/, there is enough diskspace, and if all other requirements are satisfied. However, when writing generic code, it is often difficult to guarantee those factors, so one usually uses exceptions: from shutil import move try: move('somefile.txt', '/tmp/somefile.txt') except: print 'Move failed for some reason.' I'd like to actually catch the appropriate exceptions thrown instead of just catching everything, but I simply can't find a list of exceptions thrown for most python modules. Is there a way for me to see which exceptions a given function can throw, and why? This way I can make appropriate cases for each exception, eg: from shutil import move try: move('somefile.txt', '/tmp/somefile.txt') except PermissionDenied: print 'No permission.' except DestinationDoesNotExist: print "/tmp/ doesn't exist" except NoDiskSpace: print 'No diskspace available.' Answer points go to whoever can either link me to some relevant documentation that I've somehow overlooked in the official docs, or provide a sure-fire way to figure out exactly which exceptions are thrown by which functions, and why. Thanks! UPDATE: It seems from the answers given that there really isn't a 100% straight-forward way to figure out which errors are thrown by specific functions. With meta programming, it seems that I can figure out simple cases and list some exceptions, but this is not a particularly useful or convenient method. I'd like to think that eventually there will be some standard for defining which exceptions are raised by each python function, and that this information will be included in the official documentation. Until then I think I will just allow those exceptions to pass through and error out for my users as it seems like the most sane thing to do.
[ "To amplify Messa, catch what you expect are failure modes that you know how to recover from. Ian Bicking wrote an article that addresses some of the overarching principles as does Eli Bendersky's note.\nThe problem with the sample code is that it is not handling errors, just prettifying them and discarding them. Your code does not \"know\" what to do with a NameError and there isn't much it should do other than pass it up, look at Bicking's re-raise if you feel you must add detail.\nIOError and OSError are reasonably \"expectable\" for a shutil.move but not necessarily handleable. And the caller of your function wanted it to move a file and may itself break if that \"contract\" that Eli writes of is broken.\nCatch what you can fix, adorn and re-raise what you expect but can't fix, and let the caller deal with what you didn't expect, even if the code that \"deals\" is seven levels up the stack in main.\n", "Python doesn't have a mechanism right now for declaring which exceptions are thrown, unlike (for example) Java. (In Java you have to define exactly which exceptions are thrown by what, and if one of your utility methods needs to throw another exception then you need to add it to all of the methods which call it which gets boring quickly!)\nSo if you want to discover exactly which exceptions are thrown by any given bit of python then you need to examine the documentation and the source.\nHowever python has a really good exception hierarchy.\nIf you study the exception hierarchy below you'll see that the error superclass you want to catch is called StandardError - this should catch all the errors that might be generated in normal operations. Turning the error into into a string will give a reasonable idea to the user as to what went wrong, so I'd suggest your code above should look like\nfrom shutil import move\ntry:\n move('somefile.txt', '/tmp/somefile.txt')\nexcept StandardError, e:\n print 'Move failed: %s' % e\n\nException hierarchy\nBaseException\n|---Exception\n|---|---StandardError\n|---|---|---ArithmeticError\n|---|---|---|---FloatingPointError\n|---|---|---|---OverflowError\n|---|---|---|---ZeroDivisionError\n|---|---|---AssertionError\n|---|---|---AttributeError\n|---|---|---BufferError\n|---|---|---EOFError\n|---|---|---EnvironmentError\n|---|---|---|---IOError\n|---|---|---|---OSError\n|---|---|---ImportError\n|---|---|---LookupError\n|---|---|---|---IndexError\n|---|---|---|---KeyError\n|---|---|---MemoryError\n|---|---|---NameError\n|---|---|---|---UnboundLocalError\n|---|---|---ReferenceError\n|---|---|---RuntimeError\n|---|---|---|---NotImplementedError\n|---|---|---SyntaxError\n|---|---|---|---IndentationError\n|---|---|---|---|---TabError\n|---|---|---SystemError\n|---|---|---TypeError\n|---|---|---ValueError\n|---|---|---|---UnicodeError\n|---|---|---|---|---UnicodeDecodeError\n|---|---|---|---|---UnicodeEncodeError\n|---|---|---|---|---UnicodeTranslateError\n|---|---StopIteration\n|---|---Warning\n|---|---|---BytesWarning\n|---|---|---DeprecationWarning\n|---|---|---FutureWarning\n|---|---|---ImportWarning\n|---|---|---PendingDeprecationWarning\n|---|---|---RuntimeWarning\n|---|---|---SyntaxWarning\n|---|---|---UnicodeWarning\n|---|---|---UserWarning\n|---GeneratorExit\n|---KeyboardInterrupt\n|---SystemExit\n\nThis also means that when defining your own exceptions you should base them off StandardError not Exception.\nBase class for all standard Python exceptions that do not represent\ninterpreter exiting.\n\n", "Yes, you can (for simple cases), but you need a bit of meta-programming. Like the other answers have said, a function does not declare that it throws a particular error type, so you need to look at the module and see what exception types it defines, or what exception types it raises. You can either try to grok the documentation or leverage the Python API to do this.\nTo first find which exception types a module defines, just write a simple script to go through each object in the module dictionary module.__dict__ and see if it ends in the word \"Error\" or if it is a subclass of Exception:\ndef listexns(mod):\n \"\"\"Saved as: http://gist.github.com/402861\n \"\"\"\n module = __import__(mod)\n exns = []\n for name in module.__dict__:\n if (issubclass(module.__dict__[name], Exception) or\n name.endswith('Error')):\n exns.append(name)\n for name in exns:\n print '%s.%s is an exception type' % (str(mod), name)\n return\n\nIf I run this on your example of shutils I get this:\n$ python listexn.py shutil\nLooking for exception types in module: shutil\nshutil.Error is an exception type\nshutil.WindowsError is an exception type\n$\n\nThat tells you which error types are defined, but not which ones are thrown. To achieve the latter, we need to walk over the abstract syntax tree generated when the Python interpreter parses the module, and look for every raise statement, then save a list of names which are raised. The code for this is a little long, so first I'll state the output:\n$ python listexn-raised.py /usr/lib/python2.6/shutil.py\nLooking for exception types in: /usr/lib/python2.6/shutil.py\n/usr/lib/python2.6/shutil.py:OSError is an exception type\n/usr/lib/python2.6/shutil.py:Error is an exception type\n$ \n\nSo, now we know that shutil.py defines the error types Error and WindowsError and raises the exception types OSError and Error. If we want to be a bit more complete, we could write another method to check every except clause to also see which exceptions shutil handles.\nHere's the code to walk over the AST, it just uses the compiler.visitor interface to create a walker which implements the \"visitor pattern\" from the Gang of Four book:\nclass ExceptionFinder(visitor.ASTVisitor):\n \"\"\"List all exceptions raised by a module. \n Saved as: http://gist.github.com/402869\n \"\"\"\n\n def __init__(self, filename):\n visitor.ASTVisitor.__init__(self)\n self.filename = filename\n self.exns = set()\n return\n\n def __visitName(self, node):\n \"\"\"Should not be called by generic visit, otherwise every name\n will be reported as an exception type.\n \"\"\"\n self.exns.add(node.name)\n return\n\n def __visitCallFunc(self, node):\n \"\"\"Should not be called by generic visit, otherwise every name\n will be reported as an exception type.\n \"\"\"\n self.__visitName(node.node)\n return\n\n def visitRaise(self, node):\n \"\"\"Visit a raise statement.\n Cheat the default dispatcher.\n \"\"\"\n if issubclass(node.expr1, compiler.ast.Name):\n self.__visitName(node.expr1)\n elif isinstance(node.expr1, compiler.ast.CallFunc):\n self.__visitCallFunc(node.expr1)\n return\n\n", "As these operations usually use libc functions and operating system calls, mostly you get IOError or OSError with an errno number; these errors are listed in man pages of that libc/OS calls.\nI know this is possibly not a complete answer, it would be good to have all exceptions listed in documentation...\n" ]
[ 12, 4, 3, 2 ]
[]
[]
[ "exception", "python" ]
stackoverflow_0002843112_exception_python.txt
Q: Ping from AppEngine I know I can fetch url from AppEngine. But I just want to ping a website, without to get any other data. Is it possible? A: "ping" as in ICMP or "ping" as in send an HTTP request without getting the full response? If the latter, just send a HEAD request instead of a GET. If the former, then that probably depends on your language of choice on AppEngine For python, check out Ping a site in Python? For java, check out http://blog.taragana.com/index.php/archive/how-to-do-icmp-ping-in-java-jdk-15-and-above/ A: There is a whitelist of modules and an FAQ about notable exclusions. You can't do it; use whaley's HEAD request. It is also possible for an ICMP un-pingable to serve web-pages and a ICMP pingable site to do nothing but respond to pings.
Ping from AppEngine
I know I can fetch url from AppEngine. But I just want to ping a website, without to get any other data. Is it possible?
[ "\"ping\" as in ICMP or \"ping\" as in send an HTTP request without getting the full response? If the latter, just send a HEAD request instead of a GET. \nIf the former, then that probably depends on your language of choice on AppEngine \n\nFor python, check out\nPing a site in Python?\nFor java, check out http://blog.taragana.com/index.php/archive/how-to-do-icmp-ping-in-java-jdk-15-and-above/\n\n", "There is a whitelist of modules and an FAQ about notable exclusions. You can't do it; use whaley's HEAD request.\nIt is also possible for an ICMP un-pingable to serve web-pages and a ICMP pingable site to do nothing but respond to pings.\n" ]
[ 4, 3 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0002843838_google_app_engine_python.txt
Q: How to catch an exception thrown in ctypes? I am working with some C code called from Python using ctypes. Somewhere in the bowels of the C library, an exception is occurring and/or abort() is being called. Is there any way I can catch this in my Python caller code? (Platform is Linux) A: You might be able to setup a signal handler on SIGABRT to handle the signal caused by abort(). However, failed assertions might go along with corrupted memory and other bad things - there's usually a reason why an assertion failed. So usually terminating the applications is the best thing you can do (except displaying/logging an error in your handler before terminating).
How to catch an exception thrown in ctypes?
I am working with some C code called from Python using ctypes. Somewhere in the bowels of the C library, an exception is occurring and/or abort() is being called. Is there any way I can catch this in my Python caller code? (Platform is Linux)
[ "You might be able to setup a signal handler on SIGABRT to handle the signal caused by abort().\nHowever, failed assertions might go along with corrupted memory and other bad things - there's usually a reason why an assertion failed. So usually terminating the applications is the best thing you can do (except displaying/logging an error in your handler before terminating).\n" ]
[ 3 ]
[]
[]
[ "abort", "ctypes", "exception", "exception_handling", "python" ]
stackoverflow_0002844121_abort_ctypes_exception_exception_handling_python.txt
Q: Feedback on using ASE on Android? Has anyone made use of ASE (Android scripting enviroment) for anything other than proof of concept apps? What are the major limitations? Any feedback would be great. A: As this stage, using the ASE as your actual product's platform would in general be a bad move if performance is critical. It's great for rapidly prototyping something and/or verifying your understanding of how the API works. But the performance hit is nontrivial. This is the approach Google recommends, too: With respect to the interpreters ASE provides, Lua and Python are both cross compiled C binaries that run in their own process. CPython is significantly more performant than Jython (especially since Android does not currently support JIT). As for the Android facades, the API is primarily focused on making it easier to write scripts than on the performance of those scripts. That said, remember the adage "measure first, then optimize." ASE is about rapid development after all. If you have performance concerns for your application, it's probably better to use the standard Android SDK (or NDK) where you'll have more control over the system. A: ASE, as the name implies, is a scripting environment. You shouldn't use it to build full-fledged apps, it should only be used for small everyday-use scripts. I.e. if you thought "I'll code for android using python", think again: as long as you can't compile it and have full library access, it's a no go.
Feedback on using ASE on Android?
Has anyone made use of ASE (Android scripting enviroment) for anything other than proof of concept apps? What are the major limitations? Any feedback would be great.
[ "As this stage, using the ASE as your actual product's platform would in general be a bad move if performance is critical. It's great for rapidly prototyping something and/or verifying your understanding of how the API works. But the performance hit is nontrivial. This is the approach Google recommends, too:\n\nWith respect to the interpreters ASE provides, Lua and Python are both cross compiled C binaries that run in their own process. CPython is significantly more performant than Jython (especially since Android does not currently support JIT).\nAs for the Android facades, the API is primarily focused on making it easier to write scripts than on the performance of those scripts. That said, remember the adage \"measure first, then optimize.\" ASE is about rapid development after all.\nIf you have performance concerns for your application, it's probably better to use the standard Android SDK (or NDK) where you'll have more control over the system.\n\n", "ASE, as the name implies, is a scripting environment.\nYou shouldn't use it to build full-fledged apps, it should only be used for small everyday-use scripts.\nI.e. if you thought \"I'll code for android using python\", think again: as long as you can't compile it and have full library access, it's a no go.\n" ]
[ 4, 0 ]
[ "Since the GUI support is near to zero, my feedbacks about ASE are near to zero too.\n" ]
[ -2 ]
[ "android", "ase", "python" ]
stackoverflow_0002843845_android_ase_python.txt
Q: How does git fetches commits associated to a file? I'm writing a simple parser of .git/* files. I covered almost everything, like objects, refs, pack files etc. But I have a problem. Let's say I have a big 300M repository (in a pack file) and I want to find out all the commits which changed /some/deep/inside/file file. What I'm doing now is: fetching last commit finding a file in it by: fetching parent tree finding out a tree inside recursively repeat until I get into the file additionally I'm checking hashes of each subfolders on my way to file. If one of them is the same as in commit before, I assume that file was not changed (because it's parent dir didn't change) then I store the hash of a file and fetch parent commit finding file again and check if hash change occurs if yes then original commit (i.e. one before parent) was changing a file And I repeat it over and over until I reach very first commit. This solution works, but it sucks. In worse case scenario, first search can take even 3 minutes (for 300M pack). Is there any way to speed it up ? I tried to avoid putting so large objects in memory, but right now I don't see any other way. And even that, initial memory load will take forever :( Greets and thanks for any help! A: That's the basic algorithm that git uses to track changes to a particular file. That's why "git log -- some/path/to/file.txt" is a comparatively slow operation, compared to many other SCM systems where it would be simple (e.g. in CVS, P4 et al each repo file is a server file with the file's history). It shouldn't take so long to evaluate though: the amount you ever have to keep in memory is quite small. You already mentioned the main point: remember the tree IDs going down to the path to quickly eliminate commits that didn't even touch that subtree. It's rare for tree objects to be very big, just like directories on a filesystem (unsurprisingly). Are you using the pack index? If you're not, then you essentially have to unpack the entire pack to find this out since trees could be at the end of a long delta chain. If you have an index, you'll still have to apply deltas to get your tree objects, but at least you should be able to find them quickly. Keep a cache of applied deltas, since obviously it's very common for trees to reuse the same or similar bases- most tree object changes are just changing 20 bytes from a previous tree object. So if in order to get tree T1, you have to start with object T8 and apply Td7 to get T7, T6.... etc. it's entirely likely that these other trees T2-8 will be referenced again.
How does git fetches commits associated to a file?
I'm writing a simple parser of .git/* files. I covered almost everything, like objects, refs, pack files etc. But I have a problem. Let's say I have a big 300M repository (in a pack file) and I want to find out all the commits which changed /some/deep/inside/file file. What I'm doing now is: fetching last commit finding a file in it by: fetching parent tree finding out a tree inside recursively repeat until I get into the file additionally I'm checking hashes of each subfolders on my way to file. If one of them is the same as in commit before, I assume that file was not changed (because it's parent dir didn't change) then I store the hash of a file and fetch parent commit finding file again and check if hash change occurs if yes then original commit (i.e. one before parent) was changing a file And I repeat it over and over until I reach very first commit. This solution works, but it sucks. In worse case scenario, first search can take even 3 minutes (for 300M pack). Is there any way to speed it up ? I tried to avoid putting so large objects in memory, but right now I don't see any other way. And even that, initial memory load will take forever :( Greets and thanks for any help!
[ "That's the basic algorithm that git uses to track changes to a particular file. That's why \"git log -- some/path/to/file.txt\" is a comparatively slow operation, compared to many other SCM systems where it would be simple (e.g. in CVS, P4 et al each repo file is a server file with the file's history).\nIt shouldn't take so long to evaluate though: the amount you ever have to keep in memory is quite small. You already mentioned the main point: remember the tree IDs going down to the path to quickly eliminate commits that didn't even touch that subtree. It's rare for tree objects to be very big, just like directories on a filesystem (unsurprisingly).\nAre you using the pack index? If you're not, then you essentially have to unpack the entire pack to find this out since trees could be at the end of a long delta chain. If you have an index, you'll still have to apply deltas to get your tree objects, but at least you should be able to find them quickly. Keep a cache of applied deltas, since obviously it's very common for trees to reuse the same or similar bases- most tree object changes are just changing 20 bytes from a previous tree object. So if in order to get tree T1, you have to start with object T8 and apply Td7 to get T7, T6.... etc. it's entirely likely that these other trees T2-8 will be referenced again.\n" ]
[ 1 ]
[]
[]
[ "git", "python" ]
stackoverflow_0002841863_git_python.txt
Q: Python Error-Checking Standard Practice I have a question regarding error checking in Python. Let's say I have a function that takes a file path as an input: def myFunction(filepath): infile = open(filepath) #etc etc... One possible precondition would be that the file should exist. There are a few possible ways to check for this precondition, and I'm just wondering what's the best way to do it. i) Check with an if-statement: if not os.path.exists(filepath): raise IOException('File does not exist: %s' % filepath) This is the way that I would usually do it, though the same IOException would be raised by Python if the file does not exist, even if I don't raise it. ii) Use assert to check for the precondition: assert os.path.exists(filepath), 'File does not exist: %s' % filepath Using asserts seems to be the "standard" way of checking for pre/postconditions, so I am tempted to use these. However, it is possible that these asserts are turned off when the -o flag is used during execution, which means that this check might potentially be turned off and that seems risky. iii) Don't handle the precondition at all This is because if filepath does not exist, there will be an exception generated anyway and the exception message is detailed enough for user to know that the file does not exist I'm just wondering which of the above is the standard practice that I should use for my codes. A: If all you want to do is raise an exception, use option iii: def myFunction(filepath): with open(filepath) as infile: pass To handle exceptions in a special way, use a try...except block: def myFunction(filepath): try: with open(filepath) as infile: pass except IOError: # special handling code here Under no circumstance is it preferable to check the existence of the file first (option i or ii) because in the time between when the check or assertion occurs and when python tries to open the file, it is possible that the file could be deleted, or altered (such as with a symlink), which can lead to bugs or a security hole. Also, as of Python 2.6, the best practice when opening files is to use the with open(...) syntax. This guarantees that the file will be closed, even if an exception occurs inside the with-block. In Python 2.5 you can use the with syntax if you preface your script with from __future__ import with_statement A: Definitely don't use an assert. Asserts should only fail if the code is wrong. External conditions (such as missing files) shouldn't be checked with asserts. As others have pointed out, asserts can be turned off. The formal semantics of assert are: The condition may or may not be evaluated (so don't rely on side effects of the expression). If the condition is true, execution continues. It is undefined what happens if the condition is false. More on this idea. A: The following extends from ~unutbu's example. If the file doesn't exist, or on any other type of IO error, the filename is also passed along in the error message: path = 'blam' try: with open(path) as f: print f.read() except IOError as exc: raise IOError("%s: %s" % (path, exc.strerror)) => IOError: blam: No such file or directory A: I think you should go with a mix of iii) and i). If you know for a fact, that python will throw the exception (i.e. case iii), then let python do it. If there are some other preconditions (e.g. demanded by your business logic) you should throw own exceptions, maybe even derive from Exception. Using asserts is too fragile imho, because they might be turned off.
Python Error-Checking Standard Practice
I have a question regarding error checking in Python. Let's say I have a function that takes a file path as an input: def myFunction(filepath): infile = open(filepath) #etc etc... One possible precondition would be that the file should exist. There are a few possible ways to check for this precondition, and I'm just wondering what's the best way to do it. i) Check with an if-statement: if not os.path.exists(filepath): raise IOException('File does not exist: %s' % filepath) This is the way that I would usually do it, though the same IOException would be raised by Python if the file does not exist, even if I don't raise it. ii) Use assert to check for the precondition: assert os.path.exists(filepath), 'File does not exist: %s' % filepath Using asserts seems to be the "standard" way of checking for pre/postconditions, so I am tempted to use these. However, it is possible that these asserts are turned off when the -o flag is used during execution, which means that this check might potentially be turned off and that seems risky. iii) Don't handle the precondition at all This is because if filepath does not exist, there will be an exception generated anyway and the exception message is detailed enough for user to know that the file does not exist I'm just wondering which of the above is the standard practice that I should use for my codes.
[ "If all you want to do is raise an exception, use option iii:\ndef myFunction(filepath):\n with open(filepath) as infile:\n pass\n\nTo handle exceptions in a special way, use a try...except block:\ndef myFunction(filepath):\n try:\n with open(filepath) as infile:\n pass\n except IOError:\n # special handling code here\n\nUnder no circumstance is it preferable to check the existence of the file first (option i or ii) because in the time between when the check or assertion occurs and when python tries to open the file, it is possible that the file could be deleted, or altered (such as with a symlink), which can lead to bugs or a security hole.\nAlso, as of Python 2.6, the best practice when opening files is to use the with open(...) syntax. This guarantees that the file will be closed, even if an exception occurs inside the with-block.\nIn Python 2.5 you can use the with syntax if you preface your script with\nfrom __future__ import with_statement\n\n", "Definitely don't use an assert. Asserts should only fail if the code is wrong. External conditions (such as missing files) shouldn't be checked with asserts.\nAs others have pointed out, asserts can be turned off. \nThe formal semantics of assert are:\n\nThe condition may or may not be evaluated (so don't rely on side effects of the expression).\nIf the condition is true, execution continues.\nIt is undefined what happens if the condition is false.\n\nMore on this idea.\n", "The following extends from ~unutbu's example. If the file doesn't exist, or on any other type of IO error, the filename is also passed along in the error message:\npath = 'blam'\ntry:\n with open(path) as f:\n print f.read()\nexcept IOError as exc:\n raise IOError(\"%s: %s\" % (path, exc.strerror))\n\n=> IOError: blam: No such file or directory\n", "I think you should go with a mix of iii) and i). If you know for a fact, that python will throw the exception (i.e. case iii), then let python do it. If there are some other preconditions (e.g. demanded by your business logic) you should throw own exceptions, maybe even derive from Exception. \nUsing asserts is too fragile imho, because they might be turned off.\n" ]
[ 16, 4, 3, 1 ]
[]
[]
[ "assert", "error_handling", "python" ]
stackoverflow_0002843702_assert_error_handling_python.txt
Q: Modify an XML file in Python I have two files, file1 and file2. I have to modify file1 in a particular node and add in a list of children. The list is in file2. Can I do it, and how? from xml.dom.minidom import Document from xml.dom import minidom file1=modificare.xml file2=sorgente.xml xmldoc=minidom.parse(file1) for Node in xmldoc.getElementsByTagName("Sampler"): # put in the file2 content A: use ElementTree: from xml.etree.ElementTree import Element, SubElement, Comment, tostring # Configure one attribute with set() root = Element('opml') root.set('version', '1.0') root.append(Comment('Generated by ElementTree_csv_to_xml.py for PyMOTW')) http://broadcast.oreilly.com/2010/03/pymotw-creating-xml-documents.html
Modify an XML file in Python
I have two files, file1 and file2. I have to modify file1 in a particular node and add in a list of children. The list is in file2. Can I do it, and how? from xml.dom.minidom import Document from xml.dom import minidom file1=modificare.xml file2=sorgente.xml xmldoc=minidom.parse(file1) for Node in xmldoc.getElementsByTagName("Sampler"): # put in the file2 content
[ "use ElementTree:\nfrom xml.etree.ElementTree import Element, SubElement, Comment, tostring\n\n# Configure one attribute with set()\nroot = Element('opml')\nroot.set('version', '1.0')\n\nroot.append(Comment('Generated by ElementTree_csv_to_xml.py for PyMOTW'))\n\nhttp://broadcast.oreilly.com/2010/03/pymotw-creating-xml-documents.html\n" ]
[ 3 ]
[]
[]
[ "python", "xml" ]
stackoverflow_0002844237_python_xml.txt
Q: Is it possible to craft your own packets with python? Well, I know its possible, using external libraries and modules such as scapy. But how about without external modules? Without running the script as root? No external dependencies? I've been doing a lot of googling, but haven't found much help. I'd like to be able to create my own packets, but without running as root, or installing extra dependencies. Any suggestions? A: Here's how to code raw ICMP "ping" packets in Python: http://www.g-loaded.eu/2009/10/30/python-ping/ A: Many operating systems (Linux) do not allow raw sockets unless your effective user ID is 0 (aka root). This isn't a library issue. Some operating systems (non-server Windows post Windows XP SP2) do not allow crafting raw sockets period. You can read more about raw sockets by man 7 raw on your system. Note that the socket options can all be passed using the Python socket module.
Is it possible to craft your own packets with python?
Well, I know its possible, using external libraries and modules such as scapy. But how about without external modules? Without running the script as root? No external dependencies? I've been doing a lot of googling, but haven't found much help. I'd like to be able to create my own packets, but without running as root, or installing extra dependencies. Any suggestions?
[ "Here's how to code raw ICMP \"ping\" packets in Python:\nhttp://www.g-loaded.eu/2009/10/30/python-ping/\n", "Many operating systems (Linux) do not allow raw sockets unless your effective user ID is 0 (aka root). This isn't a library issue. Some operating systems (non-server Windows post Windows XP SP2) do not allow crafting raw sockets period.\nYou can read more about raw sockets by man 7 raw on your system. Note that the socket options can all be passed using the Python socket module.\n" ]
[ 2, 1 ]
[]
[]
[ "packets", "python", "sockets" ]
stackoverflow_0002842561_packets_python_sockets.txt
Q: Google app engine: empty property in datastore Let say I have a model: class A(db.Model): B = db.StringProperty() C = db.StringProperty() How do I query if I wanted to search all empty property (not None, just empty) in C using python? A: From GAE Python documents It is not possible to perform a query for entities that are missing a given property. One alternative is to create a fixed (modeled) property with a default value of None, then create a filter for entities with None as the property value.
Google app engine: empty property in datastore
Let say I have a model: class A(db.Model): B = db.StringProperty() C = db.StringProperty() How do I query if I wanted to search all empty property (not None, just empty) in C using python?
[ "From GAE Python documents\n\nIt is not possible to perform a query\n for entities that are missing a given\n property. One alternative is to create\n a fixed (modeled) property with a\n default value of None, then create a\n filter for entities with None as the\n property value.\n\n" ]
[ 4 ]
[ "Well if you want to return all rows with empty C properties you could do this.\nempty = db.GqlQuery('SELECT * FROM A WHERE C = \"\"')\n" ]
[ -2 ]
[ "google_app_engine", "python" ]
stackoverflow_0002842661_google_app_engine_python.txt
Q: Python: how to inherit and override Consider this situation: I get an object of type A which has the function f: class A: def f(self): print 'in f' def h(self): print 'in h' and I get an instance of this class, but I want to override the f function, yet save the rest of the functionality of A. So what I was thinking was something of the sort: class B(A): def __init__(self, a): #something here .... def f(self): print 'in B->f' and the usage would be: def main(a): b = B(a) b.f() #prints "in B->f" b.h() #print "in h" What I want is a sort of copy constructor that gets a parent of the current class (A), and returns an instance of this class (B). How do you do such a thing? How would the __init__ method look? Note: this post has been edited by the original poster to incorporate changes suggested in the comments, which is why some of the suggestions look redundant or incorrect. A: How you construct an object of subclass B "based on" one of class A depends exclusively on how the latter keeps state, if any, and how do you best get to that state and copy it over. In your example, instances of A are stateless, therefore there is absolutely no work you need to do in B's '__init__'. In a more typical example, say: class A(object): def __init__(self): self._x = 23 self._y = 45 def f(self): print 'in f,', self._x def h(self): print 'in h,', self._y the state would be in the two instance attributes _x and _y, so those are what you need to copy over: class B(A): def __init__(self, a): self._x = a._x self._y = a._y def f(self): print 'in B->f,', self._x This is the most common and normal approach, where the subclass accepts and directly implements its state-dependence on the superclass -- it's very straightforward and linear. You normally look for A's instance state aspects in A's '__init__', because most normal, straightforward Python code establishes instance state at initialization (attributes might be added and removed later, or even from code outside of the class's body, but that's not common and generally not advisable). It is possible to add a little touch of "magic" (introspection-based programming), e.g...: class B1(A): def __init__(self, a): try: s = a.__getstate__() except AttributeError: s = a.__dict__ try: self.__setstate__(s) except AttributeError: self.__dict__.update(s) getstate is a special method that classes may define -- if they do, it's used (e.g. by pickling) to "get the state" of their instances for serialization purpose (otherwise, the instance's __dict__ is deemed to be the instance's "state"). It may return a dict (in which case the .update call updates self's state), but it may also return anything else if the class also defines a __setstate__ that accepts it (so this code tries that route first, before falling back to the update possibility). Note that in this use case either or both of the special methods would be inherited from A -- I wouldn't define / override them in B (unless there are further subtle goals to be achieved that way of course;-). Is it worth using these four lines of "magic" in lieu of the simple assignments I first suggested? Mostly, no -- simplicity is preferable. But if A does anything special or is subject to external code altering its state, this solution can be more powerful and general (that's what you're buying by accepting its complication). So, you have to know if the latter case applies (and then "go for the big guns" of the special state-related methods), or if A and its instances are "pretty normal vanilla ones", in which case I would strongly recommend choosing simplicity and clarity instead. A: Try this: class A: def f(self): print("in f") def h(self): print("in h") class B(A): def f(self): print("in B:f") def test(x): x.f() x.h() test(A()) test(B()) Note, I'm using Python 3, which is the reason for print taking the arguments in parenthesis. Output: in f in h in B:f in h A: You need to put the self argument into the argument list for instance methods in python. Once you've done that, it will just work, because all methods are virtual in python.
Python: how to inherit and override
Consider this situation: I get an object of type A which has the function f: class A: def f(self): print 'in f' def h(self): print 'in h' and I get an instance of this class, but I want to override the f function, yet save the rest of the functionality of A. So what I was thinking was something of the sort: class B(A): def __init__(self, a): #something here .... def f(self): print 'in B->f' and the usage would be: def main(a): b = B(a) b.f() #prints "in B->f" b.h() #print "in h" What I want is a sort of copy constructor that gets a parent of the current class (A), and returns an instance of this class (B). How do you do such a thing? How would the __init__ method look? Note: this post has been edited by the original poster to incorporate changes suggested in the comments, which is why some of the suggestions look redundant or incorrect.
[ "How you construct an object of subclass B \"based on\" one of class A depends exclusively on how the latter keeps state, if any, and how do you best get to that state and copy it over. In your example, instances of A are stateless, therefore there is absolutely no work you need to do in B's '__init__'. In a more typical example, say:\nclass A(object):\n def __init__(self):\n self._x = 23\n self._y = 45\n def f(self):\n print 'in f,', self._x\n def h(self):\n print 'in h,', self._y\n\nthe state would be in the two instance attributes _x and _y, so those are what you need to copy over:\nclass B(A):\n def __init__(self, a):\n self._x = a._x\n self._y = a._y\n\n def f(self):\n print 'in B->f,', self._x\n\nThis is the most common and normal approach, where the subclass accepts and directly implements its state-dependence on the superclass -- it's very straightforward and linear. \nYou normally look for A's instance state aspects in A's '__init__', because most normal, straightforward Python code establishes instance state at initialization (attributes might be added and removed later, or even from code outside of the class's body, but that's not common and generally not advisable).\nIt is possible to add a little touch of \"magic\" (introspection-based programming), e.g...:\nclass B1(A):\n def __init__(self, a):\n try: s = a.__getstate__()\n except AttributeError: s = a.__dict__\n try: self.__setstate__(s)\n except AttributeError: self.__dict__.update(s)\n\ngetstate is a special method that classes may define -- if they do, it's used (e.g. by pickling) to \"get the state\" of their instances for serialization purpose (otherwise, the instance's __dict__ is deemed to be the instance's \"state\"). It may return a dict (in which case the .update call updates self's state), but it may also return anything else if the class also defines a __setstate__ that accepts it (so this code tries that route first, before falling back to the update possibility). Note that in this use case either or both of the special methods would be inherited from A -- I wouldn't define / override them in B (unless there are further subtle goals to be achieved that way of course;-).\nIs it worth using these four lines of \"magic\" in lieu of the simple assignments I first suggested? Mostly, no -- simplicity is preferable. But if A does anything special or is subject to external code altering its state, this solution can be more powerful and general (that's what you're buying by accepting its complication). So, you have to know if the latter case applies (and then \"go for the big guns\" of the special state-related methods), or if A and its instances are \"pretty normal vanilla ones\", in which case I would strongly recommend choosing simplicity and clarity instead.\n", "Try this:\nclass A:\n def f(self):\n print(\"in f\")\n\n def h(self):\n print(\"in h\")\n\nclass B(A):\n def f(self):\n print(\"in B:f\")\n\ndef test(x):\n x.f()\n x.h()\n\ntest(A())\ntest(B())\n\nNote, I'm using Python 3, which is the reason for print taking the arguments in parenthesis.\nOutput:\nin f\nin h\nin B:f\nin h\n\n", "You need to put the self argument into the argument list for instance methods in python.\nOnce you've done that, it will just work, because all methods are virtual in python.\n" ]
[ 11, 5, 2 ]
[]
[]
[ "inheritance", "overriding", "python" ]
stackoverflow_0002843165_inheritance_overriding_python.txt
Q: Go through a number of functions in Python I have an unknown number of functions in my python script (well, it is known, but not constant) that start with site_... I was wondering if there's a way to go through all of these functions in some main function that calls for them. something like: foreach function_that_has_site_ as coolfunc if coolfunc(blabla,yada) == true: return coolfunc(blabla,yada) so it would go through them all until it gets something that's true. thanks! A: The inspect module, already mentioned in other answers, is especially handy because you get to easily filter the names and values of objects you care about. inspect.getmembers takes two arguments: the object whose members you're exploring, and a predicate (a function returning bool) which will accept (return True for) only the objects you care about. To get "the object that is this module" you need the following well-known idiom: import sys this_module = sys.modules[__name__] In your predicate, you want to select only objects which are functions and have names that start with site_: import inspect def function_that_has_site(f): return inspect.isfunction(f) and f.__name__.startswith('site_') With these two items in hand, your loop becomes: for n, coolfunc in inspect.getmembers(this_module, function_that_has_site): result = coolfunc(blabla, yada) if result: return result I have also split the loop body so that each function is called only once (which both saves time and is a safer approach, avoiding possible side effects)... as well as rewording it in Python;-) A: Have you tried using the inspect module? http://docs.python.org/library/inspect.html The following will return the methods: inspect.getmembers Then you could invoke with: methodobjToInvoke = getattr(classObj, methodName) methodobj("arguments") A: This method goes through all properties of the current module and executes all functions it finds with a name starting with site_: import sys import types for elm in dir(): f = getattr(sys.modules[__name__], elm) if isinstance(f, types.FunctionType) and f.__name__[:5] == "site_": f() The function-type check is unnecessary if only functions are have names starting with site_. A: def run(): for f_name, f in globals().iteritems(): if not f_name.startswith('site_'): continue x = f() if x: return x A: It's best to use a decorator to enumerate the functions you care about: _funcs = [] def enumfunc(func): _funcs.append(func) return func @enumfunc def a(): print 'foo' @enumfunc def b(): print 'bar' @enumfunc def c(): print 'baz' if __name__ == '__main__': for f in _funcs: f() A: Try dir(), globals() or locals(). Or inspect module (as mentioned above). def site_foo(): pass def site_bar(): pass for name, f in globals().items(): if name.startswith("site_"): print name, f()
Go through a number of functions in Python
I have an unknown number of functions in my python script (well, it is known, but not constant) that start with site_... I was wondering if there's a way to go through all of these functions in some main function that calls for them. something like: foreach function_that_has_site_ as coolfunc if coolfunc(blabla,yada) == true: return coolfunc(blabla,yada) so it would go through them all until it gets something that's true. thanks!
[ "The inspect module, already mentioned in other answers, is especially handy because you get to easily filter the names and values of objects you care about. inspect.getmembers takes two arguments: the object whose members you're exploring, and a predicate (a function returning bool) which will accept (return True for) only the objects you care about.\nTo get \"the object that is this module\" you need the following well-known idiom:\nimport sys\nthis_module = sys.modules[__name__]\n\nIn your predicate, you want to select only objects which are functions and have names that start with site_:\nimport inspect\ndef function_that_has_site(f):\n return inspect.isfunction(f) and f.__name__.startswith('site_')\n\nWith these two items in hand, your loop becomes:\nfor n, coolfunc in inspect.getmembers(this_module, function_that_has_site):\n result = coolfunc(blabla, yada)\n if result: return result\n\nI have also split the loop body so that each function is called only once (which both saves time and is a safer approach, avoiding possible side effects)... as well as rewording it in Python;-)\n", "Have you tried using the inspect module?\nhttp://docs.python.org/library/inspect.html\nThe following will return the methods:\ninspect.getmembers\n\nThen you could invoke with:\nmethodobjToInvoke = getattr(classObj, methodName) \nmethodobj(\"arguments\") \n\n", "This method goes through all properties of the current module and executes all functions it finds with a name starting with site_:\nimport sys\nimport types\nfor elm in dir():\n f = getattr(sys.modules[__name__], elm)\n if isinstance(f, types.FunctionType) and f.__name__[:5] == \"site_\":\n f()\n\nThe function-type check is unnecessary if only functions are have names starting with site_.\n", "def run():\n for f_name, f in globals().iteritems():\n if not f_name.startswith('site_'):\n continue\n x = f()\n if x:\n return x\n\n", "It's best to use a decorator to enumerate the functions you care about:\n_funcs = []\n\ndef enumfunc(func):\n _funcs.append(func)\n return func\n\n@enumfunc\ndef a():\n print 'foo'\n\n@enumfunc\ndef b():\n print 'bar'\n\n@enumfunc\ndef c():\n print 'baz'\n\nif __name__ == '__main__':\n for f in _funcs:\n f()\n\n", "Try dir(), globals() or locals(). Or inspect module (as mentioned above).\ndef site_foo():\n pass\n\ndef site_bar():\n pass\n\nfor name, f in globals().items():\n if name.startswith(\"site_\"):\n print name, f()\n\n" ]
[ 5, 3, 1, 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002843053_python.txt
Q: Running a Python script for a user-specified amount of time I've just started learning Python today. I've been reading a Byte of Python. Right now I have a project for Python that involves time. I can't find anything relating to time in Byte of Python, so I'll ask you: How can I run a block for a user specified amount of time and then break? For example (in some pseudo-code): time = int(raw_input('Enter the amount of seconds you want to run this: ')) while there is still time left: #run this block or even better: import sys time = sys.argv[1] while there is still time left: #run this block A: I recommend spawning another thread, making it a daemon thread, then sleeping until you want the task to die. For example: from time import sleep from threading import Thread def some_task(): while True: pass t = Thread(target=some_task) # run the some_task function in another # thread t.daemon = True # Python will exit when the main thread # exits, even if this thread is still # running t.start() snooziness = int(raw_input('Enter the amount of seconds you want to run this: ')) sleep(snooziness) # Since this is the end of the script, Python will now exit. If we # still had any other non-daemon threads running, we wouldn't exit. # However, since our task is a daemon thread, Python will exit even if # it's still going. The Python interpreter will shut down when all non-daemon threads have exited. So when your main thread exits, if the only other thread running is your task that you are running in a separate daemon thread, then Python will just exit. This is a convenient way of running something in the background if you want to be able to just quit without worrying about manually causing it to quit and waiting for it to stop. So in other words, the advantage which this approach has over using sleep in a for loop is in that case you have to code your task in such a way that it's broken up into discrete chunks and then check every so often whether your time is up. Which might be fine for your purposes, but it can have problems, such as if each chunk takes a significant amount of time, thus causing your program to run for significantly longer than what the user entered, etc. Whether this is a problem for you depends on the task you are writing, but I figured I would mention this approach in case it would be better for you. A: Try time.time(), which returns the current time as the number of seconds since a set time called the epoch (midnight on Jan. 1, 1970 for many computers). Here's one way to use it: import time max_time = int(raw_input('Enter the amount of seconds you want to run this: ')) start_time = time.time() # remember when we started while (time.time() - start_time) < max_time: do_stuff() So we'll loop as long as the time since we started is less than the user-specified maximum. This isn't perfect: most notably, if do_stuff() takes a long time, we won't stop until it finishes and we discover that we're past our deadline. If you need to be able to interrupt a task in progress as soon as the time elapses, the problem gets more complicated. A: If you're on Linux, and you want to interrupt a long-running process, use signal: import signal, time def got_alarm(signum, frame): print 'Alarm!' # call 'got_alarm' in two seconds: signal.signal(signal.SIGALRM, got_alarm) signal.alarm(2) print 'sleeping...' time.sleep(4) print 'done'
Running a Python script for a user-specified amount of time
I've just started learning Python today. I've been reading a Byte of Python. Right now I have a project for Python that involves time. I can't find anything relating to time in Byte of Python, so I'll ask you: How can I run a block for a user specified amount of time and then break? For example (in some pseudo-code): time = int(raw_input('Enter the amount of seconds you want to run this: ')) while there is still time left: #run this block or even better: import sys time = sys.argv[1] while there is still time left: #run this block
[ "I recommend spawning another thread, making it a daemon thread, then sleeping until you want the task to die. For example:\nfrom time import sleep\nfrom threading import Thread\n\ndef some_task():\n while True:\n pass\n\nt = Thread(target=some_task) # run the some_task function in another\n # thread\nt.daemon = True # Python will exit when the main thread\n # exits, even if this thread is still\n # running\nt.start()\n\nsnooziness = int(raw_input('Enter the amount of seconds you want to run this: '))\nsleep(snooziness)\n\n# Since this is the end of the script, Python will now exit. If we\n# still had any other non-daemon threads running, we wouldn't exit.\n# However, since our task is a daemon thread, Python will exit even if\n# it's still going.\n\nThe Python interpreter will shut down when all non-daemon threads have exited. So when your main thread exits, if the only other thread running is your task that you are running in a separate daemon thread, then Python will just exit. This is a convenient way of running something in the background if you want to be able to just quit without worrying about manually causing it to quit and waiting for it to stop.\nSo in other words, the advantage which this approach has over using sleep in a for loop is in that case you have to code your task in such a way that it's broken up into discrete chunks and then check every so often whether your time is up. Which might be fine for your purposes, but it can have problems, such as if each chunk takes a significant amount of time, thus causing your program to run for significantly longer than what the user entered, etc. Whether this is a problem for you depends on the task you are writing, but I figured I would mention this approach in case it would be better for you.\n", "Try time.time(), which returns the current time as the number of seconds since a set time called the epoch (midnight on Jan. 1, 1970 for many computers). Here's one way to use it:\nimport time\n\nmax_time = int(raw_input('Enter the amount of seconds you want to run this: '))\nstart_time = time.time() # remember when we started\nwhile (time.time() - start_time) < max_time:\n do_stuff()\n\nSo we'll loop as long as the time since we started is less than the user-specified maximum. This isn't perfect: most notably, if do_stuff() takes a long time, we won't stop until it finishes and we discover that we're past our deadline. If you need to be able to interrupt a task in progress as soon as the time elapses, the problem gets more complicated.\n", "If you're on Linux, and you want to interrupt a long-running process, use signal:\nimport signal, time\n\ndef got_alarm(signum, frame):\n print 'Alarm!'\n\n# call 'got_alarm' in two seconds:\nsignal.signal(signal.SIGALRM, got_alarm)\nsignal.alarm(2)\n\nprint 'sleeping...'\ntime.sleep(4)\n\nprint 'done'\n\n" ]
[ 26, 15, 5 ]
[]
[]
[ "python" ]
stackoverflow_0002831775_python.txt
Q: Using Python to add/remove Ubuntu login script items I have written a Python application and would like to give my users the option of having the app automatically launch itself when the user logs in. It is important that the user is able to toggle this option on/off from within the app itself, rather than having to manually edit login scripts, so this needs to be done from within the Python code rather than from a shell script. The app is deployed on Ubuntu Linux, any suggestions for the best way of doing this? A: Here's what you need to handle autostart.
Using Python to add/remove Ubuntu login script items
I have written a Python application and would like to give my users the option of having the app automatically launch itself when the user logs in. It is important that the user is able to toggle this option on/off from within the app itself, rather than having to manually edit login scripts, so this needs to be done from within the Python code rather than from a shell script. The app is deployed on Ubuntu Linux, any suggestions for the best way of doing this?
[ "Here's what you need to handle autostart.\n" ]
[ 2 ]
[]
[]
[ "linux", "login_script", "python", "ubuntu" ]
stackoverflow_0002844554_linux_login_script_python_ubuntu.txt
Q: Enterprise Platform in Python, Design Advice I am starting the design of a somewhat large enterprise platform in Python, and was wondering if you guys can give me some advice as to how to organize the various components and which packages would help achieve the goals of scalability, maintainability, and reliability. The system is basically a service that collects data from various outside sources, with each outside source having its own separate application. These applications would poll a central database and get any requests that have been submitted to perform on the external source. There will be a main website and REST/SOAP API that should also have access to the central data service. My initial thought was to use Django for the web site, web service and data access layer (using its built-in ORM), and then the outside source applications can use the web service(s) to get the information they need to process the request and save the results. Using this method would allow me to have multiple instances of the service applications running on the same or different machines to balance out the load. Are there more elegant means of accomplishing this? i've heard of messaging systems such as MQ, would something like that be beneficial in this scenario? My other thought was to use a completely separate data service not based on Django, and use some kind of remoting or remote objects (in they exist in Python) to interact with the data model. The downside here would be with the website which would become much slower if it had to push all of its data requests through a second layer. I would love to hear what other developers have come up with to achieve these goals in the most flexible way possible. A: Consider using Celery. It lets your web apps do as little as possible, then fire off other tasks that'll be completed later. It uses AMQP (RabbitMQ) underneath, but it's in Python and plays very well with Django. http://celeryproject.org/ (If you want to learn more AMQP, I wrote up some slides: http://johntellsall.blogspot.com/2009/11/message-queuing-slides-and-source-code.html ) A: I think that your architecture sounds fine. One comment is that SOAP is usually considered heavy in the python community. Have you considered JSON or something else instead? By now, there are JSON libraries for most languages. Another possibility for running code remotely is pyro (Python Remote Objects), which works fine on Windows, and is cross-platform. There are a couple of gotchas writing services in python (like if your service always dies after a while, make sure it's not writing to stdout and filling up its buffer), but if you're considering this route then I assume you're on top of that. :)
Enterprise Platform in Python, Design Advice
I am starting the design of a somewhat large enterprise platform in Python, and was wondering if you guys can give me some advice as to how to organize the various components and which packages would help achieve the goals of scalability, maintainability, and reliability. The system is basically a service that collects data from various outside sources, with each outside source having its own separate application. These applications would poll a central database and get any requests that have been submitted to perform on the external source. There will be a main website and REST/SOAP API that should also have access to the central data service. My initial thought was to use Django for the web site, web service and data access layer (using its built-in ORM), and then the outside source applications can use the web service(s) to get the information they need to process the request and save the results. Using this method would allow me to have multiple instances of the service applications running on the same or different machines to balance out the load. Are there more elegant means of accomplishing this? i've heard of messaging systems such as MQ, would something like that be beneficial in this scenario? My other thought was to use a completely separate data service not based on Django, and use some kind of remoting or remote objects (in they exist in Python) to interact with the data model. The downside here would be with the website which would become much slower if it had to push all of its data requests through a second layer. I would love to hear what other developers have come up with to achieve these goals in the most flexible way possible.
[ "Consider using Celery. It lets your web apps do as little as possible, then fire off other tasks that'll be completed later. It uses AMQP (RabbitMQ) underneath, but it's in Python and plays very well with Django.\nhttp://celeryproject.org/\n(If you want to learn more AMQP, I wrote up some slides:\nhttp://johntellsall.blogspot.com/2009/11/message-queuing-slides-and-source-code.html\n)\n", "I think that your architecture sounds fine. One comment is that SOAP is usually considered heavy in the python community. Have you considered JSON or something else instead? By now, there are JSON libraries for most languages.\nAnother possibility for running code remotely is pyro (Python Remote Objects), which works fine on Windows, and is cross-platform.\nThere are a couple of gotchas writing services in python (like if your service always dies after a while, make sure it's not writing to stdout and filling up its buffer), but if you're considering this route then I assume you're on top of that. :)\n" ]
[ 3, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002821122_django_python.txt
Q: Get the path to Django itself I've got some code that runs on every (nearly) every admin request but doesn't have access to the 'request' object. I need to find the path to Django installation. I could do: import django django_path = django.__file__ but that seems rather wasteful in the middle of a request. Does putting the import at the start of the module waste memory? I'm fairly sure I'm missing an obvious trick here. A: So long as Django has already been imported in the Python process (which it has, if your code is, for example, in a view function), importing it again won't do "anything"* — so go nuts, use import django; django.__file__. Now, if Django hasn't been imported by the current Python process (eg, you're calling os.system("myscript.py") and myscript.py needs to determine Django's path), then import django will be a bit wasteful. But spawning a new process on each request is also fairly wasteful… So if efficiency is important, it might be better import myscript anyway. *: actually it will set a value in a dictionary… But that's "nothing".
Get the path to Django itself
I've got some code that runs on every (nearly) every admin request but doesn't have access to the 'request' object. I need to find the path to Django installation. I could do: import django django_path = django.__file__ but that seems rather wasteful in the middle of a request. Does putting the import at the start of the module waste memory? I'm fairly sure I'm missing an obvious trick here.
[ "So long as Django has already been imported in the Python process (which it has, if your code is, for example, in a view function), importing it again won't do \"anything\"* — so go nuts, use import django; django.__file__.\nNow, if Django hasn't been imported by the current Python process (eg, you're calling os.system(\"myscript.py\") and myscript.py needs to determine Django's path), then import django will be a bit wasteful. But spawning a new process on each request is also fairly wasteful… So if efficiency is important, it might be better import myscript anyway.\n*: actually it will set a value in a dictionary… But that's \"nothing\".\n" ]
[ 5 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002845137_django_python.txt
Q: How to use nose coverage with --timid flag I'd like to run "nosetests --with-coverage" using Ned Batchelder's coverage module, but passing the coverage module the --timid flag. Is there a way (e.g. setting an environment variable) to make coverage run with --timid? A: You've got two options: Use a .coveragerc file to provide options to coverage.py Instead of running coverage inside nose, run nose inside coverage: coverage run c:\python25\scripts\nosetests-script.py (sorry for the Windows syntax if you aren't on Windows)
How to use nose coverage with --timid flag
I'd like to run "nosetests --with-coverage" using Ned Batchelder's coverage module, but passing the coverage module the --timid flag. Is there a way (e.g. setting an environment variable) to make coverage run with --timid?
[ "You've got two options:\n\nUse a .coveragerc file to provide options to coverage.py\nInstead of running coverage inside nose, run nose inside coverage:\ncoverage run c:\\python25\\scripts\\nosetests-script.py \n\n\n(sorry for the Windows syntax if you aren't on Windows)\n" ]
[ 3 ]
[]
[]
[ "code_coverage", "nose", "python" ]
stackoverflow_0002735738_code_coverage_nose_python.txt
Q: Extracting data from a text file to use in a python script? Basically, I have a file like this: Url/Host: www.example.com Login: user Password: password Data_I_Dont_Need: something_else How can I use RegEx to separate the details to place them into variables? Sorry if this is a terrible question, I can just never grasp RegEx. So another question would be, can you provide the RegEx, but kind of explain what each part of it is for? A: You should put the entries in a dictionary, not in so many separate variables -- clearly, the keys you're using need NOT be acceptable as variable names (that slash in 'Url/Host' would be a killer!-), but they'll be just fine as string keys into a dictionary. import re there = re.compile(r'''(?x) # verbose flag: allows comments & whitespace ^ # anchor to the start ([^:]+) # group with 1+ non-colons, the key :\s* # colon, then arbitrary whitespace (.*) # group everything that follows $ # anchor to the end ''') and then configdict = {} for aline in open('thefile.txt'): mo = there.match(aline) if not mo: print("Skipping invalid line %r" % aline) continue k, v = mo.groups() configdict[k] = v the possibility of making RE patterns "verbose" (by starting them with (?x) or using re.VERBOSE as the second argument to re.compile) is very useful to allow you to clarify your REs with comments and nicely-aligning whitespace. I think it's sadly underused;-). A: For a file as simple as this you don't really need regular expressions. String functions are probably easier to understand. This code: def parse(data): parsed = {} for line in data.split('\n'): if not line: continue # Blank line pair = line.split(':') parsed[pair[0].strip()] = pair[1].strip() return parsed if __name__ == '__main__': test = """Url/Host: www.example.com Login: user Password: password """ print parse(test) Will do the job, and results in: {'Login': 'user', 'Password': 'password', 'Url/Host': 'www.example.com'} A: Well, if you don't know about regex, simply change you file like this: Host = www.example.com Login = uer Password = password And use ConfigParser python module http://docs.python.org/library/configparser.html A: EDIT: Better Solution for line in input: key, val = re.search('(.*?):\s*(.*)', line).groups() A: ConfigParser module supports ':' delimiter. import ConfigParser from cStringIO import StringIO class Parser(ConfigParser.RawConfigParser): def _read(self, fp, fpname): data = StringIO("[data]\n"+fp.read()) return ConfigParser.RawConfigParser._read(self, data, fpname) p = Parser() p.read("file.txt") print dict(p.items("data")) Output: {'login': 'user', 'password': 'password', 'url/host': 'www.example.com'} Though a regex or manual parsing might be more appropriate in your case.
Extracting data from a text file to use in a python script?
Basically, I have a file like this: Url/Host: www.example.com Login: user Password: password Data_I_Dont_Need: something_else How can I use RegEx to separate the details to place them into variables? Sorry if this is a terrible question, I can just never grasp RegEx. So another question would be, can you provide the RegEx, but kind of explain what each part of it is for?
[ "You should put the entries in a dictionary, not in so many separate variables -- clearly, the keys you're using need NOT be acceptable as variable names (that slash in 'Url/Host' would be a killer!-), but they'll be just fine as string keys into a dictionary.\nimport re\n\nthere = re.compile(r'''(?x) # verbose flag: allows comments & whitespace\n ^ # anchor to the start\n ([^:]+) # group with 1+ non-colons, the key\n :\\s* # colon, then arbitrary whitespace\n (.*) # group everything that follows\n $ # anchor to the end\n ''')\n\nand then\n configdict = {}\n for aline in open('thefile.txt'):\n mo = there.match(aline)\n if not mo:\n print(\"Skipping invalid line %r\" % aline)\n continue\n k, v = mo.groups()\n configdict[k] = v\n\nthe possibility of making RE patterns \"verbose\" (by starting them with (?x) or using re.VERBOSE as the second argument to re.compile) is very useful to allow you to clarify your REs with comments and nicely-aligning whitespace. I think it's sadly underused;-).\n", "For a file as simple as this you don't really need regular expressions. String functions are probably easier to understand. This code:\ndef parse(data):\n parsed = {} \n for line in data.split('\\n'):\n if not line: continue # Blank line\n pair = line.split(':')\n parsed[pair[0].strip()] = pair[1].strip()\n return parsed\n\nif __name__ == '__main__':\n test = \"\"\"Url/Host: www.example.com\n Login: user\n Password: password\n\"\"\"\n print parse(test)\n\nWill do the job, and results in:\n{'Login': 'user', 'Password': 'password', 'Url/Host': 'www.example.com'}\n\n", "Well, if you don't know about regex, simply change you file like this:\nHost = www.example.com\nLogin = uer\nPassword = password\n\nAnd use ConfigParser python module http://docs.python.org/library/configparser.html\n", "EDIT: Better Solution\nfor line in input: \n key, val = re.search('(.*?):\\s*(.*)', line).groups()\n\n", "ConfigParser module supports ':' delimiter.\nimport ConfigParser\nfrom cStringIO import StringIO\n\nclass Parser(ConfigParser.RawConfigParser):\n def _read(self, fp, fpname):\n data = StringIO(\"[data]\\n\"+fp.read()) \n return ConfigParser.RawConfigParser._read(self, data, fpname)\n\np = Parser()\np.read(\"file.txt\")\nprint dict(p.items(\"data\"))\n\nOutput:\n{'login': 'user', 'password': 'password', 'url/host': 'www.example.com'}\n\nThough a regex or manual parsing might be more appropriate in your case.\n" ]
[ 1, 1, 0, 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0002845018_python_regex.txt
Q: Awakening a thread by a queue I want my thread to sleep when a queue is empty and wake up only when a data is put in it. Should I use a condition object? I have never used this object before and I can't find a simple example in python. A: If the queue object in question is bound to name q, just call q.get(): it will sleep patiently as long as the queue is empty, then return the queue's first item as soon as the queue is made non-empty by another thread executing a .put(whatever) on it. While the docs may not be stellarly clear about this, that's the default behavior of .get() when you call it without any argument, and indeed the most popular way for a thread to read from a queue (which is why it was made the default in the first place;-). A: Pass block=True to Queue.get(). A: There's a nice Linux Gazette article online that has code using a condition variable you might find useful: http://linuxgazette.net/107/pai.html. The article covers python threading in general. Section 4.4, almost at the bottom, covers condition objects.
Awakening a thread by a queue
I want my thread to sleep when a queue is empty and wake up only when a data is put in it. Should I use a condition object? I have never used this object before and I can't find a simple example in python.
[ "If the queue object in question is bound to name q, just call q.get(): it will sleep patiently as long as the queue is empty, then return the queue's first item as soon as the queue is made non-empty by another thread executing a .put(whatever) on it. While the docs may not be stellarly clear about this, that's the default behavior of .get() when you call it without any argument, and indeed the most popular way for a thread to read from a queue (which is why it was made the default in the first place;-).\n", "Pass block=True to Queue.get().\n", "There's a nice Linux Gazette article online that has code using a condition variable you might find useful: http://linuxgazette.net/107/pai.html. The article covers python threading in general. Section 4.4, almost at the bottom, covers condition objects.\n" ]
[ 4, 0, 0 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0002845749_multithreading_python.txt
Q: Dreaded python encoding errors, how to stop them? These have been plaguing me endlessly. Why? It seems that my console can't handle the encoding. I take it that the my browser and word processor can handle it. I don't have a master list of all the possible characters that it's choking on. What is the best way to relieve this without modifying my data? 'charmap' codec can't encode character u'\xca' A: You need to find out the encoding of your console (which system, OS, etc...?) -- 'charmap' is unfortunately a somewhat-ambiguous identification for a codec, as the docs explain: There’s another group of encodings (the so called charmap encodings) that choose a different subset of all unicode code points and how these codepoints are mapped to the bytes 0x0-0xff. To see how this is done simply open e.g. encodings/cp1252.py (which is an encoding that is used primarily on Windows). There’s a string constant with 256 characters that shows you which character is mapped to which byte value. All of these encodings can only encode 256 of the 65536 (or 1114111) codepoints defined in unicode. i.e., it identifies a set of possible codecs, not a specific one. Once you know your console supports a codec named 'foobar', change your statements that are now print(someunicode) into print(someunicode.encode('foobar'))
Dreaded python encoding errors, how to stop them?
These have been plaguing me endlessly. Why? It seems that my console can't handle the encoding. I take it that the my browser and word processor can handle it. I don't have a master list of all the possible characters that it's choking on. What is the best way to relieve this without modifying my data? 'charmap' codec can't encode character u'\xca'
[ "You need to find out the encoding of your console (which system, OS, etc...?) -- 'charmap' is unfortunately a somewhat-ambiguous identification for a codec, as the docs explain:\n\nThere’s another group of encodings\n (the so called charmap encodings) that\n choose a different subset of all\n unicode code points and how these\n codepoints are mapped to the bytes\n 0x0-0xff. To see how this is done\n simply open e.g. encodings/cp1252.py\n (which is an encoding that is used\n primarily on Windows). There’s a\n string constant with 256 characters\n that shows you which character is\n mapped to which byte value.\nAll of these encodings can only encode\n 256 of the 65536 (or 1114111)\n codepoints defined in unicode.\n\ni.e., it identifies a set of possible codecs, not a specific one.\nOnce you know your console supports a codec named 'foobar', change your statements that are now\nprint(someunicode)\n\ninto\nprint(someunicode.encode('foobar'))\n\n" ]
[ 2 ]
[]
[]
[ "character_encoding", "python", "unicode", "utf_8" ]
stackoverflow_0002846043_character_encoding_python_unicode_utf_8.txt
Q: grabbing a substring while scraping with Python2.6 Hey can someone help with the following? I'm trying to scrape a site that has the following information.. I need to pull just the number after the </strong> tag.. [<li><strong>ISBN-13:</strong> 9780375853401</li>, <li><strong>Pub. Date: </strong> 05/11/2010</li>] [<li><strong>UPC:</strong> 490355000372</li>, <li><strong>Catalog No:</strong> 15024/25</li>, <li><strong>Label:</strong> CAMERATA</li>] here's a piece of the code I've been using to grab the above data using mechanize and BeautifulSoup. I'm stuck here as it won't let me use the find() function for a list br_results = mechanize.urlopen(br_results) html = br_results.read() soup = BeautifulSoup(html) local_links = soup.findAll("a", {"class" : "down-arrow csa"}) upc_code = soup.findAll("ul", {"class" : "bc-meta3"}) for upc in upc_code: upc_text = upc.contents.contents print upc_text A: I imagine upc_code is the list you're showing us, and the local_links one has nothing to do with your question right? Given that you don't mention it further in your code...? So I'm not certain what upc_text would be in your loop's body given that upc is a ul Tag -- upc.contents is going to be a list of li tags (presumably), and I don't see how upc.contents.contents can work -- what are you seeing as a result of that code? I would have expected an exception! Anyway, the way I'd write the loop would be something like: for upc in upc_code: listitems = upc.findAll('li') for anitem in listitems: print anitem.contents[1] since you appear to want the second child of each list item (the first one is the strong tag, the second one the navigable string you want. If it's not the second child of each list item that you want, please clarify; for example, you could identify the strong and get its next sibling, if that suits you better -- just make the body of the nested loop into print anitem.find('strong').nextSibling
grabbing a substring while scraping with Python2.6
Hey can someone help with the following? I'm trying to scrape a site that has the following information.. I need to pull just the number after the </strong> tag.. [<li><strong>ISBN-13:</strong> 9780375853401</li>, <li><strong>Pub. Date: </strong> 05/11/2010</li>] [<li><strong>UPC:</strong> 490355000372</li>, <li><strong>Catalog No:</strong> 15024/25</li>, <li><strong>Label:</strong> CAMERATA</li>] here's a piece of the code I've been using to grab the above data using mechanize and BeautifulSoup. I'm stuck here as it won't let me use the find() function for a list br_results = mechanize.urlopen(br_results) html = br_results.read() soup = BeautifulSoup(html) local_links = soup.findAll("a", {"class" : "down-arrow csa"}) upc_code = soup.findAll("ul", {"class" : "bc-meta3"}) for upc in upc_code: upc_text = upc.contents.contents print upc_text
[ "I imagine upc_code is the list you're showing us, and the local_links one has nothing to do with your question right? Given that you don't mention it further in your code...?\nSo I'm not certain what upc_text would be in your loop's body given that upc is a ul Tag -- upc.contents is going to be a list of li tags (presumably), and I don't see how upc.contents.contents can work -- what are you seeing as a result of that code? I would have expected an exception!\nAnyway, the way I'd write the loop would be something like:\nfor upc in upc_code:\n listitems = upc.findAll('li')\n for anitem in listitems:\n print anitem.contents[1]\n\nsince you appear to want the second child of each list item (the first one is the strong tag, the second one the navigable string you want.\nIf it's not the second child of each list item that you want, please clarify; for example, you could identify the strong and get its next sibling, if that suits you better -- just make the body of the nested loop into\nprint anitem.find('strong').nextSibling\n\n" ]
[ 2 ]
[]
[]
[ "beautifulsoup", "list", "mechanize", "python", "substring" ]
stackoverflow_0002845689_beautifulsoup_list_mechanize_python_substring.txt