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: pygtk - how update a gtk.liststore? http://img824.imageshack.us/i/capturadetelag.png/ how update a gtk.liststore? i mean get a random number every second on a column just like example, such as a download manager list, i'd like to have a simple example to know how this Liststore works for update the list, because i can't find a effective way to do something like a: store.append(list1,list2,list3) store.update(list3,['foobar']). A: You can iterate over the rows in a list store (for row in liststore:...) as well as over the columns (values) in each row (for col_value in row:...). For simple, direct updates: row_n = 0 col_n = 2 liststore[row_n][col_n] = 'new value' Otherwise, you can update using a gtk.TreeIter (row_iter): liststore.set_value(row_iter, col_n, 'new value') A: http://www.pygtk.org/pygtk2reference/class-gtkliststore.html You need to use a gtk.TreeIter, also this has some good information. If I were more familiar I could give you an example, I just remember that it's kind of a pain to use the gtk.liststore, but there's not really any better solution
pygtk - how update a gtk.liststore?
http://img824.imageshack.us/i/capturadetelag.png/ how update a gtk.liststore? i mean get a random number every second on a column just like example, such as a download manager list, i'd like to have a simple example to know how this Liststore works for update the list, because i can't find a effective way to do something like a: store.append(list1,list2,list3) store.update(list3,['foobar']).
[ "You can iterate over the rows in a list store (for row in liststore:...) as well as over the columns (values) in each row (for col_value in row:...).\nFor simple, direct updates:\nrow_n = 0\ncol_n = 2\nliststore[row_n][col_n] = 'new value'\n\nOtherwise, you can update using a gtk.TreeIter (row_iter):\nliststore.set_value(row_iter, col_n, 'new value')\n\n", "http://www.pygtk.org/pygtk2reference/class-gtkliststore.html\nYou need to use a gtk.TreeIter, also this has some good information.\nIf I were more familiar I could give you an example, I just remember that it's kind of a pain to use the gtk.liststore, but there's not really any better solution\n" ]
[ 10, 4 ]
[]
[]
[ "pygtk", "python" ]
stackoverflow_0003109684_pygtk_python.txt
Q: Exchange Oauth Request Token for Access Token fails Google API I am having trouble exchanging my Oauth request token for an Access Token. My Python application successfully asks for a Request Token and then redirects to the Google login page asking to grant access to my website. When I grant access I retrieve a 200 status code but exchanging this authorized request token for an access token gives me a 'The token is invalid' message. The Google Oauth documentation says: "Google redirects with token and verifier regardless of whether the token has been authorized." so it seems that authorizing the request token fails but then I am not sure how I should get an authorized request token. Any suggestions? A: When you're exchanging for the access token, the oauth_verifier parameter is required. If you don't provide that parameter, then google will tell you that the token is invalid.
Exchange Oauth Request Token for Access Token fails Google API
I am having trouble exchanging my Oauth request token for an Access Token. My Python application successfully asks for a Request Token and then redirects to the Google login page asking to grant access to my website. When I grant access I retrieve a 200 status code but exchanging this authorized request token for an access token gives me a 'The token is invalid' message. The Google Oauth documentation says: "Google redirects with token and verifier regardless of whether the token has been authorized." so it seems that authorizing the request token fails but then I am not sure how I should get an authorized request token. Any suggestions?
[ "When you're exchanging for the access token, the oauth_verifier parameter is required. If you don't provide that parameter, then google will tell you that the token is invalid.\n" ]
[ 1 ]
[]
[]
[ "google_api", "oauth", "python" ]
stackoverflow_0002306984_google_api_oauth_python.txt
Q: How to save user's daily progress? I'm building an app where I'm trying to store the user's progress on a game. I want to be able to store the score of a player on a daily basis, and then retrieve the day's score when I look for the date. I wanted to store a dictionary in the database, with keys being the dates when the user played and the values being the score, but I can't store a dictionary with GAE. How can I do? I'm using google appengine with python Thanks A: I think an easy way would be to create a db.Model to represent an entry in the dictionary you were originally thinking about. Just to sketch it out, what I mean is something similar to this: class DailyProgress(db.Model): date = db.DateTimeProperty(auto_now_add=True) score = db.IntegerProperty() Then, you could store a list of those for each of your users. A: A dictionary can be transformed back and forth between a list-of-tuples. aTupleOfTuples= tuple( someDict.items() ) aDict = dict( aTupleOfTuples ) This is probably what you're looking for. A: Either unpack the dictionary into a Datastore.Model or more quickly, but more opaquely pickle.dumps() the dictionary into a string and store that via Gql.
How to save user's daily progress?
I'm building an app where I'm trying to store the user's progress on a game. I want to be able to store the score of a player on a daily basis, and then retrieve the day's score when I look for the date. I wanted to store a dictionary in the database, with keys being the dates when the user played and the values being the score, but I can't store a dictionary with GAE. How can I do? I'm using google appengine with python Thanks
[ "I think an easy way would be to create a db.Model to represent an entry in the dictionary you were originally thinking about. Just to sketch it out, what I mean is something similar to this:\nclass DailyProgress(db.Model):\n date = db.DateTimeProperty(auto_now_add=True)\n score = db.IntegerProperty()\n\nThen, you could store a list of those for each of your users.\n", "A dictionary can be transformed back and forth between a list-of-tuples.\naTupleOfTuples= tuple( someDict.items() )\n\naDict = dict( aTupleOfTuples )\n\nThis is probably what you're looking for.\n", "Either unpack the dictionary into a Datastore.Model or more quickly, but more opaquely pickle.dumps() the dictionary into a string and store that via Gql.\n" ]
[ 3, 0, 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0003110892_google_app_engine_python.txt
Q: Python: Get name of shoutcast/internet radio station from url I've been trying to get the name/title of internet radio stations based on the url in python, but with no luck so far. It seems that internet radio stations use another protocol than HTTP, but please correct me if I'm wrong. For example: http://89.238.146.142:7030 Has the title: "Ibiza Global Radio" How can i store this title in a variable? Any help will be deeply appreciated :) Kind regards, frigg A: From a little curl, it seems to be using shoutcast protocol, so you're looking for an early line starting with icy-name: $ curl http://89.238.146.142:7030 | head -5 % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 100 13191 0 13191 0 0 16013 0 --:--:-- --:--:-- --:--:-- 28516ICY 200 OK icy-notice1:<BR>This stream requires <a href="http://www.winamp.com/">Winamp</a><BR> icy-notice2:SHOUTcast Distributed Network Audio Server/Linux v1.9.8<BR> icy-name:Ibiza Global Radio icy-genre:Electronic 100 33463 0 33463 0 0 30954 0 --:--:-- 0:00:01 --:--:-- 46579 curl: (23) Failed writing body $ Therefore: >>> import urllib2 >>> f = urllib2.urlopen('http://89.238.146.142:7030') >>> for i, line in enumerate(f): ... if line.startswith('icy-name') or i > 20: break ... >>> if i > 20: print 'failed to find station name' ... else: print 'station name is', line.replace('icy-name:', '') ... station name is Ibiza Global Radio >>> You may want to add e.g. some .lower() calls because I believe these header names are meant to be case-insensitive, but that's the general idea.
Python: Get name of shoutcast/internet radio station from url
I've been trying to get the name/title of internet radio stations based on the url in python, but with no luck so far. It seems that internet radio stations use another protocol than HTTP, but please correct me if I'm wrong. For example: http://89.238.146.142:7030 Has the title: "Ibiza Global Radio" How can i store this title in a variable? Any help will be deeply appreciated :) Kind regards, frigg
[ "From a little curl, it seems to be using shoutcast protocol, so you're looking for an early line starting with icy-name:\n$ curl http://89.238.146.142:7030 | head -5\n % Total % Received % Xferd Average Speed Time Time Time Current\n Dload Upload Total Spent Left Speed\n100 13191 0 13191 0 0 16013 0 --:--:-- --:--:-- --:--:-- 28516ICY 200 OK\nicy-notice1:<BR>This stream requires <a href=\"http://www.winamp.com/\">Winamp</a><BR>\nicy-notice2:SHOUTcast Distributed Network Audio Server/Linux v1.9.8<BR>\nicy-name:Ibiza Global Radio\nicy-genre:Electronic\n100 33463 0 33463 0 0 30954 0 --:--:-- 0:00:01 --:--:-- 46579\ncurl: (23) Failed writing body\n$ \n\nTherefore:\n>>> import urllib2\n>>> f = urllib2.urlopen('http://89.238.146.142:7030')\n>>> for i, line in enumerate(f):\n... if line.startswith('icy-name') or i > 20: break\n... \n>>> if i > 20: print 'failed to find station name'\n... else: print 'station name is', line.replace('icy-name:', '')\n... \nstation name is Ibiza Global Radio\n\n>>> \n\nYou may want to add e.g. some .lower() calls because I believe these header names are meant to be case-insensitive, but that's the general idea.\n" ]
[ 8 ]
[]
[]
[ "internet_radio", "python", "shoutcast" ]
stackoverflow_0003110494_internet_radio_python_shoutcast.txt
Q: write sorted results to file I have a simple function that sorts a dictionary: data = inputfile.readlines() lineData = sorted(data, key=len, reverse=True)[:3] Printing the output: print sorted(data, key=len, reverse=True)[:3] generates the expected result, however writing to file: outputfile.writelines sorted(data, key=len, reverse=True)[:3] generates nothing. How can I write the output to the text file (outputfile)? The complete code is as follows: import sys, string inputfilenames, outputfilename = sys.argv[1:-1], sys.argv[-1] def do_something_with_input(inputfile): data = inputfile.readlines() print sorted(data, key=len, reverse=True)[:3] print sys.path[0]+"/"+ outputfilename def write_results(outputfile): data = inputfile.readlines() outputfile.writelines(sorted(data, key=len, reverse=True)[:3]) for inputfilename in inputfilenames: inputfile = open(inputfilename, "r") do_something_with_input(inputfile) outputfile = open(outputfilename, "w") write_results(outputfile) A: writelines is a method, you need to call it: outputfile.writelines(sorted(data, key=len, reverse=True)[:3]) ETA Function open provides file handle which could be iterated over once. You do it in your do_something_with_input function, after the inputfile iterated over, iterator is exhausted. Which means any further iterations, such as done in your write_results functions would yield an empty sequence. That's why nothing is written to the output file. Basically, it is equivalent to: >>> a = (i for i in range(2)) >>> list(a) [0, 1] >>> list(a) [] What you need to do is store the output of the sorted(...) and then write it to the file, not try to generate it again. A: You write: outputfile.writelines sorted(data, key=len, reverse=True)[:3] generates nothing. it should actually generate a syntax-error exception because of the missing parentheses -- if it doesn't, I guess you must be using some (allegedly) "smart" IDE like iPython which puts in the parentheses on your behalf -- is that the case? You're printing the three shortest lines, and they well may all be empty -- that should put three empty lines in your output file (and of course show nothing to stdout -- is that what you mean by "generates nothing"?). Maybe you're not properly calling outputfile.close() so by the time you check the file they're still buffered and not written to disk yet. As you see there are a huge number of possibilities around your very ambiguous "generates nothing" assertion. Can you clarify exactly what environment you're using and how in particular you're checking what your code "generates" or doesn't? Otherwise, it's very hard to help you much. Edit: the OP clarified and showed his code -- and the problem is now clear: he's totally consuming inputfile the first time, never "rewinding" it, so the file immediately ends (no lines left in it) at the second readlines call. If you do need to read the file twice independently (rather than just reading it once and passing the data around, as would be normal), you'll need a call inputfile.seek(0) to "rewind the file" each time you read it to make it ready to be read all over again.
write sorted results to file
I have a simple function that sorts a dictionary: data = inputfile.readlines() lineData = sorted(data, key=len, reverse=True)[:3] Printing the output: print sorted(data, key=len, reverse=True)[:3] generates the expected result, however writing to file: outputfile.writelines sorted(data, key=len, reverse=True)[:3] generates nothing. How can I write the output to the text file (outputfile)? The complete code is as follows: import sys, string inputfilenames, outputfilename = sys.argv[1:-1], sys.argv[-1] def do_something_with_input(inputfile): data = inputfile.readlines() print sorted(data, key=len, reverse=True)[:3] print sys.path[0]+"/"+ outputfilename def write_results(outputfile): data = inputfile.readlines() outputfile.writelines(sorted(data, key=len, reverse=True)[:3]) for inputfilename in inputfilenames: inputfile = open(inputfilename, "r") do_something_with_input(inputfile) outputfile = open(outputfilename, "w") write_results(outputfile)
[ "writelines is a method, you need to call it:\noutputfile.writelines(sorted(data, key=len, reverse=True)[:3])\n\nETA\nFunction open provides file handle which could be iterated over once. You do it in your do_something_with_input function, after the inputfile iterated over, iterator is exhausted. Which means any further iterations, such as done in your write_results functions would yield an empty sequence. That's why nothing is written to the output file. Basically, it is equivalent to:\n>>> a = (i for i in range(2))\n>>> list(a)\n[0, 1]\n>>> list(a)\n[]\n\nWhat you need to do is store the output of the sorted(...) and then write it to the file, not try to generate it again.\n", "You write:\noutputfile.writelines sorted(data, key=len, reverse=True)[:3]\n\n\ngenerates nothing.\n\nit should actually generate a syntax-error exception because of the missing parentheses -- if it doesn't, I guess you must be using some (allegedly) \"smart\" IDE like iPython which puts in the parentheses on your behalf -- is that the case?\nYou're printing the three shortest lines, and they well may all be empty -- that should put three empty lines in your output file (and of course show nothing to stdout -- is that what you mean by \"generates nothing\"?). Maybe you're not properly calling outputfile.close() so by the time you check the file they're still buffered and not written to disk yet.\nAs you see there are a huge number of possibilities around your very ambiguous \"generates nothing\" assertion. Can you clarify exactly what environment you're using and how in particular you're checking what your code \"generates\" or doesn't? Otherwise, it's very hard to help you much.\nEdit: the OP clarified and showed his code -- and the problem is now clear: he's totally consuming inputfile the first time, never \"rewinding\" it, so the file immediately ends (no lines left in it) at the second readlines call. If you do need to read the file twice independently (rather than just reading it once and passing the data around, as would be normal), you'll need a call inputfile.seek(0) to \"rewind the file\" each time you read it to make it ready to be read all over again.\n" ]
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003110920_python.txt
Q: how to import Java class with Python using Eclipse? I'm trying to write Jython where the Python file imports classes from Java I'm using Eclipse with PyDev. My Python code looks like: from eclipsejavatest import eclipseJavaTest from eclipsejavatest import JavaClass class eclipsePyPrint(eclipseJavaTest): def eclipsepyMain(self): print "python main method" eclipseJavaTest.printerCount(4) print eclipseJavaTest.gotoPython() eclipseJavaTest.printerSentence() samplepyClass = JavaClass("Jython plain") samplepyClass.setName("jython fancy") print samplepyClass.getName() but I'm getting the error ImportError: No module named eclipsejavatest The Python project references the Java project. I've tried exporting the Java project and adding the .jar to the Jython Class Path for the Python project. I'm not sure what to do to get this to work. A: I am also using Eclipse with Pydev. I wanted to call Java classes from a Java project in my workspace from a program inside a Jython project folder. I did NOT have to right click on the java package and set it as a pydev project. In my setup the java source folder would not show up when I tried to add it to the PYTHONPATH regardless of whether I configured it as a Pydev folder. I had to add it as an external library. I right-clicked on the Jython project, selected properties, selected PyDev - PYTHONPATH, selected the External Libraries tab, and then selected the add source folder button. I added the folder with the .class files from the java project; C:\blah blah blah\workspace\javafoldername\bin. At first I tried to use ...\javafoldername\src to add the .java files but that didn't work. A: Figured it out - I had to right click the java package and set it as a pydev project Then I had to go into the python project and add the .class files A: Try : import eclipsejavatest.eclipseJavaTest as eclipseJavaTest
how to import Java class with Python using Eclipse?
I'm trying to write Jython where the Python file imports classes from Java I'm using Eclipse with PyDev. My Python code looks like: from eclipsejavatest import eclipseJavaTest from eclipsejavatest import JavaClass class eclipsePyPrint(eclipseJavaTest): def eclipsepyMain(self): print "python main method" eclipseJavaTest.printerCount(4) print eclipseJavaTest.gotoPython() eclipseJavaTest.printerSentence() samplepyClass = JavaClass("Jython plain") samplepyClass.setName("jython fancy") print samplepyClass.getName() but I'm getting the error ImportError: No module named eclipsejavatest The Python project references the Java project. I've tried exporting the Java project and adding the .jar to the Jython Class Path for the Python project. I'm not sure what to do to get this to work.
[ "I am also using Eclipse with Pydev. I wanted to call Java classes from a Java project in my workspace from a program inside a Jython project folder. I did NOT have to right click on the java package and set it as a pydev project. In my setup the java source folder would not show up when I tried to add it to the PYTHONPATH regardless of whether I configured it as a Pydev folder. I had to add it as an external library.\nI right-clicked on the Jython project, selected properties, selected PyDev - PYTHONPATH, selected the External Libraries tab, and then selected the add source folder button. I added the folder with the .class files from the java project; C:\\blah blah blah\\workspace\\javafoldername\\bin. At first I tried to use ...\\javafoldername\\src to add the .java files but that didn't work.\n", "Figured it out - \nI had to right click the java package and set it as a pydev project\nThen I had to go into the python project and add the .class files\n", "Try :\nimport eclipsejavatest.eclipseJavaTest as eclipseJavaTest\n\n" ]
[ 2, 1, 0 ]
[]
[]
[ "eclipse", "import", "java", "jython", "python" ]
stackoverflow_0002878468_eclipse_import_java_jython_python.txt
Q: Do a search-and-replace across all files in a folder through python? I'd like to learn to use python as a command line scripting replacement. I spent some time with python in the past but it's been a while. This seems to be within the scope of it. I have several files in a folder that I want to do a search-and-replace on, within all of them. I'd like to do it with a python script. For example, search and replace all instances of "foo" with "foobar". A: Welcome to StackOverflow. Since you want to learn yourself (+1) I'll just give you a few pointers. Check out os.walk() to get at all the files. Then iterate over each line in the files (for line in currentfile: comes in handy here). Now you need to know if you want a "stupid" replace (find/replace each foo even if it's in the middle of a word (say foobar - do you want foofoobar as a result?) or a smart replace. For the former, look at str.replace(), for the latter, look at re.sub() and figure out what r'\bfoo\b' means. A: Normally I'd whip out the old perl -pi -e 's/foo/foobar/' for this, but if you want Python: import os import re _replace_re = re.compile("foo") for dirpath, dirnames, filenames in os.walk("directory/"): for file in filenames: file = os.path.join(dirpath, file) tempfile = file + ".temp" with open(tempfile, "w") as target: with open(file) as source: for line in source: line = _replace_re.sub("foobar", line) target.write(line) os.rename(tempfile, file) And if you're on Windows, you'll need to add an os.remove(file) before the os.rename(tempfile, file). A: I worked through it and this seems to work, but any errors that can be pointed out would be awesome. import fileinput, sys, os def replaceAll(file, findexp, replaceexp): for line in fileinput.input(file, inplace=1): if findexp in line: line = line.replace(findexp, replaceexp) sys.stdout.write(line) if __name__ == '__main__': files = os.listdir("c:/testing/") for file in files: newfile = os.path.join("C:/testing/", file) replaceAll(newfile, "black", "white") an expansion on this would be to move to folders within folders. A: this is an alternative, since you have various Python solutions presented to you. The most useful utility (according to me), in Unix/Windows, is the GNU find command and replacement tools like sed/awk. to search for files (recursively) and do replacement, a simple command like this does the trick (syntax comes from memory and not tested). this says find all text files and change the word "old" to "new" in their contents, at the same time, use sed to backup the original files... $ find /path -type f -iname "*.txt" -exec sed -i.bak 's/old/new/g' "{}" +;
Do a search-and-replace across all files in a folder through python?
I'd like to learn to use python as a command line scripting replacement. I spent some time with python in the past but it's been a while. This seems to be within the scope of it. I have several files in a folder that I want to do a search-and-replace on, within all of them. I'd like to do it with a python script. For example, search and replace all instances of "foo" with "foobar".
[ "Welcome to StackOverflow. Since you want to learn yourself (+1) I'll just give you a few pointers.\nCheck out os.walk() to get at all the files.\nThen iterate over each line in the files (for line in currentfile: comes in handy here).\nNow you need to know if you want a \"stupid\" replace (find/replace each foo even if it's in the middle of a word (say foobar - do you want foofoobar as a result?) or a smart replace. \nFor the former, look at str.replace(), for the latter, look at re.sub() and figure out what r'\\bfoo\\b' means.\n", "Normally I'd whip out the old perl -pi -e 's/foo/foobar/' for this, but if you want Python:\nimport os\nimport re\n_replace_re = re.compile(\"foo\")\nfor dirpath, dirnames, filenames in os.walk(\"directory/\"):\n for file in filenames:\n file = os.path.join(dirpath, file)\n tempfile = file + \".temp\"\n with open(tempfile, \"w\") as target:\n with open(file) as source:\n for line in source:\n line = _replace_re.sub(\"foobar\", line)\n target.write(line)\n os.rename(tempfile, file)\n\nAnd if you're on Windows, you'll need to add an os.remove(file) before the os.rename(tempfile, file).\n", "I worked through it and this seems to work, but any errors that can be pointed out would be awesome. \nimport fileinput, sys, os\n\ndef replaceAll(file, findexp, replaceexp):\n for line in fileinput.input(file, inplace=1):\n if findexp in line:\n line = line.replace(findexp, replaceexp)\n sys.stdout.write(line)\n\nif __name__ == '__main__':\n files = os.listdir(\"c:/testing/\")\n for file in files:\n newfile = os.path.join(\"C:/testing/\", file)\n replaceAll(newfile, \"black\", \"white\")\n\nan expansion on this would be to move to folders within folders. \n", "this is an alternative, since you have various Python solutions presented to you. The most useful utility (according to me), in Unix/Windows, is the GNU find command and replacement tools like sed/awk. to search for files (recursively) and do replacement, a simple command like this does the trick (syntax comes from memory and not tested). this says find all text files and change the word \"old\" to \"new\" in their contents, at the same time, use sed to backup the original files...\n$ find /path -type f -iname \"*.txt\" -exec sed -i.bak 's/old/new/g' \"{}\" +;\n\n" ]
[ 5, 2, 1, 0 ]
[]
[]
[ "python", "scripting" ]
stackoverflow_0003110469_python_scripting.txt
Q: FTP and python question Can someone help me. Why it is not working import ftplib import os def readList(request): machine=[] login=[] password=[] for line in open("netrc"): #read netrc file old=line.strip() line=line.strip().split() if old.startswith("machine"): machine.append(line[-1]) if old.startswith("login"): login.append(line[-1]) if old.startswith("password"): password.append(line[-1]) connectFtp(machine,login,password) def connectFtp(machine,login,password): for i in range(len(machine)): try: ftp = ftplib.FTP(machine[i]) print 'conected to ' + machine[i] ftp.login(login[i],password[i]) print 'login - ' + login[i] + ' pasword -' + password[i] except Exception,e: print e else: ftp.cwd("PublicFolder") print 'PublicFolder' def upload(filename, file): readList() ext = os.path.splitext(file)[1] if ext in (".txt", ".htm", ".html"): ftp.storlines("STOR " + filename, open(file)) else: ftp.storbinary("STOR " + filename, open(file, "rb"), 1024) print 'success... yra' upload('test4.txt', r'c:\example2\media\uploads\test4.txt')` When it was together it was working. But when i separate it in to functions something happened, I cant understand what. A: (Apart from the horrid indentation problems, which are presumably due to botched copy and paste otherwise you'd get syntax errors up the wazoo...!)...: Scoping problem, first: connectFtp makes a local variable ftp so that variables goes away as soon as the function's done. Then upload tries using the variable, but of course it isn't there any more. Add a return ftp at the end of connectFtp, a yield connectFtp instead of a plain call to the loop in readList, and use a for ftp in readList(): loop in upload. A: Something like this? import os def readList(request): machine = [] login = [] password = [] for line in open("netrc"): # read netrc file old = line.strip() line = line.strip().split() if old.startswith("machine"): machine.append(line[-1]) if old.startswith("login"): login.append(line[-1]) if old.startswith("password"): password.append(line[-1]) yield connectFtp def connectFtp(machine, login, password): for i in range(len(machine)): try: ftp = ftplib.FTP(machine[i]) print 'conected to ' + machine[i] ftp.login(login[i], password[i]) print 'login - ' + login[i] + ' pasword -' + password[i] except Exception, e: print e else: ftp.cwd("PublicFolder") print 'PublicFolder' return (ftp) def upload(filename, file): for ftp in readList(): ext = os.path.splitext(file)[1] if ext in (".txt", ".htm", ".html"): ftp.storlines("STOR " + filename, open(file)) else: ftp.storbinary("STOR " + filename, open(file, "rb"), 1024) print 'success... yra' upload('test4.txt', r'c:\example2\media\uploads\test4.txt') Error at line 19 something with try: unindent does not math any outer indentation level
FTP and python question
Can someone help me. Why it is not working import ftplib import os def readList(request): machine=[] login=[] password=[] for line in open("netrc"): #read netrc file old=line.strip() line=line.strip().split() if old.startswith("machine"): machine.append(line[-1]) if old.startswith("login"): login.append(line[-1]) if old.startswith("password"): password.append(line[-1]) connectFtp(machine,login,password) def connectFtp(machine,login,password): for i in range(len(machine)): try: ftp = ftplib.FTP(machine[i]) print 'conected to ' + machine[i] ftp.login(login[i],password[i]) print 'login - ' + login[i] + ' pasword -' + password[i] except Exception,e: print e else: ftp.cwd("PublicFolder") print 'PublicFolder' def upload(filename, file): readList() ext = os.path.splitext(file)[1] if ext in (".txt", ".htm", ".html"): ftp.storlines("STOR " + filename, open(file)) else: ftp.storbinary("STOR " + filename, open(file, "rb"), 1024) print 'success... yra' upload('test4.txt', r'c:\example2\media\uploads\test4.txt')` When it was together it was working. But when i separate it in to functions something happened, I cant understand what.
[ "(Apart from the horrid indentation problems, which are presumably due to botched copy and paste otherwise you'd get syntax errors up the wazoo...!)...:\nScoping problem, first: connectFtp makes a local variable ftp so that variables goes away as soon as the function's done. Then upload tries using the variable, but of course it isn't there any more.\nAdd a return ftp at the end of connectFtp, a yield connectFtp instead of a plain call to the loop in readList, and use a for ftp in readList(): loop in upload.\n", "Something like this?\nimport os\n\n\ndef readList(request):\n machine = []\n login = []\n password = []\n for line in open(\"netrc\"): # read netrc file\n old = line.strip()\n line = line.strip().split()\n if old.startswith(\"machine\"): machine.append(line[-1])\n if old.startswith(\"login\"): login.append(line[-1])\n if old.startswith(\"password\"): password.append(line[-1])\n yield connectFtp\n\n\ndef connectFtp(machine, login, password):\n for i in range(len(machine)):\n\n\ntry:\n ftp = ftplib.FTP(machine[i])\n print 'conected to ' + machine[i]\n ftp.login(login[i], password[i])\n print 'login - ' + login[i] + ' pasword -' + password[i]\nexcept Exception, e:\n print e\nelse:\n ftp.cwd(\"PublicFolder\")\n print 'PublicFolder'\n return (ftp)\n\n\ndef upload(filename, file):\n for ftp in readList():\n ext = os.path.splitext(file)[1]\n if ext in (\".txt\", \".htm\", \".html\"):\n ftp.storlines(\"STOR \" + filename, open(file))\n else:\n ftp.storbinary(\"STOR \" + filename, open(file, \"rb\"), 1024)\n print 'success... yra'\n\nupload('test4.txt', r'c:\\example2\\media\\uploads\\test4.txt')\n\nError at line 19 something with try:\nunindent does not math any outer indentation level\n" ]
[ 0, 0 ]
[]
[]
[ "ftp", "ftplib", "python" ]
stackoverflow_0003111038_ftp_ftplib_python.txt
Q: Django import problem with models.py and multiple ManyToManyFields() I am working on creating a simple contest submission system using django. This is my first real django project. Basically each user can view a list of problems, submit a file, and view a results page. Each problem can be associated with multiple contests, and different contests can use the same problem. Because of this, both problem and contest have a manyToManyField with each other. This is what is causing my problem. Here is the initial models.py implementation I am going with: startfile from django.db import models class User(models.Model): username = models.CharField(max_length=50) firstname = models.CharField(max_length=50) lastname = models.CharField(max_length=50) class Problem(models.Model): name = models.CharField(max_length=50) filename = models.CharField(max_length=300) contests = models.ManyToManyField(Contest) class Contest(models.Model): name = models.CharField(max_length=50) problems = models.ManyToManyField(Problem) date = models.DateField() class Submission(models.Model): user = models.ForeignKey(User) problem = models.ForeignKey(Problem) filename = models.CharField(max_length=300) endfile Is there a simple way to fix this? Or should I rethink my entire layout? I tried breaking each class into its own django app but I don't think thats how I should do it. The error I get is that Contest can not be found (because it exists lower in the file). All advice is appreciated! A: You don't need a ManyToManyField in both Contest and Problem. Many-to-many fields are already bidirectional. Just put it on one - doesn't matter which. A: Djano will automatically create the reverse relation for you, so you only need to create it one end, eg. class Problem(models.Model): name = models.CharField(max_length=50) filename = models.CharField(max_length=300) contests = models.ManyToManyField(Contest, related_name='problems') related_name gives you the possibility to assign a name to the reverse relation. Without defining the relation on the Contest model, you can then access eg. a_contest.problems.all()!
Django import problem with models.py and multiple ManyToManyFields()
I am working on creating a simple contest submission system using django. This is my first real django project. Basically each user can view a list of problems, submit a file, and view a results page. Each problem can be associated with multiple contests, and different contests can use the same problem. Because of this, both problem and contest have a manyToManyField with each other. This is what is causing my problem. Here is the initial models.py implementation I am going with: startfile from django.db import models class User(models.Model): username = models.CharField(max_length=50) firstname = models.CharField(max_length=50) lastname = models.CharField(max_length=50) class Problem(models.Model): name = models.CharField(max_length=50) filename = models.CharField(max_length=300) contests = models.ManyToManyField(Contest) class Contest(models.Model): name = models.CharField(max_length=50) problems = models.ManyToManyField(Problem) date = models.DateField() class Submission(models.Model): user = models.ForeignKey(User) problem = models.ForeignKey(Problem) filename = models.CharField(max_length=300) endfile Is there a simple way to fix this? Or should I rethink my entire layout? I tried breaking each class into its own django app but I don't think thats how I should do it. The error I get is that Contest can not be found (because it exists lower in the file). All advice is appreciated!
[ "You don't need a ManyToManyField in both Contest and Problem. Many-to-many fields are already bidirectional. Just put it on one - doesn't matter which.\n", "Djano will automatically create the reverse relation for you, so you only need to create it one end, eg.\nclass Problem(models.Model):\n name = models.CharField(max_length=50)\n filename = models.CharField(max_length=300)\n contests = models.ManyToManyField(Contest, related_name='problems')\n\nrelated_name gives you the possibility to assign a name to the reverse relation. Without defining the relation on the Contest model, you can then access eg. a_contest.problems.all()!\n" ]
[ 2, 1 ]
[]
[]
[ "django", "python", "web_applications" ]
stackoverflow_0003110944_django_python_web_applications.txt
Q: Python performance: Try-except or not in? In one of my classes I have a number of methods that all draw values from the same dictionaries. However, if one of the methods tries to access a value that isn't there, it has to call another method to make the value associated with that key. I currently have this implemented as follows, where findCrackDepth(tonnage) assigns a value to self.lowCrackDepth[tonnage]. if tonnage not in self.lowCrackDepth: self.findCrackDepth(tonnage) lcrack = self.lowCrackDepth[tonnage] However, it would also be possible for me to do this as try: lcrack = self.lowCrackDepth[tonnage] except KeyError: self.findCrackDepth(tonnage) lcrack = self.lowCrackDepth[tonnage] I assume there is a performance difference between the two related to how often the values is already in the dictionary. How big is this difference? I'm generating a few million such values (spread across a many dictionaries in many instances of the class), and for each time the value doesn't exist, there are probably two times where it does. A: It's a delicate problem to time this because you need care to avoid "lasting side effects" and the performance tradeoff depends on the % of missing keys. So, consider a dil.py file as follows: def make(percentmissing): global d d = dict.fromkeys(range(100-percentmissing), 1) def addit(d, k): d[k] = k def with_in(): dc = d.copy() for k in range(100): if k not in dc: addit(dc, k) lc = dc[k] def with_ex(): dc = d.copy() for k in range(100): try: lc = dc[k] except KeyError: addit(dc, k) lc = dc[k] def with_ge(): dc = d.copy() for k in range(100): lc = dc.get(k) if lc is None: addit(dc, k) lc = dc[k] and a series of timeit calls such as: $ python -mtimeit -s'import dil; dil.make(10)' 'dil.with_in()' 10000 loops, best of 3: 28 usec per loop $ python -mtimeit -s'import dil; dil.make(10)' 'dil.with_ex()' 10000 loops, best of 3: 41.7 usec per loop $ python -mtimeit -s'import dil; dil.make(10)' 'dil.with_ge()' 10000 loops, best of 3: 46.6 usec per loop this shows that, with 10% missing keys, the in check is substantially the fastest way. $ python -mtimeit -s'import dil; dil.make(1)' 'dil.with_in()' 10000 loops, best of 3: 24.6 usec per loop $ python -mtimeit -s'import dil; dil.make(1)' 'dil.with_ex()' 10000 loops, best of 3: 23.4 usec per loop $ python -mtimeit -s'import dil; dil.make(1)' 'dil.with_ge()' 10000 loops, best of 3: 42.7 usec per loop with just 1% missing keys, the exception approach is marginally fastest (and the get approach remains the slowest one in either case). So, for optimal performance, unless the vast majority (99%+) of lookups is going to succeed, the in approach is preferable. Of course, there's another, elegant possibility: adding a dict subclass like...: class dd(dict): def __init__(self, *a, **k): dict.__init__(self, *a, **k) def __missing__(self, k): addit(self, k) return self[k] def with_dd(): dc = dd(d) for k in range(100): lc = dc[k] However...: $ python -mtimeit -s'import dil; dil.make(1)' 'dil.with_dd()' 10000 loops, best of 3: 46.1 usec per loop $ python -mtimeit -s'import dil; dil.make(10)' 'dil.with_dd()' 10000 loops, best of 3: 55 usec per loop ...while slick indeed, this is not a performance winner -- it's about even with the get approach, or slower, just with much nicer-looking code to use it. (defaultdict, semantically analogous to this dd class, would be a performance win if it was applicable, but that's because the __missing__ special method, in that case, is implemented in well optimized C code). A: Checking if a key exists is cheaper or at least as cheap as retrieving it. So use the if not in solution which is much cleaner and more readable. According to your question a key not existing is not an error-like case so there's no good reason to let python raise an exception (even though you catch it immediately), and if you have a if not in check, everyone knows your intention - to get the existing value or otherwise generate it. A: When in doubt, profile. Run a test to see if, in your environment, one runs faster than another. A: If it is exceptional, use an exception. If you expect the key to be in there, use try/except, if you don't know whether the key is in there, use not in. A: I believe the .get() method of a dict has a parameter for setting the default value. You could use that and have it in one line. I'm not sure how it affects performance though.
Python performance: Try-except or not in?
In one of my classes I have a number of methods that all draw values from the same dictionaries. However, if one of the methods tries to access a value that isn't there, it has to call another method to make the value associated with that key. I currently have this implemented as follows, where findCrackDepth(tonnage) assigns a value to self.lowCrackDepth[tonnage]. if tonnage not in self.lowCrackDepth: self.findCrackDepth(tonnage) lcrack = self.lowCrackDepth[tonnage] However, it would also be possible for me to do this as try: lcrack = self.lowCrackDepth[tonnage] except KeyError: self.findCrackDepth(tonnage) lcrack = self.lowCrackDepth[tonnage] I assume there is a performance difference between the two related to how often the values is already in the dictionary. How big is this difference? I'm generating a few million such values (spread across a many dictionaries in many instances of the class), and for each time the value doesn't exist, there are probably two times where it does.
[ "It's a delicate problem to time this because you need care to avoid \"lasting side effects\" and the performance tradeoff depends on the % of missing keys. So, consider a dil.py file as follows:\ndef make(percentmissing):\n global d\n d = dict.fromkeys(range(100-percentmissing), 1)\n\ndef addit(d, k):\n d[k] = k\n\ndef with_in():\n dc = d.copy()\n for k in range(100):\n if k not in dc:\n addit(dc, k)\n lc = dc[k]\n\ndef with_ex():\n dc = d.copy()\n for k in range(100):\n try: lc = dc[k]\n except KeyError:\n addit(dc, k)\n lc = dc[k]\n\ndef with_ge():\n dc = d.copy()\n for k in range(100):\n lc = dc.get(k)\n if lc is None:\n addit(dc, k)\n lc = dc[k]\n\nand a series of timeit calls such as:\n$ python -mtimeit -s'import dil; dil.make(10)' 'dil.with_in()'\n10000 loops, best of 3: 28 usec per loop\n$ python -mtimeit -s'import dil; dil.make(10)' 'dil.with_ex()'\n10000 loops, best of 3: 41.7 usec per loop\n$ python -mtimeit -s'import dil; dil.make(10)' 'dil.with_ge()'\n10000 loops, best of 3: 46.6 usec per loop\n\nthis shows that, with 10% missing keys, the in check is substantially the fastest way.\n$ python -mtimeit -s'import dil; dil.make(1)' 'dil.with_in()'\n10000 loops, best of 3: 24.6 usec per loop\n$ python -mtimeit -s'import dil; dil.make(1)' 'dil.with_ex()'\n10000 loops, best of 3: 23.4 usec per loop\n$ python -mtimeit -s'import dil; dil.make(1)' 'dil.with_ge()'\n10000 loops, best of 3: 42.7 usec per loop\n\nwith just 1% missing keys, the exception approach is marginally fastest (and the get approach remains the slowest one in either case).\nSo, for optimal performance, unless the vast majority (99%+) of lookups is going to succeed, the in approach is preferable.\nOf course, there's another, elegant possibility: adding a dict subclass like...:\nclass dd(dict):\n def __init__(self, *a, **k):\n dict.__init__(self, *a, **k)\n def __missing__(self, k):\n addit(self, k)\n return self[k]\n\ndef with_dd():\n dc = dd(d)\n for k in range(100):\n lc = dc[k]\n\nHowever...:\n$ python -mtimeit -s'import dil; dil.make(1)' 'dil.with_dd()'\n10000 loops, best of 3: 46.1 usec per loop\n$ python -mtimeit -s'import dil; dil.make(10)' 'dil.with_dd()'\n10000 loops, best of 3: 55 usec per loop\n\n...while slick indeed, this is not a performance winner -- it's about even with the get approach, or slower, just with much nicer-looking code to use it. (defaultdict, semantically analogous to this dd class, would be a performance win if it was applicable, but that's because the __missing__ special method, in that case, is implemented in well optimized C code).\n", "Checking if a key exists is cheaper or at least as cheap as retrieving it. So use the if not in solution which is much cleaner and more readable.\nAccording to your question a key not existing is not an error-like case so there's no good reason to let python raise an exception (even though you catch it immediately), and if you have a if not in check, everyone knows your intention - to get the existing value or otherwise generate it.\n", "When in doubt, profile.\nRun a test to see if, in your environment, one runs faster than another.\n", "If it is exceptional, use an exception. If you expect the key to be in there, use try/except, if you don't know whether the key is in there, use not in.\n", "I believe the .get() method of a dict has a parameter for setting the default value. You could use that and have it in one line. I'm not sure how it affects performance though.\n" ]
[ 14, 3, 2, 1, 0 ]
[]
[]
[ "performance", "python" ]
stackoverflow_0003111195_performance_python.txt
Q: Which of these is a good way to request an API? Whenever looking at API libraries for Python, there seems to be about half of them simply using: response = urllib2.urlopen('https://www.example.com/api', data) and about half using: connection = httplib.HTTPSConnection('www.example.com/api') # ... rest omitted for simplicity I tend to think the second version is "cooler" (I'm biased towards a more OO approach to most things). Is there a benefit or reason for using one over the other. Or, am I missing something along the way. I would suspect that urllib2.urlopen uses HTTPSConnection in its implementation, so perhaps one is simply less coding on my behalf. Whichever way, I'd love some feedback. Thanks. A: Yep, urllib2 uses HTTPSConnection (or whatever kind of connection is appropriate for the protocol) in its implementation. It's basically just a shortcut to do the most common thing people do with httplib. urllib2 also has some code to handle things like redirects and authentication requests, all stuff you might have to code manually if you were doing it with plain httplib. EDIT: In response to Michael's comment, if you were wondering about object vs. data... it sort of depends on what you're going to do with it. If you need the connection object (e.g. to do something special with it, maybe a keepalive connection), then sure, go ahead and use the httplib way and return the connection object. But if you're just trying to get the data, just get the data and return it. If you like OOP, know that everything in Python technically is an object; what you get from urllib2.urlopen is a file-like object which has methods to retrieve its value as a string object or as a list of lines (also string objects). I think most Python programmers would consider it a waste of effort to use httplib in the latter case.
Which of these is a good way to request an API?
Whenever looking at API libraries for Python, there seems to be about half of them simply using: response = urllib2.urlopen('https://www.example.com/api', data) and about half using: connection = httplib.HTTPSConnection('www.example.com/api') # ... rest omitted for simplicity I tend to think the second version is "cooler" (I'm biased towards a more OO approach to most things). Is there a benefit or reason for using one over the other. Or, am I missing something along the way. I would suspect that urllib2.urlopen uses HTTPSConnection in its implementation, so perhaps one is simply less coding on my behalf. Whichever way, I'd love some feedback. Thanks.
[ "Yep, urllib2 uses HTTPSConnection (or whatever kind of connection is appropriate for the protocol) in its implementation. It's basically just a shortcut to do the most common thing people do with httplib.\nurllib2 also has some code to handle things like redirects and authentication requests, all stuff you might have to code manually if you were doing it with plain httplib.\nEDIT: In response to Michael's comment, if you were wondering about object vs. data... it sort of depends on what you're going to do with it. If you need the connection object (e.g. to do something special with it, maybe a keepalive connection), then sure, go ahead and use the httplib way and return the connection object. But if you're just trying to get the data, just get the data and return it. If you like OOP, know that everything in Python technically is an object; what you get from urllib2.urlopen is a file-like object which has methods to retrieve its value as a string object or as a list of lines (also string objects). I think most Python programmers would consider it a waste of effort to use httplib in the latter case.\n" ]
[ 4 ]
[]
[]
[ "api", "python", "urlopen" ]
stackoverflow_0003112452_api_python_urlopen.txt
Q: Python - merging many url's and parsing them Below is script that I found on forum, and it is almost exactly what I need except I need to read like 30 different url's and print them all together.I have tried few options but script just breaks. How can I merge all 30's urls, parse, and than print them out. If you can help me I would be very greatful, ty. import sys import string from urllib2 import urlopen import xml.dom.minidom var_xml = urlopen("http://www.test.com/bla/bla.xml") var_all = xml.dom.minidom.parse(var_xml) def extract_content(var_all, var_tag, var_loop_count): return var_all.firstChild.getElementsByTagName(var_tag)[var_loop_count].firstChild.data var_loop_count = 0 var_item = " " while len(var_item) > 0: var_title = extract_content(var_all, "title", var_loop_count) var_date = extract_content(var_all, "pubDate", var_loop_count) print "Title: ", var_title print "Published Date: ", var_date print " " var_loop_count += 1 try: var_item = var_all.firstChild.getElementsByTagName("item")[var_loop_count].firstChild.data except: var_item = "" A: If this is standard RSS, I'd encourage to use http://www.feedparser.org/ ; extracting all items there is straightforward. A: You are overwriting var_item, var_title, var_date. each loop. Make a list of these items, and put each var_item, var_title, var_date in the list. At the end, just print out your list. http://docs.python.org/tutorial/datastructures.html
Python - merging many url's and parsing them
Below is script that I found on forum, and it is almost exactly what I need except I need to read like 30 different url's and print them all together.I have tried few options but script just breaks. How can I merge all 30's urls, parse, and than print them out. If you can help me I would be very greatful, ty. import sys import string from urllib2 import urlopen import xml.dom.minidom var_xml = urlopen("http://www.test.com/bla/bla.xml") var_all = xml.dom.minidom.parse(var_xml) def extract_content(var_all, var_tag, var_loop_count): return var_all.firstChild.getElementsByTagName(var_tag)[var_loop_count].firstChild.data var_loop_count = 0 var_item = " " while len(var_item) > 0: var_title = extract_content(var_all, "title", var_loop_count) var_date = extract_content(var_all, "pubDate", var_loop_count) print "Title: ", var_title print "Published Date: ", var_date print " " var_loop_count += 1 try: var_item = var_all.firstChild.getElementsByTagName("item")[var_loop_count].firstChild.data except: var_item = ""
[ "If this is standard RSS, I'd encourage to use http://www.feedparser.org/ ; extracting all items there is straightforward. \n", "You are overwriting var_item, var_title, var_date. each loop. Make a list of these items, and put each var_item, var_title, var_date in the list. At the end, just print out your list.\nhttp://docs.python.org/tutorial/datastructures.html\n" ]
[ 0, 0 ]
[]
[]
[ "python", "rss", "urlopen", "xml" ]
stackoverflow_0003112548_python_rss_urlopen_xml.txt
Q: Where can I get Twisted ? Official site seems hacked the official site of Twisted is down (parked by advertisment). I just bought a book about Twisted Network Programming Essentials. Chapter 1 is getting Twisted and setting it up. But with the site down, I don't find where to download Twisted and get extra docs about it. Could somebody point me to a mirror ? A: You could download it from pypi: http://pypi.python.org/pypi/Twisted A: Ok so thanks to the people at linuxfr.org and on twisted irc channel, we now know we can access the site from http://66.35.39.65/trac/ and that the site will be back shortly. Thanks everyone. A: The official site was not "hacked", its domain name registration expired for a couple of hours. The problem has since been corrected.
Where can I get Twisted ? Official site seems hacked
the official site of Twisted is down (parked by advertisment). I just bought a book about Twisted Network Programming Essentials. Chapter 1 is getting Twisted and setting it up. But with the site down, I don't find where to download Twisted and get extra docs about it. Could somebody point me to a mirror ?
[ "You could download it from pypi:\nhttp://pypi.python.org/pypi/Twisted\n", "Ok so thanks to the people at linuxfr.org and on twisted irc channel, we now know we can access the site from http://66.35.39.65/trac/ and that the site will be back shortly. Thanks everyone.\n", "The official site was not \"hacked\", its domain name registration expired for a couple of hours. The problem has since been corrected.\n" ]
[ 0, 0, 0 ]
[]
[]
[ "python", "twisted" ]
stackoverflow_0003110025_python_twisted.txt
Q: os.path.exists() lies I'm running a number of python scripts on a linux cluster, and the output from one job is generally the input to another script, potentially run on another node. I find that there is some not insignificant lag before python notices files that have been created on other nodes -- os.path.exists() returns false and open() fails as well. I can do a while not os.path.exists(mypath) loop until the file appears, and it can take upwards of a full minute, which is not optimal in a pipeline with many steps and potentially running many datasets in parallel. The only workaround I've found so far is to call subprocess.Popen("ls %s"%(pathdir), shell=True), which magically fixes the problem. I figure this is probably a system problem, but any way python might be causing this? Some sort of cache or something? My sysadmin hasn't been much help so far. A: os.path.exists() just calls the C library's stat() function. I believe you're running into a cache in the kernel's NFS implementation. Below is a link to a page that describes the problem as well as some methods to flush the cache. File Handle Caching Directories cache file names to file handles mapping. The most common problems with this are: •You have an opened file, and you need to check if the file has been replaced by a newer file. You have to flush the parent directory's file handle cache before stat() returns the new file's information and not the opened file's. ◦Actually this case has another problem: The old file may have been deleted and replaced by a new file, but both of the files may have the same inode. You can check this case by flushing the open file's attribute cache and then seeing if fstat() fails with ESTALE. •You need to check if a file exists. For example a lock file. Kernel may have cached that the file does not exist, even if in reality it does. You have to flush the parent directory's negative file handle cache to to see if the file really exists. A few ways to flush the file handle cache: •If the parent directory's mtime changed, the file handle cache gets flushed by flushing its attribute cache. This should work quite well if the NFS server supports nanosecond or microsecond resolution. •Linux: chown() the directory to its current owner. The file handle cache is flushed if the call returns successfully. •Solaris 9, 10: The only way is to try to rmdir() the parent directory. ENOTEMPTY means the cache is flushed. Trying to rmdir() the current directory fails with EINVAL and doesn't flush the cache. •FreeBSD 6.2: The only way is to try to rmdir() either the parent directory or the file under it. ENOTEMPTY, ENOTDIR and EACCES failures mean the cache is flushed, but ENOENT did not flush it. FreeBSD does not cache negative entries, so they do not have to be flushed. http://web.archive.org/web/20100912144722/http://www.unixcoding.org/NFSCoding A: The problem is related to the fact that the Python process runs in its own shell. When you run subprocess.Popen(shell=True) you are spawning a new shell, which is working around the issue you're experiencing. Python is not causing this issue. It's a combination of how NFS (file storage) and directory listings function in Linux.
os.path.exists() lies
I'm running a number of python scripts on a linux cluster, and the output from one job is generally the input to another script, potentially run on another node. I find that there is some not insignificant lag before python notices files that have been created on other nodes -- os.path.exists() returns false and open() fails as well. I can do a while not os.path.exists(mypath) loop until the file appears, and it can take upwards of a full minute, which is not optimal in a pipeline with many steps and potentially running many datasets in parallel. The only workaround I've found so far is to call subprocess.Popen("ls %s"%(pathdir), shell=True), which magically fixes the problem. I figure this is probably a system problem, but any way python might be causing this? Some sort of cache or something? My sysadmin hasn't been much help so far.
[ "os.path.exists() just calls the C library's stat() function. \nI believe you're running into a cache in the kernel's NFS implementation. Below is a link to a page that describes the problem as well as some methods to flush the cache.\n\nFile Handle Caching\nDirectories cache file names to file handles mapping. The most common problems with this are:\n•You have an opened file, and you need to check if the file has been replaced by a newer file. You have to flush the parent directory's file handle cache before stat() returns the new file's information and not the opened file's. \n◦Actually this case has another problem: The old file may have been deleted and replaced by a new file, but both of the files may have the same inode. You can check this case by flushing the open file's attribute cache and then seeing if fstat() fails with ESTALE. \n•You need to check if a file exists. For example a lock file. Kernel may have cached that the file does not exist, even if in reality it does. You have to flush the parent directory's negative file handle cache to to see if the file really exists. \nA few ways to flush the file handle cache:\n•If the parent directory's mtime changed, the file handle cache gets flushed by flushing its attribute cache. This should work quite well if the NFS server supports nanosecond or microsecond resolution. \n•Linux: chown() the directory to its current owner. The file handle cache is flushed if the call returns successfully. \n•Solaris 9, 10: The only way is to try to rmdir() the parent directory. ENOTEMPTY means the cache is flushed. Trying to rmdir() the current directory fails with EINVAL and doesn't flush the cache. \n•FreeBSD 6.2: The only way is to try to rmdir() either the parent directory or the file under it. ENOTEMPTY, ENOTDIR and EACCES failures mean the cache is flushed, but ENOENT did not flush it. FreeBSD does not cache negative entries, so they do not have to be flushed. \n\nhttp://web.archive.org/web/20100912144722/http://www.unixcoding.org/NFSCoding\n", "The problem is related to the fact that the Python process runs in its own shell. When you run subprocess.Popen(shell=True) you are spawning a new shell, which is working around the issue you're experiencing.\nPython is not causing this issue. It's a combination of how NFS (file storage) and directory listings function in Linux.\n" ]
[ 16, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003112546_python.txt
Q: Making Python sockets visible for outside world? i already have a post which is quite similiar, but i am getting more and more frustrated because it seems nothing is wrong with my network setup. Other software can be seen from the outside (netcat listen servers etc.) but not my scripts.. How can this be?? Note: It works on LAN but not over the internet. Server: import socket host = '' port = 80001 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((host,port)) s.listen(1) print 'Listening..' conn, addr = s.accept() print 'is up and running.' print addr, 'connected.' s.close() print 'shut down.' Client: import socket host = '80.xxx.xxx.xxx' port = 80001 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((host,port)) s.close() Somebody please help me. Any help is greatly appreciated. Jake A: Edited again to add: I think you may be missing some basics on socket communication. In order for sockets to work, you need to ensure that the sockets on both your client and server will meet. With your latest revision, your server is now bound to port 63001, but on the local loopback adapter: 127.0.0.1 Computers have multiple network adapters, at least 2: one is the local loopback, which allows you to make network connections to the same machine in a fast, performant manner (for testing, ipc etc), and a network adapter that lets you connect to an actual network. Many computers may have many more adapters (virtual adapters for vlans, wireless vs wired adapters etc), but they will have at least 2. So in your server application, you need to instruct it to bind the socket to the proper network adapter. host = '' port = 63001 bind(host,port) What this does in python is binds the socket to the loopback adapter (or 127.0.0.1/localhost). In your client application you have: host = '80.xxx.xxx.xxx' port = 63001 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((host,port)) Now what your client attempts to do is to connect to a socket to port 63001 on 80.xxx.xxx.xxx (which is your wireless internet adapter). Since your server is listening on your loopback adapter, and your client is trying to connect on your wireless adapter, it's failing, because the two ends don't meet. So you have two solutions here: Change the client to connect to localhost by host = 127.0.0.1 Change the server to bind to your internet adapter by changing host = 80.xxx.xxx.xxx Now the first solution, using localhost, will only work when your server and client are on the same machine. Localhost always points back to itself (hence loopback), no matter what machine you try. So if/when you decide to take your client/server to the internet, you will have to bind to a network adapter that is on the internet. Edited to add:** Okay with your latest revision it still won't work because 65535 is the largest post available. Answer below was to the original revision of the question. In your code posted, you're listening (bound) on port 63001, but your client application is trying to connect to port 80. Thats why your client can't talk to your server. Your client needs to connect using port 63001 not port 80. Also, unless you're running an HTTP server (or your python server will handle HTTP requests), you really shouldn't bind to port 80. In your client code change: import socket host = '80.xxx.xxx.xxx' port = 63001 And in your Server Code: import socket host = '' port = 63001 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((socket.gethostbyname(socket.gethostname()), port )) A: In your server script you have port = 80, but you don't ever use it. It looks like the server is listening on 63001. And the client is connecting to 80. If you're going to use 80, make sure you don't have an http server trying to use the port at the same time as well.
Making Python sockets visible for outside world?
i already have a post which is quite similiar, but i am getting more and more frustrated because it seems nothing is wrong with my network setup. Other software can be seen from the outside (netcat listen servers etc.) but not my scripts.. How can this be?? Note: It works on LAN but not over the internet. Server: import socket host = '' port = 80001 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((host,port)) s.listen(1) print 'Listening..' conn, addr = s.accept() print 'is up and running.' print addr, 'connected.' s.close() print 'shut down.' Client: import socket host = '80.xxx.xxx.xxx' port = 80001 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((host,port)) s.close() Somebody please help me. Any help is greatly appreciated. Jake
[ "Edited again to add:\nI think you may be missing some basics on socket communication. In order for sockets to work, you need to ensure that the sockets on both your client and server will meet. With your latest revision, your server is now bound to port 63001, but on the local loopback adapter: 127.0.0.1\nComputers have multiple network adapters, at least 2: one is the local loopback, which allows you to make network connections to the same machine in a fast, performant manner (for testing, ipc etc), and a network adapter that lets you connect to an actual network. Many computers may have many more adapters (virtual adapters for vlans, wireless vs wired adapters etc), but they will have at least 2.\nSo in your server application, you need to instruct it to bind the socket to the proper network adapter.\nhost = ''\nport = 63001\n\n\nbind(host,port)\n\nWhat this does in python is binds the socket to the loopback adapter (or 127.0.0.1/localhost).\nIn your client application you have:\nhost = '80.xxx.xxx.xxx'\nport = 63001\n\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ns.connect((host,port))\n\nNow what your client attempts to do is to connect to a socket to port 63001 on 80.xxx.xxx.xxx (which is your wireless internet adapter).\nSince your server is listening on your loopback adapter, and your client is trying to connect on your wireless adapter, it's failing, because the two ends don't meet.\nSo you have two solutions here:\n\nChange the client to connect to localhost by host = 127.0.0.1\n\nChange the server to bind to your internet adapter by changing host = 80.xxx.xxx.xxx\nNow the first solution, using localhost, will only work when your server and client are on the same machine. Localhost always points back to itself (hence loopback), no matter what machine you try. So if/when you decide to take your client/server to the internet, you will have to bind to a network adapter that is on the internet.\n\n\nEdited to add:**\nOkay with your latest revision it still won't work because 65535 is the largest post available.\nAnswer below was to the original revision of the question.\nIn your code posted, you're listening (bound) on port 63001, but your client application is trying to connect to port 80. Thats why your client can't talk to your server. Your client needs to connect using port 63001 not port 80.\nAlso, unless you're running an HTTP server (or your python server will handle HTTP requests), you really shouldn't bind to port 80.\nIn your client code change:\nimport socket\nhost = '80.xxx.xxx.xxx'\nport = 63001\n\nAnd in your Server Code:\nimport socket\n\nhost = ''\nport = 63001\n\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ns.bind((socket.gethostbyname(socket.gethostname()), port ))\n\n", "In your server script you have port = 80, but you don't ever use it. It looks like the server is listening on 63001. And the client is connecting to 80.\nIf you're going to use 80, make sure you don't have an http server trying to use the port at the same time as well.\n" ]
[ 9, 1 ]
[]
[]
[ "client", "python", "sockets" ]
stackoverflow_0003112980_client_python_sockets.txt
Q: Determine MP3 bit depth in Python via Mutagen Is there a way to determine an MP3 file's encoded bit depth (ie 8, 16, 24, 32) in Python using the Mutagen library? A: The transformations done by the MP3 encoding process drop completely the concept of “bit depth”. You can only know the bit depth of the source audio if such information was stored in a tag of the MP3 file. Otherwise, you can take the MP3 data and produce 8-bit, 16-bit or 24-bit audio. A: I've not heard "bit depth" with regard to mp3s so I'm assuming you mean bit rate. From the Mutagen tutorial: from mutagen.mp3 import MP3 audio = MP3("example.mp3") print audio.info.length, audio.info.bitrate That second portion (audio.info.bitrate) should be what you need.
Determine MP3 bit depth in Python via Mutagen
Is there a way to determine an MP3 file's encoded bit depth (ie 8, 16, 24, 32) in Python using the Mutagen library?
[ "The transformations done by the MP3 encoding process drop completely the concept of “bit depth”. You can only know the bit depth of the source audio if such information was stored in a tag of the MP3 file. Otherwise, you can take the MP3 data and produce 8-bit, 16-bit or 24-bit audio.\n", "I've not heard \"bit depth\" with regard to mp3s so I'm assuming you mean bit rate. From the Mutagen tutorial:\nfrom mutagen.mp3 import MP3\naudio = MP3(\"example.mp3\")\nprint audio.info.length, audio.info.bitrate\n\nThat second portion (audio.info.bitrate) should be what you need.\n" ]
[ 4, 0 ]
[]
[]
[ "lame", "mp3", "mutagen", "python" ]
stackoverflow_0002909605_lame_mp3_mutagen_python.txt
Q: Path in variable How can I add letter to path? For example if i have a path like 'c:\example2\media\uploads\test5.txt' (stored in a variable), but I need something like r'c:\example2\media\uploads\test5.txt', how can I add letter `r? Because the function open() does not want to open the first path. When I try add path to function open() it gives me an error and path like this: u'c:\\example2\\media\\uploads\\test5.txt' and says that file or directory is absent. What should i do? Error looks like: [Error 3] The system cannot find the path specified: u'C:\\example2\\media\\upload\\ZipFile.zip' when i do this open('c:\example2\media\uploads\test5.txt') it not work. And gives me error ( which you can see on the top) A: From the error message it is clear that the string is stored in the correct format (backslashes are escaped by doubling). So it seems the path is wrong, and the file is indeed absent. On the other hand, in your second example that you added in your edit, you use open('c:\example2\media\uploads\test5.txt') - this will definitely fail because \t is a tab character (whereas all the other backslash-letter combinations don't exist, so the backslash will be treated like it was escaped correctly). But you said that the string was stored in a variable, so I don't see how this example helps here. Consider the following: >>> path = 'c:\example2\media\uploads\test5.txt' >>> path 'c:\\example2\\media\\uploads\test5.txt' See? All the backslashes are converted to escaped backslashes except for the \t one because that's the only one with special meaning. And now, of course, this path is wrong. So if the variables you're referring to have been defined this way (and now contain invalid paths) there's not much you can do except fix the source: >>> path = r'c:\example2\media\uploads\test5.txt' >>> path 'c:\\example2\\media\\uploads\\test5.txt' You might think you could "fix" a defective path afterwards like this: >>> path = 'c:\example2\media\uploads\test5.txt' >>> path.replace("\t","\\t") 'c:\\example2\\media\\uploads\\test5.txt' ...but there are many other escape codes (\b, \r, \n etc.), so that's not really a feasible way, especially because you'd be doctoring around the symptoms instead of fixing the underlying problem. A: well is it upload or uploads? Your question says the one, but your error says the other. The 'u' at the beginning indicates that the string is unicode format, this shouldn't have any impact. the '\\' character is necessary for python to escape the '\' character. A: The letter 'r' is for the Python interpreter only. It indicates, that interpreter shouldn't escape any sequences, when parsing a string. If the string is already stored in a variable, there is nothing to do with the 'r' letter. I guess the problem is that there is actualy no such file. Try copying this line you get in the exception (the path from that line I mean) and pasting it into windows run dialog (Win+r will show it up). Then hit 'enter'. If you get an error, check the paths. You have both upload and uploads in your question, make sure you use the right one in your code.
Path in variable
How can I add letter to path? For example if i have a path like 'c:\example2\media\uploads\test5.txt' (stored in a variable), but I need something like r'c:\example2\media\uploads\test5.txt', how can I add letter `r? Because the function open() does not want to open the first path. When I try add path to function open() it gives me an error and path like this: u'c:\\example2\\media\\uploads\\test5.txt' and says that file or directory is absent. What should i do? Error looks like: [Error 3] The system cannot find the path specified: u'C:\\example2\\media\\upload\\ZipFile.zip' when i do this open('c:\example2\media\uploads\test5.txt') it not work. And gives me error ( which you can see on the top)
[ "From the error message it is clear that the string is stored in the correct format (backslashes are escaped by doubling). So it seems the path is wrong, and the file is indeed absent.\nOn the other hand, in your second example that you added in your edit, you use open('c:\\example2\\media\\uploads\\test5.txt') - this will definitely fail because \\t is a tab character (whereas all the other backslash-letter combinations don't exist, so the backslash will be treated like it was escaped correctly). But you said that the string was stored in a variable, so I don't see how this example helps here.\nConsider the following:\n>>> path = 'c:\\example2\\media\\uploads\\test5.txt'\n>>> path\n'c:\\\\example2\\\\media\\\\uploads\\test5.txt'\n\nSee? All the backslashes are converted to escaped backslashes except for the \\t one because that's the only one with special meaning. And now, of course, this path is wrong. So if the variables you're referring to have been defined this way (and now contain invalid paths) there's not much you can do except fix the source:\n>>> path = r'c:\\example2\\media\\uploads\\test5.txt'\n>>> path\n'c:\\\\example2\\\\media\\\\uploads\\\\test5.txt'\n\nYou might think you could \"fix\" a defective path afterwards like this:\n>>> path = 'c:\\example2\\media\\uploads\\test5.txt'\n>>> path.replace(\"\\t\",\"\\\\t\")\n'c:\\\\example2\\\\media\\\\uploads\\\\test5.txt'\n\n...but there are many other escape codes (\\b, \\r, \\n etc.), so that's not really a feasible way, especially because you'd be doctoring around the symptoms instead of fixing the underlying problem.\n", "well is it upload or uploads? Your question says the one, but your error says the other. The 'u' at the beginning indicates that the string is unicode format, this shouldn't have any impact. the '\\\\' character is necessary for python to escape the '\\' character.\n", "The letter 'r' is for the Python interpreter only. It indicates, that interpreter shouldn't escape any sequences, when parsing a string. If the string is already stored in a variable, there is nothing to do with the 'r' letter.\nI guess the problem is that there is actualy no such file. Try copying this line you get in the exception (the path from that line I mean) and pasting it into windows run dialog (Win+r will show it up). Then hit 'enter'.\nIf you get an error, check the paths. You have both upload and uploads in your question, make sure you use the right one in your code.\n" ]
[ 6, 2, 0 ]
[]
[]
[ "python", "string", "variables" ]
stackoverflow_0003113095_python_string_variables.txt
Q: Of web service implementation I am trying to implement a small, very flexible REST web service. I've done it in the past, but I didn't like the approach and I still don't like. How can one parse the query variables in a more elegant way ? Doing things like: if query_variable in uri: do_things_based_on_query_variable look fairly ugly to me, especially when all of those query variables map back to a database. Can someone give an example of how an Web Service is implemented ? I am interested mostly in Python Web Services and how they're handled in the controller implementation. A: Have you looked at Routes?
Of web service implementation
I am trying to implement a small, very flexible REST web service. I've done it in the past, but I didn't like the approach and I still don't like. How can one parse the query variables in a more elegant way ? Doing things like: if query_variable in uri: do_things_based_on_query_variable look fairly ugly to me, especially when all of those query variables map back to a database. Can someone give an example of how an Web Service is implemented ? I am interested mostly in Python Web Services and how they're handled in the controller implementation.
[ "Have you looked at Routes?\n" ]
[ 0 ]
[]
[]
[ "python", "web_services" ]
stackoverflow_0003113188_python_web_services.txt
Q: Linking using OpenMp with ctypes I have a c99 function that uses openmp, which works as expected. I also wrote a python interface using ctypes which causes the problem. Ctypes/python can not find the library for openmp. Here is the error message: File "foo.py", line 2, in <module> foobar=cdll.LoadLibrary("./libfoo.so") File "/usr/lib/python2.6/ctypes/__init__.py", line 431, in LoadLibrary return self._dlltype(name) File "/usr/lib/python2.6/ctypes/__init__.py", line 353, in __init__ self._handle = _dlopen(self._name, mode) OSError: ./libfoo.so: undefined symbol: GOMP_parallel_end And I use these cmds: gcc -fPIC -std=c99 -lm -Wall -fopenmp -pedantic -c foo.c gcc -shared -o libfoo.so foo.o python foo.py I already googled and found a ''solution'' online, but I don't understand what is meant with: I suppose I should set restype on constructors to ctypes.c_void_p. And that I should set the corresponding types in argtypes on called functions to ctypes.c_void_p. Will this cause necessary conversions to take place? I'd like some confirmation that this is the right way to approach this situation. What does the solution mean or do you know an other way? [update] So here is the correct cmd line options with the help from Iulian Şerbănoiu: gcc -fPIC -std=c99 -lm -Wall -fopenmp -pedantic -c foo.c gcc -shared -lgomp -lrt -o libfoo.so foo.o python foo.py A: Try adding -lgomp option in order to link with openmp library. From here.
Linking using OpenMp with ctypes
I have a c99 function that uses openmp, which works as expected. I also wrote a python interface using ctypes which causes the problem. Ctypes/python can not find the library for openmp. Here is the error message: File "foo.py", line 2, in <module> foobar=cdll.LoadLibrary("./libfoo.so") File "/usr/lib/python2.6/ctypes/__init__.py", line 431, in LoadLibrary return self._dlltype(name) File "/usr/lib/python2.6/ctypes/__init__.py", line 353, in __init__ self._handle = _dlopen(self._name, mode) OSError: ./libfoo.so: undefined symbol: GOMP_parallel_end And I use these cmds: gcc -fPIC -std=c99 -lm -Wall -fopenmp -pedantic -c foo.c gcc -shared -o libfoo.so foo.o python foo.py I already googled and found a ''solution'' online, but I don't understand what is meant with: I suppose I should set restype on constructors to ctypes.c_void_p. And that I should set the corresponding types in argtypes on called functions to ctypes.c_void_p. Will this cause necessary conversions to take place? I'd like some confirmation that this is the right way to approach this situation. What does the solution mean or do you know an other way? [update] So here is the correct cmd line options with the help from Iulian Şerbănoiu: gcc -fPIC -std=c99 -lm -Wall -fopenmp -pedantic -c foo.c gcc -shared -lgomp -lrt -o libfoo.so foo.o python foo.py
[ "Try adding -lgomp option in order to link with openmp library. From here.\n" ]
[ 3 ]
[]
[]
[ "c", "ctypes", "linux", "openmp", "python" ]
stackoverflow_0003111810_c_ctypes_linux_openmp_python.txt
Q: Optimize algorithm for creating a list of items rated together, in Python given a list of purchase events (customer_id,item) 1-hammer 1-screwdriver 1-nails 2-hammer 2-nails 3-screws 3-screwdriver 4-nails 4-screws i'm trying to build a data structure that tells how many times an item was bought with another item. Not bought at the same time, but bought since I started saving data. the result would look like { hammer : {screwdriver : 1, nails : 2}, screwdriver : {hammer : 1, screws : 1, nails : 1}, screws : {screwdriver : 1, nails : 1}, nails : {hammer : 1, screws : 1, screwdriver : 1} } indicating That a hammer was bought with nails twice (persons 1,3) and a screwdriver once (person 1), screws were bought with a screwdriver once (person 3), and so on... my current approach is users = dict where userid is the key and a list of items bought is the value usersForItem = dict where itemid is the key and list of users who bought item is the value userlist = temporary list of users who have rated the current item pseudo: for each event(customer,item)(sorted by item): add user to users dict if not exists, and add the items add item to items dict if not exists, and add the user ---------- for item,user in rows: # add the user to the users dict if they don't already exist. users[user]=users.get(user,[]) # append the current item_id to the list of items rated by the current user users[user].append(item) if item != last_item: # we just started a new item which means we just finished processing an item # write the userlist for the last item to the usersForItem dictionary. if last_item != None: usersForItem[last_item]=userlist userlist=[user] last_item = item items.append(item) else: userlist.append(user) usersForItem[last_item]=userlist So, at this point, I have 2 dicts - who bought what, and what was bought by whom. Here's where it gets tricky. Now that usersForItem is populated, I loop through it, loop through each user who bought the item, and look at the users' other purchases. I acknowledge that this is not the most pythonic way of doing things - I'm trying to make sure I get the correct result(which I am) before getting fancy with the Python. relatedItems = {} for key,listOfUsers in usersForItem.iteritems(): relatedItems[key]={} related=[] for ux in listOfReaders: for itemRead in users[ux]: if itemRead != key: if itemRead not in related: related.append(itemRead) relatedItems[key][itemRead]= relatedItems[key].get(itemRead,0) + 1 calc jaccard/tanimoto similarity between relatedItems[key] and its values Is there a more efficient way that I can be doing this? Additionally, if there is a proper academic name for this type of operation, I'd love to hear it. edit: clarified to include the fact that I'm not restricting purchases to items bought together at the same time. Items can be bought at any time. A: Do you really need to precompute all the possible pairs? What if you were to do it lazily, i.e. on an on-demand basis? This can be represented as a 2D matrix. The rows correspond to the customers and the columns correspond to the products. Each entry is either 0 or 1, saying whether the product corresponding to the column was bought by the customer corresponding to the row. If you look at each column as a vector of (around 5000) 0s and 1s, then the number of times two products were bought together is just the dot product of the corresponding vectors! Thus you can just compute those vectors first, and then compute the dot product lazily, on demand. To compute the dot-product: Now, a good representation of a vector with only 0s and 1s is an array of integers, which is basically a bitmap. For 5000 entries, you will need an array of 79 64-bit integers. So given two such arrays, you need to count the number of 1s that are common. To count the number of bits common to two integers, first you can do the bitwise AND and then count the numbers of 1s that are set in the resulting number. For this either you can use lookup tables or some bitcounting methods (not sure if python will support them), like here: http://graphics.stanford.edu/~seander/bithacks.html So your algorithm will be something like this: Initialize an array of 79 64 bit integers for each product. For each customer, look at the products bought and set the appropriate bit for that customer in that corresponding products. Now given a query of two products for which you need to know the number of customer who bought them together, just take the dot-product as describe above. This should be reasonably fast. As a further optimization, you can possibly consider grouping the customers. A: events = """\ 1-hammer 1-screwdriver 1-nails 2-hammer 2-nails 3-screws 3-screwdriver 4-nails 4-screws""".splitlines() events = sorted(map(str.strip,e.split('-')) for e in events) from collections import defaultdict from itertools import groupby # tally each occurrence of each pair of items summary = defaultdict(int) for val,items in groupby(events, key=lambda x:x[0]): items = sorted(it[1] for it in items) for i,item1 in enumerate(items): for item2 in items[i+1:]: summary[(item1,item2)] += 1 summary[(item2,item1)] += 1 # now convert raw pair counts into friendlier lookup table pairmap = defaultdict(dict) for k,v in summary.items(): item1, item2 = k pairmap[item1][item2] = v # print the results for k,v in sorted(pairmap.items()): print k,':',v Gives: hammer : {'nails': 2, 'screwdriver': 1} nails : {'screws': 1, 'hammer': 2, 'screwdriver': 1} screwdriver : {'screws': 1, 'nails': 1, 'hammer': 1} screws : {'nails': 1, 'screwdriver': 1} (This addresses your initial request grouping items by purchase event. To group by user, just change the first key of the events list from event number to user id.) A: Paul's answer might be the best, but here's what I came up with over my lunch break (untested, admittedly, but still a fun exercise in thinking). Not sure of the quickness/optimization of my algorithm. I'd personally suggest looking at something like MongoDB, a NoSQL database, since it seems it may lend itself nicely to solving this kind of problem (what with map/reduce and all) # assuming events is a dictionary of id keyed to item bought... user = {} for (cust_id, item) in events: if not cust_id in users: user[cust_id] = set() user[cust_id].add(item) # now we have a dictionary of cust_ids keyed to a set of every item # they've ever bought (given that repeats don't matter) # now we construct a dict of items keyed to a dictionary of other items # which are in turn keyed to num times present items = {} def insertOrIter(d, k, v): if k in d: d[k] += v else: d[k] = v for key in user: # keep track of items bought with each other itemsbyuser = [] for item in user[key]: # make sure the item with dict is set up if not item in items: items[item] = {} # as we see each item, add to it others and others to it for other in itemsbyuser: insertOrIter(items[other], item, 1) insertOrIter(items[item], other, 1) itemsbyuser.append(item) # now, unless i've screwed up my logic, we have a dictionary of items keyed # to a dictionary of other items keyed to how many times they've been # bought with the first item. *whew* # If you want something more (potentially) useful, we just turn that around to be a # dictionary of items keyed to a list of tuples of (times seen, other item) and # you're good to go. useful = {} for i in items: temp = [] for other in items[i]: temp[].append((items[i][other], other)) useful[i] = sorted(temp, reverse=True) # Now you should have a dictionary of items keyed to tuples of # (number times bought with item, other item) sorted in descending order of # number of times bought together A: Rather strange seeing that every time you want to get the stats, all solutions above churn through entire database to get counts. Would suggest to keep the data in flat, indexes and only get results for specific item, one at the time. If your item count is large, it will me more efficient. from collections import defaultdict from itertools import groupby class myDB: '''Example of "indexed" "database" of orders <-> items on order''' def __init__(self): self.id_based_index = defaultdict(set) self.item_based_index = defaultdict(set) def add(self, order_data): for id, item in order_data: self.id_based_index[id].add(item) self.item_based_index[item].add(id) def get_compliments(self, item): all_items = [] for id in self.item_based_index[item]: all_items.extend(self.id_based_index[id]) gi = groupby(sorted(all_items), lambda x: x) return dict([(k, len(list(g))) for k, g in gi]) Example of using it: events = """1-hammer 1-screwdriver 1-nails 2-hammer 2-nails 3-screws 3-screwdriver 4-nails 4-screws""" db = myDB() db.add( [ map(str.strip,e.split('-')) for e in events.splitlines() ] ) # index is incrementally increased db.add([['5','plunger'],['5','beer']]) # this scans and counts only needed items assert db.get_compliments('NotToBeFound') == {} assert db.get_compliments('hammer') == {'nails': 2, 'hammer': 2, 'screwdriver': 1} # you get back the count for the requested product as well. Discard if not needed. This is all fun, but, seriously, just go for real database storage. Because indexing is already built into any DB engine, all of the above code in SQL would just be: select p_others.product_name, count(1) cnt from products p join order_product_map opm on p.product_id = opm.product_id join products p_others on opm.product_id = p_others.product_id where p.product_name in ('hammer') group by p_others.product_name
Optimize algorithm for creating a list of items rated together, in Python
given a list of purchase events (customer_id,item) 1-hammer 1-screwdriver 1-nails 2-hammer 2-nails 3-screws 3-screwdriver 4-nails 4-screws i'm trying to build a data structure that tells how many times an item was bought with another item. Not bought at the same time, but bought since I started saving data. the result would look like { hammer : {screwdriver : 1, nails : 2}, screwdriver : {hammer : 1, screws : 1, nails : 1}, screws : {screwdriver : 1, nails : 1}, nails : {hammer : 1, screws : 1, screwdriver : 1} } indicating That a hammer was bought with nails twice (persons 1,3) and a screwdriver once (person 1), screws were bought with a screwdriver once (person 3), and so on... my current approach is users = dict where userid is the key and a list of items bought is the value usersForItem = dict where itemid is the key and list of users who bought item is the value userlist = temporary list of users who have rated the current item pseudo: for each event(customer,item)(sorted by item): add user to users dict if not exists, and add the items add item to items dict if not exists, and add the user ---------- for item,user in rows: # add the user to the users dict if they don't already exist. users[user]=users.get(user,[]) # append the current item_id to the list of items rated by the current user users[user].append(item) if item != last_item: # we just started a new item which means we just finished processing an item # write the userlist for the last item to the usersForItem dictionary. if last_item != None: usersForItem[last_item]=userlist userlist=[user] last_item = item items.append(item) else: userlist.append(user) usersForItem[last_item]=userlist So, at this point, I have 2 dicts - who bought what, and what was bought by whom. Here's where it gets tricky. Now that usersForItem is populated, I loop through it, loop through each user who bought the item, and look at the users' other purchases. I acknowledge that this is not the most pythonic way of doing things - I'm trying to make sure I get the correct result(which I am) before getting fancy with the Python. relatedItems = {} for key,listOfUsers in usersForItem.iteritems(): relatedItems[key]={} related=[] for ux in listOfReaders: for itemRead in users[ux]: if itemRead != key: if itemRead not in related: related.append(itemRead) relatedItems[key][itemRead]= relatedItems[key].get(itemRead,0) + 1 calc jaccard/tanimoto similarity between relatedItems[key] and its values Is there a more efficient way that I can be doing this? Additionally, if there is a proper academic name for this type of operation, I'd love to hear it. edit: clarified to include the fact that I'm not restricting purchases to items bought together at the same time. Items can be bought at any time.
[ "Do you really need to precompute all the possible pairs? What if you were to do it lazily, i.e. on an on-demand basis?\nThis can be represented as a 2D matrix. The rows correspond to the customers and the columns correspond to the products.\nEach entry is either 0 or 1, saying whether the product corresponding to the column was bought by the customer corresponding to the row.\nIf you look at each column as a vector of (around 5000) 0s and 1s, then the number of times two products were bought together is just the dot product of the corresponding vectors!\nThus you can just compute those vectors first, and then compute the dot product lazily, on demand.\nTo compute the dot-product:\nNow, a good representation of a vector with only 0s and 1s is an array of integers, which is basically a bitmap.\nFor 5000 entries, you will need an array of 79 64-bit integers.\nSo given two such arrays, you need to count the number of 1s that are common. \nTo count the number of bits common to two integers, first you can do the bitwise AND and then count the numbers of 1s that are set in the resulting number.\nFor this either you can use lookup tables or some bitcounting methods (not sure if python will support them), like here: http://graphics.stanford.edu/~seander/bithacks.html\nSo your algorithm will be something like this:\n\nInitialize an array of 79 64 bit integers for each product.\nFor each customer, look at the products bought and set the appropriate bit for that customer in that corresponding products.\nNow given a query of two products for which you need to know the number of customer who bought them together, just take the dot-product as describe above.\n\nThis should be reasonably fast. \nAs a further optimization, you can possibly consider grouping the customers.\n", "events = \"\"\"\\\n1-hammer \n1-screwdriver \n1-nails \n2-hammer \n2-nails \n3-screws \n3-screwdriver \n4-nails \n4-screws\"\"\".splitlines()\nevents = sorted(map(str.strip,e.split('-')) for e in events)\n\nfrom collections import defaultdict\nfrom itertools import groupby\n\n# tally each occurrence of each pair of items\nsummary = defaultdict(int)\nfor val,items in groupby(events, key=lambda x:x[0]):\n items = sorted(it[1] for it in items)\n for i,item1 in enumerate(items):\n for item2 in items[i+1:]:\n summary[(item1,item2)] += 1\n summary[(item2,item1)] += 1\n\n# now convert raw pair counts into friendlier lookup table\npairmap = defaultdict(dict)\nfor k,v in summary.items():\n item1, item2 = k\n pairmap[item1][item2] = v\n\n# print the results \nfor k,v in sorted(pairmap.items()):\n print k,':',v\n\nGives:\nhammer : {'nails': 2, 'screwdriver': 1}\nnails : {'screws': 1, 'hammer': 2, 'screwdriver': 1}\nscrewdriver : {'screws': 1, 'nails': 1, 'hammer': 1}\nscrews : {'nails': 1, 'screwdriver': 1}\n\n(This addresses your initial request grouping items by purchase event. To group by user, just change the first key of the events list from event number to user id.)\n", "Paul's answer might be the best, but here's what I came up with over my lunch break (untested, admittedly, but still a fun exercise in thinking). Not sure of the quickness/optimization of my algorithm. I'd personally suggest looking at something like MongoDB, a NoSQL database, since it seems it may lend itself nicely to solving this kind of problem (what with map/reduce and all)\n# assuming events is a dictionary of id keyed to item bought...\nuser = {}\nfor (cust_id, item) in events:\n if not cust_id in users:\n user[cust_id] = set()\n user[cust_id].add(item)\n# now we have a dictionary of cust_ids keyed to a set of every item\n# they've ever bought (given that repeats don't matter)\n# now we construct a dict of items keyed to a dictionary of other items\n# which are in turn keyed to num times present\nitems = {}\ndef insertOrIter(d, k, v):\n if k in d:\n d[k] += v\n else:\n d[k] = v\nfor key in user:\n # keep track of items bought with each other\n itemsbyuser = []\n for item in user[key]:\n # make sure the item with dict is set up\n if not item in items:\n items[item] = {}\n # as we see each item, add to it others and others to it\n for other in itemsbyuser:\n insertOrIter(items[other], item, 1)\n insertOrIter(items[item], other, 1)\n itemsbyuser.append(item)\n# now, unless i've screwed up my logic, we have a dictionary of items keyed\n# to a dictionary of other items keyed to how many times they've been\n# bought with the first item. *whew* \n# If you want something more (potentially) useful, we just turn that around to be a\n# dictionary of items keyed to a list of tuples of (times seen, other item) and\n# you're good to go.\nuseful = {}\nfor i in items:\n temp = []\n for other in items[i]:\n temp[].append((items[i][other], other))\n useful[i] = sorted(temp, reverse=True)\n# Now you should have a dictionary of items keyed to tuples of\n# (number times bought with item, other item) sorted in descending order of\n# number of times bought together\n\n", "Rather strange seeing that every time you want to get the stats, all solutions above churn through entire database to get counts.\nWould suggest to keep the data in flat, indexes and only get results for specific item, one at the time. If your item count is large, it will me more efficient.\nfrom collections import defaultdict\nfrom itertools import groupby\n\nclass myDB:\n '''Example of \"indexed\" \"database\" of orders <-> items on order'''\n def __init__(self):\n self.id_based_index = defaultdict(set) \n self.item_based_index = defaultdict(set)\n\n def add(self, order_data):\n for id, item in order_data:\n self.id_based_index[id].add(item)\n self.item_based_index[item].add(id)\n\n def get_compliments(self, item):\n all_items = []\n for id in self.item_based_index[item]:\n all_items.extend(self.id_based_index[id])\n gi = groupby(sorted(all_items), lambda x: x)\n return dict([(k, len(list(g))) for k, g in gi])\n\nExample of using it:\nevents = \"\"\"1-hammer \n 1-screwdriver \n 1-nails \n 2-hammer \n 2-nails \n 3-screws \n 3-screwdriver \n 4-nails \n 4-screws\"\"\"\n\ndb = myDB()\ndb.add(\n [ map(str.strip,e.split('-')) for e in events.splitlines() ]\n )\n# index is incrementally increased \ndb.add([['5','plunger'],['5','beer']])\n\n# this scans and counts only needed items\nassert db.get_compliments('NotToBeFound') == {}\nassert db.get_compliments('hammer') == {'nails': 2, 'hammer': 2, 'screwdriver': 1}\n# you get back the count for the requested product as well. Discard if not needed.\n\nThis is all fun, but, seriously, just go for real database storage. Because indexing is already built into any DB engine, all of the above code in SQL would just be:\nselect\n p_others.product_name,\n count(1) cnt\nfrom products p\njoin order_product_map opm\n on p.product_id = opm.product_id\njoin products p_others\n on opm.product_id = p_others.product_id\nwhere p.product_name in ('hammer')\ngroup by p_others.product_name\n\n" ]
[ 3, 2, 1, 1 ]
[]
[]
[ "algorithm", "optimization", "python", "similarity" ]
stackoverflow_0003109755_algorithm_optimization_python_similarity.txt
Q: Python subprocess Help I'm testing python subprocess and I keep getting this error: $ python subprocess-test.py Traceback (most recent call last): File "subprocess-test.py", line 3, in <module> p = subprocess.Popen(['rsync', '-azP', 'rsync://cdimage.ubuntu.com/cdimage/daily-live/current/maverick-desktop-amd64.iso', '/home/roaksoax/Desktop/iso'], stdout=subprocess.PIPE) AttributeError: 'module' object has no attribute 'Popen' My script is: import subprocess p = subprocess.Popen(['rsync', '-azP', 'rsync://cdimage.ubuntu.com/cdimage/daily-live/current/maverick-desktop-amd64.iso', '/home/testing/maverick.iso'], stdout=subprocess.PIPE) Do you guys know what might be happening? A: Wild guess: you have your own file called subprocess.py which is masking the standard library module. What do you see with this?: import subprocess print subprocess.__file__ This will show what file is being imported as subprocess.
Python subprocess Help
I'm testing python subprocess and I keep getting this error: $ python subprocess-test.py Traceback (most recent call last): File "subprocess-test.py", line 3, in <module> p = subprocess.Popen(['rsync', '-azP', 'rsync://cdimage.ubuntu.com/cdimage/daily-live/current/maverick-desktop-amd64.iso', '/home/roaksoax/Desktop/iso'], stdout=subprocess.PIPE) AttributeError: 'module' object has no attribute 'Popen' My script is: import subprocess p = subprocess.Popen(['rsync', '-azP', 'rsync://cdimage.ubuntu.com/cdimage/daily-live/current/maverick-desktop-amd64.iso', '/home/testing/maverick.iso'], stdout=subprocess.PIPE) Do you guys know what might be happening?
[ "Wild guess: you have your own file called subprocess.py which is masking the standard library module.\nWhat do you see with this?:\nimport subprocess\nprint subprocess.__file__\n\nThis will show what file is being imported as subprocess.\n" ]
[ 27 ]
[]
[]
[ "python", "subprocess" ]
stackoverflow_0003113544_python_subprocess.txt
Q: PHP vs. Other Languages in Hadoop/MapReduce implementations, and in the Cloud generally I'm beginning to learn some Hadoop/MapReduce, coming mostly from a PHP background, with a little bit of Java and Python. But, it seems like most implementations of MapReduce out there are in Java, Ruby, C++ or Python. I've looked, and it looks like there are some Hadoop/MapReduce in PHP, but the overwhelming body of the literature seems to be dedicated to those 4 languages. Is there a good reason why PHP is a 2nd class language in cloud computing projects like those that involve Hadoop/MapReduce? This is particularly surprising, considering that, outside of cloud computing world, PHP seems like its the most commonly supported language, to the detriment of the 3 above (sans C++) languages. If this is arbitrary--if PHP is just as good at handling these operations as, say, Python, what libraries/projects should I look into? A: PHP is designed primarily as a language for displaying output to a browser. Most jobs being run on MapReduce/Hadoop clusters have nothing to do with displaying output. They instead tend to lean much more heavily towards data processing. PHP is not the most commonly supported language for data processing, by far. Thus, it's logical that the most common supported languages for data processing-related technologies don't include PHP. A: You can take a look at Doctrine MongoDB Object Document Mapper. It supports map/reduce. A: The reason is PHP lack of support for multi-threading and process communication.
PHP vs. Other Languages in Hadoop/MapReduce implementations, and in the Cloud generally
I'm beginning to learn some Hadoop/MapReduce, coming mostly from a PHP background, with a little bit of Java and Python. But, it seems like most implementations of MapReduce out there are in Java, Ruby, C++ or Python. I've looked, and it looks like there are some Hadoop/MapReduce in PHP, but the overwhelming body of the literature seems to be dedicated to those 4 languages. Is there a good reason why PHP is a 2nd class language in cloud computing projects like those that involve Hadoop/MapReduce? This is particularly surprising, considering that, outside of cloud computing world, PHP seems like its the most commonly supported language, to the detriment of the 3 above (sans C++) languages. If this is arbitrary--if PHP is just as good at handling these operations as, say, Python, what libraries/projects should I look into?
[ "PHP is designed primarily as a language for displaying output to a browser. Most jobs being run on MapReduce/Hadoop clusters have nothing to do with displaying output.\nThey instead tend to lean much more heavily towards data processing. PHP is not the most commonly supported language for data processing, by far. Thus, it's logical that the most common supported languages for data processing-related technologies don't include PHP.\n", "You can take a look at Doctrine MongoDB Object Document Mapper. It supports map/reduce.\n", "The reason is PHP lack of support for multi-threading and process communication.\n" ]
[ 10, 2, 1 ]
[]
[]
[ "hadoop", "java", "mapreduce", "php", "python" ]
stackoverflow_0003113573_hadoop_java_mapreduce_php_python.txt
Q: Update datastore in Google App Engine from the iPhone I'm working on an app that communicates with Google App Engine to update and retrieve user information, but I can't think of a way to modify elements in the datastore. For example, every user for my app is represented by a User object in the datastore. If this user inputs things like email, phone number, etc into fields inside the iPhone application, I want to be able to update those objects in the datastore. The datastore can be in Java or Python, I'm just looking for an idea that will work. Thanks A: Why not have the iPhone application communicate this information to app engine by making a simple HTTP request? Specifically, I would do an HTTP POST to the server and include the relevant fields. Then your app engine request handler would simply store the information in the datastore.
Update datastore in Google App Engine from the iPhone
I'm working on an app that communicates with Google App Engine to update and retrieve user information, but I can't think of a way to modify elements in the datastore. For example, every user for my app is represented by a User object in the datastore. If this user inputs things like email, phone number, etc into fields inside the iPhone application, I want to be able to update those objects in the datastore. The datastore can be in Java or Python, I'm just looking for an idea that will work. Thanks
[ "Why not have the iPhone application communicate this information to app engine by making a simple HTTP request?\nSpecifically, I would do an HTTP POST to the server and include the relevant fields. Then your app engine request handler would simply store the information in the datastore.\n" ]
[ 5 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "iphone", "java", "python" ]
stackoverflow_0003113734_google_app_engine_google_cloud_datastore_iphone_java_python.txt
Q: How can I know the name of the exception in C++? With Python, I could get the name of the exception easily as follows. run the code, i.e. x = 3/0 to get the exception from python "ZeroDivisionError: integer division or modulo by zero" tells me this is ZeroDivisionError Modify the code i.e. try: x=3/0 except ZeroDivisionError: DO something Is there any similar way to find the exception name with C++? When I run the x = 3/0, the compiled binary just throws 'Floating point exception', which is not so useful compared to python. A: While you can't easily ask for the name of the exception, if the exception derives from std::exception you can find out the specified reason it was shown with what(): try { ... } catch (const std::exception &exc) { std::err << exc.what() << std::endl; } On a side note, dividing by 0 is not guaranteed to raise a C++ exception (I think the MS platforms may do that but you won't get that on Linux). A: If you want to know the name of the exception class, you could use RTTI. However, the vast majority of C++ code will throw an exception derived from std::exception. However, all you get is the exception data contained in std::exception::what, and you can get the name of the exception class from RTTI and catch that explicitly if you need more information (and it contains more information). A: For most exceptions if you have the RTTI option set in your compiler, you can do: catch(std::exception & e) { cout << typeid(e).name(); } Unfortunately the exception thrown by a divide by zero does not derive from std::exception, so this trick will not work. A: If this is a debugging issue, you may be able to set your compiler to break when it hits an exception, which can be infinitely useful.
How can I know the name of the exception in C++?
With Python, I could get the name of the exception easily as follows. run the code, i.e. x = 3/0 to get the exception from python "ZeroDivisionError: integer division or modulo by zero" tells me this is ZeroDivisionError Modify the code i.e. try: x=3/0 except ZeroDivisionError: DO something Is there any similar way to find the exception name with C++? When I run the x = 3/0, the compiled binary just throws 'Floating point exception', which is not so useful compared to python.
[ "While you can't easily ask for the name of the exception, if the exception derives from std::exception you can find out the specified reason it was shown with what():\ntry\n{\n ...\n}\ncatch (const std::exception &exc)\n{\n std::err << exc.what() << std::endl;\n}\n\nOn a side note, dividing by 0 is not guaranteed to raise a C++ exception (I think the MS platforms may do that but you won't get that on Linux).\n", "If you want to know the name of the exception class, you could use RTTI. However, the vast majority of C++ code will throw an exception derived from std::exception.\nHowever, all you get is the exception data contained in std::exception::what, and you can get the name of the exception class from RTTI and catch that explicitly if you need more information (and it contains more information).\n", "For most exceptions if you have the RTTI option set in your compiler, you can do:\ncatch(std::exception & e)\n{\n cout << typeid(e).name();\n}\n\nUnfortunately the exception thrown by a divide by zero does not derive from std::exception, so this trick will not work.\n", "If this is a debugging issue, you may be able to set your compiler to break when it hits an exception, which can be infinitely useful.\n" ]
[ 4, 1, 1, 1 ]
[]
[]
[ "c++", "exception_handling", "python" ]
stackoverflow_0003113929_c++_exception_handling_python.txt
Q: Python - Why the use of assert(required_param)? I found this today while looking at a library for an API . def my_function(self, required_param=None): assert(required_param) ... Do cool function stuff Wouldn't it be easier to do this: def my_function(self, required_param): ... Do cool function stuff Or, am I missing something? The assert() of course gives you one unified exception that could come up, but unless you wanted this function to fail silently to do something in that case, wouldn't you rather have it break loudly so that you can catch such errors early on? I've never understood why people use assertions in production code. Perhaps, I will after I get some answers for this. A: The only reason I can imagine for the situation you've described is to also reject False, 0, [], (,), etc. But that doesn't make sense to assert against the default value. If the author wasn't intending to reject other false-ish values, then that assert is even more dubious.
Python - Why the use of assert(required_param)?
I found this today while looking at a library for an API . def my_function(self, required_param=None): assert(required_param) ... Do cool function stuff Wouldn't it be easier to do this: def my_function(self, required_param): ... Do cool function stuff Or, am I missing something? The assert() of course gives you one unified exception that could come up, but unless you wanted this function to fail silently to do something in that case, wouldn't you rather have it break loudly so that you can catch such errors early on? I've never understood why people use assertions in production code. Perhaps, I will after I get some answers for this.
[ "The only reason I can imagine for the situation you've described is to also reject False, 0, [], (,), etc. But that doesn't make sense to assert against the default value.\nIf the author wasn't intending to reject other false-ish values, then that assert is even more dubious.\n" ]
[ 2 ]
[]
[]
[ "assert", "assertions", "python" ]
stackoverflow_0003114016_assert_assertions_python.txt
Q: Spawning multiple browsers from Selenium RC utilizing Python I've been trying to develop an automated test case solution using Selenium RC and Python and after lengthy testing I've hit a pretty hard block in the road, so to speak. I have three files: unit.py, case1.py, and case1m.py unit.py configures instances of case1m.py with a browser and a port, then runs the test by sending the case1m instance through unittest.main(). The case1.py file is a vanilla case that is generated from Selenium IDE; when run from the command line, it executes the test case and exits with OK. I used this file to help debug the failing points of the other two files. Here is the source for all three files: unit.py: import unittest from case1m import case1m browser = "*chrome" port = 4444 a = case1m() a.setBrowser("*chrome",4444) unittest.main(a) case1m.py - handles browser/port arguments and runs selenium test cases: from selenium import selenium import unittest, time, re class case1m(unittest.TestCase): def setBrowser(self,b,p): print "entered setBrowser" self.browser = b self.port = p print "leaving setBrowser" self.setUp() def setUp(self): print self.browser,", ",self.port self.verificationErrors = [] self.selenium = selenium("localhost", self.browser, self.port, "http://megagate-ffcdcb.xl_net.internal/") self.selenium.start() print "end setUp" self.runTest() def runTest(self): print "entered runTest" sel = self.selenium sel.open("/seltest/") try: self.failUnless(sel.is_text_present("BODY")) except AssertionError, e: self.verificationErrors.append(str(e)) print "leaving runTest" self.tearDown() def tearDown(self): print "entered tearDown" self.selenium.stop() self.assertEqual([], self.verificationErrors) print "leaving tearDown" case1.py: from selenium import selenium import unittest, time, re class case1(unittest.TestCase): def setUp(self): print "entered setUp" self.verificationErrors = [] self.selenium = selenium("localhost", 4444, "*chrome", "http://megagate-ffcdcb.xl_net.internal/") self.selenium.start() def runTest(self): sel = self.selenium sel.open("/seltest/") try: self.failUnless(sel.is_text_present("BODY")) except AssertionError, e: self.verificationErrors.append(str(e)) def tearDown(self): self.selenium.stop() self.assertEqual([], self.verificationErrors) if __name__ == '__main__': unittest.main() The first problem I ran into was passing the browser and port values to an instance of the case1m class. I tried using __init__ to collect them as arguments, but apparently sub-classing the TestCase class and then adding an __init__ override causes problems; the setUp(), runTest() and tearDown() methods no longer triggered automatically as they do in the case1 class. So instead, I overrode and inserted a setBrowser() method to collect the values and create the browser and port variables within the class instance. This again causes the same issue as before, so I resorted to inserting method calls into setUp(), runTest() and tearDown(). When executed, it runs until it tries the do_command() method in the selenium instance. Here is the error: Traceback (most recent call last): File "C:\sel-test\unit.py", line 13, in a.setBrowser("*chrome",4444) File "C:\sel-test\case1m.py", line 10, in setBrowser self.setUp() File "C:\sel-test\case1m.py", line 16, in setUp self.selenium.start() File "C:\Python26\lib\selenium.py", line 190, in start result = self.get_string("getNewBrowserSession", [self.browserStartCommand, self.browserURL, self.extensionJs]) File "C:\Python26\lib\selenium.py", line 225, in get_string result = self.do_command(verb, args) File "C:\Python26\lib\selenium.py", line 213, in do_command conn.request("POST", "/selenium-server/driver/", body, headers) File "C:\Python26\lib\httplib.py", line 910, in request self._send_request(method, url, body, headers) File "C:\Python26\lib\httplib.py", line 947, in _send_request self.endheaders() File "C:\Python26\lib\httplib.py", line 904, in endheaders self._send_output() File "C:\Python26\lib\httplib.py", line 776, in _send_output self.send(msg) File "C:\Python26\lib\httplib.py", line 735, in send self.connect() File "C:\Python26\lib\httplib.py", line 716, in connect self.timeout) File "C:\Python26\lib\socket.py", line 500, in create_connection for res in getaddrinfo(host, port, 0, SOCK_STREAM): socket.gaierror: [Errno 10109] getaddrinfo failed My questions is: why does the unit.py/case1m.py combination result in socket.gaierror when the case1.py file will run without error? From what I can see, the selenium class should be receiving the exact same information by the time it reaches self.do_command(). The only difference is that case1.py is being run directly from the commandline, while case1m.py is being run as an imported module. A: Looking at the 2 code snippets side by side, I think you have inverted the browser and port arguments. This is probably the source of your error. case1.py (runs fine): self.selenium = selenium("localhost", 4444, "*chrome", "http://megagate-ffcdcb.xl_net.internal/") case1m.py (socket error): self.selenium = selenium("localhost", self.browser, self.port, "http://megagate-ffcdcb.xl_net.internal/")
Spawning multiple browsers from Selenium RC utilizing Python
I've been trying to develop an automated test case solution using Selenium RC and Python and after lengthy testing I've hit a pretty hard block in the road, so to speak. I have three files: unit.py, case1.py, and case1m.py unit.py configures instances of case1m.py with a browser and a port, then runs the test by sending the case1m instance through unittest.main(). The case1.py file is a vanilla case that is generated from Selenium IDE; when run from the command line, it executes the test case and exits with OK. I used this file to help debug the failing points of the other two files. Here is the source for all three files: unit.py: import unittest from case1m import case1m browser = "*chrome" port = 4444 a = case1m() a.setBrowser("*chrome",4444) unittest.main(a) case1m.py - handles browser/port arguments and runs selenium test cases: from selenium import selenium import unittest, time, re class case1m(unittest.TestCase): def setBrowser(self,b,p): print "entered setBrowser" self.browser = b self.port = p print "leaving setBrowser" self.setUp() def setUp(self): print self.browser,", ",self.port self.verificationErrors = [] self.selenium = selenium("localhost", self.browser, self.port, "http://megagate-ffcdcb.xl_net.internal/") self.selenium.start() print "end setUp" self.runTest() def runTest(self): print "entered runTest" sel = self.selenium sel.open("/seltest/") try: self.failUnless(sel.is_text_present("BODY")) except AssertionError, e: self.verificationErrors.append(str(e)) print "leaving runTest" self.tearDown() def tearDown(self): print "entered tearDown" self.selenium.stop() self.assertEqual([], self.verificationErrors) print "leaving tearDown" case1.py: from selenium import selenium import unittest, time, re class case1(unittest.TestCase): def setUp(self): print "entered setUp" self.verificationErrors = [] self.selenium = selenium("localhost", 4444, "*chrome", "http://megagate-ffcdcb.xl_net.internal/") self.selenium.start() def runTest(self): sel = self.selenium sel.open("/seltest/") try: self.failUnless(sel.is_text_present("BODY")) except AssertionError, e: self.verificationErrors.append(str(e)) def tearDown(self): self.selenium.stop() self.assertEqual([], self.verificationErrors) if __name__ == '__main__': unittest.main() The first problem I ran into was passing the browser and port values to an instance of the case1m class. I tried using __init__ to collect them as arguments, but apparently sub-classing the TestCase class and then adding an __init__ override causes problems; the setUp(), runTest() and tearDown() methods no longer triggered automatically as they do in the case1 class. So instead, I overrode and inserted a setBrowser() method to collect the values and create the browser and port variables within the class instance. This again causes the same issue as before, so I resorted to inserting method calls into setUp(), runTest() and tearDown(). When executed, it runs until it tries the do_command() method in the selenium instance. Here is the error: Traceback (most recent call last): File "C:\sel-test\unit.py", line 13, in a.setBrowser("*chrome",4444) File "C:\sel-test\case1m.py", line 10, in setBrowser self.setUp() File "C:\sel-test\case1m.py", line 16, in setUp self.selenium.start() File "C:\Python26\lib\selenium.py", line 190, in start result = self.get_string("getNewBrowserSession", [self.browserStartCommand, self.browserURL, self.extensionJs]) File "C:\Python26\lib\selenium.py", line 225, in get_string result = self.do_command(verb, args) File "C:\Python26\lib\selenium.py", line 213, in do_command conn.request("POST", "/selenium-server/driver/", body, headers) File "C:\Python26\lib\httplib.py", line 910, in request self._send_request(method, url, body, headers) File "C:\Python26\lib\httplib.py", line 947, in _send_request self.endheaders() File "C:\Python26\lib\httplib.py", line 904, in endheaders self._send_output() File "C:\Python26\lib\httplib.py", line 776, in _send_output self.send(msg) File "C:\Python26\lib\httplib.py", line 735, in send self.connect() File "C:\Python26\lib\httplib.py", line 716, in connect self.timeout) File "C:\Python26\lib\socket.py", line 500, in create_connection for res in getaddrinfo(host, port, 0, SOCK_STREAM): socket.gaierror: [Errno 10109] getaddrinfo failed My questions is: why does the unit.py/case1m.py combination result in socket.gaierror when the case1.py file will run without error? From what I can see, the selenium class should be receiving the exact same information by the time it reaches self.do_command(). The only difference is that case1.py is being run directly from the commandline, while case1m.py is being run as an imported module.
[ "Looking at the 2 code snippets side by side, I think you have inverted the browser and port arguments. This is probably the source of your error.\ncase1.py (runs fine):\nself.selenium = selenium(\"localhost\", 4444, \"*chrome\", \"http://megagate-ffcdcb.xl_net.internal/\")\n\ncase1m.py (socket error):\nself.selenium = selenium(\"localhost\", self.browser, self.port, \"http://megagate-ffcdcb.xl_net.internal/\")\n\n" ]
[ 1 ]
[]
[]
[ "browser", "python", "selenium", "selenium_rc" ]
stackoverflow_0003112673_browser_python_selenium_selenium_rc.txt
Q: Classifying Documents into Categories I've got about 300k documents stored in a Postgres database that are tagged with topic categories (there are about 150 categories in total). I have another 150k documents that don't yet have categories. I'm trying to find the best way to programmaticly categorize them. I've been exploring NLTK and its Naive Bayes Classifier. Seems like a good starting point (if you can suggest a better classification algorithm for this task, I'm all ears). My problem is that I don't have enough RAM to train the NaiveBayesClassifier on all 150 categoies/300k documents at once (training on 5 categories used 8GB). Furthermore, accuracy of the classifier seems to drop as I train on more categories (90% accuracy with 2 categories, 81% with 5, 61% with 10). Should I just train a classifier on 5 categories at a time, and run all 150k documents through the classifier to see if there are matches? It seems like this would work, except that there would be a lot of false positives where documents that don't really match any of the categories get shoe-horned into on by the classifier just because it's the best match available... Is there a way to have a "none of the above" option for the classifier just in case the document doesn't fit into any of the categories? Here is my test class http://gist.github.com/451880 A: You should start by converting your documents into TF-log(1 + IDF) vectors: term frequencies are sparse so you should use python dict with term as keys and count as values and then divide by total count to get the global frequencies. Another solution is to use the abs(hash(term)) for instance as positive integer keys. Then you an use scipy.sparse vectors which are more handy and more efficient to perform linear algebra operation than python dict. Also build the 150 frequencies vectors by averaging the frequencies of all the labeled documents belonging to the same category. Then for new document to label, you can compute the cosine similarity between the document vector and each category vector and choose the most similar category as label for your document. If this is not good enough, then you should try to train a logistic regression model using a L1 penalty as explained in this example of scikit-learn (this is a wrapper for liblinear as explained by @ephes). The vectors used to train your logistic regression model should be the previously introduced TD-log(1+IDF) vectors to get good performance (precision and recall). The scikit learn lib offers a sklearn.metrics module with routines to compute those score for a given model and given dataset. For larger datasets: you should try the vowpal wabbit which is probably the fastest rabbit on earth for large scale document classification problems (but not easy to use python wrappers AFAIK). A: How big (number of words) are your documents? Memory consumption at 150K trainingdocs should not be an issue. Naive Bayes is a good choice especially when you have many categories with only a few training examples or very noisy trainingdata. But in general, linear Support Vector Machines do perform much better. Is your problem multiclass (a document belongs only to one category exclusivly) or multilabel (a document belongs to one or more categories)? Accuracy is a poor choice to judge classifier performance. You should rather use precision vs recall, precision recall breakeven point (prbp), f1, auc and have to look at the precision vs recall curve where recall (x) is plotted against precision (y) based on the value of your confidence-threshold (wether a document belongs to a category or not). Usually you would build one binary classifier per category (positive training examples of one category vs all other trainingexamples which don't belong to your current category). You'll have to choose an optimal confidence threshold per category. If you want to combine those single measures per category into a global performance measure, you'll have to micro (sum up all true positives, false positives, false negatives and true negatives and calc combined scores) or macro (calc score per category and then average those scores over all categories) average. We have a corpus of tens of million documents, millions of training examples and thousands of categories (multilabel). Since we face serious training time problems (the number of documents are new, updated or deleted per day is quite high), we use a modified version of liblinear. But for smaller problems using one of the python wrappers around liblinear (liblinear2scipy or scikit-learn) should work fine. A: Is there a way to have a "none of the above" option for the classifier just in case the document doesn't fit into any of the categories? You might get this effect simply by having a "none of the above" pseudo-category trained each time. If the max you can train is 5 categories (though I'm not sure why it's eating up quite so much RAM), train 4 actual categories from their actual 2K docs each, and a "none of the above" one with its 2K documents taken randomly from all the other 146 categories (about 13-14 from each if you want the "stratified sampling" approach, which may be sounder). Still feels like a bit of a kludge and you might be better off with a completely different approach -- find a multi-dimensional doc measure that defines your 300K pre-tagged docs into 150 reasonably separable clusters, then just assign each of the other yet-untagged docs to the appropriate cluster as thus determined. I don't think NLTK has anything directly available to support this kind of thing, but, hey, NLTK's been growing so fast that I may well have missed something...;-)
Classifying Documents into Categories
I've got about 300k documents stored in a Postgres database that are tagged with topic categories (there are about 150 categories in total). I have another 150k documents that don't yet have categories. I'm trying to find the best way to programmaticly categorize them. I've been exploring NLTK and its Naive Bayes Classifier. Seems like a good starting point (if you can suggest a better classification algorithm for this task, I'm all ears). My problem is that I don't have enough RAM to train the NaiveBayesClassifier on all 150 categoies/300k documents at once (training on 5 categories used 8GB). Furthermore, accuracy of the classifier seems to drop as I train on more categories (90% accuracy with 2 categories, 81% with 5, 61% with 10). Should I just train a classifier on 5 categories at a time, and run all 150k documents through the classifier to see if there are matches? It seems like this would work, except that there would be a lot of false positives where documents that don't really match any of the categories get shoe-horned into on by the classifier just because it's the best match available... Is there a way to have a "none of the above" option for the classifier just in case the document doesn't fit into any of the categories? Here is my test class http://gist.github.com/451880
[ "You should start by converting your documents into TF-log(1 + IDF) vectors: term frequencies are sparse so you should use python dict with term as keys and count as values and then divide by total count to get the global frequencies.\nAnother solution is to use the abs(hash(term)) for instance as positive integer keys. Then you an use scipy.sparse vectors which are more handy and more efficient to perform linear algebra operation than python dict.\nAlso build the 150 frequencies vectors by averaging the frequencies of all the labeled documents belonging to the same category. Then for new document to label, you can compute the cosine similarity between the document vector and each category vector and choose the most similar category as label for your document.\nIf this is not good enough, then you should try to train a logistic regression model using a L1 penalty as explained in this example of scikit-learn (this is a wrapper for liblinear as explained by @ephes). The vectors used to train your logistic regression model should be the previously introduced TD-log(1+IDF) vectors to get good performance (precision and recall). The scikit learn lib offers a sklearn.metrics module with routines to compute those score for a given model and given dataset.\nFor larger datasets: you should try the vowpal wabbit which is probably the fastest rabbit on earth for large scale document classification problems (but not easy to use python wrappers AFAIK).\n", "How big (number of words) are your documents? Memory consumption at 150K trainingdocs should not be an issue.\nNaive Bayes is a good choice especially when you have many categories with only a few training examples or very noisy trainingdata. But in general, linear Support Vector Machines do perform much better.\nIs your problem multiclass (a document belongs only to one category exclusivly) or multilabel (a document belongs to one or more categories)? \nAccuracy is a poor choice to judge classifier performance. You should rather use precision vs recall, precision recall breakeven point (prbp), f1, auc and have to look at the precision vs recall curve where recall (x) is plotted against precision (y) based on the value of your confidence-threshold (wether a document belongs to a category or not). Usually you would build one binary classifier per category (positive training examples of one category vs all other trainingexamples which don't belong to your current category). You'll have to choose an optimal confidence threshold per category. If you want to combine those single measures per category into a global performance measure, you'll have to micro (sum up all true positives, false positives, false negatives and true negatives and calc combined scores) or macro (calc score per category and then average those scores over all categories) average.\nWe have a corpus of tens of million documents, millions of training examples and thousands of categories (multilabel). Since we face serious training time problems (the number of documents are new, updated or deleted per day is quite high), we use a modified version of liblinear. But for smaller problems using one of the python wrappers around liblinear (liblinear2scipy or scikit-learn) should work fine.\n", "\nIs there a way to have a \"none of the\n above\" option for the classifier just\n in case the document doesn't fit into\n any of the categories?\n\nYou might get this effect simply by having a \"none of the above\" pseudo-category trained each time. If the max you can train is 5 categories (though I'm not sure why it's eating up quite so much RAM), train 4 actual categories from their actual 2K docs each, and a \"none of the above\" one with its 2K documents taken randomly from all the other 146 categories (about 13-14 from each if you want the \"stratified sampling\" approach, which may be sounder).\nStill feels like a bit of a kludge and you might be better off with a completely different approach -- find a multi-dimensional doc measure that defines your 300K pre-tagged docs into 150 reasonably separable clusters, then just assign each of the other yet-untagged docs to the appropriate cluster as thus determined. I don't think NLTK has anything directly available to support this kind of thing, but, hey, NLTK's been growing so fast that I may well have missed something...;-)\n" ]
[ 33, 11, 2 ]
[]
[]
[ "machine_learning", "naivebayes", "nlp", "nltk", "python" ]
stackoverflow_0003113428_machine_learning_naivebayes_nlp_nltk_python.txt
Q: wxPython App - Ensure All Dialogs are Destroyed I'm working on an application that will need to use a variety of Dialogs. I'm having trouble getting events bound in a way that ensures that my Dialogs are destroyed properly if someone closes the application before dismissing the dialogs. I would expect to use something like this: class Form(wx.Dialog): def __init__(self): wx.Dialog.__init__(None, -1, "Dialog") self.Bind(wx.EVT_CLOSE, self.onClose) self.Bind(wx.EVT_CLOSE, self.onClose, MAIN_WINDOW) ... def onClose(self, evt): self.Destroy() The behavior I'm currently encountering is that if someone opens a Dialog, then closes the Application before dismissing the Dialog the Application does not exit fully. MAIN_WINDOW is a reference to the Frame that's registered as my Top Level Window. Thanks in advance! A: I was attempting to use event bubbling incorrectly. The solution is to make sure the Dialogs are children of the Top Level Window so that the Application exiting forces the Dialogs to destroy as well. class Form(wx.Dialog): def __init__(self): wx.Dialog.__init__(MAIN_WINDOW, -1, "Dialog") self.Bind(wx.EVT_CLOSE, self.onClose) ... def onClose(self, evt): self.Destroy()
wxPython App - Ensure All Dialogs are Destroyed
I'm working on an application that will need to use a variety of Dialogs. I'm having trouble getting events bound in a way that ensures that my Dialogs are destroyed properly if someone closes the application before dismissing the dialogs. I would expect to use something like this: class Form(wx.Dialog): def __init__(self): wx.Dialog.__init__(None, -1, "Dialog") self.Bind(wx.EVT_CLOSE, self.onClose) self.Bind(wx.EVT_CLOSE, self.onClose, MAIN_WINDOW) ... def onClose(self, evt): self.Destroy() The behavior I'm currently encountering is that if someone opens a Dialog, then closes the Application before dismissing the Dialog the Application does not exit fully. MAIN_WINDOW is a reference to the Frame that's registered as my Top Level Window. Thanks in advance!
[ "I was attempting to use event bubbling incorrectly. The solution is to make sure the Dialogs are children of the Top Level Window so that the Application exiting forces the Dialogs to destroy as well.\nclass Form(wx.Dialog):\n def __init__(self):\n wx.Dialog.__init__(MAIN_WINDOW, -1, \"Dialog\")\n self.Bind(wx.EVT_CLOSE, self.onClose)\n ...\n def onClose(self, evt):\n self.Destroy()\n\n" ]
[ 2 ]
[]
[]
[ "destructor", "event_handling", "python", "wxpython" ]
stackoverflow_0003112456_destructor_event_handling_python_wxpython.txt
Q: Is there a nice way to handle exceptions in Python? I have a bunch of code that looks similar to this: try: auth = page.ItemAttributes.Author except: try: auth = page.ItemAttributes.Creator except: auth = None Is there a nicer way to write out this logic? This makes my code really painful to read. I thought try..finally would work, but I assumed wrong A: You can use hasattr to avoid the try/except blocks: auth = None for attrname in ['Author', 'Creator']: if hasattr(page.ItemAttributes, attrname): auth = getattr(page.ItemAttributes, attrname) break An alternate way to write the above is to use the else clause of a Python for loop: for attrname in ['Author', 'Creator']: if hasattr(page.ItemAttributes, attrname): auth = getattr(page.ItemAttributes, attrname) break else: auth = None A: This makes my code really painful to read Whatever you do, don't catch wildcards. except: is the pythonic way to say: Hey, all exceptions are equal, I want every single error in my try block to end up here, I don't care if I catch an AttributeError or a WorldGotFuckedUpException. In your case, except AttributeError is much, much better AND easier to read. This is just a side note. Mark's answer shows the best way to do it, IMHO. A: @Mark Byers's answer is more flexible, but if you wanted a one-liner auth = getattr(page.ItemAttributes, 'Author', None) or getattr(page.ItemAttributes, 'Creator', None)
Is there a nice way to handle exceptions in Python?
I have a bunch of code that looks similar to this: try: auth = page.ItemAttributes.Author except: try: auth = page.ItemAttributes.Creator except: auth = None Is there a nicer way to write out this logic? This makes my code really painful to read. I thought try..finally would work, but I assumed wrong
[ "You can use hasattr to avoid the try/except blocks:\nauth = None\nfor attrname in ['Author', 'Creator']:\n if hasattr(page.ItemAttributes, attrname):\n auth = getattr(page.ItemAttributes, attrname)\n break\n\nAn alternate way to write the above is to use the else clause of a Python for loop:\nfor attrname in ['Author', 'Creator']:\n if hasattr(page.ItemAttributes, attrname):\n auth = getattr(page.ItemAttributes, attrname)\n break\nelse:\n auth = None\n\n", "\n\nThis makes my code really painful to read\n\n\nWhatever you do, don't catch wildcards.\nexcept: is the pythonic way to say: Hey, all exceptions are equal, I want every single error in my try block to end up here, I don't care if I catch an AttributeError or a WorldGotFuckedUpException. In your case, except AttributeError is much, much better AND easier to read.\nThis is just a side note. Mark's answer shows the best way to do it, IMHO.\n", "@Mark Byers's answer is more flexible, but if you wanted a one-liner\nauth = getattr(page.ItemAttributes, 'Author', None) or getattr(page.ItemAttributes, 'Creator', None)\n\n" ]
[ 11, 3, 2 ]
[]
[]
[ "exception", "python" ]
stackoverflow_0003114246_exception_python.txt
Q: python/django unittest function override I have a time-consuming method with non-predefined number of iterations inside it that I need to test: def testmethod(): objects = get_objects() for objects in objects: # Time-consuming iterations do_something(object) One iteration is sufficient to test for me. What is the best practice to test this method with one iteration only? A: Perhaps turn your method into def my_method(self, objs=None): if objs is None: objs = get_objects() for obj in objs: do_something(obj) Then in your test you can call it with a custom objs parameter. A: Update: I misread the original question, so here's how I would solve the problem without altering the source code: Lambda out your call to get objects to return a single object. For example: from your_module import get_objects def test_testmethdod(self): original_get_objects = get_objects one_object = YourObject() get_objects = lambda : [one_object,] # ... # your tests here # ... # Reset the original function, so it doesn't mess up other tests get_objects = original_get_objects
python/django unittest function override
I have a time-consuming method with non-predefined number of iterations inside it that I need to test: def testmethod(): objects = get_objects() for objects in objects: # Time-consuming iterations do_something(object) One iteration is sufficient to test for me. What is the best practice to test this method with one iteration only?
[ "Perhaps turn your method into\ndef my_method(self, objs=None):\n if objs is None:\n objs = get_objects()\n for obj in objs:\n do_something(obj)\n\nThen in your test you can call it with a custom objs parameter.\n", "Update:\nI misread the original question, so here's how I would solve the problem without altering the source code:\nLambda out your call to get objects to return a single object. For example:\nfrom your_module import get_objects\n\ndef test_testmethdod(self):\n original_get_objects = get_objects\n one_object = YourObject()\n get_objects = lambda : [one_object,]\n\n # ...\n # your tests here\n # ...\n\n # Reset the original function, so it doesn't mess up other tests\n get_objects = original_get_objects\n\n" ]
[ 2, 2 ]
[]
[]
[ "django", "python", "unit_testing" ]
stackoverflow_0003114326_django_python_unit_testing.txt
Q: Call python function as if it were inline I want to have a function in a different module, that when called, has access to all variables that its caller has access to, and functions just as if its body had been pasted into the caller rather than having its own context, basically like a C Macro instead of a normal function. I know I can pass locals() into the function and then it can access the local variables as a dict, but I want to be able to access them normally (eg x.y, not x["y"] and I want all names the caller has access to not just the locals, as well as things that were 'imported' into the caller's file but not into the module that contains the function. Is this possible to pull off? Edit 2 Here's the simplest possible example I can come up with of what I'm really trying to do: def getObj(expression) ofs = expression.rfind(".") obj = eval(expression[:ofs]) print "The part of the expression Left of the period is of type ", type(obj), Problem is that 'expression' requires the imports and local variables of the caller in order to eval without error.In reality theres a lot more than just an eval, so I'm trying to avoid the solution of just passing locals() in and through to the eval() since that won't fix my general case problem. A: And another, even uglier way to do it -- please don't do this, even if it's possible -- import sys def insp(): l = sys._getframe(1).f_locals expression = l["expression"] ofs = expression.rfind(".") expofs = expression[:ofs] obj = eval(expofs, globals(), l) print "The part of the expression %r Left of the period (%r) is of type %r" % (expression, expofs, type(obj)), def foo(): derp = 5 expression = "derp.durr" insp() foo() outputs The part of the expression 'derp.durr' Left of the period ('derp') is of type (type 'int') A: Is this possible to pull off? Yes (sort of, in a very roundabout way) which I would strongly advise against it in general (more on that later). Consider: myfile.py def func_in_caller(): print "in caller" import otherfile globals()["imported_func"] = otherfile.remote_func imported_func(123, globals()) otherfile.py def remote_func(x1, extra): for k,v in extra.iteritems(): globals()[k] = v print x1 func_in_caller() This yields (as expected): 123 in caller What we're doing here is trickery: we just copy every item into another namespace in order to make this work. This can (and will) break very easily and/or lead to hard to find bugs. There's almost certainly a better way of solving your problem / structuring your code (we need more information in general on what you're trying to achieve). A: I don't presume this is the answer that you wanted to hear, but trying to access local variables from a caller module's scope is not a good idea. If you normally program in PHP or C, you might be used to this sort of thing? If you still want to do this, you might consider creating a class and passing an instance of that class in place of locals(): #other_module.py def some_func(lcls): print(lcls.x) Then, >>> import other_module >>> >>> >>> x = 'Hello World' >>> >>> class MyLocals(object): ... def __init__(self, lcls): ... self.lcls = lcls ... def __getattr__(self, name): ... return self.lcls[name] ... >>> # Call your function with an instance of this instead. >>> other_module.some_func(MyLocals(locals())) 'Hello World' Give it a whirl. A: From The Zen of Python: 2) Explicit is better than implicit. In other words, pass in the parameter and don't try to get really fancy just because you think it would be easier for you. Writing code is not just about you.
Call python function as if it were inline
I want to have a function in a different module, that when called, has access to all variables that its caller has access to, and functions just as if its body had been pasted into the caller rather than having its own context, basically like a C Macro instead of a normal function. I know I can pass locals() into the function and then it can access the local variables as a dict, but I want to be able to access them normally (eg x.y, not x["y"] and I want all names the caller has access to not just the locals, as well as things that were 'imported' into the caller's file but not into the module that contains the function. Is this possible to pull off? Edit 2 Here's the simplest possible example I can come up with of what I'm really trying to do: def getObj(expression) ofs = expression.rfind(".") obj = eval(expression[:ofs]) print "The part of the expression Left of the period is of type ", type(obj), Problem is that 'expression' requires the imports and local variables of the caller in order to eval without error.In reality theres a lot more than just an eval, so I'm trying to avoid the solution of just passing locals() in and through to the eval() since that won't fix my general case problem.
[ "And another, even uglier way to do it -- please don't do this, even if it's possible --\nimport sys\n\ndef insp():\n l = sys._getframe(1).f_locals\n expression = l[\"expression\"]\n ofs = expression.rfind(\".\")\n expofs = expression[:ofs]\n obj = eval(expofs, globals(), l)\n print \"The part of the expression %r Left of the period (%r) is of type %r\" % (expression, expofs, type(obj)), \n\ndef foo():\n derp = 5\n expression = \"derp.durr\"\n insp()\n\nfoo()\n\noutputs\n\nThe part of the expression 'derp.durr' Left of the period ('derp') is of type (type 'int')\n\n", "Is this possible to pull off?\nYes (sort of, in a very roundabout way) which I would strongly advise against it in general (more on that later).\nConsider:\nmyfile.py\ndef func_in_caller():\n print \"in caller\"\n\nimport otherfile\nglobals()[\"imported_func\"] = otherfile.remote_func\n\nimported_func(123, globals()) \n\notherfile.py\ndef remote_func(x1, extra):\n for k,v in extra.iteritems(): \n globals()[k] = v\n print x1\n func_in_caller()\n\nThis yields (as expected):\n123\nin caller\n\nWhat we're doing here is trickery: we just copy every item into another namespace in order to make this work. This can (and will) break very easily and/or lead to hard to find bugs.\nThere's almost certainly a better way of solving your problem / structuring your code (we need more information in general on what you're trying to achieve).\n", "I don't presume this is the answer that you wanted to hear, but trying to access local variables from a caller module's scope is not a good idea. If you normally program in PHP or C, you might be used to this sort of thing?\nIf you still want to do this, you might consider creating a class and passing an instance of that class in place of locals():\n#other_module.py\ndef some_func(lcls):\n print(lcls.x)\n\nThen,\n>>> import other_module\n>>> \n>>> \n>>> x = 'Hello World'\n>>> \n>>> class MyLocals(object):\n... def __init__(self, lcls):\n... self.lcls = lcls\n... def __getattr__(self, name):\n... return self.lcls[name]\n... \n>>> # Call your function with an instance of this instead.\n>>> other_module.some_func(MyLocals(locals()))\n'Hello World'\n\nGive it a whirl.\n", "From The Zen of Python:\n\n2) Explicit is better than implicit. \n\nIn other words, pass in the parameter and don't try to get really fancy just because you think it would be easier for you. Writing code is not just about you.\n" ]
[ 3, 2, 2, 2 ]
[]
[]
[ "inline", "namespaces", "python" ]
stackoverflow_0003114015_inline_namespaces_python.txt
Q: Calling a Python program from PHP I've got a version of the A* algorithm that builds a graph of the UK road and cycle network in Python lists. It takes about 30 seconds to initialise, but once done can very quickly find the shortest route between any two vertices. The start and finish vertex ids are provided by PHP. I'm trying to work out the best way of communicating between PHP and the Python program. I only want to do the initialisation phase when the Apache server starts, so my question is: How do I keep the python program alive and request routes from it via php? I have a GLAMP setup. A: Easiest way that I can think of would be XMLRPC. Python makes it horribly easy to set up an XMLRPC server, and there's php_xmlrpc for bindings on the PHP side... def calculate_path(v1, v2): return [v1, ..., v2] from SimpleXMLRPCServer import SimpleXMLRPCServer server = SimpleXMLRPCServer(('localhost', 9393)) server.register_function(calculate_path) server.serve_forever() and you're running and should be able to do an XMLRPC call for calculate_path on http://localhost:9393/ from your PHP app. A: Check this question out: Calling Python in PHP Also check out this extension: http://www.csh.rit.edu/~jon/projects/pip/ I don't know if you're hosting environment allows you to add new php extensions, but you get the idea. A: I would make a "backend" server from your Python application. There are many ways to call into the Python application: Thrift and protocol buffers HTTP (CherryPy is simple to get cranking) with XML or JSON XMLRPC in Python Raw sockets This avoids any startup penalty for the Python application. A: You could do something as simple as a REST web server in Python using web.py: http://webpy.org/ and then call that via PHP, should make the whole task super simple. See this for more info: http://johnpaulett.com/2008/09/20/getting-restful-with-webpy/
Calling a Python program from PHP
I've got a version of the A* algorithm that builds a graph of the UK road and cycle network in Python lists. It takes about 30 seconds to initialise, but once done can very quickly find the shortest route between any two vertices. The start and finish vertex ids are provided by PHP. I'm trying to work out the best way of communicating between PHP and the Python program. I only want to do the initialisation phase when the Apache server starts, so my question is: How do I keep the python program alive and request routes from it via php? I have a GLAMP setup.
[ "Easiest way that I can think of would be XMLRPC. Python makes it horribly easy to set up an XMLRPC server, and there's php_xmlrpc for bindings on the PHP side...\ndef calculate_path(v1, v2):\n return [v1, ..., v2]\n\nfrom SimpleXMLRPCServer import SimpleXMLRPCServer\nserver = SimpleXMLRPCServer(('localhost', 9393))\nserver.register_function(calculate_path)\nserver.serve_forever()\n\nand you're running and should be able to do an XMLRPC call for calculate_path on http://localhost:9393/ from your PHP app.\n", "Check this question out: Calling Python in PHP\nAlso check out this extension: http://www.csh.rit.edu/~jon/projects/pip/\nI don't know if you're hosting environment allows you to add new php extensions, but you get the idea.\n", "I would make a \"backend\" server from your Python application. There are many ways to call into the Python application: \n\nThrift and protocol buffers\nHTTP (CherryPy is simple to get cranking) with XML or JSON\nXMLRPC in Python\nRaw sockets\n\nThis avoids any startup penalty for the Python application.\n", "You could do something as simple as a REST web server in Python using web.py:\nhttp://webpy.org/\nand then call that via PHP, should make the whole task super simple.\nSee this for more info:\nhttp://johnpaulett.com/2008/09/20/getting-restful-with-webpy/\n" ]
[ 2, 0, 0, 0 ]
[]
[]
[ "ipc", "php", "python" ]
stackoverflow_0003114532_ipc_php_python.txt
Q: How do I parse a listing of files to get just the filenames in Python? So lets say I'm using Python's ftplib to retrieve a list of log files from an FTP server. How would I parse that list of files to get just the file names (the last column) inside a list? See the link above for example output. A: Using retrlines() probably isn't the best idea there, since it just prints to the console and so you'd have to do tricky things to even get at that output. A likely better bet would be to use the nlst() method, which returns exactly what you want: a list of the file names. A: This best answer You may want to use ftp.nlst() instead of ftp.retrlines(). It will give you exactly what you want. If you can't, read the following : Generators for sysadmin processes In his now famous review, Generator Tricks For Systems Programmers An Introduction, David M. Beazley gives a lot of receipes to answer to this kind of data problem with wuick and reusable code. E.G : # empty list that will receive all the log entry log = [] # we pass a callback function bypass the print_line that would be called by retrlines # we do that only because we cannot use something better than retrlines ftp.retrlines('LIST', callback=log.append) # we use rsplit because it more efficient in our case if we have a big file files = (line.rsplit(None, 1)[1] for line in log) # get you file list files_list = list(files) Why don't we generate immediately the list ? Well, it's because doing it this way offer you much flexibility : you can apply any intermediate generator to filter files before turning it into files_list : it's just like pipe, add a line, you add a process without overheat (since it's generators). And if you get rid off retrlines, it still work be it's even better because you don't store the list even one time. EDIT : well, I read the comment to the other answer and it says that this won't work if there is any space in the name. Cool, this will illustrate why this method is handy. If you want to change something in the process, you just change a line. Swap : files = (line.rsplit(None, 1)[1] for line in log) and # join split the line, get all the item from the field 8 then join them files = (' '.join(line.split()[8:]) for line in log) Ok, this may no be obvious here, but for huge batch process scripts, it's nice :-) A: And a slightly less-optimal method, by the way, if you're stuck using retrlines() for some reason, is to pass a function as the second argument to retrlines(); it'll be called for each item in the list. So something like this (assuming you have an FTP object named 'ftp') would work as well: filenames = [] ftp.retrlines('LIST', lambda line: filenames.append(line.split()[-1])) The list 'filenames' will then be a list of the file names. A: Since every filename in the output starts at the same column, all you have to do is get the position of the dot on the first line: drwxrwsr-x 5 ftp-usr pdmaint 1536 Mar 20 09:48 . Then slice the filename out of the other lines using the position of that dot as the starting index. Since the dot is the last character on the line, you can use the length of the line minus 1 as the index. So the final code is something like this: lines = ftp.retrlines('LIST') lines = lines.split("\n") # This should split the string into an array of lines filename_index = len(lines[0]) - 1 files = [] for line in lines: files.append(line[filename_index:]) A: Is there any reason why ftplib.FTP.nlst() won't work for you? I just checked and it returns only names of the files in a given directory. A: If the FTP server supports the MLSD command, then please see section “single directory case” from that answer. Use an instance (say ftpd) of the FTPDirectory class, call its .getdata method with connected ftplib.FTP instance in the correct folder, then you can: directory_filenames= [ftpfile.name for ftpfile in ftpd.files] A: I believe it should work for you. file_name_list = [' '.join(each_file.split()).split()[-1] for each_file_detail in file_list_from_log] NOTES - Here I am making a assumption that you want the data in the program (as list), not on console. each_file_detail is each line that is being produced by the program. ' '.join(each_file.split()) To replace multiple spaces by 1 space.
How do I parse a listing of files to get just the filenames in Python?
So lets say I'm using Python's ftplib to retrieve a list of log files from an FTP server. How would I parse that list of files to get just the file names (the last column) inside a list? See the link above for example output.
[ "Using retrlines() probably isn't the best idea there, since it just prints to the console and so you'd have to do tricky things to even get at that output. A likely better bet would be to use the nlst() method, which returns exactly what you want: a list of the file names.\n", "This best answer\nYou may want to use ftp.nlst() instead of ftp.retrlines(). It will give you exactly what you want.\nIf you can't, read the following :\nGenerators for sysadmin processes\nIn his now famous review, Generator Tricks For Systems Programmers An Introduction, David M. Beazley gives a lot of receipes to answer to this kind of data problem with wuick and reusable code.\nE.G :\n# empty list that will receive all the log entry\nlog = [] \n# we pass a callback function bypass the print_line that would be called by retrlines\n# we do that only because we cannot use something better than retrlines\nftp.retrlines('LIST', callback=log.append)\n# we use rsplit because it more efficient in our case if we have a big file\nfiles = (line.rsplit(None, 1)[1] for line in log)\n# get you file list\nfiles_list = list(files)\n\nWhy don't we generate immediately the list ?\nWell, it's because doing it this way offer you much flexibility : you can apply any intermediate generator to filter files before turning it into files_list : it's just like pipe, add a line, you add a process without overheat (since it's generators). And if you get rid off retrlines, it still work be it's even better because you don't store the list even one time.\nEDIT : well, I read the comment to the other answer and it says that this won't work if there is any space in the name.\nCool, this will illustrate why this method is handy. If you want to change something in the process, you just change a line. Swap :\nfiles = (line.rsplit(None, 1)[1] for line in log)\n\nand\n# join split the line, get all the item from the field 8 then join them\nfiles = (' '.join(line.split()[8:]) for line in log)\n\nOk, this may no be obvious here, but for huge batch process scripts, it's nice :-)\n", "And a slightly less-optimal method, by the way, if you're stuck using retrlines() for some reason, is to pass a function as the second argument to retrlines(); it'll be called for each item in the list. So something like this (assuming you have an FTP object named 'ftp') would work as well:\nfilenames = []\nftp.retrlines('LIST', lambda line: filenames.append(line.split()[-1]))\n\nThe list 'filenames' will then be a list of the file names.\n", "Since every filename in the output starts at the same column, all you have to do is get the position of the dot on the first line:\n\ndrwxrwsr-x 5 ftp-usr pdmaint 1536 Mar 20 09:48 .\n\nThen slice the filename out of the other lines using the position of that dot as the starting index.\nSince the dot is the last character on the line, you can use the length of the line minus 1 as the index. So the final code is something like this:\nlines = ftp.retrlines('LIST')\nlines = lines.split(\"\\n\") # This should split the string into an array of lines\n\nfilename_index = len(lines[0]) - 1\nfiles = []\n\nfor line in lines:\n files.append(line[filename_index:])\n\n", "Is there any reason why ftplib.FTP.nlst() won't work for you? I just checked and it returns only names of the files in a given directory.\n", "If the FTP server supports the MLSD command, then please see section “single directory case” from that answer.\nUse an instance (say ftpd) of the FTPDirectory class, call its .getdata method with connected ftplib.FTP instance in the correct folder, then you can:\ndirectory_filenames= [ftpfile.name for ftpfile in ftpd.files]\n\n", "I believe it should work for you.\nfile_name_list = [' '.join(each_file.split()).split()[-1] for each_file_detail in file_list_from_log]\n\nNOTES - \n\nHere I am making a assumption that you want the data in the program (as list), not on console.\neach_file_detail is each line that is being produced by the program.\n' '.join(each_file.split())\n\nTo replace multiple spaces by 1 space.\n" ]
[ 9, 8, 1, 1, 1, 1, 0 ]
[]
[]
[ "ftp", "ftplib", "parsing", "python", "scripting" ]
stackoverflow_0000237699_ftp_ftplib_parsing_python_scripting.txt
Q: mod_python and subpackages importing issues: ImportError: No module named I'm exploring mod_python and I'm having trouble with the package importing. I've a structure like this: my base dir | +- __init__.py +- index.py +- package (directory) | +- __init__.py +- package.py (file) and an Apache Virtual Host like this: <VirtualHost *:80> ServerAdmin root at localhost ServerName myname DocumentRoot /path/to/my base dir <Location /> DirectoryIndex index.html index.py Options Indexes MultiViews FollowSymLinks AddHandler mod_python .py PythonHandler mod_python.publisher </Location> </VirtualHost> in the index.py file I've something like this: from package.package import myobject .... .... When I load index.py from Apache, I get a 500 Internal Server Error as follows: ImportError: No module named package.package What am I doing wrong? Cheers, Ivan A: Firstly, if you're just beginning with Python web deployment you should not be using mod_python. It is now officially a dead project and is deprecated. Use mod_wsgi instead. The actual issue with your code is that you haven't put your root directory on the Python path, so mod_python doesn't know where to find it. DocumentRoot is used for static documents, not code - in fact you shouldn't set it to your base dir, as that is insecure and may lead to the contents of your Python code being exposed over the web, which is not what you want. Instead, use the PythonPath directive: PythonPath "['/path/to/my base dir']" A: Make sure your PYTHONPATH is correct: http://www.modpython.org/live/mod_python-3.2.8/doc-html/dir-other-pp.html A: In mod_python 3.3, the structure of Python code files for mod_python.publisher is not a package. Ensure you read: http://www.modpython.org/live/current/doc-html/pyapi-apmeth.html Specifically, the documentation about import_module() as it explains how code importing works.
mod_python and subpackages importing issues: ImportError: No module named
I'm exploring mod_python and I'm having trouble with the package importing. I've a structure like this: my base dir | +- __init__.py +- index.py +- package (directory) | +- __init__.py +- package.py (file) and an Apache Virtual Host like this: <VirtualHost *:80> ServerAdmin root at localhost ServerName myname DocumentRoot /path/to/my base dir <Location /> DirectoryIndex index.html index.py Options Indexes MultiViews FollowSymLinks AddHandler mod_python .py PythonHandler mod_python.publisher </Location> </VirtualHost> in the index.py file I've something like this: from package.package import myobject .... .... When I load index.py from Apache, I get a 500 Internal Server Error as follows: ImportError: No module named package.package What am I doing wrong? Cheers, Ivan
[ "Firstly, if you're just beginning with Python web deployment you should not be using mod_python. It is now officially a dead project and is deprecated. Use mod_wsgi instead.\nThe actual issue with your code is that you haven't put your root directory on the Python path, so mod_python doesn't know where to find it. DocumentRoot is used for static documents, not code - in fact you shouldn't set it to your base dir, as that is insecure and may lead to the contents of your Python code being exposed over the web, which is not what you want.\nInstead, use the PythonPath directive:\nPythonPath \"['/path/to/my base dir']\"\n\n", "Make sure your PYTHONPATH is correct:\nhttp://www.modpython.org/live/mod_python-3.2.8/doc-html/dir-other-pp.html\n", "In mod_python 3.3, the structure of Python code files for mod_python.publisher is not a package. Ensure you read:\nhttp://www.modpython.org/live/current/doc-html/pyapi-apmeth.html\nSpecifically, the documentation about import_module() as it explains how code importing works.\n" ]
[ 3, 0, 0 ]
[]
[]
[ "apache", "mod_python", "python" ]
stackoverflow_0003109474_apache_mod_python_python.txt
Q: How to convert a Foreignkey field into ManyToMany field in Django? Possible Duplicate: Django data migration when changing a field to ManyToMany how I can accomplish this without losing data? someone know how to do that? thanks to all. A: Look at south
How to convert a Foreignkey field into ManyToMany field in Django?
Possible Duplicate: Django data migration when changing a field to ManyToMany how I can accomplish this without losing data? someone know how to do that? thanks to all.
[ "Look at south\n" ]
[ 1 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0003114097_django_django_models_python.txt
Q: Google App Engine - headers[] and headers.add_header() for cache control What is the proper way to set cache control? Sometimes I see the use of headers[] self.response.headers["Pragma"]="no-cache" self.response.headers["Cache-Control"]="no-cache, no-store, must-revalidate, pre-check=0, post-check=0" self.response.headers["Expires"]="Thu, 01 Dec 1994 16:00:00" Other times, I see headers.add_header() self.response.headers.add_header("Pragma","no-cache") self.response.headers.add_header("Cache-Control","no-cache, no-store, must-revalidate, pre-check=0, post-check=0") self.response.headers.add_header("Expires","Thu, 01 Dec 1994 16:00:00") And even a mix of both headers[] and headers.add_header() self.response.headers["Pragma"]="no-cache" self.response.headers.add_header("Cache-Control","no-cache, no-store, must-revalidate, pre-check=0, post-check=0") self.response.headers.add_header("Expires","Thu, 01 Dec 1994 16:00:00") A: The difference is that using headers[] will overwrite previous values, while add_header won't. From the wsgiref.headers docs (referred to by the GAE docs), "Setting a header deletes any existing values for that header, then adds a new value at the end of the wrapped header list."
Google App Engine - headers[] and headers.add_header() for cache control
What is the proper way to set cache control? Sometimes I see the use of headers[] self.response.headers["Pragma"]="no-cache" self.response.headers["Cache-Control"]="no-cache, no-store, must-revalidate, pre-check=0, post-check=0" self.response.headers["Expires"]="Thu, 01 Dec 1994 16:00:00" Other times, I see headers.add_header() self.response.headers.add_header("Pragma","no-cache") self.response.headers.add_header("Cache-Control","no-cache, no-store, must-revalidate, pre-check=0, post-check=0") self.response.headers.add_header("Expires","Thu, 01 Dec 1994 16:00:00") And even a mix of both headers[] and headers.add_header() self.response.headers["Pragma"]="no-cache" self.response.headers.add_header("Cache-Control","no-cache, no-store, must-revalidate, pre-check=0, post-check=0") self.response.headers.add_header("Expires","Thu, 01 Dec 1994 16:00:00")
[ "The difference is that using headers[] will overwrite previous values, while add_header won't.\nFrom the wsgiref.headers docs (referred to by the GAE docs), \"Setting a header deletes any existing values for that header, then adds a new value at the end of the wrapped header list.\"\n" ]
[ 10 ]
[]
[]
[ "google_app_engine", "header", "no_cache", "python" ]
stackoverflow_0003114803_google_app_engine_header_no_cache_python.txt
Q: What's a good swiss-army framework for the next 5 years? Basically, we want to use no flash, and eschew php where possible (for marketing reasons). Right now, I'm looking at Ruby on Rails and like what I see... but I'm not really a programmer, having working primarily with Wordpress, Drupal, and Joomla for the past 10 years. Our sites need to have a lot of custom apps built into them (video uploading and galleries, user accounts, employee time logging, and more) with consistant looks. We don't expect to have any high-traffic sites (nothing in excess of 500 unique views in a day). Anyone think that Rails is Not a good choice for the next 5 years or so? A: HTML5 While we can't predict the future, we could work in learning well the currently available technologies. A: I'd say python/Django over RoR. If you weren't avoiding PHP, Zend would be a safe(ish) bet for the next 5 years (probably). Mind you, you're by your own admission not a programmer and you're at least partially basing an engineering/technical decision on marketing (OMFG), so I'd be more worried about you lasting 5 years than any framework you choose... A: Rails will still be around in 5 years. So will C# (.net), silverlight etc. The Microsoft stack is too widely used to vanish.
What's a good swiss-army framework for the next 5 years?
Basically, we want to use no flash, and eschew php where possible (for marketing reasons). Right now, I'm looking at Ruby on Rails and like what I see... but I'm not really a programmer, having working primarily with Wordpress, Drupal, and Joomla for the past 10 years. Our sites need to have a lot of custom apps built into them (video uploading and galleries, user accounts, employee time logging, and more) with consistant looks. We don't expect to have any high-traffic sites (nothing in excess of 500 unique views in a day). Anyone think that Rails is Not a good choice for the next 5 years or so?
[ "HTML5 \nWhile we can't predict the future, we could work in learning well the currently available technologies.\n", "I'd say python/Django over RoR. \nIf you weren't avoiding PHP, Zend would be a safe(ish) bet for the next 5 years (probably).\nMind you, you're by your own admission not a programmer and you're at least partially basing an engineering/technical decision on marketing (OMFG), so I'd be more worried about you lasting 5 years than any framework you choose...\n", "Rails will still be around in 5 years. So will C# (.net), silverlight etc. The Microsoft stack is too widely used to vanish.\n" ]
[ 1, 1, 0 ]
[]
[]
[ "frameworks", "python", "ruby", "ruby_on_rails" ]
stackoverflow_0003114788_frameworks_python_ruby_ruby_on_rails.txt
Q: Automatic task execution on google app engine development server (python) The docs for the python dev server say this about running tasks: When your app is running in the development server, task queues are not processed automatically. Instead, task queues accrue tasks which you can examine and execute from the developer console... But the release notes for version 1.3.4 of the python sdk (which I am using) say: Auto task execution is now enabled in the dev_appserver. To turn this off use the flag --disable_task_running. So maybe the docs are a little behind, right? Except when I go to "http://localhost:8080/_ah/admin/tasks?queue=default", I see this: Tasks will not run automatically. Push the 'Run' button to execute each task. Can tasks be run automatically or not? If so, what is the trick? A: It seems the problem was that I was running the dev server with python 2.6 instead of 2.5. When using 2.5, everything worked.
Automatic task execution on google app engine development server (python)
The docs for the python dev server say this about running tasks: When your app is running in the development server, task queues are not processed automatically. Instead, task queues accrue tasks which you can examine and execute from the developer console... But the release notes for version 1.3.4 of the python sdk (which I am using) say: Auto task execution is now enabled in the dev_appserver. To turn this off use the flag --disable_task_running. So maybe the docs are a little behind, right? Except when I go to "http://localhost:8080/_ah/admin/tasks?queue=default", I see this: Tasks will not run automatically. Push the 'Run' button to execute each task. Can tasks be run automatically or not? If so, what is the trick?
[ "It seems the problem was that I was running the dev server with python 2.6 instead of 2.5. When using 2.5, everything worked.\n" ]
[ 2 ]
[]
[]
[ "google_app_engine", "python", "task" ]
stackoverflow_0003115053_google_app_engine_python_task.txt
Q: I have a serial Python application that takes hours to process, how can I decrease the time it takes to run? Could someone please post a few examples of multi-threaded python? I am searching all over the internet but cannot find a simple, easy-to-replicate tutorial. Simple examples are fine. I have written a program which takes a few hours to run serially--I am hoping I can bring it's run time down to minutes after multi-threading it. A: I see you got a lot of examples, all so far from @Noctis, but I'm not sure how they're going to help you. Addressing your question more directly: the only way multithreading can speed your application up, in today's CPython, is if your slow-down is due in good part to "blocking I/O" operations, e.g. due to interactions with (for example) DB servers, mail servers, websites, and so on. (A powerful alternative to speed up I/O is asynchronous, AKA event-driven, programming, for which the richest Python framework is twisted -- but it can be harder to learn, if you've never done event-driven coding). Even if you have many cores in your machine, one multi-threaded Python process will use only one of them at a time, except when it's executing specially coded extensions (typically in C, C++, Cython, and the like) which "release the GIL" (the global interpreter lock) when feasible. If you do have many cores, multiprocessing (a module whose interface is designed to look a lot like threading) can indeed speed up your program. There are many other packages supporting "symmetric multi-processor" distributed programming, see the list here, but, out of all of them, multiprocessing is the one that comes as part of the standard library (a very convenient thing). If you have multiple computers with a fast LAN between them, you should also consider the more general approach of distributed processing, which could let you use all of your available computers for the same task (some of these packages are also listed at the previous URL I gave, under the "cluster computing" header). What speed-up you can get for any number of available cores or computers ultimately depends on the nature of your problems -- and, if the problems per se are suitable for it, then also of the algorithms and data structures you're using... not all will speed-up well (it varies between "embarassingly parallel" problems such as ray-tracing, which speed up linearly all the way, to "intrinsically serial" ones where 100 machines won't be any faster than one). So, it's hard to advise you further without understanding the nature of your problems; care to explain that? A: This is not a direct answer to your question but: Have you considered using Python's multiprocessing module instead? It works by forking new processes, which has slightly more overhead but can often be faster because it avoid contention problems with Python's global interpreter lock. The documentation is quite thorough and there are a number of other articles about it online. A: Here is a good tutorial. Section 3.1.2 (page 72 of the tutorial) has a simple client/server example using threads. A: the C (CPython) implementation of Python is multi-threaded but NOT concurrent. Only one thread runs at a time, because of the Global Interpeter Lock (GIL). If you want true concurrency you can use the mulitprocessing module. None of the examples posted will help your multi-hour process run shorter, they will actually cause it to run L O N G E R. Also you don't mention what you are actually doing, but you are probably I/O bound if you are reading/writing data to anything (network or disk). And concurrency will just exacerbate the problem if that is the case. A: Example 1 import thread class sync: def __init__(self, threads): self.__threads = threads self.__count = 0 self.__main = thread.allocate_lock() self.__exit = thread.allocate_lock() self.__exit.acquire() def sync(self): self.__main.acquire() self.__count += 1 if self.__count < self.__threads: self.__main.release() else: self.__exit.release() self.__exit.acquire() self.__count -= 1 if self.__count > 0: self.__exit.release() else: self.__main.release() def example(): def get_input(share): while share[0]: share[1] = raw_input('Please say something.\n') share[2].sync() share[3].sync() def do_output(share): while share[0]: share[2].sync() print 'You said, "%s"' % share[1] share[3].sync() share = [True, None, sync(2), sync(3)] thread.start_new_thread(get_input, (share,)) thread.start_new_thread(do_output, (share,)) import time; time.sleep(60) share[0] = False share[3].sync() if __name__ == '__main__': example() A: Example 2 from os.path import basename from Queue import Queue from random import random from sys import argv, exit from threading import Thread from time import sleep # for creating widgets class Widget: pass # for creating stacks class Stack: def __init__(self): self.__stack = list() def __len__(self): return len(self.__stack) def push(self, item): self.__stack.append(item) def pop(self): return self.__stack.pop() # provides an outline for the execution of the program def main(): # check and parse the command line arguments parse_sys_argv() # setup the variables used by the threads run_flag = [True] queue = Queue(argv[1]) send = Stack() recv = Stack() # start the threads producer = Thread(target=produce, args=(run_flag, queue, send)) consumer = Thread(target=consume, args=(run_flag, queue, recv, producer)) producer.start() consumer.start() # let the threads do their work sleep(argv[2]) run_flag[0] = False consumer.join() # verify that the solution was valid calculate_results(send, recv) # parses and checks the command line arguments def parse_sys_argv(): try: # there should be two command line arguments assert len(argv) == 3 # convert <buf_size> and check argv[1] = abs(int(argv[1])) assert argv[1] > 0 # convert <run_time> and check argv[2] = abs(float(argv[2])) assert argv[2] > 0 except: # print out usage information print basename(argv[0]), print '<buf_size> <run_time>' # exits the program exit(1) # called by the producer thread def produce(run_flag, queue, send): while run_flag[0]: # simulate production sleep(random()) # put widget in buffer item = Widget() queue.put(item) send.push(item) # called by the consumer thread def consume(run_flag, queue, recv, producer): # consume items while running while run_flag[0]: do_consume(queue, recv) # empty the queue to allow maximum room while not queue.empty(): do_consume(queue, recv) # wait for the producer to end producer.join() # consume any other items that might have been produced while not queue.empty(): do_consume(queue, recv) # executes one consumption operation def do_consume(queue, recv): # get a widget from the queue recv.push(queue.get()) # simulate consumption sleep(random()) # verifies that send and recv were equal def calculate_results(send, recv): print 'Solution has', try: # make sure that send and recv have the same length assert len(send) == len(recv) # check all of the contents of send and recv while send: # check the identity of the items in send and recv assert send.pop() is recv.pop() print 'passed.' except: print 'failed.' # starts the program if __name__ == '__main__': main() A: Example 3 from os.path import basename from Queue import Queue from random import random, seed from sys import argv, exit from threading import Thread from time import sleep ################################################################################ class Widget: pass class Stack: def __init__(self): self.__stack = list() def __len__(self): return len(self.__stack) def push(self, item): self.__stack.append(item) def pop(self): return self.__stack.pop() ################################################################################ def main(): parse_argv() run_flag, buffer_queue, producer_stack, consumer_stack, print_queue = [True], Queue(argv[1]), Stack(), Stack(), Queue() producer_thread = Thread(target=producer, args=(run_flag, argv[3], buffer_queue, producer_stack, print_queue)) consumer_thread = Thread(target=consumer, args=(run_flag, producer_thread, buffer_queue, consumer_stack, argv[4], print_queue)) printer_thread = Thread(target=printer, args=(run_flag, consumer_thread, print_queue)) producer_thread.start() consumer_thread.start() printer_thread.start() sleep(argv[2]) run_flag[0] = False printer_thread.join() check_results(producer_stack , consumer_stack) def parse_argv(): try: assert len(argv) > 4 argv[1] = abs(int(argv[1])) argv[2] = abs(float(argv[2])) assert argv[1] and argv[2] argv[3] = abs(float(argv[3])) argv[4] = abs(float(argv[4])) if len(argv) > 5: seed(convert(' '.join(argv[5:]))) except: print basename(argv[0]), '<buff_size> <main_time> <prod_time> <cons_time> [<seed>]' exit(1) def convert(string): number = 1 for character in string: number <<= 8 number += ord(character) return number def check_results(producer_stack , consumer_stack): print 'Solution has', try: assert len(producer_stack) == len(consumer_stack) while producer_stack: assert producer_stack.pop() is consumer_stack.pop() print 'passed.' except: print 'failed.' ################################################################################ def producer(run_flag, max_time, buffer_queue, producer_stack, print_queue): while run_flag[0]: sleep(random() * max_time) widget = Widget() buffer_queue.put(widget) producer_stack.push(widget) print_queue.put('Producer: %s Widget' % id(widget)) def consumer(run_flag, producer_thread, buffer_queue, consumer_stack, max_time, print_queue): while run_flag[0] or producer_thread.isAlive() or not buffer_queue.empty(): widget = buffer_queue.get() consumer_stack.push(widget) sleep(random() * max_time) print_queue.put('Consumer: %s Widget' % id(widget)) def printer(run_flag, consumer_thread, print_queue): while run_flag[0] or consumer_thread.isAlive() or not print_queue.empty(): if print_queue.empty(): sleep(0.1) else: print print_queue.get() ################################################################################ if __name__ == '__main__': main() A: Example 4 import socket import sys import thread def main(setup, error): sys.stderr = file(error, 'a') for settings in parse(setup): thread.start_new_thread(server, settings) lock = thread.allocate_lock() lock.acquire() lock.acquire() def parse(setup): settings = list() for line in file(setup): parts = line.split() settings.append((parts[0], int(parts[1]), int(parts[2]))) return settings def server(*settings): try: dock_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) dock_socket.bind(('', settings[2])) dock_socket.listen(5) while True: client_socket = dock_socket.accept()[0] server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_socket.connect((settings[0], settings[1])) thread.start_new_thread(forward, (client_socket, server_socket)) thread.start_new_thread(forward, (server_socket, client_socket)) finally: thread.start_new_thread(server, settings) def forward(source, destination): string = ' ' while string: string = source.recv(1024) if string: destination.sendall(string) else: source.shutdown(socket.SHUT_RD) destination.shutdown(socket.SHUT_WR) if __name__ == '__main__': main('proxy.ini', 'error.log') A: Example 5 # #include <windows.h> import thread # #include <math.h> import math # #include <stdio.h> import sys # #include <stdlib.h> import time # static int runFlag = TRUE; runFlag = True # void main(int argc, char *argv[]) { def main(argc, argv): global runFlag # unsigned int runTime # PYTHON: NO CODE # SYSTEMTIME now; # PYTHON: NO CODE # WORD stopTimeMinute, stopTimeSecond; # PYTHON: NO CODE # // Get command line argument, N try: N = abs(int(argv[1])) except: sys.exit(1) # // Get the time the threads should run, runtime try: runTime = abs(int(argv[2])) except: sys.exit(1) # // Calculate time to halt (learn better ways to do this later) # GetSystemTime(&now); now = time.localtime() # printf("mthread: Suite starting at system time # %d:%d:%d\n", now.wHour, now.wMinute, now.wSecond); sys.stdout.write('mthread: Suite starting at system time %d:%d:%d\n' \ % (now.tm_hour, now.tm_min, now.tm_sec)) # stopTimeSecond = (now.wSecond + (WORD) runTime) % 60; stopTimeSecond = (now.tm_sec + runTime) % 60 # stopTimeMinute = now.wMinute + (now.wSecond + # (WORD) runTime) / 60; stopTimeMinute = now.tm_min + (now.tm_sec + runTime) / 60 # // For 1 to N # for (i = 0; i < N; i++) { for i in range(N): # // Create a new thread to execute simulated word thread.start_new_thread(threadWork, ()) # Sleep(100); // Let newly created thread run time.sleep(0.1) # } # PYTHON: NO CODE # // Cycle while children work ... # while (runFlag) { while runFlag: # GetSystemTime(&now); now = time.localtime() # if ((now.wMinute >= stopTimeMinute) # && # (now.wSecond >= stopTimeSecond) # ) if now.tm_min >= stopTimeMinute \ and now.tm_sec >= stopTimeSecond: # runFlag = FALSE; runFlag = False # Sleep(1000); time.sleep(1) # } # PYTHON: NO CODE # Sleep(5000); time.sleep(5) # } # PYTHON: NO CODE # // The code executed by each worker thread (simulated work) # DWORD WINAPI threadWork(LPVOID threadNo) { def threadWork(): threadNo = thread.get_ident() # // Local variables # double y; # PYTHON: NO CODE # const double x = 3.14159; x = 3.14159 # const double e = 2.7183; e = 2.7183 # int i; # PYTHON: NO CODE # const int napTime = 1000; // in milliseconds napTime = 1000 # const int busyTime = 40000; busyTime = 40000 # DWORD result = 0; result = 0 # // Create load # while (runFlag) { while runFlag: # // Parameterized processor burst phase # for (i = 0; i < busyTime; i++) for i in range(busyTime): # y = pow(x, e); y = math.pow(x, e) # // Parameterized sleep phase # Sleep(napTime); time.sleep(napTime / 1000.0) # // Write message to stdout sys.stdout.write('Thread %s just woke up.\n' % threadNo) # } # PYTHON: NO CODE # // Terminating # return result; return result # } # PYTHON: NO CODE if __name__ == '__main__': main(len(sys.argv), sys.argv) A: Example 6 import tkinter import _thread import time EPOCH_DELTA = 946684800 MICREV_IN_DAY = 1000000 MILREV_IN_DAY = 1000 SECOND_IN_DAY = 86400 DAY_IN_WEEK = 7 WEEK_IN_MONTH = 4 MONTH_IN_SEASON = 3 SEASON_IN_YEAR = 4 SECOND_IN_WEEK = SECOND_IN_DAY * DAY_IN_WEEK SECOND_IN_MONTH = SECOND_IN_WEEK * WEEK_IN_MONTH SECOND_IN_SEASON = SECOND_IN_MONTH * MONTH_IN_SEASON SECOND_IN_YEAR = SECOND_IN_SEASON * SEASON_IN_YEAR def seconds(): "Return seconds since the epoch." return time.time() - EPOCH_DELTA def micrev(seconds): "Convert from seconds to micrev." x = seconds % SECOND_IN_DAY * MICREV_IN_DAY / SECOND_IN_DAY % MILREV_IN_DAY return int(x) def milrev(seconds): "Convert from seconds to milrev." x = seconds % SECOND_IN_DAY * MILREV_IN_DAY / SECOND_IN_DAY return int(x) def day(seconds): "Convert from seconds to days." x = seconds / SECOND_IN_DAY % DAY_IN_WEEK return int(x) def week(seconds): "Convert from seconds to weeks." x = seconds / SECOND_IN_WEEK % WEEK_IN_MONTH return int(x) def month(seconds): "Convert from seconds to months." x = seconds / SECOND_IN_MONTH % MONTH_IN_SEASON return int(x) def season(seconds): "Convert from seconds to seasons." x = seconds / SECOND_IN_SEASON % SEASON_IN_YEAR return int(x) def year(seconds): "Convert from seconds to years." x = seconds / SECOND_IN_YEAR return int(x) UNITS = year, season, month, week, day, milrev, micrev def text(seconds, spec='{0}.{1}.{2}.{3}.{4}.{5:03}.{6:03}', unit=UNITS): "Convert from seconds to text." return spec.format(*[func(seconds) for func in unit]) class Quantum_Timer: "Quantum_Timer(function, *args, **kwargs) -> Quantum_Timer" def __init__(self, function, *args, **kwargs): "Initialize the Quantum_Timer object." self.__function = function self.__args = args self.__kwargs = kwargs self.__thread = False self.__lock = _thread.allocate_lock() def start(self): "Start the Quantum_Timer object." with self.__lock: self.__active = True if not self.__thread: self.__thread = True _thread.start_new_thread(self.__run, ()) def stop(self): "Stop the Quantum_Timer object." with self.__lock: self.__active = False def __run(self): "Private class method." while True: secs = time.clock() plus = secs + 0.0864 over = plus % 0.0864 diff = plus - secs - over time.sleep(diff) with self.__lock: if not self.__active: self.__thread = False break self.__function(*self.__args, **self.__kwargs) def main(): root = tkinter.Tk() root.resizable(False, False) root.title('Time in Tessaressunago') secs = tkinter.StringVar() text = tkinter.Label(textvariable=secs, font=('helvetica', 16, 'bold')) text.grid(padx=5, pady=5) thread = Quantum_Timer(update, secs) thread.start() root.mainloop() def update(secs): s = seconds() t = text(s) p = 1000000000 * 1.01 ** (s / SECOND_IN_YEAR) secs.set('Time = {0}\nNational = {1}'.format(t, fix(p))) def fix(number, sep=','): number = str(int(number)) string = '' while number: string = number[-1] + string number = number[:-1] if number and not (len(string) + 1) % 4: string = sep + string return string if __name__ == '__main__': main() A: Example 7 HOST = '127.0.0.1' PORT = 8080 from Tkinter import * import tkColorChooser import socket import thread import cPickle ################################################################################ class ZSP: 'ZSP(socket) -> ZSP' def __init__(self, socket): 'Initialize the Zero SPOTS Protocol object.' self.__file = socket.makefile('b', 0) def send(self, obj): 'Send one object.' cPickle.dump(obj, self.__file, cPickle.HIGHEST_PROTOCOL) def recv(self): 'Receive one object.' return cPickle.load(self.__file) ################################################################################ def main(): global hold, fill, draw, look hold = [] fill = '#000000' connect() root = Tk() root.title('Paint 2.0') root.resizable(False, False) upper = LabelFrame(root, text='Your Canvas') lower = LabelFrame(root, text='Their Canvas') draw = Canvas(upper, bg='#ffffff', width=400, height=300, highlightthickness=0) look = Canvas(lower, bg='#ffffff', width=400, height=300, highlightthickness=0) cursor = Button(upper, text='Cursor Color', command=change_cursor) canvas = Button(upper, text='Canvas Color', command=change_canvas) draw.bind('<Motion>', motion) draw.bind('<ButtonPress-1>', press) draw.bind('<ButtonRelease-1>', release) draw.bind('<Button-3>', delete) upper.grid(padx=5, pady=5) lower.grid(padx=5, pady=5) draw.grid(row=0, column=0, padx=5, pady=5, columnspan=2) look.grid(padx=5, pady=5) cursor.grid(row=1, column=0, padx=5, pady=5, sticky=EW) canvas.grid(row=1, column=1, padx=5, pady=5, sticky=EW) root.mainloop() ################################################################################ def connect(): try: start_client() except: start_server() thread.start_new_thread(processor, ()) def start_client(): global ZSP server = socket.socket() server.connect((HOST, PORT)) ZSP = ZSP(server) def start_server(): global ZSP server = socket.socket() server.bind(('', PORT)) server.listen(1) ZSP = ZSP(server.accept()[0]) def processor(): while True: func, args, kwargs = ZSP.recv() getattr(look, func)(*args, **kwargs) def call(func, *args, **kwargs): ZSP.send((func, args, kwargs)) ################################################################################ def change_cursor(): global fill color = tkColorChooser.askcolor(color=fill)[1] if color is not None: fill = color def change_canvas(): color = tkColorChooser.askcolor(color=draw['bg'])[1] if color is not None: draw.config(bg=color) call('config', bg=color) ################################################################################ def motion(event): if hold: hold.extend([event.x, event.y]) event.widget.create_line(hold[-4:], fill=fill, tag='TEMP') call('create_line', hold[-4:], fill=fill, tag='TEMP') def press(event): global hold hold = [event.x, event.y] def release(event): global hold if len(hold) > 2: event.widget.delete('TEMP') event.widget.create_line(hold, fill=fill, smooth=True) call('delete', 'TEMP') call('create_line', hold, fill=fill, smooth=True) hold = [] def delete(event): event.widget.delete(ALL) call('delete', ALL) ################################################################################ if __name__ == '__main__': main() A: Example 8 HOST = '127.0.0.1' PORT = 8080 try: from Tkinter import * except ImportError: from tkinter import * try: import tkColorChooser except ImportError: import tkinter.colorchooser as tkColorChooser try: import thread except ImportError: import _thread as thread import socket import pickle import time import sys ################################################################################ class ZSP: 'ZSP(socket) -> ZSP' def __init__(self, socket): 'Initialize the Zero SPOTS Protocol object.' self.__o_file = socket.makefile('bw', 0) self.__i_file = socket.makefile('br', 0) def send(self, obj): 'Send one object.' pickle.dump(obj, self.__o_file, pickle.HIGHEST_PROTOCOL) def recv(self): 'Receive one object.' return pickle.load(self.__i_file) ################################################################################ class QRP: 'QRP(ZSP) -> QRP' def __init__(self, ZSP): 'Initialize the Query/Reply Protocol object.' self.__ZSP = ZSP self.__error = None self.__Q_anchor = [] self.__Q_packet = [] self.__R_anchor = {} self.__Q_lock = thread.allocate_lock() self.__R_lock = thread.allocate_lock() thread.start_new_thread(self.__thread, ()) def send_Q(self, ID, obj): 'Send one query.' if self.__error: raise self.__error self.__ZSP.send((False, ID, obj)) def recv_Q(self, timeout=None): 'Receive one query.' if self.__error: raise self.__error if timeout is not None: if not isinstance(timeout, (float, int)): raise TypeError('timeout must be of type float or int') if not timeout >= 0: raise ValueError('timeout must be greater than or equal to 0') self.__Q_lock.acquire() try: try: if self.__Q_packet: Q = True ID, obj = self.__Q_packet.pop() else: Q = False anchor = [thread.allocate_lock()] anchor[0].acquire() self.__Q_anchor.append(anchor) finally: self.__Q_lock.release() except AttributeError: raise self.__error if Q: return ID, obj if timeout: thread.start_new_thread(self.__Q_thread, (timeout, anchor)) anchor[0].acquire() try: Q = anchor[1] except IndexError: if self.__error: raise self.__error raise Warning return Q def send_R(self, ID, obj): 'Send one reply.' if self.__error: raise self.__error self.__ZSP.send((True, ID, obj)) def recv_R(self, ID, timeout=None): 'Receive one reply.' if self.__error: raise self.__error if timeout is not None: if not isinstance(timeout, (float, int)): raise TypeError('timeout must be of type float or int') if not timeout >= 0: raise ValueError('timeout must be greater than or equal to 0') anchor = [thread.allocate_lock()] anchor[0].acquire() self.__R_lock.acquire() try: try: self.__R_anchor[ID] = anchor finally: self.__R_lock.release() except AttributeError: raise self.__error if timeout: thread.start_new_thread(self.__R_thread, (timeout, ID)) anchor[0].acquire() try: R = anchor[1] except IndexError: if self.__error: raise self.__error raise Warning return R def __thread(self): 'Private class method.' try: while True: R, ID, obj = self.__ZSP.recv() if R: self.__R_lock.acquire() if self.__R_anchor: self.__R_anchor[ID].append(obj) self.__R_anchor[ID][0].release() del self.__R_anchor[ID] self.__R_lock.release() else: self.__Q_lock.acquire() if self.__Q_anchor: anchor = self.__Q_anchor.pop() anchor.append((ID, obj)) anchor[0].release() else: self.__Q_packet.append((ID, obj)) self.__Q_lock.release() except Exception: error = sys.exc_info()[1] if isinstance(error, EOFError): self.__error = EOFError else: self.__error = IOError self.__Q_lock.acquire() for anchor in self.__Q_anchor: anchor[0].release() del self.__Q_anchor del self.__Q_packet self.__Q_lock.release() self.__R_lock.acquire() for key in self.__R_anchor: self.__R_anchor[key][0].release() del self.__R_anchor self.__R_lock.release() def __Q_thread(self, timeout, anchor): 'Private class method.' time.sleep(timeout) self.__Q_lock.acquire() if not self.__error and anchor in self.__Q_anchor: anchor[0].release() self.__Q_anchor.remove(anchor) self.__Q_lock.release() def __R_thread(self, timeout, ID): 'Private class method.' time.sleep(timeout) self.__R_lock.acquire() if not self.__error and ID in self.__R_anchor: self.__R_anchor[ID][0].release() del self.__R_anchor[ID] self.__R_lock.release() ################################################################################ class QRI: 'QRI(QRP) -> QRI' def __init__(self, QRP): 'Initialize the Query/Reply Interface object.' self.__QRP = QRP self.__ID = 0 self.__lock = thread.allocate_lock() def call(self, obj, timeout=None): 'Send one query and receive one reply.' self.__lock.acquire() ID = ''.join(chr(self.__ID >> shift & 0xFF) for shift in range(24, -8, -8)) self.__ID = (self.__ID + 1) % (2 ** 32) self.__lock.release() self.__QRP.send_Q(ID, obj) return self.__QRP.recv_R(ID, timeout) def query(self, timeout=None): 'Receive one query.' return self.__QRP.recv_Q(timeout) def reply(self, ID, obj): 'Send one reply.' self.__QRP.send_R(ID, obj) ################################################################################ def qri(socket): 'Construct a QRI object.' return QRI(QRP(ZSP(socket))) ################################################################################ def main(): global hold, fill, draw, look hold = [] fill = '#000000' connect() root = Tk() root.title('Paint 1.0') root.resizable(False, False) upper = LabelFrame(root, text='Your Canvas') lower = LabelFrame(root, text='Their Canvas') draw = Canvas(upper, bg='#ffffff', width=400, height=300, highlightthickness=0) look = Canvas(lower, bg='#ffffff', width=400, height=300, highlightthickness=0) cursor = Button(upper, text='Cursor Color', command=change_cursor) canvas = Button(upper, text='Canvas Color', command=change_canvas) draw.bind('<Motion>', motion) draw.bind('<ButtonPress-1>', press) draw.bind('<ButtonRelease-1>', release) draw.bind('<Button-3>', delete) upper.grid(padx=5, pady=5) lower.grid(padx=5, pady=5) draw.grid(row=0, column=0, padx=5, pady=5, columnspan=2) look.grid(padx=5, pady=5) cursor.grid(row=1, column=0, padx=5, pady=5, sticky=EW) canvas.grid(row=1, column=1, padx=5, pady=5, sticky=EW) root.mainloop() ################################################################################ def connect(): try: start_client() except: start_server() thread.start_new_thread(processor, ()) def start_client(): global QRI server = socket.socket() server.connect((HOST, PORT)) QRI = qri(server) def start_server(): global QRI server = socket.socket() server.bind(('', PORT)) server.listen(1) QRI = qri(server.accept()[0]) def processor(): while True: ID, (func, args, kwargs) = QRI.query() getattr(look, func)(*args, **kwargs) def call(func, *args, **kwargs): try: QRI.call((func, args, kwargs), 0.05) except: pass ################################################################################ def change_cursor(): global fill color = tkColorChooser.askcolor(color=fill)[1] if color is not None: fill = color def change_canvas(): color = tkColorChooser.askcolor(color=draw['bg'])[1] if color is not None: draw['bg'] = color draw.config(bg=color) call('config', bg=color) ################################################################################ def motion(event): if hold: hold.extend([event.x, event.y]) event.widget.create_line(hold[-4:], fill=fill, tag='TEMP') call('create_line', hold[-4:], fill=fill, tag='TEMP') def press(event): global hold hold = [event.x, event.y] def release(event): global hold if len(hold) > 2: event.widget.delete('TEMP') event.widget.create_line(hold, fill=fill, smooth=True) call('delete', 'TEMP') call('create_line', hold, fill=fill, smooth=True) hold = [] def delete(event): event.widget.delete(ALL) call('delete', ALL) ################################################################################ if __name__ == '__main__': main()
I have a serial Python application that takes hours to process, how can I decrease the time it takes to run?
Could someone please post a few examples of multi-threaded python? I am searching all over the internet but cannot find a simple, easy-to-replicate tutorial. Simple examples are fine. I have written a program which takes a few hours to run serially--I am hoping I can bring it's run time down to minutes after multi-threading it.
[ "I see you got a lot of examples, all so far from @Noctis, but I'm not sure how they're going to help you. Addressing your question more directly: the only way multithreading can speed your application up, in today's CPython, is if your slow-down is due in good part to \"blocking I/O\" operations, e.g. due to interactions with (for example) DB servers, mail servers, websites, and so on. (A powerful alternative to speed up I/O is asynchronous, AKA event-driven, programming, for which the richest Python framework is twisted -- but it can be harder to learn, if you've never done event-driven coding).\nEven if you have many cores in your machine, one multi-threaded Python process will use only one of them at a time, except when it's executing specially coded extensions (typically in C, C++, Cython, and the like) which \"release the GIL\" (the global interpreter lock) when feasible.\nIf you do have many cores, multiprocessing (a module whose interface is designed to look a lot like threading) can indeed speed up your program. There are many other packages supporting \"symmetric multi-processor\" distributed programming, see the list here, but, out of all of them, multiprocessing is the one that comes as part of the standard library (a very convenient thing). If you have multiple computers with a fast LAN between them, you should also consider the more general approach of distributed processing, which could let you use all of your available computers for the same task (some of these packages are also listed at the previous URL I gave, under the \"cluster computing\" header).\nWhat speed-up you can get for any number of available cores or computers ultimately depends on the nature of your problems -- and, if the problems per se are suitable for it, then also of the algorithms and data structures you're using... not all will speed-up well (it varies between \"embarassingly parallel\" problems such as ray-tracing, which speed up linearly all the way, to \"intrinsically serial\" ones where 100 machines won't be any faster than one). So, it's hard to advise you further without understanding the nature of your problems; care to explain that?\n", "This is not a direct answer to your question but:\nHave you considered using Python's multiprocessing module instead? It works by forking new processes, which has slightly more overhead but can often be faster because it avoid contention problems with Python's global interpreter lock. The documentation is quite thorough and there are a number of other articles about it online.\n", "Here is a good tutorial. Section 3.1.2 (page 72 of the tutorial) has a simple client/server example using threads.\n", "the C (CPython) implementation of Python is multi-threaded but NOT concurrent. Only one thread runs at a time, because of the Global Interpeter Lock (GIL). If you want true concurrency you can use the mulitprocessing module. \nNone of the examples posted will help your multi-hour process run shorter, they will actually cause it to run L O N G E R. \nAlso you don't mention what you are actually doing, but you are probably I/O bound if you are reading/writing data to anything (network or disk). And concurrency will just exacerbate the problem if that is the case.\n", "Example 1\nimport thread\n\nclass sync:\n\n def __init__(self, threads):\n self.__threads = threads\n self.__count = 0\n self.__main = thread.allocate_lock()\n self.__exit = thread.allocate_lock()\n self.__exit.acquire()\n\n def sync(self):\n self.__main.acquire()\n self.__count += 1\n if self.__count < self.__threads:\n self.__main.release()\n else:\n self.__exit.release()\n self.__exit.acquire()\n self.__count -= 1\n if self.__count > 0:\n self.__exit.release()\n else:\n self.__main.release()\n\ndef example():\n def get_input(share):\n while share[0]:\n share[1] = raw_input('Please say something.\\n')\n share[2].sync()\n share[3].sync()\n def do_output(share):\n while share[0]:\n share[2].sync()\n print 'You said, \"%s\"' % share[1]\n share[3].sync()\n share = [True, None, sync(2), sync(3)]\n thread.start_new_thread(get_input, (share,))\n thread.start_new_thread(do_output, (share,))\n import time; time.sleep(60)\n share[0] = False\n share[3].sync()\n\nif __name__ == '__main__':\n example()\n\n", "Example 2\nfrom os.path import basename\nfrom Queue import Queue\nfrom random import random\nfrom sys import argv, exit\nfrom threading import Thread\nfrom time import sleep\n\n# for creating widgets\nclass Widget:\n pass\n\n# for creating stacks\nclass Stack:\n def __init__(self):\n self.__stack = list()\n def __len__(self):\n return len(self.__stack)\n def push(self, item):\n self.__stack.append(item)\n def pop(self):\n return self.__stack.pop()\n\n# provides an outline for the execution of the program\ndef main():\n # check and parse the command line arguments\n parse_sys_argv()\n # setup the variables used by the threads\n run_flag = [True]\n queue = Queue(argv[1])\n send = Stack()\n recv = Stack()\n # start the threads\n producer = Thread(target=produce, args=(run_flag, queue, send))\n consumer = Thread(target=consume, args=(run_flag, queue, recv, producer))\n producer.start()\n consumer.start()\n # let the threads do their work\n sleep(argv[2])\n run_flag[0] = False\n consumer.join()\n # verify that the solution was valid\n calculate_results(send, recv)\n\n# parses and checks the command line arguments\ndef parse_sys_argv():\n try:\n # there should be two command line arguments\n assert len(argv) == 3\n # convert <buf_size> and check\n argv[1] = abs(int(argv[1]))\n assert argv[1] > 0\n # convert <run_time> and check\n argv[2] = abs(float(argv[2]))\n assert argv[2] > 0\n except:\n # print out usage information\n print basename(argv[0]),\n print '<buf_size> <run_time>'\n # exits the program\n exit(1)\n\n# called by the producer thread\ndef produce(run_flag, queue, send):\n while run_flag[0]:\n # simulate production\n sleep(random())\n # put widget in buffer\n item = Widget()\n queue.put(item)\n send.push(item)\n\n# called by the consumer thread\ndef consume(run_flag, queue, recv, producer):\n # consume items while running\n while run_flag[0]:\n do_consume(queue, recv)\n # empty the queue to allow maximum room\n while not queue.empty():\n do_consume(queue, recv)\n # wait for the producer to end\n producer.join()\n # consume any other items that might have been produced\n while not queue.empty():\n do_consume(queue, recv)\n\n# executes one consumption operation\ndef do_consume(queue, recv):\n # get a widget from the queue\n recv.push(queue.get())\n # simulate consumption\n sleep(random())\n\n# verifies that send and recv were equal\ndef calculate_results(send, recv):\n print 'Solution has',\n try:\n # make sure that send and recv have the same length\n assert len(send) == len(recv)\n # check all of the contents of send and recv\n while send:\n # check the identity of the items in send and recv\n assert send.pop() is recv.pop()\n print 'passed.'\n except:\n print 'failed.'\n\n# starts the program\nif __name__ == '__main__':\n main()\n\n", "Example 3\nfrom os.path import basename\nfrom Queue import Queue\nfrom random import random, seed\nfrom sys import argv, exit\nfrom threading import Thread\nfrom time import sleep\n\n################################################################################\n\nclass Widget:\n pass\n\nclass Stack:\n def __init__(self):\n self.__stack = list()\n def __len__(self):\n return len(self.__stack)\n def push(self, item):\n self.__stack.append(item)\n def pop(self):\n return self.__stack.pop()\n\n################################################################################\n\ndef main():\n parse_argv()\n run_flag, buffer_queue, producer_stack, consumer_stack, print_queue = [True], Queue(argv[1]), Stack(), Stack(), Queue()\n producer_thread = Thread(target=producer, args=(run_flag, argv[3], buffer_queue, producer_stack, print_queue))\n consumer_thread = Thread(target=consumer, args=(run_flag, producer_thread, buffer_queue, consumer_stack, argv[4], print_queue))\n printer_thread = Thread(target=printer, args=(run_flag, consumer_thread, print_queue))\n producer_thread.start()\n consumer_thread.start()\n printer_thread.start()\n sleep(argv[2])\n run_flag[0] = False\n printer_thread.join()\n check_results(producer_stack , consumer_stack)\n\ndef parse_argv():\n try:\n assert len(argv) > 4\n argv[1] = abs(int(argv[1]))\n argv[2] = abs(float(argv[2]))\n assert argv[1] and argv[2]\n argv[3] = abs(float(argv[3]))\n argv[4] = abs(float(argv[4]))\n if len(argv) > 5:\n seed(convert(' '.join(argv[5:])))\n except:\n print basename(argv[0]), '<buff_size> <main_time> <prod_time> <cons_time> [<seed>]'\n exit(1)\n\ndef convert(string):\n number = 1\n for character in string:\n number <<= 8\n number += ord(character)\n return number\n\ndef check_results(producer_stack , consumer_stack):\n print 'Solution has',\n try:\n assert len(producer_stack) == len(consumer_stack)\n while producer_stack:\n assert producer_stack.pop() is consumer_stack.pop()\n print 'passed.'\n except:\n print 'failed.'\n\n################################################################################\n\ndef producer(run_flag, max_time, buffer_queue, producer_stack, print_queue):\n while run_flag[0]:\n sleep(random() * max_time)\n widget = Widget()\n buffer_queue.put(widget)\n producer_stack.push(widget)\n print_queue.put('Producer: %s Widget' % id(widget))\n\ndef consumer(run_flag, producer_thread, buffer_queue, consumer_stack, max_time, print_queue):\n while run_flag[0] or producer_thread.isAlive() or not buffer_queue.empty():\n widget = buffer_queue.get()\n consumer_stack.push(widget)\n sleep(random() * max_time)\n print_queue.put('Consumer: %s Widget' % id(widget))\n\ndef printer(run_flag, consumer_thread, print_queue):\n while run_flag[0] or consumer_thread.isAlive() or not print_queue.empty():\n if print_queue.empty():\n sleep(0.1)\n else:\n print print_queue.get()\n\n################################################################################\n\nif __name__ == '__main__':\n main()\n\n", "Example 4\nimport socket\nimport sys\nimport thread\n\ndef main(setup, error):\n sys.stderr = file(error, 'a')\n for settings in parse(setup):\n thread.start_new_thread(server, settings)\n lock = thread.allocate_lock()\n lock.acquire()\n lock.acquire()\n\ndef parse(setup):\n settings = list()\n for line in file(setup):\n parts = line.split()\n settings.append((parts[0], int(parts[1]), int(parts[2])))\n return settings\n\ndef server(*settings):\n try:\n dock_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n dock_socket.bind(('', settings[2]))\n dock_socket.listen(5)\n while True:\n client_socket = dock_socket.accept()[0]\n server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n server_socket.connect((settings[0], settings[1]))\n thread.start_new_thread(forward, (client_socket, server_socket))\n thread.start_new_thread(forward, (server_socket, client_socket))\n finally:\n thread.start_new_thread(server, settings)\n\ndef forward(source, destination):\n string = ' '\n while string:\n string = source.recv(1024)\n if string:\n destination.sendall(string)\n else:\n source.shutdown(socket.SHUT_RD)\n destination.shutdown(socket.SHUT_WR)\n\nif __name__ == '__main__':\n main('proxy.ini', 'error.log')\n\n", "Example 5\n# #include <windows.h>\nimport thread\n# #include <math.h>\nimport math\n# #include <stdio.h>\nimport sys\n# #include <stdlib.h>\nimport time\n\n# static int runFlag = TRUE;\nrunFlag = True\n\n# void main(int argc, char *argv[]) {\ndef main(argc, argv):\n global runFlag\n # unsigned int runTime\n # PYTHON: NO CODE\n\n # SYSTEMTIME now;\n # PYTHON: NO CODE\n # WORD stopTimeMinute, stopTimeSecond;\n # PYTHON: NO CODE\n\n # // Get command line argument, N\n try:\n N = abs(int(argv[1]))\n except:\n sys.exit(1)\n # // Get the time the threads should run, runtime\n try:\n runTime = abs(int(argv[2]))\n except:\n sys.exit(1)\n # // Calculate time to halt (learn better ways to do this later)\n # GetSystemTime(&now);\n now = time.localtime()\n # printf(\"mthread: Suite starting at system time\n # %d:%d:%d\\n\", now.wHour, now.wMinute, now.wSecond);\n sys.stdout.write('mthread: Suite starting at system time %d:%d:%d\\n' \\\n % (now.tm_hour, now.tm_min, now.tm_sec))\n # stopTimeSecond = (now.wSecond + (WORD) runTime) % 60;\n stopTimeSecond = (now.tm_sec + runTime) % 60\n # stopTimeMinute = now.wMinute + (now.wSecond +\n # (WORD) runTime) / 60;\n stopTimeMinute = now.tm_min + (now.tm_sec + runTime) / 60\n\n # // For 1 to N\n # for (i = 0; i < N; i++) {\n for i in range(N):\n # // Create a new thread to execute simulated word\n thread.start_new_thread(threadWork, ())\n # Sleep(100); // Let newly created thread run\n time.sleep(0.1)\n # }\n # PYTHON: NO CODE\n\n # // Cycle while children work ...\n # while (runFlag) {\n while runFlag:\n # GetSystemTime(&now);\n now = time.localtime()\n # if ((now.wMinute >= stopTimeMinute)\n # &&\n # (now.wSecond >= stopTimeSecond)\n # )\n if now.tm_min >= stopTimeMinute \\\n and now.tm_sec >= stopTimeSecond:\n # runFlag = FALSE;\n runFlag = False\n # Sleep(1000);\n time.sleep(1)\n # }\n # PYTHON: NO CODE\n # Sleep(5000);\n time.sleep(5)\n# }\n# PYTHON: NO CODE\n\n# // The code executed by each worker thread (simulated work)\n# DWORD WINAPI threadWork(LPVOID threadNo) {\ndef threadWork():\n threadNo = thread.get_ident()\n # // Local variables\n # double y;\n # PYTHON: NO CODE\n # const double x = 3.14159;\n x = 3.14159\n # const double e = 2.7183;\n e = 2.7183\n # int i;\n # PYTHON: NO CODE\n # const int napTime = 1000; // in milliseconds\n napTime = 1000\n # const int busyTime = 40000;\n busyTime = 40000\n # DWORD result = 0;\n result = 0\n\n # // Create load\n # while (runFlag) {\n while runFlag:\n # // Parameterized processor burst phase\n # for (i = 0; i < busyTime; i++)\n for i in range(busyTime):\n # y = pow(x, e);\n y = math.pow(x, e)\n # // Parameterized sleep phase\n # Sleep(napTime);\n time.sleep(napTime / 1000.0)\n # // Write message to stdout\n sys.stdout.write('Thread %s just woke up.\\n' % threadNo)\n # }\n # PYTHON: NO CODE\n # // Terminating\n # return result;\n return result\n# }\n# PYTHON: NO CODE\n\nif __name__ == '__main__':\n main(len(sys.argv), sys.argv)\n\n", "Example 6\nimport tkinter\nimport _thread\nimport time\n\nEPOCH_DELTA = 946684800\nMICREV_IN_DAY = 1000000\nMILREV_IN_DAY = 1000\n\nSECOND_IN_DAY = 86400\nDAY_IN_WEEK = 7\nWEEK_IN_MONTH = 4\nMONTH_IN_SEASON = 3\nSEASON_IN_YEAR = 4\n\nSECOND_IN_WEEK = SECOND_IN_DAY * DAY_IN_WEEK\nSECOND_IN_MONTH = SECOND_IN_WEEK * WEEK_IN_MONTH\nSECOND_IN_SEASON = SECOND_IN_MONTH * MONTH_IN_SEASON\nSECOND_IN_YEAR = SECOND_IN_SEASON * SEASON_IN_YEAR\n\ndef seconds():\n \"Return seconds since the epoch.\"\n return time.time() - EPOCH_DELTA\n\ndef micrev(seconds):\n \"Convert from seconds to micrev.\"\n x = seconds % SECOND_IN_DAY * MICREV_IN_DAY / SECOND_IN_DAY % MILREV_IN_DAY\n return int(x)\n\ndef milrev(seconds):\n \"Convert from seconds to milrev.\"\n x = seconds % SECOND_IN_DAY * MILREV_IN_DAY / SECOND_IN_DAY\n return int(x)\n\ndef day(seconds):\n \"Convert from seconds to days.\"\n x = seconds / SECOND_IN_DAY % DAY_IN_WEEK\n return int(x)\n\ndef week(seconds):\n \"Convert from seconds to weeks.\"\n x = seconds / SECOND_IN_WEEK % WEEK_IN_MONTH\n return int(x)\n\ndef month(seconds):\n \"Convert from seconds to months.\"\n x = seconds / SECOND_IN_MONTH % MONTH_IN_SEASON\n return int(x)\n\ndef season(seconds):\n \"Convert from seconds to seasons.\"\n x = seconds / SECOND_IN_SEASON % SEASON_IN_YEAR\n return int(x)\n\ndef year(seconds):\n \"Convert from seconds to years.\"\n x = seconds / SECOND_IN_YEAR\n return int(x)\n\nUNITS = year, season, month, week, day, milrev, micrev\n\ndef text(seconds, spec='{0}.{1}.{2}.{3}.{4}.{5:03}.{6:03}', unit=UNITS):\n \"Convert from seconds to text.\"\n return spec.format(*[func(seconds) for func in unit])\n\nclass Quantum_Timer:\n\n \"Quantum_Timer(function, *args, **kwargs) -> Quantum_Timer\"\n\n def __init__(self, function, *args, **kwargs):\n \"Initialize the Quantum_Timer object.\"\n self.__function = function\n self.__args = args\n self.__kwargs = kwargs\n self.__thread = False\n self.__lock = _thread.allocate_lock()\n\n def start(self):\n \"Start the Quantum_Timer object.\"\n with self.__lock:\n self.__active = True\n if not self.__thread:\n self.__thread = True\n _thread.start_new_thread(self.__run, ())\n\n def stop(self):\n \"Stop the Quantum_Timer object.\"\n with self.__lock:\n self.__active = False\n\n def __run(self):\n \"Private class method.\"\n while True:\n secs = time.clock()\n plus = secs + 0.0864\n over = plus % 0.0864\n diff = plus - secs - over\n time.sleep(diff)\n with self.__lock:\n if not self.__active:\n self.__thread = False\n break\n self.__function(*self.__args, **self.__kwargs)\n\ndef main():\n root = tkinter.Tk()\n root.resizable(False, False)\n root.title('Time in Tessaressunago')\n secs = tkinter.StringVar()\n text = tkinter.Label(textvariable=secs, font=('helvetica', 16, 'bold'))\n text.grid(padx=5, pady=5)\n thread = Quantum_Timer(update, secs)\n thread.start()\n root.mainloop()\n\ndef update(secs):\n s = seconds()\n t = text(s)\n p = 1000000000 * 1.01 ** (s / SECOND_IN_YEAR)\n secs.set('Time = {0}\\nNational = {1}'.format(t, fix(p)))\n\ndef fix(number, sep=','):\n number = str(int(number))\n string = ''\n while number:\n string = number[-1] + string\n number = number[:-1]\n if number and not (len(string) + 1) % 4:\n string = sep + string\n return string\n\nif __name__ == '__main__':\n main()\n\n", "Example 7\nHOST = '127.0.0.1'\nPORT = 8080\n\nfrom Tkinter import *\nimport tkColorChooser\n\nimport socket\nimport thread\nimport cPickle\n\n################################################################################\n\nclass ZSP:\n\n 'ZSP(socket) -> ZSP'\n\n def __init__(self, socket):\n 'Initialize the Zero SPOTS Protocol object.'\n self.__file = socket.makefile('b', 0)\n\n def send(self, obj):\n 'Send one object.'\n cPickle.dump(obj, self.__file, cPickle.HIGHEST_PROTOCOL)\n\n def recv(self):\n 'Receive one object.'\n return cPickle.load(self.__file)\n\n################################################################################\n\ndef main():\n global hold, fill, draw, look\n hold = []\n fill = '#000000'\n connect()\n root = Tk()\n root.title('Paint 2.0')\n root.resizable(False, False)\n upper = LabelFrame(root, text='Your Canvas')\n lower = LabelFrame(root, text='Their Canvas')\n draw = Canvas(upper, bg='#ffffff', width=400, height=300, highlightthickness=0)\n look = Canvas(lower, bg='#ffffff', width=400, height=300, highlightthickness=0)\n cursor = Button(upper, text='Cursor Color', command=change_cursor)\n canvas = Button(upper, text='Canvas Color', command=change_canvas)\n draw.bind('<Motion>', motion)\n draw.bind('<ButtonPress-1>', press)\n draw.bind('<ButtonRelease-1>', release)\n draw.bind('<Button-3>', delete)\n upper.grid(padx=5, pady=5)\n lower.grid(padx=5, pady=5)\n draw.grid(row=0, column=0, padx=5, pady=5, columnspan=2)\n look.grid(padx=5, pady=5)\n cursor.grid(row=1, column=0, padx=5, pady=5, sticky=EW)\n canvas.grid(row=1, column=1, padx=5, pady=5, sticky=EW)\n root.mainloop()\n\n################################################################################\n\ndef connect():\n try:\n start_client()\n except:\n start_server()\n thread.start_new_thread(processor, ())\n\ndef start_client():\n global ZSP\n server = socket.socket()\n server.connect((HOST, PORT))\n ZSP = ZSP(server)\n\ndef start_server():\n global ZSP\n server = socket.socket()\n server.bind(('', PORT))\n server.listen(1)\n ZSP = ZSP(server.accept()[0])\n\ndef processor():\n while True:\n func, args, kwargs = ZSP.recv()\n getattr(look, func)(*args, **kwargs)\n\ndef call(func, *args, **kwargs):\n ZSP.send((func, args, kwargs))\n\n################################################################################\n\ndef change_cursor():\n global fill\n color = tkColorChooser.askcolor(color=fill)[1]\n if color is not None:\n fill = color\n\ndef change_canvas():\n color = tkColorChooser.askcolor(color=draw['bg'])[1]\n if color is not None:\n draw.config(bg=color)\n call('config', bg=color)\n\n################################################################################\n\ndef motion(event):\n if hold:\n hold.extend([event.x, event.y])\n event.widget.create_line(hold[-4:], fill=fill, tag='TEMP')\n call('create_line', hold[-4:], fill=fill, tag='TEMP')\n\ndef press(event):\n global hold\n hold = [event.x, event.y]\n\ndef release(event):\n global hold\n if len(hold) > 2:\n event.widget.delete('TEMP')\n event.widget.create_line(hold, fill=fill, smooth=True)\n call('delete', 'TEMP')\n call('create_line', hold, fill=fill, smooth=True)\n hold = []\n\ndef delete(event):\n event.widget.delete(ALL)\n call('delete', ALL)\n\n################################################################################\n\nif __name__ == '__main__':\n main()\n\n", "Example 8\nHOST = '127.0.0.1'\nPORT = 8080\n\ntry:\n from Tkinter import *\nexcept ImportError:\n from tkinter import *\n\ntry:\n import tkColorChooser\nexcept ImportError:\n import tkinter.colorchooser as tkColorChooser\n\ntry:\n import thread\nexcept ImportError:\n import _thread as thread\n\nimport socket\nimport pickle\nimport time\nimport sys\n\n################################################################################\n\nclass ZSP:\n\n 'ZSP(socket) -> ZSP'\n\n def __init__(self, socket):\n 'Initialize the Zero SPOTS Protocol object.'\n self.__o_file = socket.makefile('bw', 0)\n self.__i_file = socket.makefile('br', 0)\n\n def send(self, obj):\n 'Send one object.'\n pickle.dump(obj, self.__o_file, pickle.HIGHEST_PROTOCOL)\n\n def recv(self):\n 'Receive one object.'\n return pickle.load(self.__i_file)\n\n################################################################################\n\nclass QRP:\n\n 'QRP(ZSP) -> QRP'\n\n def __init__(self, ZSP):\n 'Initialize the Query/Reply Protocol object.'\n self.__ZSP = ZSP\n self.__error = None\n self.__Q_anchor = []\n self.__Q_packet = []\n self.__R_anchor = {}\n self.__Q_lock = thread.allocate_lock()\n self.__R_lock = thread.allocate_lock()\n thread.start_new_thread(self.__thread, ())\n\n def send_Q(self, ID, obj):\n 'Send one query.'\n if self.__error:\n raise self.__error\n self.__ZSP.send((False, ID, obj))\n\n def recv_Q(self, timeout=None):\n 'Receive one query.'\n if self.__error:\n raise self.__error\n if timeout is not None:\n if not isinstance(timeout, (float, int)):\n raise TypeError('timeout must be of type float or int')\n if not timeout >= 0:\n raise ValueError('timeout must be greater than or equal to 0')\n self.__Q_lock.acquire()\n try:\n try:\n if self.__Q_packet:\n Q = True\n ID, obj = self.__Q_packet.pop()\n else:\n Q = False\n anchor = [thread.allocate_lock()]\n anchor[0].acquire()\n self.__Q_anchor.append(anchor)\n finally:\n self.__Q_lock.release()\n except AttributeError:\n raise self.__error\n if Q:\n return ID, obj\n if timeout:\n thread.start_new_thread(self.__Q_thread, (timeout, anchor))\n anchor[0].acquire()\n try:\n Q = anchor[1]\n except IndexError:\n if self.__error:\n raise self.__error\n raise Warning\n return Q\n\n def send_R(self, ID, obj):\n 'Send one reply.'\n if self.__error:\n raise self.__error\n self.__ZSP.send((True, ID, obj))\n\n def recv_R(self, ID, timeout=None):\n 'Receive one reply.'\n if self.__error:\n raise self.__error\n if timeout is not None:\n if not isinstance(timeout, (float, int)):\n raise TypeError('timeout must be of type float or int')\n if not timeout >= 0:\n raise ValueError('timeout must be greater than or equal to 0')\n anchor = [thread.allocate_lock()]\n anchor[0].acquire()\n self.__R_lock.acquire()\n try:\n try:\n self.__R_anchor[ID] = anchor\n finally:\n self.__R_lock.release()\n except AttributeError:\n raise self.__error\n if timeout:\n thread.start_new_thread(self.__R_thread, (timeout, ID))\n anchor[0].acquire()\n try:\n R = anchor[1]\n except IndexError:\n if self.__error:\n raise self.__error\n raise Warning\n return R\n\n def __thread(self):\n 'Private class method.'\n try:\n while True:\n R, ID, obj = self.__ZSP.recv()\n if R:\n self.__R_lock.acquire()\n if self.__R_anchor:\n self.__R_anchor[ID].append(obj)\n self.__R_anchor[ID][0].release()\n del self.__R_anchor[ID]\n self.__R_lock.release()\n else:\n self.__Q_lock.acquire()\n if self.__Q_anchor:\n anchor = self.__Q_anchor.pop()\n anchor.append((ID, obj))\n anchor[0].release()\n else:\n self.__Q_packet.append((ID, obj))\n self.__Q_lock.release()\n except Exception:\n error = sys.exc_info()[1]\n if isinstance(error, EOFError):\n self.__error = EOFError\n else:\n self.__error = IOError\n self.__Q_lock.acquire()\n for anchor in self.__Q_anchor:\n anchor[0].release()\n del self.__Q_anchor\n del self.__Q_packet\n self.__Q_lock.release()\n self.__R_lock.acquire()\n for key in self.__R_anchor:\n self.__R_anchor[key][0].release()\n del self.__R_anchor\n self.__R_lock.release()\n\n def __Q_thread(self, timeout, anchor):\n 'Private class method.'\n time.sleep(timeout)\n self.__Q_lock.acquire()\n if not self.__error and anchor in self.__Q_anchor:\n anchor[0].release()\n self.__Q_anchor.remove(anchor)\n self.__Q_lock.release()\n\n def __R_thread(self, timeout, ID):\n 'Private class method.'\n time.sleep(timeout)\n self.__R_lock.acquire()\n if not self.__error and ID in self.__R_anchor:\n self.__R_anchor[ID][0].release()\n del self.__R_anchor[ID]\n self.__R_lock.release()\n\n################################################################################\n\nclass QRI:\n\n 'QRI(QRP) -> QRI'\n\n def __init__(self, QRP):\n 'Initialize the Query/Reply Interface object.'\n self.__QRP = QRP\n self.__ID = 0\n self.__lock = thread.allocate_lock()\n\n def call(self, obj, timeout=None):\n 'Send one query and receive one reply.'\n self.__lock.acquire()\n ID = ''.join(chr(self.__ID >> shift & 0xFF) for shift in range(24, -8, -8))\n self.__ID = (self.__ID + 1) % (2 ** 32)\n self.__lock.release()\n self.__QRP.send_Q(ID, obj)\n return self.__QRP.recv_R(ID, timeout)\n\n def query(self, timeout=None):\n 'Receive one query.'\n return self.__QRP.recv_Q(timeout)\n\n def reply(self, ID, obj):\n 'Send one reply.'\n self.__QRP.send_R(ID, obj)\n\n################################################################################\n\ndef qri(socket):\n 'Construct a QRI object.'\n return QRI(QRP(ZSP(socket)))\n\n################################################################################\n\ndef main():\n global hold, fill, draw, look\n hold = []\n fill = '#000000'\n connect()\n root = Tk()\n root.title('Paint 1.0')\n root.resizable(False, False)\n upper = LabelFrame(root, text='Your Canvas')\n lower = LabelFrame(root, text='Their Canvas')\n draw = Canvas(upper, bg='#ffffff', width=400, height=300, highlightthickness=0)\n look = Canvas(lower, bg='#ffffff', width=400, height=300, highlightthickness=0)\n cursor = Button(upper, text='Cursor Color', command=change_cursor)\n canvas = Button(upper, text='Canvas Color', command=change_canvas)\n draw.bind('<Motion>', motion)\n draw.bind('<ButtonPress-1>', press)\n draw.bind('<ButtonRelease-1>', release)\n draw.bind('<Button-3>', delete)\n upper.grid(padx=5, pady=5)\n lower.grid(padx=5, pady=5)\n draw.grid(row=0, column=0, padx=5, pady=5, columnspan=2)\n look.grid(padx=5, pady=5)\n cursor.grid(row=1, column=0, padx=5, pady=5, sticky=EW)\n canvas.grid(row=1, column=1, padx=5, pady=5, sticky=EW)\n root.mainloop()\n\n################################################################################\n\ndef connect():\n try:\n start_client()\n except:\n start_server()\n thread.start_new_thread(processor, ())\n\ndef start_client():\n global QRI\n server = socket.socket()\n server.connect((HOST, PORT))\n QRI = qri(server)\n\ndef start_server():\n global QRI\n server = socket.socket()\n server.bind(('', PORT))\n server.listen(1)\n QRI = qri(server.accept()[0])\n\ndef processor():\n while True:\n ID, (func, args, kwargs) = QRI.query()\n getattr(look, func)(*args, **kwargs)\n\ndef call(func, *args, **kwargs):\n try:\n QRI.call((func, args, kwargs), 0.05)\n except:\n pass\n\n################################################################################\n\ndef change_cursor():\n global fill\n color = tkColorChooser.askcolor(color=fill)[1]\n if color is not None:\n fill = color\n\ndef change_canvas():\n color = tkColorChooser.askcolor(color=draw['bg'])[1]\n if color is not None:\n draw['bg'] = color\n draw.config(bg=color)\n call('config', bg=color)\n\n################################################################################\n\ndef motion(event):\n if hold:\n hold.extend([event.x, event.y])\n event.widget.create_line(hold[-4:], fill=fill, tag='TEMP')\n call('create_line', hold[-4:], fill=fill, tag='TEMP')\n\ndef press(event):\n global hold\n hold = [event.x, event.y]\n\ndef release(event):\n global hold\n if len(hold) > 2:\n event.widget.delete('TEMP')\n event.widget.create_line(hold, fill=fill, smooth=True)\n call('delete', 'TEMP')\n call('create_line', hold, fill=fill, smooth=True)\n hold = []\n\ndef delete(event):\n event.widget.delete(ALL)\n call('delete', ALL)\n\n################################################################################\n\nif __name__ == '__main__':\n main()\n\n" ]
[ 6, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003114924_python.txt
Q: Python syntax for and/or'ing things together? I'm trying to devise a scheme for validating form fields. I've decided you can pass in a list of validators to each field like, Field(validators=[email_validator, required_validator]) But then I thought, what if you wanted to or the validators together, rather than anding them? For example, a field that accepts either a Canadian postal code, or a US zip code. Sure, I could just create a new validator that could accept either, but it would be neat if I could come up of a way of allowing the user to choose. Is there maybe some way that I could manipulate the bitwise operators? Field(validators = required&(postal_code|zip_code)) Or am I just making things way too complicated and shooting myself in the foot? A: Django solves this by using Q objects which can be combined using & and | to create more complex conditions. Mimicing what they use is probably an acceptable solution. A: What about a list whose items are either single validators, or list of validators to be anded together -- the top-level list does an or on all of them. You could do it the other way 'round of course, but normally "and binds tighter" by convention, so this seems acceptable. More explicitly, you could use items that are the literal (quoted) strings 'and', 'or' (and possibly 'nand' and 'nor'!) as "operators" -- if the first item of a string (top-level or substring) is such an operator, it says what to do with all the others (the default could be 'and'). A: You would want to implement __or__(self, other) and __and__(self, other) on your validator class, which dynamically returns a new validator that knows how to do the appropriate job. So, you'd basically want to implement your validators such that they can be dynamically combined in this manner (i.e., if they work with regular expressions, and you can make assumptions about how the regular expressions are written, you could combine the regular expressions appropriately in the new validator you return). http://docs.python.org/reference/datamodel.html#emulating-numeric-types A: sqlobject uses something like this, here's an example: MyTable.select((MyTable.q.name == "bob") | (MyTable.q.age == 5)) The major problem with this approach is the precedence of operators. It requires many more brackets to do it nicely. A nicer approach is to use an And() and Or() function and use prefix notation instead of infix notation. This has the benefit that it's discoverable to a new programmer who is reading your code. In your example above, I would suggest something like: Field(validators=[required, Or(postal_code, zip_code)]) Where all the validators in this list are Anded together implicitly. This makes the trivial case easy (the trivial case meaning, "match all these validators") and then have quite complicated expressions possible, such as: Field(validators=Or(And(IsAmerica(), zip_code), And(Not(IsAmerica()), city))]) Of course, this is just a suggestion. As demonstrated, using & and | work fine in some systems (Django, sqlobject). You can see clearly in my example that complicated cases have problems with many layers of brackets, and that's a tradeoff you should consider.
Python syntax for and/or'ing things together?
I'm trying to devise a scheme for validating form fields. I've decided you can pass in a list of validators to each field like, Field(validators=[email_validator, required_validator]) But then I thought, what if you wanted to or the validators together, rather than anding them? For example, a field that accepts either a Canadian postal code, or a US zip code. Sure, I could just create a new validator that could accept either, but it would be neat if I could come up of a way of allowing the user to choose. Is there maybe some way that I could manipulate the bitwise operators? Field(validators = required&(postal_code|zip_code)) Or am I just making things way too complicated and shooting myself in the foot?
[ "Django solves this by using Q objects which can be combined using & and | to create more complex conditions. Mimicing what they use is probably an acceptable solution.\n", "What about a list whose items are either single validators, or list of validators to be anded together -- the top-level list does an or on all of them. You could do it the other way 'round of course, but normally \"and binds tighter\" by convention, so this seems acceptable.\nMore explicitly, you could use items that are the literal (quoted) strings 'and', 'or' (and possibly 'nand' and 'nor'!) as \"operators\" -- if the first item of a string (top-level or substring) is such an operator, it says what to do with all the others (the default could be 'and').\n", "You would want to implement __or__(self, other) and __and__(self, other) on your validator class, which dynamically returns a new validator that knows how to do the appropriate job. So, you'd basically want to implement your validators such that they can be dynamically combined in this manner (i.e., if they work with regular expressions, and you can make assumptions about how the regular expressions are written, you could combine the regular expressions appropriately in the new validator you return).\nhttp://docs.python.org/reference/datamodel.html#emulating-numeric-types\n", "sqlobject uses something like this, here's an example:\nMyTable.select((MyTable.q.name == \"bob\") | (MyTable.q.age == 5))\n\nThe major problem with this approach is the precedence of operators. It requires many more brackets to do it nicely. A nicer approach is to use an And() and Or() function and use prefix notation instead of infix notation. This has the benefit that it's discoverable to a new programmer who is reading your code.\nIn your example above, I would suggest something like:\nField(validators=[required, Or(postal_code, zip_code)])\n\nWhere all the validators in this list are Anded together implicitly. This makes the trivial case easy (the trivial case meaning, \"match all these validators\") and then have quite complicated expressions possible, such as:\nField(validators=Or(And(IsAmerica(), zip_code), \n And(Not(IsAmerica()), city))])\n\nOf course, this is just a suggestion. As demonstrated, using & and | work fine in some systems (Django, sqlobject). You can see clearly in my example that complicated cases have problems with many layers of brackets, and that's a tradeoff you should consider.\n" ]
[ 4, 1, 1, 1 ]
[]
[]
[ "python", "syntax" ]
stackoverflow_0003115170_python_syntax.txt
Q: How do i test django ratings in my application? I have installed django-ratings application in my django project. Am wondering how best can i test my app voting functionality because django ratings is only allowing me to vote once for the same user, object and Ip address. Is there a way i can disable this checks so that i can just insert votes, test my application and when am happy i can enable this checks back. e.g. you can only run this once in the same machine; myobject.rating.add(score=1, user='user_name', ip_address='127.0.0.1') Again the user need to have been authenticated, unless you use None, but again you can only vote once. Gath A: You cannot 'disable' these checks because they're specified in the Vote model: unique_together = (('content_type', 'object_id', 'key', 'user', 'ip_address')) You could edit it but that'd be monkey-patching (and maybe would brake the app). Consider writing tests, or if you just want to have some votes filled just for the purpose of development, use fixtures (which are also useful in tests).
How do i test django ratings in my application?
I have installed django-ratings application in my django project. Am wondering how best can i test my app voting functionality because django ratings is only allowing me to vote once for the same user, object and Ip address. Is there a way i can disable this checks so that i can just insert votes, test my application and when am happy i can enable this checks back. e.g. you can only run this once in the same machine; myobject.rating.add(score=1, user='user_name', ip_address='127.0.0.1') Again the user need to have been authenticated, unless you use None, but again you can only vote once. Gath
[ "You cannot 'disable' these checks because they're specified in the Vote model:\nunique_together = (('content_type', 'object_id', 'key', 'user', 'ip_address'))\n\nYou could edit it but that'd be monkey-patching (and maybe would brake the app).\nConsider writing tests, or if you just want to have some votes filled just for the purpose of development, use fixtures (which are also useful in tests).\n" ]
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003109150_django_python.txt
Q: Creating multiple sites with django I have to create a project in django where the admin can create the sites dynamically and assign the administrators for the same, which would manage that particular site. Can someone please suggest with some hint on how it can be done? Thanks in advance. A: If you are already familiar with django sites, extend the User profile and write a custom auth in a similar way as in this question: 1404131/how-to-get-unique-users-across-multiple-django-sites-powered-by-the-sites-frame
Creating multiple sites with django
I have to create a project in django where the admin can create the sites dynamically and assign the administrators for the same, which would manage that particular site. Can someone please suggest with some hint on how it can be done? Thanks in advance.
[ "If you are already familiar with django sites, extend the User profile and write a custom auth in a similar way as in this question: 1404131/how-to-get-unique-users-across-multiple-django-sites-powered-by-the-sites-frame\n" ]
[ 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003107434_django_python.txt
Q: Python write to file I've got a little problem here. I'm converting binary to ascii, in order to compress data. All seems to work fine, but when I convert '11011011' to ascii and try to write it into file, I keep getting error UnicodeEncodeError: 'charmap' codec can't encode character '\xdb' in position 0: character maps to Here's my code: byte = "" handleR = open(self.getInput()) handleW = open(self.getOutput(), 'w') file = handleR.readlines() for line in file: for a in range(0, len(line)): chunk = result[ord(line[a])] for b in chunk: if (len(byte) < 8): byte+=str(chunk[b]) else: char = chr(eval('0b'+byte)) print(byte, char) handleW.write(char) byte = "" handleR.close() handleW.close() Any help appreciated, Thank You A: I think you want: handleR = open(self.getInput(), 'rb') handleW = open(self.getOutput(), 'wb') That will ensure you're reading and writing byte streams. Also, you can parse binary strings without eval: char = chr(int(byte, 2)) And of course, it would be faster to use bit manipulation. Instead of appending to a string, you can use << (left shift) and | (bitwise or). EDIT: For the actual writing, you can use: handleW.write(bytes([char])) This creates and writes a bytes from a list consisting of a single number. EDIT 2: Correction, it should be: handleW.write(bytes([int(byte, 2)])) There is no need to use chr.
Python write to file
I've got a little problem here. I'm converting binary to ascii, in order to compress data. All seems to work fine, but when I convert '11011011' to ascii and try to write it into file, I keep getting error UnicodeEncodeError: 'charmap' codec can't encode character '\xdb' in position 0: character maps to Here's my code: byte = "" handleR = open(self.getInput()) handleW = open(self.getOutput(), 'w') file = handleR.readlines() for line in file: for a in range(0, len(line)): chunk = result[ord(line[a])] for b in chunk: if (len(byte) < 8): byte+=str(chunk[b]) else: char = chr(eval('0b'+byte)) print(byte, char) handleW.write(char) byte = "" handleR.close() handleW.close() Any help appreciated, Thank You
[ "I think you want:\nhandleR = open(self.getInput(), 'rb')\nhandleW = open(self.getOutput(), 'wb')\n\nThat will ensure you're reading and writing byte streams. Also, you can parse binary strings without eval:\nchar = chr(int(byte, 2))\n\nAnd of course, it would be faster to use bit manipulation. Instead of appending to a string, you can use << (left shift) and | (bitwise or).\nEDIT: For the actual writing, you can use:\nhandleW.write(bytes([char]))\n\nThis creates and writes a bytes from a list consisting of a single number.\nEDIT 2: Correction, it should be:\nhandleW.write(bytes([int(byte, 2)]))\n\nThere is no need to use chr.\n" ]
[ 2 ]
[]
[]
[ "ascii", "binary", "python" ]
stackoverflow_0003115734_ascii_binary_python.txt
Q: python search from tag i need help with python programming: i need a command which can search all the words between tags from a text file. for example in the text file has <concept> food </concept>. i need to search all the words between <concept> and </concept> and display them. can anybody help please....... A: Load the text file into a string. Search the string for the first occurrence of <concept> using pos1 = s.find('<concept>') Search for </concept> using pos2 = s.find('</concept>', pos1) The words you seek are then s[pos1+len('<concept>'):pos2] A: There is a great library for HTML/XML traversing named BeautifulSoup. With it: from BeautifulSoup import BeautifulStoneSoup soup = BeautifulStoneSoup(open('myfile.xml', 'rt').read()) for t in soup.findAll('concept'): print t.string A: Have a look at regular expressions. http://docs.python.org/library/re.html If you want to have for example the tag <i>, try text = "text to search. <i>this</i> is the word and also <i>that</i> end" import re re.findall("<i>(.*?)</i>",text) Here's a short explanation how findall works: It looks in the given string for a given regular expression. The regular expression is <i>(.*?)</i>: <i> denotes just the opening tag <i> (.*?) creates a group and matches as much as possible until it comes to the first </i>, which concludes the tag Note that the above solution does not mach something like <i> here's a line break </i> Since you just wanted to extract words. However, it is of course possible to do so: re.findall("<i>(.*?)</i>",text,re.DOTALL)
python search from tag
i need help with python programming: i need a command which can search all the words between tags from a text file. for example in the text file has <concept> food </concept>. i need to search all the words between <concept> and </concept> and display them. can anybody help please.......
[ "\nLoad the text file into a string.\nSearch the string for the first occurrence of <concept> using pos1 = s.find('<concept>')\nSearch for </concept> using pos2 = s.find('</concept>', pos1)\n\nThe words you seek are then s[pos1+len('<concept>'):pos2]\n", "There is a great library for HTML/XML traversing named BeautifulSoup. With it:\nfrom BeautifulSoup import BeautifulStoneSoup\nsoup = BeautifulStoneSoup(open('myfile.xml', 'rt').read())\nfor t in soup.findAll('concept'):\n print t.string\n\n", "Have a look at regular expressions. http://docs.python.org/library/re.html\nIf you want to have for example the tag <i>, try\ntext = \"text to search. <i>this</i> is the word and also <i>that</i> end\"\nimport re\nre.findall(\"<i>(.*?)</i>\",text)\n\nHere's a short explanation how findall works: It looks in the given string for a given regular expression. The regular expression is <i>(.*?)</i>: \n\n<i> denotes just the opening tag <i>\n(.*?) creates a group and matches as much as possible until it comes to the first\n</i>, which concludes the tag\n\nNote that the above solution does not mach something like\n<i> here's a line\nbreak </i>\n\nSince you just wanted to extract words.\nHowever, it is of course possible to do so:\nre.findall(\"<i>(.*?)</i>\",text,re.DOTALL)\n\n" ]
[ 3, 3, 1 ]
[]
[]
[ "parsing", "python" ]
stackoverflow_0003116195_parsing_python.txt
Q: Automate or send kepresses to application running in background with PyS60 I'm running PyS60 on a Nokia N95 phone, and I want to find a way of having my script interact with an application running in the background. I found this http://wiki.forum.nokia.com/index.php/How_to_simulate_a_keypress_in_PyS60 .. but it doesn't mention anything about sending the keypresses to a specific target. The reason I want to do this is because I need to use the functionality of another piece of software, and I want to avoid having to go through the menus and setting it up each time I start it, so I want to have it started by my python script and have it automatically set up the program. I wanted to do something similar to what scanscrobbler does but avoid having to set it to 1D barcode scanning mode each time. If I can't open the application in the background and automate the setup while it's hidden, would it be possible to send the keypresses to it when it is the active program? If so, is there some event I can listen for to know when the application has fully loaded? Is this possible? Is there another way I could approach this? A: You could use apptools to switch to a specific applications and then use the keypress module to emulate key presses.
Automate or send kepresses to application running in background with PyS60
I'm running PyS60 on a Nokia N95 phone, and I want to find a way of having my script interact with an application running in the background. I found this http://wiki.forum.nokia.com/index.php/How_to_simulate_a_keypress_in_PyS60 .. but it doesn't mention anything about sending the keypresses to a specific target. The reason I want to do this is because I need to use the functionality of another piece of software, and I want to avoid having to go through the menus and setting it up each time I start it, so I want to have it started by my python script and have it automatically set up the program. I wanted to do something similar to what scanscrobbler does but avoid having to set it to 1D barcode scanning mode each time. If I can't open the application in the background and automate the setup while it's hidden, would it be possible to send the keypresses to it when it is the active program? If so, is there some event I can listen for to know when the application has fully loaded? Is this possible? Is there another way I could approach this?
[ "You could use apptools to switch to a specific applications and then use the keypress module to emulate key presses.\n" ]
[ 1 ]
[]
[]
[ "automation", "keypress", "n95", "pys60", "python" ]
stackoverflow_0003091074_automation_keypress_n95_pys60_python.txt
Q: ide code information I've been annoyed lately by the fact that PyDev doesn't information about classes and function when it code completes wxPython code. Can anybody tell me FOSS IDE's or extensions that offer code information (function params, returns etc.) when it code completes for C/C++ and Python. I am a fan of CodeLite, Eclipse CDT and CodeBlocks in that order for C/C++ (excepting non-FOSS) and PyScripter, PyDev for Python in that order. A: Vim + Exuberant Ctags See here, here and here for C++ autocompletion (also referred to as IntelliSense, taken from the name for Visual Studio's autocomplete). And here for Python autocomplete/"intellisense" for vim. (I should point out I found the link to that from this post on SO). If that doesn't include the ctags for wxPython as you require, you might want to check out this guy's ctags-based highlighting which apparently does work for wxPython (and perhaps take the ctags file from that?) Probably also worth checking out this enormous list of Python IDEs on SO (specifically those with "AC" tags) if you've not already seen that? I realise your question is a bit more specific than just basic Auto Complete, but perhaps there's some new options in there for you... A: I use notepad++ and am vary happy with it.
ide code information
I've been annoyed lately by the fact that PyDev doesn't information about classes and function when it code completes wxPython code. Can anybody tell me FOSS IDE's or extensions that offer code information (function params, returns etc.) when it code completes for C/C++ and Python. I am a fan of CodeLite, Eclipse CDT and CodeBlocks in that order for C/C++ (excepting non-FOSS) and PyScripter, PyDev for Python in that order.
[ "Vim + Exuberant Ctags\nSee here, here and here for C++ autocompletion (also referred to as IntelliSense, taken from the name for Visual Studio's autocomplete).\nAnd here for Python autocomplete/\"intellisense\" for vim. (I should point out I found the link to that from this post on SO).\nIf that doesn't include the ctags for wxPython as you require, you might want to check out this guy's ctags-based highlighting which apparently does work for wxPython (and perhaps take the ctags file from that?)\nProbably also worth checking out this enormous list of Python IDEs on SO (specifically those with \"AC\" tags) if you've not already seen that? I realise your question is a bit more specific than just basic Auto Complete, but perhaps there's some new options in there for you...\n", "I use notepad++ and am vary happy with it.\n" ]
[ 2, 0 ]
[]
[]
[ "c", "c++", "code_completion", "ide", "python" ]
stackoverflow_0003101160_c_c++_code_completion_ide_python.txt
Q: How to split strings based on capitalization? Possible Duplicate: Python: Split a string at uppercase letters I'm trying to figure out how to change TwoWords into Two Words and I can't think of a way to do it. I need to split based on where it's capitalized, that will always be a new word. Does anyone have any suggestions? In python. A: You can use regular expressions to do this: import re words = re.findall('[A-Z][a-z]*', 'TheWords') A: You can use regular expressions: import re re.findall("[A-Z][a-z]*","TwoWordsAATest") re.findall("[A-Z][^A-Z]*","TwoWordsAATest") http://docs.python.org/library/re.html
How to split strings based on capitalization?
Possible Duplicate: Python: Split a string at uppercase letters I'm trying to figure out how to change TwoWords into Two Words and I can't think of a way to do it. I need to split based on where it's capitalized, that will always be a new word. Does anyone have any suggestions? In python.
[ "You can use regular expressions to do this:\nimport re\nwords = re.findall('[A-Z][a-z]*', 'TheWords')\n\n", "You can use regular expressions:\nimport re\nre.findall(\"[A-Z][a-z]*\",\"TwoWordsAATest\")\n\nre.findall(\"[A-Z][^A-Z]*\",\"TwoWordsAATest\")\n\nhttp://docs.python.org/library/re.html\n" ]
[ 0, 0 ]
[]
[]
[ "python", "string" ]
stackoverflow_0003116363_python_string.txt
Q: I/O Reading from a file I'm using code like this: f = open('boo.txt') line = f.readline() print line f.close() How can I make it read a different line or a random line every time I open the script, instead of just printing out the first line? A: f = open('boo.txt') lines = [line for line in f] f.close() import random selectedline = random.choice(lines) print (selectedline) A: Another way with use of context managers: import random with open("boo.txt", "r") as f: print random.choice(f.readlines()) A: f = open('boo.txt') import random print random.choice(f.readlines())
I/O Reading from a file
I'm using code like this: f = open('boo.txt') line = f.readline() print line f.close() How can I make it read a different line or a random line every time I open the script, instead of just printing out the first line?
[ "f = open('boo.txt')\nlines = [line for line in f]\nf.close()\nimport random\nselectedline = random.choice(lines)\nprint (selectedline)\n\n", "Another way with use of context managers:\nimport random\n\nwith open(\"boo.txt\", \"r\") as f:\n print random.choice(f.readlines()) \n\n", "f = open('boo.txt')\nimport random\nprint random.choice(f.readlines())\n\n" ]
[ 6, 6, 2 ]
[]
[]
[ "python" ]
stackoverflow_0003116487_python.txt
Q: How can I check if there exist any reverse element in list of dict without looping on it My list is like l1 = [ {k1:v1} , {k2:v2}, {v1:k1} ] Is there any better way to check if any dictionary in the list is having reverse pair? A: I would suggest to transform the dictionaries in tuple and put the tuple in a set. And look in the set if the reverse tuple is in the set. That would have a complexity of O(n) instead of O(n^2). A: This code seems to work without loop: k1 = 'k1' k2 = 'k2' v1 = 'v1' v2 = 'v2' l1 = [ {k1:v1} , {k2:v2}, {v1:k1} ] kv = [e.items()[0] for e in l1] print(kv) vk = [(v, k) for (k, v) in kv] print(vk) result = [(k, v) for (k, v) in kv if (k, v) in vk] print(result)
How can I check if there exist any reverse element in list of dict without looping on it
My list is like l1 = [ {k1:v1} , {k2:v2}, {v1:k1} ] Is there any better way to check if any dictionary in the list is having reverse pair?
[ "I would suggest to transform the dictionaries in tuple and put the tuple in a set. And look in the set if the reverse tuple is in the set. That would have a complexity of O(n) instead of O(n^2).\n", "This code seems to work without loop:\nk1 = 'k1'\nk2 = 'k2'\nv1 = 'v1'\nv2 = 'v2'\nl1 = [ {k1:v1} , {k2:v2}, {v1:k1} ]\n\nkv = [e.items()[0] for e in l1]\nprint(kv)\n\nvk = [(v, k) for (k, v) in kv]\nprint(vk)\n\nresult = [(k, v) for (k, v) in kv if (k, v) in vk]\nprint(result)\n\n" ]
[ 3, 1 ]
[]
[]
[ "dictionary", "list", "python", "reverse" ]
stackoverflow_0003116249_dictionary_list_python_reverse.txt
Q: Django form is throwing error: "takes exactly 1 argument (0 given)" I'm working on a basic event form created from a model, but I keep getting the following error message: TypeError at /addlaundry/ addlaundry() takes exactly 1 argument (0 given) I think it's because I'm not passing the argument through on views, but I can't find documented anywhere how to do this right, at least not written in a way I understand. Here is my urls.py: urlpatterns = patterns('', url('^addlaundry/$', 'beacon.laundry.views.addlaundry'), } And the views itself: # Create your views here. from schedule.views import EventForm def addlaundry(request): if request.method == 'POST': form = EventForm(request.POST) if form.is_valid(): return HttpResponseRedirect('/thanks/') #redirect after succesfully adding new delivery else: form = addlaundry() return render_to_response('newlaundry.html', { 'form': form, }) Do I indeed have my views wrongly structured, or am I missing something else? If there's documentation I need to read up on, I want to I just haven't found it but feel like I'm missing something basic. Thanks, Michael A: The problem is here: form = addlaundry() You're calling your view function addlaundry which takes 1 required argument (request), but you're not passing it any arguments. Of course, that's not the right way to construct a form, anyway. You'll want to take a look at the examples given in the Django forms documentation to see how to create and use forms in Django. A: Your view is called addlaundry, and it calls (presumably) something else called addlaundry. Rename one of them, or use the other addlaundry from inside its namespace. A: This is your problem: form = addlaundry() That's attempting to call the view itself! That's not what you want. You need to define a form class and call (instantiate) it here. A: views.py : from schedule.forms import EventForm def addlaundry(request): if request.method == 'POST': form = EventForm(request.POST) if form.is_valid(): return HttpResponseRedirect('/thanks/') else: form = EventForm() return render_to_response('newlaundry.html', { 'form': form, }) That means : using a forms.py file to define your forms initializing your form in a non post context (regular first page load), that will be passed to your template A: Also, in urls.py your view should not be a string.
Django form is throwing error: "takes exactly 1 argument (0 given)"
I'm working on a basic event form created from a model, but I keep getting the following error message: TypeError at /addlaundry/ addlaundry() takes exactly 1 argument (0 given) I think it's because I'm not passing the argument through on views, but I can't find documented anywhere how to do this right, at least not written in a way I understand. Here is my urls.py: urlpatterns = patterns('', url('^addlaundry/$', 'beacon.laundry.views.addlaundry'), } And the views itself: # Create your views here. from schedule.views import EventForm def addlaundry(request): if request.method == 'POST': form = EventForm(request.POST) if form.is_valid(): return HttpResponseRedirect('/thanks/') #redirect after succesfully adding new delivery else: form = addlaundry() return render_to_response('newlaundry.html', { 'form': form, }) Do I indeed have my views wrongly structured, or am I missing something else? If there's documentation I need to read up on, I want to I just haven't found it but feel like I'm missing something basic. Thanks, Michael
[ "The problem is here:\nform = addlaundry()\n\nYou're calling your view function addlaundry which takes 1 required argument (request), but you're not passing it any arguments.\nOf course, that's not the right way to construct a form, anyway. You'll want to take a look at the examples given in the Django forms documentation to see how to create and use forms in Django.\n", "Your view is called addlaundry, and it calls (presumably) something else called addlaundry. Rename one of them, or use the other addlaundry from inside its namespace.\n", "This is your problem:\n form = addlaundry()\n\nThat's attempting to call the view itself! That's not what you want. You need to define a form class and call (instantiate) it here.\n", "views.py : \nfrom schedule.forms import EventForm\n\ndef addlaundry(request):\n if request.method == 'POST':\n form = EventForm(request.POST)\n if form.is_valid():\n return HttpResponseRedirect('/thanks/')\n else:\n form = EventForm()\n\n return render_to_response('newlaundry.html', {\n 'form': form,\n })\n\nThat means : \n\nusing a forms.py file to define your forms\ninitializing your form in a non post context (regular first page load), that will be passed to your template\n\n", "Also, in urls.py your view should not be a string.\n" ]
[ 3, 1, 1, 1, 1 ]
[ "else:\n form = addlaundry()\n\nJust as the exception says: The view function needs 1 argument, but you didn't supply any.\n" ]
[ -1 ]
[ "django", "django_forms", "python" ]
stackoverflow_0003105495_django_django_forms_python.txt
Q: Python FTP Most Recent File How do I determine the most recently modified file from an ftp directory listing? I used the max function on the unix timestamp locally, but the ftp listing is harder to parse. The contents of each line is only separated by a space. from ftplib import FTP ftp = FTP('ftp.cwi.nl') ftp.login() data = [] ftp.dir(data.append) ftp.quit() for line in data: print line output: drwxrwsr-x 5 ftp-usr pdmaint 1536 Mar 20 09:48 . dr-xr-srwt 105 ftp-usr pdmaint 1536 Mar 21 14:32 .. -rw-r--r-- 1 ftp-usr pdmaint 5305 Mar 20 09:48 INDEX A: Just to make some corrections: date_str = ' '.join(line.split()[5:8]) time.strptime(date_str, '%b %d %H:%M') # import time And to find the most recent file for line in data: col_list = line.split() date_str = ' '.join(line.split()[5:8]) if datePattern.search(col_list[8]): file_dict[time.strptime(date_str, '%b %d %H:%M')] = col_list[8] date_list = list([key for key, value in file_dict.items()]) s = file_dict[max(date_list)] print s A: If the FTP server supports the MLSD command (and quite possibly it does), you can use the FTPDirectory class from that answer in a related question. Create an ftplib.FTP instance (eg aftp) and an FTPDirectory instance (eg aftpdir), connect to the server, .cwd to the directory you want, and read the files using aftpdir.getdata(aftp). After that, you get name of the freshest file as: import operator max(aftpdir, key=operator.attrgetter('mtime')).name A: To parse the date, you can use (from version 2.5 onwards): datetime.datetime.strptime('Mar 21 14:32', '%b %d %H:%M') A: You can split each line and get the date: date_str = ' '.join(line.split(' ')[5:8]) Then parse the date (check out egenix mxDateTime package, specifically the DateTimeFromString function) to get comparable objects.
Python FTP Most Recent File
How do I determine the most recently modified file from an ftp directory listing? I used the max function on the unix timestamp locally, but the ftp listing is harder to parse. The contents of each line is only separated by a space. from ftplib import FTP ftp = FTP('ftp.cwi.nl') ftp.login() data = [] ftp.dir(data.append) ftp.quit() for line in data: print line output: drwxrwsr-x 5 ftp-usr pdmaint 1536 Mar 20 09:48 . dr-xr-srwt 105 ftp-usr pdmaint 1536 Mar 21 14:32 .. -rw-r--r-- 1 ftp-usr pdmaint 5305 Mar 20 09:48 INDEX
[ "Just to make some corrections:\ndate_str = ' '.join(line.split()[5:8])\ntime.strptime(date_str, '%b %d %H:%M') # import time\n\nAnd to find the most recent file\nfor line in data:\n col_list = line.split()\n date_str = ' '.join(line.split()[5:8])\n if datePattern.search(col_list[8]):\n file_dict[time.strptime(date_str, '%b %d %H:%M')] = col_list[8]\n date_list = list([key for key, value in file_dict.items()])\ns = file_dict[max(date_list)]\nprint s\n\n", "If the FTP server supports the MLSD command (and quite possibly it does), you can use the FTPDirectory class from that answer in a related question.\nCreate an ftplib.FTP instance (eg aftp) and an FTPDirectory instance (eg aftpdir), connect to the server, .cwd to the directory you want, and read the files using aftpdir.getdata(aftp). After that, you get name of the freshest file as:\nimport operator\n\nmax(aftpdir, key=operator.attrgetter('mtime')).name\n\n", "To parse the date, you can use (from version 2.5 onwards):\ndatetime.datetime.strptime('Mar 21 14:32', '%b %d %H:%M')\n\n", "You can split each line and get the date:\ndate_str = ' '.join(line.split(' ')[5:8])\n\nThen parse the date (check out egenix mxDateTime package, specifically the DateTimeFromString function) to get comparable objects.\n" ]
[ 4, 4, 2, 0 ]
[]
[]
[ "ftp", "python" ]
stackoverflow_0001335552_ftp_python.txt
Q: "Annotating" querysets with model function returns Basically I want to do something similar to annotating a queryset but with a call on a function in the model attached to the response. Currently I have something like: objs = WebSvc.objects.all().order_by('content_type', 'id') for o in objs: o.state = o.cast().get_state() where get_state() is a function in the model that calls an external web service. I don't want to go down the road of caching the values. I was just hoping for a more succinct way of doing this. A: One way to do this, using python properties: class WebSvc(models.Model): ... def _get_state(): return self.cast().get_state() state = property(_get_state) Advantages: will only run when the property is needed. Possible disadvantage: when you call the property multiple times, the web service will be called anew (can be required behaviour but I doubt it). You can cache using memoization. Other way, just do it by overriding init: class WebSvc(models.Model): ... def __init__(*args, **kwargs): super(WebSvc, self).__init__(*args,**kwargs) self.state = self.caste().get_state() Advantages: Will only be computed once per instance without need for memoization. Possible disadvantage: will be calculated for each instantiated object. In most typical django cases however, you will only run once over properties of an object and you will probably not instantiate object where you won't use the .state property on. So in these cases the approaches are more or less similar in 'performance'.
"Annotating" querysets with model function returns
Basically I want to do something similar to annotating a queryset but with a call on a function in the model attached to the response. Currently I have something like: objs = WebSvc.objects.all().order_by('content_type', 'id') for o in objs: o.state = o.cast().get_state() where get_state() is a function in the model that calls an external web service. I don't want to go down the road of caching the values. I was just hoping for a more succinct way of doing this.
[ "One way to do this, using python properties:\nclass WebSvc(models.Model):\n ...\n\n def _get_state():\n return self.cast().get_state()\n\n state = property(_get_state)\n\nAdvantages: will only run when the property is needed.\nPossible disadvantage: when you call the property multiple times, the web service will be called anew (can be required behaviour but I doubt it). You can cache using memoization.\nOther way, just do it by overriding init:\nclass WebSvc(models.Model):\n ...\n def __init__(*args, **kwargs):\n super(WebSvc, self).__init__(*args,**kwargs)\n self.state = self.caste().get_state()\n\nAdvantages: Will only be computed once per instance without need for memoization.\nPossible disadvantage: will be calculated for each instantiated object.\nIn most typical django cases however, you will only run once over properties of an object and you will probably not instantiate object where you won't use the .state property on. So in these cases the approaches are more or less similar in 'performance'.\n" ]
[ 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003117063_django_python.txt
Q: How to test jquery ajax tabs with selenium? I'm testing a django app with selenium, and one of my pages uses the jquery ui tabs element. One of the tabs contains a simple table listing some users, and is loaded via ajax. When using the app, the tab works just fine, but when automating the test with selenium, the tab doesn't appear to load it's content! I'm writing the tests myself in python. At first, I was using the click method of selenium RC, but as I -painfully- learned from a previous test, that is rather buggy when it comes to anchor tags, so I resorted to the solution I used before: the wait_for_condition method and explicitly called the tab click event (and even the load event!) and nevertheless the tab was still not working! I'm in despair here, the majority of my tests depend on that page and almost half of them are on that table, but, alas, it seems selenium is screwing up the javascript! (I have other tests in the class, and they run just fine, so nothing weird is going on at the server level, it seems to be a problem caused by selenium in the client side) My test code is similar to this: class TestMyApp(TransactionTestCase): urls = 'myapp.test_urls' def setUp(self): self.verificationErrors = [] self.selenium = selenium("localhost", 4444, "*chrome", "http://localhost:8000/") self.selenium.start() #self.selenium.set_speed(2000) self.selenium.window_maximize() def test_users_list(self): """Test that an app's users are correctly listed""" sel = self.selenium users = [] for u in range(settings.FREE_USER_LIMIT/2): users.append(self.app.users.create(name="testUser_%s"%uuid4())) sel.open("/") sel.wait_for_page_to_load("30000") sel.wait_for_condition('selenium.browserbot.getCurrentWindow().jQuery("#tabs").tabs("select",1);\ selenium.browserbot.getCurrentWindow().jQuery("#tabs").tabs("load",1);', 3000) for user in users: try: self.failUnless(sel.is_text_present(user.name)) except AssertionError, e: self.verificationErrors.append(str(e)) try: self.failUnless(sel.is_text_present(str(user.added.date()))) except AssertionError, e: self.verificationErrors.append(str(e)) def tearDown(self): self.selenium.stop() self.assertEqual([], self.verificationErrors) A: This could be a few things. It could be that Selenium is having trouble clicking the anchor but I actually haven't heard of that trouble and it sounds less likely. It sounds like the click() method returns OK, it doesn't give you "element not found", right? When you do the click the jquery tab javascript just isn't doing what's expected. In my experience this usually comes down to the same issue -- since Selenium executes very quickly, when javascript is rendering portions of the page and effecting the DOM continuously sometimes when Selenium goes to interact with dynamically generated parts of the page (say to click this tab), the piece it's interacting with depends on some other piece that actually hasn't fully loaded yet. It's probably microseconds away from fully loading in fact, but selenium is too fast. You already understand this of course, you have the right idea with the wait_for condition looking for the tabs to be loaded. My guess would be it's probably just not long enough. You have to find some evaluation to make that says the whole UI tabs thing is loaded and rendered. Does the tabs API have some callbacks you can add to set a "done loading" variable or does it expose a variable like that? Barring figuring out what the proper expression is to find the point in time when the UI tabs are actually ready to be clicked, which possibly could be tricky, you can resort to outright pauses to make sure the part of the page is ready to go before you interact with it. I see no problem in sleep(2), or even sleep(5), etc. in the code if it's necessary to get it to work. One way you can test that this is really what's going on is by firing up the scenario in the interactive interpreter (gotta love Python, beats the pants off of doing this in Java). Paste the code in line by line to get to the trouble point, or comment out the selenium.stop() call in your teardown method and any test code after the trouble point, so it leaves the selenium window open and exits. Then instantiate a selenium object in the interactive interpretter and hijack the open session: selenium = selenium("localhost", 4444, "*chrome", "http://localhost:8000/") selenium.sessionId = "0asdd234234023424foo" #Get this from the Se window ...to get interactive control of the window. Then you can see about making the selenium.click() or make selenium.get_eval('...js...') calls to investigate the javascript landscape at that point in time. My guess is when you do this, the click() will actually work fine when you type it in, because by the time you get the session loaded and get around to typing in selenium.click('blah_tab_locator'), the tab guts will all be loaded and ready to go. It's just that when Python is making the calls it does it way too fast for the browser when there are these dynamic renderings going on. If the click works fine when you do it manually through selenium like this, then you know it's a timing issue. Find that proper wait_for_condition or condescend to a python sleep(). Otherwise, if the click continues to not work when you do this, then it's probably a problem with the locator being used. The tab UI has a click or a mouseup or a focus or some kind of event handler on some part of the tab structure, maybe it's just about finding the right part of the tab to click or the right event to fire. If it isn't that then it perhaps could be as you mention some kind of strange interaction between Selenium and Jquery UI, but that would surprise me and I'd be curious to know. Poke around with get_eval() to see what's going on in the javascript if so. It sounds like a timing issue to me though.
How to test jquery ajax tabs with selenium?
I'm testing a django app with selenium, and one of my pages uses the jquery ui tabs element. One of the tabs contains a simple table listing some users, and is loaded via ajax. When using the app, the tab works just fine, but when automating the test with selenium, the tab doesn't appear to load it's content! I'm writing the tests myself in python. At first, I was using the click method of selenium RC, but as I -painfully- learned from a previous test, that is rather buggy when it comes to anchor tags, so I resorted to the solution I used before: the wait_for_condition method and explicitly called the tab click event (and even the load event!) and nevertheless the tab was still not working! I'm in despair here, the majority of my tests depend on that page and almost half of them are on that table, but, alas, it seems selenium is screwing up the javascript! (I have other tests in the class, and they run just fine, so nothing weird is going on at the server level, it seems to be a problem caused by selenium in the client side) My test code is similar to this: class TestMyApp(TransactionTestCase): urls = 'myapp.test_urls' def setUp(self): self.verificationErrors = [] self.selenium = selenium("localhost", 4444, "*chrome", "http://localhost:8000/") self.selenium.start() #self.selenium.set_speed(2000) self.selenium.window_maximize() def test_users_list(self): """Test that an app's users are correctly listed""" sel = self.selenium users = [] for u in range(settings.FREE_USER_LIMIT/2): users.append(self.app.users.create(name="testUser_%s"%uuid4())) sel.open("/") sel.wait_for_page_to_load("30000") sel.wait_for_condition('selenium.browserbot.getCurrentWindow().jQuery("#tabs").tabs("select",1);\ selenium.browserbot.getCurrentWindow().jQuery("#tabs").tabs("load",1);', 3000) for user in users: try: self.failUnless(sel.is_text_present(user.name)) except AssertionError, e: self.verificationErrors.append(str(e)) try: self.failUnless(sel.is_text_present(str(user.added.date()))) except AssertionError, e: self.verificationErrors.append(str(e)) def tearDown(self): self.selenium.stop() self.assertEqual([], self.verificationErrors)
[ "This could be a few things. It could be that Selenium is having trouble clicking the anchor but I actually haven't heard of that trouble and it sounds less likely. It sounds like the click() method returns OK, it doesn't give you \"element not found\", right? When you do the click the jquery tab javascript just isn't doing what's expected. In my experience this usually comes down to the same issue -- since Selenium executes very quickly, when javascript is rendering portions of the page and effecting the DOM continuously sometimes when Selenium goes to interact with dynamically generated parts of the page (say to click this tab), the piece it's interacting with depends on some other piece that actually hasn't fully loaded yet. It's probably microseconds away from fully loading in fact, but selenium is too fast. You already understand this of course, you have the right idea with the wait_for condition looking for the tabs to be loaded. My guess would be it's probably just not long enough. You have to find some evaluation to make that says the whole UI tabs thing is loaded and rendered. Does the tabs API have some callbacks you can add to set a \"done loading\" variable or does it expose a variable like that? Barring figuring out what the proper expression is to find the point in time when the UI tabs are actually ready to be clicked, which possibly could be tricky, you can resort to outright pauses to make sure the part of the page is ready to go before you interact with it. I see no problem in sleep(2), or even sleep(5), etc. in the code if it's necessary to get it to work. One way you can test that this is really what's going on is by firing up the scenario in the interactive interpreter (gotta love Python, beats the pants off of doing this in Java). Paste the code in line by line to get to the trouble point, or comment out the selenium.stop() call in your teardown method and any test code after the trouble point, so it leaves the selenium window open and exits. Then instantiate a selenium object in the interactive interpretter and hijack the open session:\nselenium = selenium(\"localhost\", 4444, \"*chrome\", \"http://localhost:8000/\")\nselenium.sessionId = \"0asdd234234023424foo\" #Get this from the Se window\n\n...to get interactive control of the window. Then you can see about making the selenium.click() or make selenium.get_eval('...js...') calls to investigate the javascript landscape at that point in time. My guess is when you do this, the click() will actually work fine when you type it in, because by the time you get the session loaded and get around to typing in selenium.click('blah_tab_locator'), the tab guts will all be loaded and ready to go. It's just that when Python is making the calls it does it way too fast for the browser when there are these dynamic renderings going on. If the click works fine when you do it manually through selenium like this, then you know it's a timing issue. Find that proper wait_for_condition or condescend to a python sleep(). Otherwise, if the click continues to not work when you do this, then it's probably a problem with the locator being used. The tab UI has a click or a mouseup or a focus or some kind of event handler on some part of the tab structure, maybe it's just about finding the right part of the tab to click or the right event to fire. If it isn't that then it perhaps could be as you mention some kind of strange interaction between Selenium and Jquery UI, but that would surprise me and I'd be curious to know. Poke around with get_eval() to see what's going on in the javascript if so. It sounds like a timing issue to me though. \n" ]
[ 5 ]
[]
[]
[ "django", "jquery_ui", "python", "selenium_rc", "unit_testing" ]
stackoverflow_0003114731_django_jquery_ui_python_selenium_rc_unit_testing.txt
Q: How can I ensure good test-coverage of my big Python proejct I have a very large python project with a very large test suite. Recently we have decided to quantify the quality of our test-coverage. I'm looking for a tool to automate the test coverage report generation. Ideally I'd like to have attractive, easy to read reports but I'd settle for less attractive reports if I could make it work quickly. I've tried Nose, which is not good enough: It is incompatible with distribute / setuptools' namespace package feature. Unfortunately nose coverage will never work for us since we make abundant use of this feature. That's a real shame because Nose seems to work really nicely in Hudson (mostly) As an alternative, I've heard that there's a way to do a Python coverage analysis in Eclipse, but I've not quite locked-down the perfect technique. Any suggestions welcome! FYI we use Python 2.4.4 on Windows XP 32bit A: Have you tried using coverage.py? It underlies "nose coverage", but can be run perfectly well outside of nose if you need to. If you run your tests with (hypothetically) python run_my_tests.py, then you can measure coverage with coverage run run_my_tests.py, then get HTML reports with coverage html. From your description, I'm not sure what problem you had with nose, especially whether it was a nose issue, or a coverage.py issue. Provide some more details, and I'm sure we can work through them. A: Ned has already mentioned his excellent coverage.py module. If the problem you're having is something nose specific, you might want to consider using another test runner. I've used py.test along with the pytest_coverage plugin that lets you generate coverage statistics. It also has a pytest_nose plugin to help you migrate. However, I don't understand exactly what the problem you're facing is. Can you elaborate a little on the "distribute / setuptools' namespace package feature" you mentioned? I'm curious to know what the problem is.
How can I ensure good test-coverage of my big Python proejct
I have a very large python project with a very large test suite. Recently we have decided to quantify the quality of our test-coverage. I'm looking for a tool to automate the test coverage report generation. Ideally I'd like to have attractive, easy to read reports but I'd settle for less attractive reports if I could make it work quickly. I've tried Nose, which is not good enough: It is incompatible with distribute / setuptools' namespace package feature. Unfortunately nose coverage will never work for us since we make abundant use of this feature. That's a real shame because Nose seems to work really nicely in Hudson (mostly) As an alternative, I've heard that there's a way to do a Python coverage analysis in Eclipse, but I've not quite locked-down the perfect technique. Any suggestions welcome! FYI we use Python 2.4.4 on Windows XP 32bit
[ "Have you tried using coverage.py? It underlies \"nose coverage\", but can be run perfectly well outside of nose if you need to.\nIf you run your tests with (hypothetically) python run_my_tests.py, then you can measure coverage with coverage run run_my_tests.py, then get HTML reports with coverage html.\nFrom your description, I'm not sure what problem you had with nose, especially whether it was a nose issue, or a coverage.py issue. Provide some more details, and I'm sure we can work through them.\n", "Ned has already mentioned his excellent coverage.py module. \nIf the problem you're having is something nose specific, you might want to consider using another test runner. I've used py.test along with the pytest_coverage plugin that lets you generate coverage statistics. It also has a pytest_nose plugin to help you migrate. \nHowever, I don't understand exactly what the problem you're facing is. Can you elaborate a little on the \"distribute / setuptools' namespace package feature\" you mentioned? I'm curious to know what the problem is. \n" ]
[ 4, 1 ]
[]
[]
[ "code_coverage", "python", "python_coverage", "unit_testing" ]
stackoverflow_0003117011_code_coverage_python_python_coverage_unit_testing.txt
Q: Sort a list of tuples without case sensitivity How can I efficiently and easily sort a list of tuples without being sensitive to case? For example this: [('a', 'c'), ('A', 'b'), ('a', 'a'), ('a', 5)] Should look like this once sorted: [('a', 5), ('a', 'a'), ('A', 'b'), ('a', 'c')] The regular lexicographic sort will put 'A' before 'a' and yield this: [('A', 'b'), ('a', 5), ('a', 'a'), ('a', 'c')] A: You can use sort's key argument to define how you wish to regard each element with respect to sorting: def lower_if_possible(x): try: return x.lower() except AttributeError: return x L=[('a', 'c'), ('A', 'b'), ('a', 'a'), ('a', 5)] L.sort(key=lambda x: map(lower_if_possible,x)) print(L) See http://wiki.python.org/moin/HowTo/Sorting for an explanation of how to use key. A: list_of_tuples.sort(key=lambda t : tuple(s.lower() if isinstance(s,basestring) else s for s in t)) A: Something like this should work: def sort_ci(items): def sort_tuple(tuple): return ([lower(x) for x in tuple],) + tuple temp = [sort_tuple(tuple) for tuple in items] temp.sort() return [tuple[1:] for tuple in temp] In other words, create a new list, where each item is a tuple consisting of the old tuple, prefixed with the same tuple with each item in lower case. Then sort that. This is a bit faster than using sort's optional comparison function argument, if your list is long. A: Here's a solution which uses the decorator idea illustrated in the "sorted by keys" section of a Python wiki article (http://wiki.python.org/moin/HowTo/Sorting/). # Create a list of new tuples whose first element is lowercase # version of the original tuple. I use an extra function to # handle tuples which contain non-strings. f = lambda x : x.lower() if type(x)==str else x deco = [(tuple(f(e) for e in t), t) for t in ex] # now we can directly sort deco and get the result we want deco.sort() # extract the original tuples in the case-insensitive sorted order out = [t for _,t in deco] A: A simplified version of Paul McGuires works: list_of_tuples.sort(key=lambda t : tuple(t[0].lower())) (where t[0] references which tuple element you want to use, in this case the first)
Sort a list of tuples without case sensitivity
How can I efficiently and easily sort a list of tuples without being sensitive to case? For example this: [('a', 'c'), ('A', 'b'), ('a', 'a'), ('a', 5)] Should look like this once sorted: [('a', 5), ('a', 'a'), ('A', 'b'), ('a', 'c')] The regular lexicographic sort will put 'A' before 'a' and yield this: [('A', 'b'), ('a', 5), ('a', 'a'), ('a', 'c')]
[ "You can use sort's key argument to define how you wish to regard each element with respect to sorting:\ndef lower_if_possible(x):\n try:\n return x.lower()\n except AttributeError:\n return x\n\nL=[('a', 'c'), ('A', 'b'), ('a', 'a'), ('a', 5)]\n\nL.sort(key=lambda x: map(lower_if_possible,x))\nprint(L)\n\nSee http://wiki.python.org/moin/HowTo/Sorting for an explanation of how to use key.\n", "list_of_tuples.sort(key=lambda t : tuple(s.lower() if isinstance(s,basestring) else s for s in t))\n\n", "Something like this should work:\ndef sort_ci(items):\n def sort_tuple(tuple):\n return ([lower(x) for x in tuple],) + tuple\n temp = [sort_tuple(tuple) for tuple in items]\n temp.sort()\n return [tuple[1:] for tuple in temp]\n\nIn other words, create a new list, where each item is a tuple consisting of the old tuple, prefixed with the same tuple with each item in lower case. Then sort that.\nThis is a bit faster than using sort's optional comparison function argument, if your list is long.\n", "Here's a solution which uses the decorator idea illustrated in the \"sorted by keys\" section of a Python wiki article (http://wiki.python.org/moin/HowTo/Sorting/).\n# Create a list of new tuples whose first element is lowercase\n# version of the original tuple. I use an extra function to\n# handle tuples which contain non-strings.\nf = lambda x : x.lower() if type(x)==str else x\ndeco = [(tuple(f(e) for e in t), t) for t in ex]\n\n# now we can directly sort deco and get the result we want\ndeco.sort()\n\n# extract the original tuples in the case-insensitive sorted order\nout = [t for _,t in deco]\n\n", "A simplified version of Paul McGuires works:\nlist_of_tuples.sort(key=lambda t : tuple(t[0].lower()))\n\n(where t[0] references which tuple element you want to use, in this case the first)\n" ]
[ 12, 2, 0, 0, 0 ]
[]
[]
[ "case_insensitive", "python", "sorting", "tuples" ]
stackoverflow_0002494740_case_insensitive_python_sorting_tuples.txt
Q: Is this use of isinstance pythonic/"good"? A side effect of this question is that I was lead to this post, which states: Whenever isinstance is used, control flow forks; one type of object goes down one code path, and other types of object go down the other --- even if they implement the same interface! and suggests that this is a bad thing. However, I've used code like this before, in what I thought was an OO way. Something like the following: class MyTime(object): def __init__(self, h=0, m=0, s=0): self.h = 0 self.m = 0 self.s = 0 def __iadd__(self, other): if isinstance(other, MyTime): self.h += other.h self.m += other.m self.s += other.s elif isinstance(other, int): self.h += other/3600 other %= 3600 self.m += other/60 other %= 60 self.s += other else: raise TypeError('Addition not supported for ' + type(other).__name__) So my question: Is this use of isinstance "pythonic" and "good" OOP? A: Not in general. An object's interface should define its behavior. In your example above, it would be better if other used a consistent interface: def __iadd__(self, other): self.h += other.h self.m += other.m self.s += other.s Even though this looks like it is less functional, conceptually it is much cleaner. Now you leave it to the language to throw an exception if other does not match the interface. You can solve the problem of adding int times by - for example - creating a MyTime "constructor" using the integer's "interface". This keeps the code cleaner and leaves fewer surprises for the next guy. Others may disagree, but I feel there may be a place for isinstance if you are using reflection in special cases such as when implementing a plugin architecture. A: isinstance, since Python 2.6, has become quite nice as long as you follow the "key rule of good design" as explained in the classic "gang of 4" book: design to an interface, not to an implementation. Specifically, 2.6's new Abstract Base Classes are the only things you should be using for isinstance and issubclass checks, not concrete "implementation" types. Unfortunately there is no abstract class in 2.6's standard library to summarize the concept of "this number is Integral", but you can make one such ABC by checking whether the class has a special method __index__ (don't use __int__, which is also supplied by such definitely non-integral classes as float and str -- __index__ was introduced specifically to assert "instances of this class can be made into integers with no loss of important information") and use isinstance on that "interface" (abstract base class) rather than the specific implementation int, which is way too restrictive. You could also make an ABC summarizing the concept of "having m, h and s attributes" (might be useful to accept attribute synonyms so as to tolerate a datetime.time or maybe timedelta instance, for example -- not sure whether you're representing an instant or a lapse of time with your MyTime class, the name suggests the former but the existence of addition suggests the latter), again to avoid the very restrictive implications of isinstance with a concrete implementation cass. A: The first use is fine, the second is not. Pass the argument to int() instead so that you can use number-like types. A: To elaborate further on the comment I made under Justin's answer, I would keep his code for __iadd__ (i.e., so MyTime objects can only be added to other MyTime objects) and rewrite __init__ in this way: def __init__(self, **params): if params.get('sec'): t = params['sec'] self.h = t/3600 t %= 3600 self.m = t/60 t %= 60 self.s = t elif params.get('time'): t = params['time'] self.h = t.h self.m = t.m self.s = t.s else: if params: raise TypeError("__init__() got unexpected keyword argument '%s'" % params.keys()[0]) else: raise TypeError("__init__() expected keyword argument 'sec' or 'time'") # example usage t1 = MyTime(sec=30) t2 = MyTime(sec=60) t2 += t1 t3 = MyTime(time=t1) I just tried to pick short keyword arguments, but you may want to get more descriptive than I did.
Is this use of isinstance pythonic/"good"?
A side effect of this question is that I was lead to this post, which states: Whenever isinstance is used, control flow forks; one type of object goes down one code path, and other types of object go down the other --- even if they implement the same interface! and suggests that this is a bad thing. However, I've used code like this before, in what I thought was an OO way. Something like the following: class MyTime(object): def __init__(self, h=0, m=0, s=0): self.h = 0 self.m = 0 self.s = 0 def __iadd__(self, other): if isinstance(other, MyTime): self.h += other.h self.m += other.m self.s += other.s elif isinstance(other, int): self.h += other/3600 other %= 3600 self.m += other/60 other %= 60 self.s += other else: raise TypeError('Addition not supported for ' + type(other).__name__) So my question: Is this use of isinstance "pythonic" and "good" OOP?
[ "Not in general. An object's interface should define its behavior. In your example above, it would be better if other used a consistent interface:\ndef __iadd__(self, other):\n self.h += other.h\n self.m += other.m\n self.s += other.s\n\nEven though this looks like it is less functional, conceptually it is much cleaner. Now you leave it to the language to throw an exception if other does not match the interface. You can solve the problem of adding int times by - for example - creating a MyTime \"constructor\" using the integer's \"interface\". This keeps the code cleaner and leaves fewer surprises for the next guy.\nOthers may disagree, but I feel there may be a place for isinstance if you are using reflection in special cases such as when implementing a plugin architecture.\n", "isinstance, since Python 2.6, has become quite nice as long as you follow the \"key rule of good design\" as explained in the classic \"gang of 4\" book: design to an interface, not to an implementation. Specifically, 2.6's new Abstract Base Classes are the only things you should be using for isinstance and issubclass checks, not concrete \"implementation\" types.\nUnfortunately there is no abstract class in 2.6's standard library to summarize the concept of \"this number is Integral\", but you can make one such ABC by checking whether the class has a special method __index__ (don't use __int__, which is also supplied by such definitely non-integral classes as float and str -- __index__ was introduced specifically to assert \"instances of this class can be made into integers with no loss of important information\") and use isinstance on that \"interface\" (abstract base class) rather than the specific implementation int, which is way too restrictive.\nYou could also make an ABC summarizing the concept of \"having m, h and s attributes\" (might be useful to accept attribute synonyms so as to tolerate a datetime.time or maybe timedelta instance, for example -- not sure whether you're representing an instant or a lapse of time with your MyTime class, the name suggests the former but the existence of addition suggests the latter), again to avoid the very restrictive implications of isinstance with a concrete implementation cass.\n", "The first use is fine, the second is not. Pass the argument to int() instead so that you can use number-like types.\n", "To elaborate further on the comment I made under Justin's answer, I would keep his code for __iadd__ (i.e., so MyTime objects can only be added to other MyTime objects) and rewrite __init__ in this way:\ndef __init__(self, **params):\n if params.get('sec'):\n t = params['sec']\n self.h = t/3600\n t %= 3600\n self.m = t/60\n t %= 60\n self.s = t\n elif params.get('time'):\n t = params['time']\n self.h = t.h\n self.m = t.m\n self.s = t.s\n else:\n if params:\n raise TypeError(\"__init__() got unexpected keyword argument '%s'\" % params.keys()[0])\n else:\n raise TypeError(\"__init__() expected keyword argument 'sec' or 'time'\")\n\n# example usage\nt1 = MyTime(sec=30)\nt2 = MyTime(sec=60)\nt2 += t1 \nt3 = MyTime(time=t1)\n\nI just tried to pick short keyword arguments, but you may want to get more descriptive than I did.\n" ]
[ 7, 4, 2, 2 ]
[]
[]
[ "oop", "python" ]
stackoverflow_0003111611_oop_python.txt
Q: Sending emails with sendmail doesn't work for large emails I'm using python's sendmail in the following way: msg = <SOME MESSAGE> s = smtplib.SMTP('localhost') s.sendmail(me, you, msg.as_string()) s.quit() This usually works fine (I.e I get the email) but it fails (I.e no exception is shown but the email just doesn't arrive) when the message is pretty big (around 200 lines). Any ideas what can cause this? A: Who are you sending to? You should consider some email servers (such as Yahoo and Hotmail) quarantine incoming email for a period of time if the email is categorized as potential spam. Spamminess is going to be a function of the content, image to text ratio, nature of attachments, nature of html links, sending rate, number of duplicates, sender, and numerous other factors. A: Try setting the debuglevel to get a trace of the protocol progress. SMTP.set_debuglevel(level) Set the debug output level. A true value for level results in debug messages for connection and for all messages sent to and received from the server. When a message is successfully queued, the tail of the debug trace looks like: >>> conn = smtplib.SMTP('mail') >>> conn.set_debuglevel(1) >>> conn.sendmail('you@example.com','me@example.com','subject: test\n\ntest.\n') ... send: 'subject: test\r\n\r\ntest.\r\n.\r\n' reply: '250 2.5.0 Message received and queued.\r\n' reply: retcode (250); Msg: 2.5.0 Message received and queued. data: (250, '2.5.0 Message received and queued.') {} A: You can try seeing what SMTP actually sends by hooking a netcat on a port then sending there: nc -l 5678 then in Python smtplib.SMTP('localhost', 5678). If that looks correct (and there should be no reason why it wouldn't), you can try giving it to telnet localhost smtp to see the response directly. That should give you some idea what goes wrong. A: I have just started picking around with sending emails through SMPT servers as well. What software are you using to create your localhost server? sometimes the software may be setup to reject messages over a given length. Check your server settings.
Sending emails with sendmail doesn't work for large emails
I'm using python's sendmail in the following way: msg = <SOME MESSAGE> s = smtplib.SMTP('localhost') s.sendmail(me, you, msg.as_string()) s.quit() This usually works fine (I.e I get the email) but it fails (I.e no exception is shown but the email just doesn't arrive) when the message is pretty big (around 200 lines). Any ideas what can cause this?
[ "Who are you sending to? You should consider some email servers (such as Yahoo and Hotmail) quarantine incoming email for a period of time if the email is categorized as potential spam. Spamminess is going to be a function of the content, image to text ratio, nature of attachments, nature of html links, sending rate, number of duplicates, sender, and numerous other factors.\n", "Try setting the debuglevel to get a trace of the protocol progress.\n\nSMTP.set_debuglevel(level)\nSet the debug output level. A true value for level results in debug messages for connection and for all messages sent to and received from the server.\n\nWhen a message is successfully queued, the tail of the debug trace looks like:\n>>> conn = smtplib.SMTP('mail')\n>>> conn.set_debuglevel(1)\n>>> conn.sendmail('you@example.com','me@example.com','subject: test\\n\\ntest.\\n')\n...\nsend: 'subject: test\\r\\n\\r\\ntest.\\r\\n.\\r\\n'\nreply: '250 2.5.0 Message received and queued.\\r\\n'\nreply: retcode (250); Msg: 2.5.0 Message received and queued.\ndata: (250, '2.5.0 Message received and queued.')\n{}\n\n", "You can try seeing what SMTP actually sends by hooking a netcat on a port then sending there: nc -l 5678 then in Python smtplib.SMTP('localhost', 5678).\nIf that looks correct (and there should be no reason why it wouldn't), you can try giving it to telnet localhost smtp to see the response directly. That should give you some idea what goes wrong.\n", "I have just started picking around with sending emails through SMPT servers as well. What software are you using to create your localhost server? sometimes the software may be setup to reject messages over a given length. Check your server settings. \n" ]
[ 2, 1, 0, 0 ]
[]
[]
[ "email", "python", "sendmail", "smtp" ]
stackoverflow_0003031528_email_python_sendmail_smtp.txt
Q: Conquering Complexity, Eckel on Java and Python and Chunk Theory In the introduction to Bruce Eckel's Thinking In Java, he says, in 1998: Programming is about managing complexity: the complexity of the problem you want to solve, laid upon the complexity of the machine in which it is solved. Because of this complexity, most of our programming projects fail. And yet, of all the programming languages of which I am aware, none of them have gone all-out and decided that their main design goal would be to conquer the complexity of developing and maintaining programs. In the second and later editions he adds this footnote (circa 2003): I take this back on the 2nd edition: I believe that the Python language comes closest to doing exactly that. See www.Python.org. I am a dabbler with java, with a background in Delphi (Pascal), C, C++, and Python. Here is what I want to know: What exactly did Eckel consider when he called Python 'better' at conquering complexity, and are his thoughts on track with others who have used both? What do you think about conquering complexity? Is the shorter and more terse syntax of Python a key way to conquer complexity (and thus, for instance, Jython might be a nice bridge of Java's great libraries, and Python's terse syntax), or is the strong-typing-mentality of Java, which inherits this idea from C++, which inherited that idea from simula, I think it was, a key to conquering complexity? Or is it the Rapid Application Designer (think Delphi, or for Java, the excellent free NetBeans window/form designer tools) or components, or beans, or J2EE? What conquers all, for you? This is already tagged subjective. [edit] Note: More on Bruce's thoughts, on why he loves Python are found here. A key quote from the article: Bruce Eckel: They say you can hold seven plus or minus two pieces of information in your mind. I can't remember how to open files in Java. I've written chapters on it. I've done it a bunch of times, but it's too many steps. And when I actually analyze it, I realize these are just silly design decisions that they made. Even if they insisted on using the Decorator pattern in java.io, they should have had a convenience constructor for opening files simply. Because we open files all the time, but nobody can remember how. It is too much information to hold in your mind. So, chunk theory. By the chunk theory metric, Python kills everybody else dead. I'll grant him that. But what is the metric you use? I would like to particularly invite people to stand up for Java, and oppose Bruce, if you care to. [Please do not vote to re-open, this subject is inherently incendiary, and my gaffes have made it more-so. I agree with the moderators.] A: Bruce Eckel: They say you can hold seven plus or minus two pieces of information in your mind. I can't remember how to open files in Java. I can: new FileInputStream(filename); I've written chapters on it. I've done it a bunch of times, but it's too many steps. And when I actually analyze it, I realize these are just silly design decisions that they made. Even if they insisted on using the Decorator pattern in java.io, they should have had a convenience constructor for opening files simply. This is solved in a matter of minutes by writing that utility method with a simple api. And it has been. If that is the strongest criticism than can be directed at Java, I remain distinctly unimpressed. A: I think Bruce was taking his cue from Fred Brooks, who talks about complexity in his essay "No Silver Bullet", and describes two types. The first type is inherent in the problem you are trying to solve, which he calls essential complexity and is the same regardless of what language you use. The second is the complexity added by the tools and languages we use - all the stuff you have to think about that does not directly add to solving the problem. By this measure Java has a LOT more complexity than Python. The simplest example is the canonical Hello World program. In Python (and several other languages) it is one line: print "hello World!" In Java it is class HelloWorld { static public void main( String args[] ) { System.out.println( "Hello World!" ); } } most of which has nothing to do with the task of printing "Hello World" and is basically noise. There are several factors that IMHO add to the complexity of Java compared to other languages like Python. 1) everything must be in a class. This forces you to use the OO paradigm even when it is not appropriate, like the example above, and add lots of unnecessary boilplate class definitions. 2) Even though it forces you to use classes it is not fully object oriented. By this I mean that not everything is an object, such as primitive types and methods. In python you can subclass all the builtin types and pass functions & methods around like any other object. 3) Java is not functional - in fact it goes out of its way to stop you using a functional paradigm. Being able to pass functions around and create closures and lambdas can simplify a lot of code. The closest you can get in Java is to use anonymous inner classes for things like callbacks. 3) Java forces you to put in type declarations everywhere, which adds a lot of clutter without adding useful information. This is not just a static vs dynamic issue - there are statically typed languages like Scala that can infer the types 90% of the time and cut out all the noise. 4) Although Java forces you to use static typing, many (perhaps most) real world Java programs use dynamic type checking part of the time. Every time you do a cast from an Object to a specific type you are doing dynamic type checking - before generics were added in Java 5 this meant every time you used a container class for example. Even when using generic containers some of their type checking is done at runtime. Also every time you have an XML file with class or method names in it them somewhere in the code it has to do a dynamic type check to make sure it matches up with a real class. So many Java programs still have the alleged "dangers" of dynamic typing but with all the verbosity that Java's static typing forces you to add. I could go on (and often do), but I will stop here with the observation that I have seen a lot of code that is simpler, cleaner and less complex in Python than in Java but none the other way around. If anyone can point me to some then I would love to see it. A: And yet, of all the programming languages of which I am aware, none of them have gone all-out and decided that their main design goal would be to conquer the complexity of developing and maintaining programs. Almost every single language is based on conquering complexity. There is no other aim worth pursuing. Assembly, C++, Java, Python, and virtually every other language in existence is based on making programming easier. How is python good at conquering complexity? Python definitely has some of the most intuitive syntax of any language IMHO. Its use of block indenting solves a lot of problems, and most of it is as close to plain language as you should get. M = [x for x in S if x % 2 == 0] is a good example, see any python book for countless more. Is the shorter and more terse syntax of Python a key way to conquer complexity? I believe the simple syntax of python is a good way of conquering complexity. However, that's the only definitive answer I can give to your other query: What do you think about conquering complexity? You are asking the question that is the entire core of language theory, which encompasses battles that will probably rage until the end of time. static vs dynamic typing is one such debate. There are mounds of other developments in language theory like Procedural vs OO vs Functional languages and Aspect Oriented Programming that try to simplify programming. Look at the latest (or any) release of a language to see some examples of what's being done to 'conquer complexity'. There is never going be one definitive answer, and a full discussion of each approach would take a few months to read, and would probably completely change by the time your were done. :D A: For me, switching from Java to Python was a big win. I can write code faster, with the same or fewer bugs, and modify it more easily. The code also remains much more readable, so when I come back to it after a couple months I can figure out what it's doing faster (and rewrite it without too much trouble when I can't). Java, being strongly typed, requires a lot of work up front to design and maintain correct type definitions. If you declare a variable as an int, and then decide it should have been a float, you'll need to change that type throughout your program. Are you storing that value in an array? You'll need to change that type declaration, too. Decide to refactor several classes to share a common interface? You'll have to change function definitions throughout your codebase to handle it. If you have a particularly complicated design, you'll find yourself having to deal with a lot of those issues. Python also has a lot of support in the language for changing how certain things work. Python decorators, for example, can abstract away a lot of complicated code (dealing with caching, or registering functions) keeping code maintenance down. Sophisticated IDEs can help maintain your code, but you're better off starting with a less complicated language. A: Having earned an A in my "OOP With Java" course last semester, and self taught in Python for a few years now, plus being interested in programming in general, and having written several K lines in both languages (not counting the comments), including a Jack lexer/parser in Python (and seeing the equivalent performed -- or not -- in Java by my compatriots), I think I have enough experience to be worth at least a few cents anyway. Or not, but now that I'm done tooting my own horn you can decide for yourself ;) First of all, I agree wholeheartedly that programming is about reducing complexity. I also agree that Java does not do a great job at reducing complexity. For instance, to get user input from the command line? Scanner input = new Scanner(new BufferedReader(System.in)); (I think? And it's only been 2 or 3 months since I've used that) Python is raw_input() and in 3.0 it's just plain input() How do you read from a file in Java? Well, honestly I don't know. We didn't do much of it, and it was worse than Scanner. As has been mentioned, the complexity of Java is above and beyond that of any other real language I know, but not quite so bad as "that" language. I think the main problem with the complexity of Java is found in the example meriton uses in defense of Java. Rather than importing awesome community APIs and implementing them as part of the language, Java has a "core" language and APIs are just an extension of that. What I find interesting is the wealth of tools that Java has to build APIs and documentation for said APIs. I mean, you write your code, put in some certain comments, and (at least in Eclipse) select an item inside a menu and you have generated some beautiful javadocs. Even though it's wonderful to have such great documentation, I wonder if it didn't actually evolve out of necessity because looking at a program gives you no clue what Java is doing. Scanner? Buffered Reader? WTF?? There are layers and layers of added complexity that could (and some argue should) be abstracted away. Heck, I can open and read a file in assembly with less fuss than Java. Of course comparing a few lines is really rather trivial and fairly worthless, but the point is that Java often introduces complexity, rather than solves it. Here is the biggest reason that I feel Python has the advantage: useful types/functionality is built-in to the language, and they tend to be very well named (and at least if they're not super well named, they at least have some hint). For instance, let's say I want to open a comma separated file (without using extra APIs or imports), and store each element in a generic collection. In Python (2.6+, or 2.5 with a import from future) it's literally two lines: with open('myfile.csv') as f: print f.read().split(',') done. In Java I don't think you can do it without importing external classes. Of course in reality I think either language just goes to preference, and possibly either genetics or training. Some people feel that static or dynamic types introduce the least complexity. I fall into the latter camp, but I understand the argument. After all, your compiler will complain if you try to pass a different type, and you always know what something is supposed to be, because it's either explicitly declared or cast as such. Of course that adds the complexity of the casting operation (minor as it may be), but it benefits from not having to wonder "How in the world did the integer I passed in turn into a float|string??" But when it comes down to it, most people can take a look at a Python program and understand what's going on. Novice programmers to extremely advanced programmers will be able to comprehend the program and purpose by looking at it. Heck, I just wrote a plugin for Bazaar by a combination of reading the (poor) documentation and reading the code for the Bazaar built-in functions. It took relatively little effort, and they even have a few custom definitions. The same thing for some golly scripts. When coding stuff in my Java class, I was also able to understand some other classes. However, I think I was at a severe advantage in that class because the Java concepts are very similar to Python concepts. Or vice versa, whichever way you prefer. (Or they're both similar to Lisp concepts ;) I guess honestly I think the complexity is just the learning curve. Python has a very shallow learning curve, with the power being an inverse function to the learning curve. Java has a steeper learning curve, with its power curve having a linear (2x? 3x?) relationship. Once you've learned the language and the underlying concepts, the complexity is reduced to near-zero for both languages, I think.
Conquering Complexity, Eckel on Java and Python and Chunk Theory
In the introduction to Bruce Eckel's Thinking In Java, he says, in 1998: Programming is about managing complexity: the complexity of the problem you want to solve, laid upon the complexity of the machine in which it is solved. Because of this complexity, most of our programming projects fail. And yet, of all the programming languages of which I am aware, none of them have gone all-out and decided that their main design goal would be to conquer the complexity of developing and maintaining programs. In the second and later editions he adds this footnote (circa 2003): I take this back on the 2nd edition: I believe that the Python language comes closest to doing exactly that. See www.Python.org. I am a dabbler with java, with a background in Delphi (Pascal), C, C++, and Python. Here is what I want to know: What exactly did Eckel consider when he called Python 'better' at conquering complexity, and are his thoughts on track with others who have used both? What do you think about conquering complexity? Is the shorter and more terse syntax of Python a key way to conquer complexity (and thus, for instance, Jython might be a nice bridge of Java's great libraries, and Python's terse syntax), or is the strong-typing-mentality of Java, which inherits this idea from C++, which inherited that idea from simula, I think it was, a key to conquering complexity? Or is it the Rapid Application Designer (think Delphi, or for Java, the excellent free NetBeans window/form designer tools) or components, or beans, or J2EE? What conquers all, for you? This is already tagged subjective. [edit] Note: More on Bruce's thoughts, on why he loves Python are found here. A key quote from the article: Bruce Eckel: They say you can hold seven plus or minus two pieces of information in your mind. I can't remember how to open files in Java. I've written chapters on it. I've done it a bunch of times, but it's too many steps. And when I actually analyze it, I realize these are just silly design decisions that they made. Even if they insisted on using the Decorator pattern in java.io, they should have had a convenience constructor for opening files simply. Because we open files all the time, but nobody can remember how. It is too much information to hold in your mind. So, chunk theory. By the chunk theory metric, Python kills everybody else dead. I'll grant him that. But what is the metric you use? I would like to particularly invite people to stand up for Java, and oppose Bruce, if you care to. [Please do not vote to re-open, this subject is inherently incendiary, and my gaffes have made it more-so. I agree with the moderators.]
[ "\nBruce Eckel: They say you can hold\n seven plus or minus two pieces of\n information in your mind. I can't\n remember how to open files in Java.\n\nI can:\nnew FileInputStream(filename);\n\n\nI've written chapters on it. I've done\n it a bunch of times, but it's too many\n steps. And when I actually analyze it,\n I realize these are just silly design\n decisions that they made. Even if they\n insisted on using the Decorator\n pattern in java.io, they should have\n had a convenience constructor for\n opening files simply. \n\nThis is solved in a matter of minutes by writing that utility method with a simple api. And it has been. If that is the strongest criticism than can be directed at Java, I remain distinctly unimpressed.\n", "I think Bruce was taking his cue from Fred Brooks, who talks about complexity in his essay \"No Silver Bullet\", and describes two types. The first type is inherent in the problem you are trying to solve, which he calls essential complexity and is the same regardless of what language you use. The second is the complexity added by the tools and languages we use - all the stuff you have to think about that does not directly add to solving the problem. By this measure Java has a LOT more complexity than Python. The simplest example is the canonical Hello World program. In Python (and several other languages) it is one line:\nprint \"hello World!\"\n\nIn Java it is \nclass HelloWorld {\n static public void main( String args[] ) {\n System.out.println( \"Hello World!\" );\n }\n}\n\nmost of which has nothing to do with the task of printing \"Hello World\" and is basically noise.\nThere are several factors that IMHO add to the complexity of Java compared to other languages like Python.\n1) everything must be in a class. This forces you to use the OO paradigm even when it is not appropriate, like the example above, and add lots of unnecessary boilplate class definitions.\n2) Even though it forces you to use classes it is not fully object oriented. By this I mean that not everything is an object, such as primitive types and methods. In python you can subclass all the builtin types and pass functions & methods around like any other object.\n3) Java is not functional - in fact it goes out of its way to stop you using a functional paradigm. Being able to pass functions around and create closures and lambdas can simplify a lot of code. The closest you can get in Java is to use anonymous inner classes for things like callbacks. \n3) Java forces you to put in type declarations everywhere, which adds a lot of clutter without adding useful information. This is not just a static vs dynamic issue - there are statically typed languages like Scala that can infer the types 90% of the time and cut out all the noise.\n4) Although Java forces you to use static typing, many (perhaps most) real world Java programs use dynamic type checking part of the time. Every time you do a cast from an Object to a specific type you are doing dynamic type checking - before generics were added in Java 5 this meant every time you used a container class for example. Even when using generic containers some of their type checking is done at runtime. Also every time you have an XML file with class or method names in it them somewhere in the code it has to do a dynamic type check to make sure it matches up with a real class. So many Java programs still have the alleged \"dangers\" of dynamic typing but with all the verbosity that Java's static typing forces you to add.\nI could go on (and often do), but I will stop here with the observation that I have seen a lot of code that is simpler, cleaner and less complex in Python than in Java but none the other way around. If anyone can point me to some then I would love to see it.\n", "\nAnd yet, of all the programming languages of which I am aware, none of them have gone all-out and decided that their main design goal would be to conquer the complexity of developing and maintaining programs.\n\nAlmost every single language is based on conquering complexity. There is no other aim worth pursuing. Assembly, C++, Java, Python, and virtually every other language in existence is based on making programming easier.\n\nHow is python good at conquering complexity?\n\nPython definitely has some of the most intuitive syntax of any language IMHO. Its use of block indenting solves a lot of problems, and most of it is as close to plain language as you should get. M = [x for x in S if x % 2 == 0] is a good example, see any python book for countless more.\n\nIs the shorter and more terse syntax of Python a key way to conquer complexity?\n\nI believe the simple syntax of python is a good way of conquering complexity. However, that's the only definitive answer I can give to your other query: \n\nWhat do you think about conquering complexity?\n\nYou are asking the question that is the entire core of language theory, which encompasses battles that will probably rage until the end of time. static vs dynamic typing is one such debate. There are mounds of other developments in language theory like Procedural vs OO vs Functional languages and Aspect Oriented Programming that try to simplify programming. Look at the latest (or any) release of a language to see some examples of what's being done to 'conquer complexity'. There is never going be one definitive answer, and a full discussion of each approach would take a few months to read, and would probably completely change by the time your were done. :D\n", "For me, switching from Java to Python was a big win. I can write code faster, with the same or fewer bugs, and modify it more easily. The code also remains much more readable, so when I come back to it after a couple months I can figure out what it's doing faster (and rewrite it without too much trouble when I can't).\nJava, being strongly typed, requires a lot of work up front to design and maintain correct type definitions. If you declare a variable as an int, and then decide it should have been a float, you'll need to change that type throughout your program. Are you storing that value in an array? You'll need to change that type declaration, too. Decide to refactor several classes to share a common interface? You'll have to change function definitions throughout your codebase to handle it. If you have a particularly complicated design, you'll find yourself having to deal with a lot of those issues.\nPython also has a lot of support in the language for changing how certain things work. Python decorators, for example, can abstract away a lot of complicated code (dealing with caching, or registering functions) keeping code maintenance down. Sophisticated IDEs can help maintain your code, but you're better off starting with a less complicated language. \n", "Having earned an A in my \"OOP With Java\" course last semester, and self taught in Python for a few years now, plus being interested in programming in general, and having written several K lines in both languages (not counting the comments), including a Jack lexer/parser in Python (and seeing the equivalent performed -- or not -- in Java by my compatriots), I think I have enough experience to be worth at least a few cents anyway. Or not, but now that I'm done tooting my own horn you can decide for yourself ;)\nFirst of all, I agree wholeheartedly that programming is about reducing complexity. I also agree that Java does not do a great job at reducing complexity.\nFor instance, to get user input from the command line?\nScanner input = new Scanner(new BufferedReader(System.in)); (I think? And it's only been 2 or 3 months since I've used that)\nPython is raw_input() and in 3.0 it's just plain input()\nHow do you read from a file in Java? Well, honestly I don't know. We didn't do much of it, and it was worse than Scanner. As has been mentioned, the complexity of Java is above and beyond that of any other real language I know, but not quite so bad as \"that\" language.\nI think the main problem with the complexity of Java is found in the example meriton uses in defense of Java. Rather than importing awesome community APIs and implementing them as part of the language, Java has a \"core\" language and APIs are just an extension of that. What I find interesting is the wealth of tools that Java has to build APIs and documentation for said APIs. I mean, you write your code, put in some certain comments, and (at least in Eclipse) select an item inside a menu and you have generated some beautiful javadocs. Even though it's wonderful to have such great documentation, I wonder if it didn't actually evolve out of necessity because looking at a program gives you no clue what Java is doing. Scanner? Buffered Reader? WTF?? There are layers and layers of added complexity that could (and some argue should) be abstracted away. Heck, I can open and read a file in assembly with less fuss than Java. Of course comparing a few lines is really rather trivial and fairly worthless, but the point is that Java often introduces complexity, rather than solves it.\nHere is the biggest reason that I feel Python has the advantage: useful types/functionality is built-in to the language, and they tend to be very well named (and at least if they're not super well named, they at least have some hint).\nFor instance, let's say I want to open a comma separated file (without using extra APIs or imports), and store each element in a generic collection.\nIn Python (2.6+, or 2.5 with a import from future) it's literally two lines:\nwith open('myfile.csv') as f:\n print f.read().split(',')\n\ndone.\nIn Java I don't think you can do it without importing external classes. Of course in reality I think either language just goes to preference, and possibly either genetics or training.\nSome people feel that static or dynamic types introduce the least complexity. I fall into the latter camp, but I understand the argument. After all, your compiler will complain if you try to pass a different type, and you always know what something is supposed to be, because it's either explicitly declared or cast as such. Of course that adds the complexity of the casting operation (minor as it may be), but it benefits from not having to wonder \"How in the world did the integer I passed in turn into a float|string??\"\nBut when it comes down to it, most people can take a look at a Python program and understand what's going on. Novice programmers to extremely advanced programmers will be able to comprehend the program and purpose by looking at it. Heck, I just wrote a plugin for Bazaar by a combination of reading the (poor) documentation and reading the code for the Bazaar built-in functions. It took relatively little effort, and they even have a few custom definitions. The same thing for some golly scripts. When coding stuff in my Java class, I was also able to understand some other classes. However, I think I was at a severe advantage in that class because the Java concepts are very similar to Python concepts. Or vice versa, whichever way you prefer. (Or they're both similar to Lisp concepts ;)\nI guess honestly I think the complexity is just the learning curve. Python has a very shallow learning curve, with the power being an inverse function to the learning curve. Java has a steeper learning curve, with its power curve having a linear (2x? 3x?) relationship. Once you've learned the language and the underlying concepts, the complexity is reduced to near-zero for both languages, I think.\n" ]
[ 5, 5, 4, 3, 2 ]
[]
[]
[ "complexity_theory", "java", "python" ]
stackoverflow_0003113409_complexity_theory_java_python.txt
Q: Capture the last occurrence of a tag My text is of the form: <Story> <Sentence id="1"> some text </Sentence> <Sentence id="2"> some text </Sentence> <Sentence id="3"> some text </Sentence> My task is to insert a closing tag </Story> after the last </Sentence>. In the text, every </Sentence> is followed by 3 spaces. I tried capturing the last </Sentence> using the regex </Sentence>(?!.*<Sentence) and used re.DOTALL too. But its not working. Actual code used is line = re.sub(re.compile('</Sentence>(?!.*<Sentence)',re.DOTALL),'</Sentence></Story>',line) Please help. Thanks. A: Is the same code producing the whole file - if so then use an xml library to generate it then all tags will be nested correctly - if not fix the code producing it so that it is valid XML. regexes and xml do not go together well. A: You really should use a parser like BeautifulSoup to do the job. BeautifulSoup can parse very incorrect HTML/XML and tries to make them look correct. Your code could look like this (I'm assuming you have some tags before and after your incorrect Story tag, or else you would follow the advice from David's comment): from BeautifulSoup import BeautifulStoneSoup html = ''' <Document> <PrevTag></PrevTag> <Story> <Sentence id="1"> some text </Sentence> <Sentence id="2"> some text </Sentence> <Sentence id="3"> some text </Sentence> <EndTag></EndTag> </Document> ''' # Parse the document: soup = BeautifulStoneSoup(html) Look how BeautifulSoup parsed it: print soup.prettify() #<document> # <prevtag> # </prevtag> # <story> # <sentence id="1"> # some text # </sentence> # <sentence id="2"> # some text # </sentence> # <sentence id="3"> # some text # </sentence> # <endtag> # </endtag> # </story> #</document> Notice that BeautifulSoup closed the Story right before the closing of the tag that surrounded it (Document), so you have to move the closing tag next to the last sentence. # Find the last sentence: last_sentence = soup.findAll('sentence')[-1] # Find the Story tag: story = soup.find('story') # Move all tags after the last sentence outside the Story tag: sib = last_sentence.nextSibling while sib: story.parent.append(sib.extract()) sib = last_sentence.nextSibling print soup.prettify() #<document> # <prevtag> # </prevtag> # <story> # <sentence id="1"> # some text # </sentence> # <sentence id="2"> # some text # </sentence> # <sentence id="3"> # some text # </sentence> # </story> # <endtag> # </endtag> #</document> The end result should be exactly what you wanted. Note that this code assumes there is only one Story in the document -- if not, it should be modified slightly. Good luck! A: If all you need is to find the last occurrence of the tag, you can: reSentenceClose= re.compile('</Sentence> *') match= None for match in reSentenceClose.finditer(your_text): pass if match: # it was found print match.end() # the index in your_text where the pattern was found A: Why not match all three (or however many) <Sentence> elements and plug them back in with a group reference? re.sub(r'(?:(\r?\n) *<Sentence.*?</Sentence> *)+', r'$0$1</Story>', line)
Capture the last occurrence of a tag
My text is of the form: <Story> <Sentence id="1"> some text </Sentence> <Sentence id="2"> some text </Sentence> <Sentence id="3"> some text </Sentence> My task is to insert a closing tag </Story> after the last </Sentence>. In the text, every </Sentence> is followed by 3 spaces. I tried capturing the last </Sentence> using the regex </Sentence>(?!.*<Sentence) and used re.DOTALL too. But its not working. Actual code used is line = re.sub(re.compile('</Sentence>(?!.*<Sentence)',re.DOTALL),'</Sentence></Story>',line) Please help. Thanks.
[ "Is the same code producing the whole file - if so then use an xml library to generate it then all tags will be nested correctly - if not fix the code producing it so that it is valid XML.\nregexes and xml do not go together well.\n", "You really should use a parser like BeautifulSoup to do the job. BeautifulSoup can parse very incorrect HTML/XML and tries to make them look correct. Your code could look like this (I'm assuming you have some tags before and after your incorrect Story tag, or else you would follow the advice from David's comment):\nfrom BeautifulSoup import BeautifulStoneSoup\n\nhtml = '''\n<Document>\n<PrevTag></PrevTag>\n<Story>\n <Sentence id=\"1\"> some text </Sentence> \n <Sentence id=\"2\"> some text </Sentence> \n <Sentence id=\"3\"> some text </Sentence>\n<EndTag></EndTag>\n</Document> \n'''\n# Parse the document:\nsoup = BeautifulStoneSoup(html)\n\nLook how BeautifulSoup parsed it:\nprint soup.prettify()\n\n#<document>\n# <prevtag>\n# </prevtag>\n# <story>\n# <sentence id=\"1\">\n# some text\n# </sentence>\n# <sentence id=\"2\">\n# some text\n# </sentence>\n# <sentence id=\"3\">\n# some text\n# </sentence>\n# <endtag>\n# </endtag>\n# </story>\n#</document>\n\nNotice that BeautifulSoup closed the Story right before the closing of the tag that surrounded it (Document), so you have to move the closing tag next to the last sentence.\n# Find the last sentence:\nlast_sentence = soup.findAll('sentence')[-1]\n\n# Find the Story tag:\nstory = soup.find('story')\n\n# Move all tags after the last sentence outside the Story tag:\nsib = last_sentence.nextSibling\nwhile sib:\n story.parent.append(sib.extract())\n sib = last_sentence.nextSibling\n\nprint soup.prettify()\n\n#<document>\n# <prevtag>\n# </prevtag>\n# <story>\n# <sentence id=\"1\">\n# some text\n# </sentence>\n# <sentence id=\"2\">\n# some text\n# </sentence>\n# <sentence id=\"3\">\n# some text\n# </sentence>\n# </story>\n# <endtag>\n# </endtag>\n#</document>\n\nThe end result should be exactly what you wanted. Note that this code assumes there is only one Story in the document -- if not, it should be modified slightly. Good luck!\n", "If all you need is to find the last occurrence of the tag, you can:\nreSentenceClose= re.compile('</Sentence> *')\nmatch= None\nfor match in reSentenceClose.finditer(your_text):\n pass\n\nif match: # it was found\n print match.end() # the index in your_text where the pattern was found\n\n", "Why not match all three (or however many) <Sentence> elements and plug them back in with a group reference?\nre.sub(r'(?:(\\r?\\n) *<Sentence.*?</Sentence> *)+',\n r'$0$1</Story>',\n line)\n\n" ]
[ 3, 1, 0, 0 ]
[]
[]
[ "last_occurrence", "python", "regex", "xml" ]
stackoverflow_0003107588_last_occurrence_python_regex_xml.txt
Q: Entity exists, empty template is returned I got the following very basic template: <html> <head> </head> <body> <div> <!-- Using "for" to iterate through potential pages would prevent getting empty strings even if only one page is returned because the "page" is not equal the query, it is a subcomponent of the query --> <div>{{ page.name }}</div> <div>{{ page.leftText }}</div> <div>{{ page.imageURL }}</div> <div>{{ page.rightText }}</div> </div> </body> </html> And the very basic Model: class Page(db.Model): name = db.StringProperty(required=True) leftText = db.TextProperty() rightText = db.TextProperty() imageURL = db.LinkProperty() And the very basic Handlers: class BaseRequestHandler(webapp.RequestHandler): ####### class PageContentLoadRequestHandler(BaseRequestHandler): def renderPage(self, values): directory = os.path.dirname(__file__) path = os.path.join(directory, 'templates', 'simple_page.html') return template.render(path, values, True) def get(self): page = db.get('aghwc21vZWJlbHIKCxIEUGFnZRgBDA') #alternative code # page db.get(db.key(self.request.get('key'))) # The solution is to call/fetch the wanted object/query data = page.get() # or ... = Page.gql("GQL CODE").fetch(1) values = {'page': page} template_name = "simple_page.html" return self.response.out.write(self.renderPage(values)) The key is just randomly taken out of my storage, it is a real existing key of a filled entity. They idea is to load a page content dynamically into the doc via AJAX, problem is, that this handler returns an empty template. No ERRORS, 200 HTTP Code, key exists etc, etc, etc. I am totally broken and a bit annoyed, by such problems, because I quiet do not know where the fault could be. regards, EDIT: Changing the template values to there correct names, I now get the following erro: values = {'page': page, 'name': page.name,} AttributeError: 'NoneType' object has no attribute 'name' A: Your properties are called 'leftText', 'rightText', and 'imageURL', but you're trying to print out 'left_text', 'right_text' and 'image_url'. Django, in its infinite wisdom, simply returns an empty string when you try to access a property that doesn't exist, rather than throwing an exception.
Entity exists, empty template is returned
I got the following very basic template: <html> <head> </head> <body> <div> <!-- Using "for" to iterate through potential pages would prevent getting empty strings even if only one page is returned because the "page" is not equal the query, it is a subcomponent of the query --> <div>{{ page.name }}</div> <div>{{ page.leftText }}</div> <div>{{ page.imageURL }}</div> <div>{{ page.rightText }}</div> </div> </body> </html> And the very basic Model: class Page(db.Model): name = db.StringProperty(required=True) leftText = db.TextProperty() rightText = db.TextProperty() imageURL = db.LinkProperty() And the very basic Handlers: class BaseRequestHandler(webapp.RequestHandler): ####### class PageContentLoadRequestHandler(BaseRequestHandler): def renderPage(self, values): directory = os.path.dirname(__file__) path = os.path.join(directory, 'templates', 'simple_page.html') return template.render(path, values, True) def get(self): page = db.get('aghwc21vZWJlbHIKCxIEUGFnZRgBDA') #alternative code # page db.get(db.key(self.request.get('key'))) # The solution is to call/fetch the wanted object/query data = page.get() # or ... = Page.gql("GQL CODE").fetch(1) values = {'page': page} template_name = "simple_page.html" return self.response.out.write(self.renderPage(values)) The key is just randomly taken out of my storage, it is a real existing key of a filled entity. They idea is to load a page content dynamically into the doc via AJAX, problem is, that this handler returns an empty template. No ERRORS, 200 HTTP Code, key exists etc, etc, etc. I am totally broken and a bit annoyed, by such problems, because I quiet do not know where the fault could be. regards, EDIT: Changing the template values to there correct names, I now get the following erro: values = {'page': page, 'name': page.name,} AttributeError: 'NoneType' object has no attribute 'name'
[ "Your properties are called 'leftText', 'rightText', and 'imageURL', but you're trying to print out 'left_text', 'right_text' and 'image_url'. Django, in its infinite wisdom, simply returns an empty string when you try to access a property that doesn't exist, rather than throwing an exception.\n" ]
[ 2 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0003118327_google_app_engine_google_cloud_datastore_python.txt
Q: Python tar generation question I'm creating a tar file from a directory as such /home/user/bla/mydir/ Now I want to create a tar.gz file which starts from mydir/, not having directory list of the archieve content listing starting from /home/user/bla/mydir/. How can this be done? Here is my original one: tar = tarfile.open("/home/user/mytar.tar.gz", "w:gz") tar.add("/home/user/bla/mydir/") tar.close() A: Use the add() method's arcname parameter: tar.add("/home/user/bla/mydir/", arcname="mydir")
Python tar generation question
I'm creating a tar file from a directory as such /home/user/bla/mydir/ Now I want to create a tar.gz file which starts from mydir/, not having directory list of the archieve content listing starting from /home/user/bla/mydir/. How can this be done? Here is my original one: tar = tarfile.open("/home/user/mytar.tar.gz", "w:gz") tar.add("/home/user/bla/mydir/") tar.close()
[ "Use the add() method's arcname parameter:\ntar.add(\"/home/user/bla/mydir/\", arcname=\"mydir\")\n\n" ]
[ 2 ]
[]
[]
[ "python", "tar" ]
stackoverflow_0003118473_python_tar.txt
Q: How to declare a C struct with a pointer to array in ctypes? I read the official ctypes tutorial and also searched SO, but I could not find a way to declare this kind of structure with ctypes. This structure is returned by one of the functions I write an Python interface for. typedef struct{ int i; float *b1; float (*w1)[]; }foo; This is what I have so far: class foo(Structure): _fields_=[("i",c_int), ("b1",POINTER(c_int)), ("w1",?????????)] Thanks for your help! A: In C, a pointer to an array stores the same memory address as a pointer to the first element in the array. Therefore: class foo(Structure): _fields_=[("i",c_int), ("b1",POINTER(c_int)), ("w1",POINTER(c_float))] You can access the elements of the array using integer indexes. For example: myfoo.w1[5]. It would be better C coding style to declare w1 as float *w1, so that you can access elements of the array using myfoo->w1[5] instead of having to dereference twice.
How to declare a C struct with a pointer to array in ctypes?
I read the official ctypes tutorial and also searched SO, but I could not find a way to declare this kind of structure with ctypes. This structure is returned by one of the functions I write an Python interface for. typedef struct{ int i; float *b1; float (*w1)[]; }foo; This is what I have so far: class foo(Structure): _fields_=[("i",c_int), ("b1",POINTER(c_int)), ("w1",?????????)] Thanks for your help!
[ "In C, a pointer to an array stores the same memory address as a pointer to the first element in the array. Therefore:\nclass foo(Structure):\n _fields_=[(\"i\",c_int),\n (\"b1\",POINTER(c_int)),\n (\"w1\",POINTER(c_float))]\n\nYou can access the elements of the array using integer indexes. For example: myfoo.w1[5].\nIt would be better C coding style to declare w1 as float *w1, so that you can access elements of the array using myfoo->w1[5] instead of having to dereference twice.\n" ]
[ 1 ]
[]
[]
[ "c", "ctypes", "python" ]
stackoverflow_0003118071_c_ctypes_python.txt
Q: why does python os.path.isfile seem to ignore certain file types? simple script on a unix system (Mac) which seems to only return certain files True. Can't figure out why: workdir = '/Volumes/place/sub place' def myFunc(bla, dir, flist): for f in flist: print f, os.path.isfile(f) os.path.walk(workdir,myFunc,None) Returns: tests.py False utils.py False utils.pyc False writeXmlForMpgInPath.py False .DS_Store True Playout False Playout Masters False Projects False ProRes Masters False Source False Sydney Playout Masters False Web Preview False .AU009644-M.xml.swp False .DS_Store True .DS_Store True .DS_Store True .DS_Store True A: You're using the function wrong: workdir = '/Volumes/place/sub place' def myFunc(_, dir, flist): for f in flist: fpath = os.path.join(dir, f) # need to make a full path first print f, fpath, os.path.isfile(fpath) os.path.walk(workdir,myFunc,None) see also os.walk, its nicer.
why does python os.path.isfile seem to ignore certain file types?
simple script on a unix system (Mac) which seems to only return certain files True. Can't figure out why: workdir = '/Volumes/place/sub place' def myFunc(bla, dir, flist): for f in flist: print f, os.path.isfile(f) os.path.walk(workdir,myFunc,None) Returns: tests.py False utils.py False utils.pyc False writeXmlForMpgInPath.py False .DS_Store True Playout False Playout Masters False Projects False ProRes Masters False Source False Sydney Playout Masters False Web Preview False .AU009644-M.xml.swp False .DS_Store True .DS_Store True .DS_Store True .DS_Store True
[ "You're using the function wrong:\nworkdir = '/Volumes/place/sub place'\n\ndef myFunc(_, dir, flist):\n for f in flist:\n fpath = os.path.join(dir, f) # need to make a full path first\n print f, fpath, os.path.isfile(fpath)\n\nos.path.walk(workdir,myFunc,None)\n\nsee also os.walk, its nicer.\n" ]
[ 4 ]
[]
[]
[ "python" ]
stackoverflow_0003118521_python.txt
Q: Emitting Cythonic warnings? In Cython, the usual raise keyword emits C code that contains a reference to the line and name of the Cython source file, allowing a useful error message to be generated. However, I haven't seen anything for warnings. Simply calling warnings.warn leaves the interpreter confused as to where the warning came from. I could use PyErr_WarnExplicit if there was something similar to the __LINE__ macro for pyx files. Is there either a standard way to issue warnings or a standard way to refer to the pyx line number in Cython? Update This question has been open for months, so I can only assume that Cython does not presently have a good way to issue warnings. I'll leave it open here in case someone does find a way/submit a patch to make this work right. A: Here's something that works OK warn.pyx: import warnings cdef extern from "Python.h": char* __FILE__ cdef extern from "Python.h": int __LINE__ def dowarn(): warnings.warn_explicit("a warning", category=UserWarning, filename=__FILE__, lineno=__LINE__) setup.py: from distutils.core import setup from distutils.extension import Extension from Cython.Compiler.Main import default_options default_options['emit_linenums'] = True from Cython.Distutils import build_ext ext_modules = [ Extension("warn", ["warn.pyx"]) ] setup( name = "warn", cmdclass = {"build_ext": build_ext}, ext_modules = ext_modules ) The trick is to make cython emit #line directives when generating the C code and tricking it into thinking the __FILE__ and __LINE__ are real variables that it can use. Then the warn_explicit function from warnings can be used to override the default method of determining the source file and line number.
Emitting Cythonic warnings?
In Cython, the usual raise keyword emits C code that contains a reference to the line and name of the Cython source file, allowing a useful error message to be generated. However, I haven't seen anything for warnings. Simply calling warnings.warn leaves the interpreter confused as to where the warning came from. I could use PyErr_WarnExplicit if there was something similar to the __LINE__ macro for pyx files. Is there either a standard way to issue warnings or a standard way to refer to the pyx line number in Cython? Update This question has been open for months, so I can only assume that Cython does not presently have a good way to issue warnings. I'll leave it open here in case someone does find a way/submit a patch to make this work right.
[ "Here's something that works OK\nwarn.pyx:\nimport warnings\n\ncdef extern from \"Python.h\":\n char* __FILE__\n\ncdef extern from \"Python.h\":\n int __LINE__\n\ndef dowarn():\n warnings.warn_explicit(\"a warning\", category=UserWarning, filename=__FILE__, lineno=__LINE__)\n\nsetup.py:\nfrom distutils.core import setup\nfrom distutils.extension import Extension\nfrom Cython.Compiler.Main import default_options\ndefault_options['emit_linenums'] = True\nfrom Cython.Distutils import build_ext\n\n\next_modules = [ Extension(\"warn\", [\"warn.pyx\"]) ]\n\nsetup(\n name = \"warn\",\n cmdclass = {\"build_ext\": build_ext},\n ext_modules = ext_modules\n)\n\nThe trick is to make cython emit #line directives when generating the C code and tricking it into thinking the __FILE__ and __LINE__ are real variables that it can use. Then the warn_explicit function from warnings can be used to override the default method of determining the source file and line number.\n" ]
[ 4 ]
[]
[]
[ "cython", "python", "warnings" ]
stackoverflow_0002647128_cython_python_warnings.txt
Q: Problems calling Python from C++ test.py def add(a,b): """ """ print a,b,a+b return a+b c program #include <python.h> int _tmain(int argc, _TCHAR* argv[]) { try { PyObject *pName,*pModule,*pDict,*pFunc,*pArgs1,*pArgs2,*pOutput; Py_Initialize(); if(!Py_IsInitialized()) return -1; pModule=PyImport_ImportModule("test"); pDict=PyModule_GetDict(pModule); pFunc=PyDict_GetItemString(pDict,"add"); pArgs1=Py_BuildValue("ii", 1,2); //pArgs2=Py_BuildValue("i", 2); pOutput=PyEval_CallObject(pFunc,pArgs1); int c=0; PyArg_Parse(pOutput, "d", &c); cout<<c; //PyRun_SimpleString(""); Py_Finalize(); } catch(exception* ex) { cout<<ex->what(); } char c; cin>>c; return 0; } Console print nothing and closed. What's wrong? Thanks! A: Last I checked, C doesn't have exceptions. Surely, you're not going to get any exceptions thrown by calls to the Python lib. First, since you're using C++, you may need to include the Python lib with an extern declaration. extern "C" { #include "python.h" } Next, since you don't have exceptions in C calls, you should test the result of each call as you go along. This will help you better understand where it's failing. Since you're not getting a segfault or anything, I suspect you're getting to if(!Py_IsInitialized()) return -1; And exiting. Instead, you could print the return value so you know what's happening. int is_init = Py_IsInitialized(); cout << "are we initialized? " << is_init; if(!is_init) return -1; If that doesn't demonstrate the trouble, then add additional cout statements throughout your code to trace where the problem is occurring... or better yet, use a debugger and step through the code as it runs. Surely you'll find what's going wrong. A: I found it contains some chinese words in first line. #XXX And, it also didn't work in pythonwin. Said something wrong. So, I deleted them, and it's OK!
Problems calling Python from C++
test.py def add(a,b): """ """ print a,b,a+b return a+b c program #include <python.h> int _tmain(int argc, _TCHAR* argv[]) { try { PyObject *pName,*pModule,*pDict,*pFunc,*pArgs1,*pArgs2,*pOutput; Py_Initialize(); if(!Py_IsInitialized()) return -1; pModule=PyImport_ImportModule("test"); pDict=PyModule_GetDict(pModule); pFunc=PyDict_GetItemString(pDict,"add"); pArgs1=Py_BuildValue("ii", 1,2); //pArgs2=Py_BuildValue("i", 2); pOutput=PyEval_CallObject(pFunc,pArgs1); int c=0; PyArg_Parse(pOutput, "d", &c); cout<<c; //PyRun_SimpleString(""); Py_Finalize(); } catch(exception* ex) { cout<<ex->what(); } char c; cin>>c; return 0; } Console print nothing and closed. What's wrong? Thanks!
[ "Last I checked, C doesn't have exceptions. Surely, you're not going to get any exceptions thrown by calls to the Python lib.\nFirst, since you're using C++, you may need to include the Python lib with an extern declaration.\nextern \"C\" {\n #include \"python.h\"\n}\n\nNext, since you don't have exceptions in C calls, you should test the result of each call as you go along. This will help you better understand where it's failing.\nSince you're not getting a segfault or anything, I suspect you're getting to\nif(!Py_IsInitialized())\n return -1;\n\nAnd exiting. Instead, you could print the return value so you know what's happening.\nint is_init = Py_IsInitialized();\ncout << \"are we initialized? \" << is_init;\nif(!is_init)\n return -1;\n\nIf that doesn't demonstrate the trouble, then add additional cout statements throughout your code to trace where the problem is occurring... or better yet, use a debugger and step through the code as it runs. Surely you'll find what's going wrong.\n", "I found it contains some chinese words in first line.\n#XXX\n\nAnd, it also didn't work in pythonwin.\nSaid something wrong.\nSo, I deleted them, and it's OK!\n" ]
[ 3, 0 ]
[]
[]
[ "api", "c++", "python" ]
stackoverflow_0003101225_api_c++_python.txt
Q: Python 3.1 Installation missing Tkinter on OS 10.6.4 Has anyone else had this problem? I have re-installed twice with the same result. The pre-install of 2.6 on the Mac had a lib-tk folder with the correct modules. Nothing like this is being created for 3.1. There is a Tkinter folder but it contains only a few obscure modules. Importing _tkinter and tkinter works but not Tkinter and all of the example programs fail. A: Tkinter was substantially refactored in Python 3 from a set of modules into packages. Tkinter is now tkinter and the lib-tk folder no longer exists. At least some of the example tkinter programs included in the OS X 3.1 distribution work if you ensure they are being launched under Python 3 and not Python 2. See the Python 3.1 library reference.
Python 3.1 Installation missing Tkinter on OS 10.6.4
Has anyone else had this problem? I have re-installed twice with the same result. The pre-install of 2.6 on the Mac had a lib-tk folder with the correct modules. Nothing like this is being created for 3.1. There is a Tkinter folder but it contains only a few obscure modules. Importing _tkinter and tkinter works but not Tkinter and all of the example programs fail.
[ "Tkinter was substantially refactored in Python 3 from a set of modules into packages. Tkinter is now tkinter and the lib-tk folder no longer exists. At least some of the example tkinter programs included in the OS X 3.1 distribution work if you ensure they are being launched under Python 3 and not Python 2. See the Python 3.1 library reference.\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0003118880_python.txt
Q: datetime issue with xlrd & xlwt python libs I'm trying to write some dates from one excel spreadsheet to another. Currently, I'm getting a representation in excel that isn't quite what I want such as this: "40299.2501157407" I can get the date to print out fine to the console, however it doesn't seem to work right writing to the excel spreadsheet -- the data must be a date type in excel, I can't have a text version of it. Here's the line that reads the date in: date_ccr = xldate_as_tuple(sheet_ccr.cell(row_ccr_index, 9).value, book_ccr.datemode) Here's the line that writes the date out: row.set_cell_date(11, datetime(*date_ccr)) There isn't anything being done to date_ccr in between those two lines other than a few comparisons. Any ideas? A: You can write the floating point number directly to the spreadsheet and set the number format of the cell. Set the format using the num_format_str of an XFStyle object when you write the value. https://secure.simplistix.co.uk/svn/xlwt/trunk/xlwt/doc/xlwt.html#xlwt.Worksheet.write-method The following example writes the date 01-05-2010. (Also includes time of 06:00:10, but this is hidden by the format chosen in this example.) import xlwt # d can also be a datetime object d = 40299.2501157407 wb = xlwt.Workbook() sheet = wb.add_sheet('new') style = xlwt.XFStyle() style.num_format_str = 'DD-MM-YYYY' sheet.write(5, 5, d, style) wb.save('test_new.xls') There are examples of number formats (num_formats.py) in the examples folder of the xlwt source code. On my Windows machine: C:\Python26\Lib\site-packages\xlwt\examples You can read about how Excel stores dates (third section on this page): https://secure.simplistix.co.uk/svn/xlrd/trunk/xlrd/doc/xlrd.html
datetime issue with xlrd & xlwt python libs
I'm trying to write some dates from one excel spreadsheet to another. Currently, I'm getting a representation in excel that isn't quite what I want such as this: "40299.2501157407" I can get the date to print out fine to the console, however it doesn't seem to work right writing to the excel spreadsheet -- the data must be a date type in excel, I can't have a text version of it. Here's the line that reads the date in: date_ccr = xldate_as_tuple(sheet_ccr.cell(row_ccr_index, 9).value, book_ccr.datemode) Here's the line that writes the date out: row.set_cell_date(11, datetime(*date_ccr)) There isn't anything being done to date_ccr in between those two lines other than a few comparisons. Any ideas?
[ "You can write the floating point number directly to the spreadsheet and set the number format of the cell. Set the format using the num_format_str of an XFStyle object when you write the value.\nhttps://secure.simplistix.co.uk/svn/xlwt/trunk/xlwt/doc/xlwt.html#xlwt.Worksheet.write-method\nThe following example writes the date 01-05-2010. (Also includes time of 06:00:10, but this is hidden by the format chosen in this example.)\nimport xlwt\n\n# d can also be a datetime object\nd = 40299.2501157407\n\nwb = xlwt.Workbook()\nsheet = wb.add_sheet('new')\n\nstyle = xlwt.XFStyle()\nstyle.num_format_str = 'DD-MM-YYYY'\n\nsheet.write(5, 5, d, style)\nwb.save('test_new.xls')\n\nThere are examples of number formats (num_formats.py) in the examples folder of the xlwt source code. On my Windows machine: C:\\Python26\\Lib\\site-packages\\xlwt\\examples\nYou can read about how Excel stores dates (third section on this page): https://secure.simplistix.co.uk/svn/xlrd/trunk/xlrd/doc/xlrd.html\n" ]
[ 9 ]
[]
[]
[ "datetime", "excel", "python", "xlrd", "xlwt" ]
stackoverflow_0003118940_datetime_excel_python_xlrd_xlwt.txt
Q: Python global variable insanity You have three files: main.py, second.py, and common.py common.py #!/usr/bin/python GLOBAL_ONE = "Frank" main.py #!/usr/bin/python from common import * from second import secondTest if __name__ == "__main__": global GLOBAL_ONE print GLOBAL_ONE #Prints "Frank" GLOBAL_ONE = "Bob" print GLOBAL_ONE #Prints "Bob" secondTest() print GLOBAL_ONE #Prints "Bob" second.py #!/usr/bin/python from common import * def secondTest(): global GLOBAL_ONE print GLOBAL_ONE #Prints "Frank" Why does secondTest not use the global variables of its calling program? What is the point of calling something 'global' if, in fact, it is not!? What am I missing in order to get secondTest (or any external function I call from main) to recognize and use the correct variables? A: global means global for this module, not for whole program. When you do from lala import * you add all definitions of lala as locals to this module. So in your case you get two copies of GLOBAL_ONE A: The first and obvious question is why? There are a few situations in which global variables are necessary/useful, but those are indeed few. Your issue is with namespaces. When you import common into second.py, GLOBAL_ONE comes from that namespace. When you import secondTest it still references GLOBAL_ONE from common.py. Your real issue, however, is with design. I can't think of a single logical good reason to implement a global variable this way. Global variables are a tricky business in Python because there's no such thing as a constant variable. However, convention is that when you want to keep something constant in Python you name it WITH_ALL_CAPS. Ergo: somevar = MY_GLOBAL_VAR # good! MY_GLOBAL_VAR = somevar # What? You "can't" assign to a constant! Bad! There are plenty of reasons that doing something like this: earth = 6e24 def badfunction(): global earth earth += 1e5 print '%.2e' % earth is terrible. Of course if you're just doing this as an exercise in understanding namespaces and the global call, carry on. If not, some of the reasons that global variables are A Bad Thing™ are: Namespace pollution Functional integration - you want your functions to be compartmentalized Functional side effects - what happens when you write a function that modifies the global variable balance and either you or someone else is reusing your function and don't take that into account? If you were calculating account balance, all of the sudden you either have too much, or not enough. Bugs like this are difficult to find. If you have a function that needs a value, you should pass it that value as a parameter, unless you have a really good reason otherwise. One reason would be having a global of PI - depending on your precision needs you may want it to be 3.14, or you may want it 3.14159265... but that is one case where a global makes sense. There are probably only a handful or two of real-world cases that can use globals properly. One of the cases are constants in game programming. It's easier to import pygame.locals and use KP_UP than remember the integer value responding to that event. These are exceptions to the rule. And (at least in pygame) these constants are stored in a separate file - just for the constants. Any module that needs those constants will import said constants. When you program, you write functions to break your problem up into manageable chunks. Preferably a function should do one thing, and have no side effects. That means a function such as calculatetime() should calculate the time. It probably shouldn't go reading a file that contains the time, and forbid that it should do something like write the time somewhere. It can return the time, and take parameters if it needs them - both of these are good, acceptable things for functions to do. Functions are a sort of contract between you (the programmer of the function) and anyone (including you) who uses the function. Accessing and changing global variables are a violation of that contract because the function can modify the outside data in ways that are not defined or expected. When I use that calculatetime() function, I expect that it will calculate the time and probably return it, not modify the global variable time which responds to the module time that I just imported. Modifying global variables break the contract and the logical distinction between actions that your program takes. They can introduce bugs into your program. They make it hard to upgrade and modify functions. When you use globals as variables instead of constant, death awaits you with sharp pointy teeth! A: Compare the results of the following to yours. When you use the correct namespaces you will get the results you expect. common.py #!/usr/bin/python GLOBAL_ONE = "Frank" main.py #!/usr/bin/python from second import secondTest import common if __name__ == "__main__": print common.GLOBAL_ONE # Prints "Frank" common.GLOBAL_ONE = "Bob" print common.GLOBAL_ONE # Prints "Bob" secondTest() print common.GLOBAL_ONE # Prints "Bob" second.py #!/usr/bin/python import common def secondTest(): print common.GLOBAL_ONE # Prints "Bob" A: Let me first say that I agree with everybody else who answered before saying that this is probably not what you want to do. But in case you are really sure this is the way to go you can do the following. Instead of defining GLOBAL_ONE as a string in common.py, define it as a list, that is, GLOBAL_ONE = ["Frank"]. Then, you read and modify GLOBAL_ONE[0] instead of GLOBAL_ONE and everything works the way you want. Note that I do not think that this is good style and there are probably better ways to achieve what you really want.
Python global variable insanity
You have three files: main.py, second.py, and common.py common.py #!/usr/bin/python GLOBAL_ONE = "Frank" main.py #!/usr/bin/python from common import * from second import secondTest if __name__ == "__main__": global GLOBAL_ONE print GLOBAL_ONE #Prints "Frank" GLOBAL_ONE = "Bob" print GLOBAL_ONE #Prints "Bob" secondTest() print GLOBAL_ONE #Prints "Bob" second.py #!/usr/bin/python from common import * def secondTest(): global GLOBAL_ONE print GLOBAL_ONE #Prints "Frank" Why does secondTest not use the global variables of its calling program? What is the point of calling something 'global' if, in fact, it is not!? What am I missing in order to get secondTest (or any external function I call from main) to recognize and use the correct variables?
[ "global means global for this module, not for whole program. When you do\nfrom lala import *\n\nyou add all definitions of lala as locals to this module.\nSo in your case you get two copies of GLOBAL_ONE\n", "The first and obvious question is why?\nThere are a few situations in which global variables are necessary/useful, but those are indeed few.\nYour issue is with namespaces. When you import common into second.py, GLOBAL_ONE comes from that namespace. When you import secondTest it still references GLOBAL_ONE from common.py.\nYour real issue, however, is with design. I can't think of a single logical good reason to implement a global variable this way. Global variables are a tricky business in Python because there's no such thing as a constant variable. However, convention is that when you want to keep something constant in Python you name it WITH_ALL_CAPS. Ergo:\nsomevar = MY_GLOBAL_VAR # good!\nMY_GLOBAL_VAR = somevar # What? You \"can't\" assign to a constant! Bad!\n\nThere are plenty of reasons that doing something like this:\nearth = 6e24\ndef badfunction():\n global earth\n earth += 1e5\nprint '%.2e' % earth\n\nis terrible.\nOf course if you're just doing this as an exercise in understanding namespaces and the global call, carry on.\nIf not, some of the reasons that global variables are A Bad Thing™ are:\n\nNamespace pollution\nFunctional integration - you want your functions to be compartmentalized\nFunctional side effects - what happens when you write a function that modifies the global variable balance and either you or someone else is reusing your function and don't take that into account? If you were calculating account balance, all of the sudden you either have too much, or not enough. Bugs like this are difficult to find.\n\nIf you have a function that needs a value, you should pass it that value as a parameter, unless you have a really good reason otherwise. One reason would be having a global of PI - depending on your precision needs you may want it to be 3.14, or you may want it 3.14159265... but that is one case where a global makes sense. There are probably only a handful or two of real-world cases that can use globals properly. One of the cases are constants in game programming. It's easier to import pygame.locals and use KP_UP than remember the integer value responding to that event. These are exceptions to the rule.\nAnd (at least in pygame) these constants are stored in a separate file - just for the constants. Any module that needs those constants will import said constants.\nWhen you program, you write functions to break your problem up into manageable chunks. Preferably a function should do one thing, and have no side effects. That means a function such as calculatetime() should calculate the time. It probably shouldn't go reading a file that contains the time, and forbid that it should do something like write the time somewhere. It can return the time, and take parameters if it needs them - both of these are good, acceptable things for functions to do. Functions are a sort of contract between you (the programmer of the function) and anyone (including you) who uses the function. Accessing and changing global variables are a violation of that contract because the function can modify the outside data in ways that are not defined or expected. When I use that calculatetime() function, I expect that it will calculate the time and probably return it, not modify the global variable time which responds to the module time that I just imported.\nModifying global variables break the contract and the logical distinction between actions that your program takes. They can introduce bugs into your program. They make it hard to upgrade and modify functions. When you use globals as variables instead of constant, death awaits you with sharp pointy teeth!\n", "Compare the results of the following to yours. When you use the correct namespaces you will get the results you expect.\ncommon.py\n#!/usr/bin/python\nGLOBAL_ONE = \"Frank\"\n\nmain.py\n#!/usr/bin/python\nfrom second import secondTest\nimport common\n\nif __name__ == \"__main__\":\n print common.GLOBAL_ONE # Prints \"Frank\"\n common.GLOBAL_ONE = \"Bob\"\n print common.GLOBAL_ONE # Prints \"Bob\"\n\n secondTest()\n\n print common.GLOBAL_ONE # Prints \"Bob\"\n\nsecond.py\n#!/usr/bin/python\nimport common\n\ndef secondTest():\n print common.GLOBAL_ONE # Prints \"Bob\"\n\n", "Let me first say that I agree with everybody else who answered before saying that this is probably not what you want to do. But in case you are really sure this is the way to go you can do the following. Instead of defining GLOBAL_ONE as a string in common.py, define it as a list, that is, GLOBAL_ONE = [\"Frank\"]. Then, you read and modify GLOBAL_ONE[0] instead of GLOBAL_ONE and everything works the way you want. Note that I do not think that this is good style and there are probably better ways to achieve what you really want.\n" ]
[ 11, 5, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003119287_python.txt
Q: Jython project in Eclipse can't find the xml module, but works in an identical project I have two projects in Eclipse with Java and Python code, using Jython. Also I'm using PyDev. One project can import and use the xml module just fine, and the other gives the error ImportError: No module named xml. As far as I can tell, all the project properties are set identically. The working project was created from scratch and the other comes from code checked out of an svn repository and put into a new project. What could be the difference? edit- Same for os, btw. It's just missing some path somewhere... A: eclipse stores project data in files like .project .pydevprojct .classpath with checkin / checkout via svn it is possible to lost some of these files check your dot-files
Jython project in Eclipse can't find the xml module, but works in an identical project
I have two projects in Eclipse with Java and Python code, using Jython. Also I'm using PyDev. One project can import and use the xml module just fine, and the other gives the error ImportError: No module named xml. As far as I can tell, all the project properties are set identically. The working project was created from scratch and the other comes from code checked out of an svn repository and put into a new project. What could be the difference? edit- Same for os, btw. It's just missing some path somewhere...
[ "eclipse stores project data in files like\n\n.project \n.pydevprojct\n.classpath\n\nwith checkin / checkout via svn it is possible to lost some of these files\ncheck your dot-files\n" ]
[ 2 ]
[]
[]
[ "eclipse", "java", "jython", "pydev", "python" ]
stackoverflow_0003057382_eclipse_java_jython_pydev_python.txt
Q: How to select an item in a gtk.IconView (Python) In a gtk.IconView I can use get_selected_items() to find the paths of the items a user selected in the view. I'm now looking for the corresponding method to set the selection of an IconView. But I can't find any!? What am I missing? A: There's a select_path() method. I somehow missed it on scanning through the docs.
How to select an item in a gtk.IconView (Python)
In a gtk.IconView I can use get_selected_items() to find the paths of the items a user selected in the view. I'm now looking for the corresponding method to set the selection of an IconView. But I can't find any!? What am I missing?
[ "There's a select_path() method. I somehow missed it on scanning through the docs.\n" ]
[ 0 ]
[]
[]
[ "gtk", "pygtk", "python", "selection" ]
stackoverflow_0003118909_gtk_pygtk_python_selection.txt
Q: Python: deepcopy(list) vs new_list = old_list[:] I'm doing exercise #9 from http://openbookproject.net/thinkcs/python/english2e/ch09.html and have ran into something that doesn't make sense. The exercise suggests using copy.deepcopy() to make my task easier but I don't see how it could. def add_row(matrix): """ >>> m = [[0, 0], [0, 0]] >>> add_row(m) [[0, 0], [0, 0], [0, 0]] >>> n = [[3, 2, 5], [1, 4, 7]] >>> add_row(n) [[3, 2, 5], [1, 4, 7], [0, 0, 0]] >>> n [[3, 2, 5], [1, 4, 7]] """ import copy # final = copy.deepcopy(matrix) # first way final = matrix[:] # second way li = [] for i in range(len(matrix[0])): li.append(0) # return final.append(li) # why doesn't this work? final.append(li) # but this does return final I'm confused why the book suggests using deepcopy() when a simple list[:] copies it. Am I using it wrong? Is my function completely out of wack? I also have some confusion returning values. the question is documents in the code above. TIA A: You asked two questions: Deep vs. shallow copy matrix[:] is a shallow copy -- it only copies the elements directly stored in it, and doesn't recursively duplicate the elements of arrays or other references within itself. That means: a = [[4]] b = a[:] a[0].append(5) print b[0] # Outputs [4, 5], as a[0] and b[0] point to the same array The same would happen if you stored an object in a. deepcopy() is, naturally, a deep copy -- it makes copies of each of its elements recursively, all the way down the tree: a = [[4]] c = copy.deepcopy(a) a[0].append(5) print c[0] # Outputs [4], as c[0] is a copy of the elements of a[0] into a new array Returning return final.append(li) is different from calling append and returning final because list.append does not return the list object itself, it returns None A: See the documentation on deep and shallow copy. list[:] does not create copies of nested elements. For your problem regarding the return statement, it looks like you're not inside a function when you call it, I assume that happened while pasting the code here. Regarding the return value Michael Mrozek is right.
Python: deepcopy(list) vs new_list = old_list[:]
I'm doing exercise #9 from http://openbookproject.net/thinkcs/python/english2e/ch09.html and have ran into something that doesn't make sense. The exercise suggests using copy.deepcopy() to make my task easier but I don't see how it could. def add_row(matrix): """ >>> m = [[0, 0], [0, 0]] >>> add_row(m) [[0, 0], [0, 0], [0, 0]] >>> n = [[3, 2, 5], [1, 4, 7]] >>> add_row(n) [[3, 2, 5], [1, 4, 7], [0, 0, 0]] >>> n [[3, 2, 5], [1, 4, 7]] """ import copy # final = copy.deepcopy(matrix) # first way final = matrix[:] # second way li = [] for i in range(len(matrix[0])): li.append(0) # return final.append(li) # why doesn't this work? final.append(li) # but this does return final I'm confused why the book suggests using deepcopy() when a simple list[:] copies it. Am I using it wrong? Is my function completely out of wack? I also have some confusion returning values. the question is documents in the code above. TIA
[ "You asked two questions:\nDeep vs. shallow copy\nmatrix[:] is a shallow copy -- it only copies the elements directly stored in it, and doesn't recursively duplicate the elements of arrays or other references within itself. That means:\na = [[4]]\nb = a[:]\na[0].append(5)\nprint b[0] # Outputs [4, 5], as a[0] and b[0] point to the same array\n\nThe same would happen if you stored an object in a.\ndeepcopy() is, naturally, a deep copy -- it makes copies of each of its elements recursively, all the way down the tree:\na = [[4]]\nc = copy.deepcopy(a)\na[0].append(5)\nprint c[0] # Outputs [4], as c[0] is a copy of the elements of a[0] into a new array\n\nReturning\nreturn final.append(li) is different from calling append and returning final because list.append does not return the list object itself, it returns None\n", "See the documentation on deep and shallow copy.\nlist[:]\n\ndoes not create copies of nested elements.\nFor your problem regarding the return statement, it looks like you're not inside a function when you call it, I assume that happened while pasting the code here. Regarding the return value Michael Mrozek is right.\n" ]
[ 23, 2 ]
[]
[]
[ "copy", "list", "python" ]
stackoverflow_0003119901_copy_list_python.txt
Q: library for text rendering that supports text-on-path I need a good, reliable library or toolchain for programatically rendering text to png, with different sizes, fonts, weights, etc. It also needs to be able to render text in an arc or to a path. I would like it to be fast, because I'd be running it as on a server. I've tried using SVG and librsvg, but that doesn't render <textPath> elements. I've tried pycairo, but again, the text to path doesn't work great, and everywhere in the cairo documentation it mentions that text-to-path is a "toy" and shouldn't be used for serious applications. Python bindings would be best, because the server runs python. But I'll take any suggestion. A: Qt has a SVG module, i believe it supports the textPath element. http://doc.trolltech.com/4.1/qtsvg.html
library for text rendering that supports text-on-path
I need a good, reliable library or toolchain for programatically rendering text to png, with different sizes, fonts, weights, etc. It also needs to be able to render text in an arc or to a path. I would like it to be fast, because I'd be running it as on a server. I've tried using SVG and librsvg, but that doesn't render <textPath> elements. I've tried pycairo, but again, the text to path doesn't work great, and everywhere in the cairo documentation it mentions that text-to-path is a "toy" and shouldn't be used for serious applications. Python bindings would be best, because the server runs python. But I'll take any suggestion.
[ "Qt has a SVG module, i believe it supports the textPath element.\nhttp://doc.trolltech.com/4.1/qtsvg.html\n" ]
[ 0 ]
[]
[]
[ "python", "rendering", "text_rendering" ]
stackoverflow_0003119882_python_rendering_text_rendering.txt
Q: Tips on Python MIL-STD-1553 Has anyone ever worked with MIL-STD-1553 in Python? How did you do it? A: If the 1553 interface has a Windows DLL, you can use the ctypes library to access it. I've done this for Python and my organization's 1553 products. To start, I would write a quick test that accesses a DLL function that doesn't access the 1553 hardware, or accesses the hardware in a very simple manner. If that succeeds, then you know that you can access the DLL. Once you know you can access the DLL then you can work on getting the rest of the DLL functions to work in Python.
Tips on Python MIL-STD-1553
Has anyone ever worked with MIL-STD-1553 in Python? How did you do it?
[ "If the 1553 interface has a Windows DLL, you can use the ctypes library to access it. I've done this for Python and my organization's 1553 products. \nTo start, I would write a quick test that accesses a DLL function that doesn't access the 1553 hardware, or accesses the hardware in a very simple manner. If that succeeds, then you know that you can access the DLL. Once you know you can access the DLL then you can work on getting the rest of the DLL functions to work in Python.\n" ]
[ 3 ]
[]
[]
[ "python" ]
stackoverflow_0003119027_python.txt
Q: How to lazily evaluate ORM call after fixtures are loaded into db in Django? I've got a module pagetypes.py that extracts a couple of constants (I shouldn't really use word constant here) from the db for later reuse: def _get_page_type_(type): return PageType.objects.get(type=type) PAGE_TYPE_MAIN = _get_page_type_('Main') PAGE_TYPE_OTHER = _get_page_type_('Other') then somewhere in views I do: import pagetypes ... print pagetypes.PAGE_TYPE_MAIN #simplified It all works fine when db has those records and I make sure it does... unless this code is under test. In that case I want to load those records into db via fixtures. The problem with that is that fixtures are not loaded (even syncdb is not run) by the time pagetypes module is imported resulting in _get_page_type_ call failing with: psycopg2.ProgrammingError: relation "pagetype" does not exist Test runner always tries to import pagetypes module, because it is imported by view that is under test. How do I get around this problem? I was thinking of lazily loading pagetype constants PAGE_TYPE_MAIN, PAGE_TYPE_OTHER, but then I want it to fail early if those records are not in the db (or fixtures if under test), so I don't really know how to implement this. I was also thinking of object level caching and just call PageType.objects.get(type=type) whenever constant is used/called, but wouldn't that be an overkill? Calling orm without cache would result in too many db calls, which I want to prevent. It must be something very simple, but I can't work it out. ;-) A: I would use the functions instead of the constants, but memoize them: _cache = {} def get_page_type(type_name): if type_name not in _cache: _cache[type_name] = PageType.objects.get(type=type_name) return _cache[type_name] So now you'd call get_page_type('Main') directly when necessary.
How to lazily evaluate ORM call after fixtures are loaded into db in Django?
I've got a module pagetypes.py that extracts a couple of constants (I shouldn't really use word constant here) from the db for later reuse: def _get_page_type_(type): return PageType.objects.get(type=type) PAGE_TYPE_MAIN = _get_page_type_('Main') PAGE_TYPE_OTHER = _get_page_type_('Other') then somewhere in views I do: import pagetypes ... print pagetypes.PAGE_TYPE_MAIN #simplified It all works fine when db has those records and I make sure it does... unless this code is under test. In that case I want to load those records into db via fixtures. The problem with that is that fixtures are not loaded (even syncdb is not run) by the time pagetypes module is imported resulting in _get_page_type_ call failing with: psycopg2.ProgrammingError: relation "pagetype" does not exist Test runner always tries to import pagetypes module, because it is imported by view that is under test. How do I get around this problem? I was thinking of lazily loading pagetype constants PAGE_TYPE_MAIN, PAGE_TYPE_OTHER, but then I want it to fail early if those records are not in the db (or fixtures if under test), so I don't really know how to implement this. I was also thinking of object level caching and just call PageType.objects.get(type=type) whenever constant is used/called, but wouldn't that be an overkill? Calling orm without cache would result in too many db calls, which I want to prevent. It must be something very simple, but I can't work it out. ;-)
[ "I would use the functions instead of the constants, but memoize them:\n_cache = {}\n\ndef get_page_type(type_name):\n if type_name not in _cache:\n _cache[type_name] = PageType.objects.get(type=type_name)\n return _cache[type_name]\n\nSo now you'd call get_page_type('Main') directly when necessary.\n" ]
[ 2 ]
[]
[]
[ "django", "fixtures", "lazy_loading", "python", "unit_testing" ]
stackoverflow_0003119606_django_fixtures_lazy_loading_python_unit_testing.txt
Q: parsing a line of text to get a specific number I have a line of text in the form " some spaces variable = 7 = '0x07' some more data" I want to parse it and get the number 7 from "some variable = 7". How can this be done in python? A: I would use a simpler solution, avoiding regular expressions. Split on '=' and get the value at the position you expect text = 'some spaces variable = 7 = ...' if '=' in text: chunks = text.split('=') assignedval = chunks[1]#second value, 7 print 'assigned value is', assignedval else: print 'no assignment in line' A: Use a regular expression. Essentially, you create an expression that goes something like "variable = (\d+)", do a match, and then take the first group, which will give you the string 7. You can then convert it to an int. Read the tutorial in the link above. A: Basic regex code snippet to find numbers in a string. >>> import re >>> input = " some spaces variable = 7 = '0x07' some more data" >>> nums = re.findall("[0-9]*", input) >>> nums = [i for i in nums if i] # remove empty strings >>> nums ['7', '0', '07'] Check out the documentation and How-To on python.org.
parsing a line of text to get a specific number
I have a line of text in the form " some spaces variable = 7 = '0x07' some more data" I want to parse it and get the number 7 from "some variable = 7". How can this be done in python?
[ "I would use a simpler solution, avoiding regular expressions.\nSplit on '=' and get the value at the position you expect\ntext = 'some spaces variable = 7 = ...'\nif '=' in text:\n chunks = text.split('=')\n assignedval = chunks[1]#second value, 7\n print 'assigned value is', assignedval\nelse:\n print 'no assignment in line'\n\n", "Use a regular expression.\nEssentially, you create an expression that goes something like \"variable = (\\d+)\", do a match, and then take the first group, which will give you the string 7. You can then convert it to an int.\nRead the tutorial in the link above.\n", "Basic regex code snippet to find numbers in a string. \n>>> import re\n>>> input = \" some spaces variable = 7 = '0x07' some more data\"\n>>> nums = re.findall(\"[0-9]*\", input)\n>>> nums = [i for i in nums if i] # remove empty strings\n>>> nums\n['7', '0', '07']\n\nCheck out the documentation and How-To on python.org.\n" ]
[ 4, 2, 0 ]
[]
[]
[ "parsing", "python" ]
stackoverflow_0003120426_parsing_python.txt
Q: Is there an Objective-C equivalent to Python urllib and urllib2? Are there any equivalents in objective-c to the following python urllib2 functions? Request, urlopen, HTTPError, HTTPCookieProRequest, urlopen, HTTPError, HTTPCookieProcessor Also, how would I able to to this and change the method from "get" to "post"? A: You're looking for some combination of NSURL, NSURLRequest, NSURLConnection, NSHTTPConnection, etc. Check out the URL Loading System Programming Guide for all the information you need. A: NSMutableHTTPURLRequest, a category of NSMutableURLRequest, is how you set up an HTTP request. Using that class you will specify a method (GET or POST), headers and a url. NSURLConnection is how you open the connection. You will pass in a request and delegate, and the delegate will receive data, errors and messages related to the connection as they become available. NSHTTPCookieStorage is how you manage existing cookies. There are a number of related classes in the NSHTTPCookie family. With urlopen, you open a connection and read from it. There is no direct equivalent to that unless you use something lower level like CFReadStreamCreateForHTTPRequest. In Objective-C everything is passive, where you are notified when events occur on the stream.
Is there an Objective-C equivalent to Python urllib and urllib2?
Are there any equivalents in objective-c to the following python urllib2 functions? Request, urlopen, HTTPError, HTTPCookieProRequest, urlopen, HTTPError, HTTPCookieProcessor Also, how would I able to to this and change the method from "get" to "post"?
[ "You're looking for some combination of NSURL, NSURLRequest, NSURLConnection, NSHTTPConnection, etc. Check out the URL Loading System Programming Guide for all the information you need.\n", "NSMutableHTTPURLRequest, a category of NSMutableURLRequest, is how you set up an HTTP request. Using that class you will specify a method (GET or POST), headers and a url.\nNSURLConnection is how you open the connection. You will pass in a request and delegate, and the delegate will receive data, errors and messages related to the connection as they become available.\nNSHTTPCookieStorage is how you manage existing cookies. There are a number of related classes in the NSHTTPCookie family.\nWith urlopen, you open a connection and read from it. There is no direct equivalent to that unless you use something lower level like CFReadStreamCreateForHTTPRequest. In Objective-C everything is passive, where you are notified when events occur on the stream.\n" ]
[ 1, 1 ]
[]
[]
[ "objective_c", "python" ]
stackoverflow_0003120430_objective_c_python.txt
Q: Python, subclassing immutable types I've the following class: class MySet(set): def __init__(self, arg=None): if isinstance(arg, basestring): arg = arg.split() set.__init__(self, arg) This works as expected (initialising the set with the words of the string rather than the letters). However when I want to do the same with the immutable version of set, the __init__ method seems to be ignored: class MySet(frozenset): def __init__(self, arg=None): if isinstance(arg, basestring): arg = arg.split() frozenset.__init__(self, arg) Can I achieve something similar with __new__ ? A: Yes, you need to override __new__ special method: class MySet(frozenset): def __new__(cls, *args): if args and isinstance (args[0], basestring): args = (args[0].split (),) + args[1:] return super (MySet, cls).__new__(cls, *args) print MySet ('foo bar baz') And the output is: MySet(['baz', 'foo', 'bar'])
Python, subclassing immutable types
I've the following class: class MySet(set): def __init__(self, arg=None): if isinstance(arg, basestring): arg = arg.split() set.__init__(self, arg) This works as expected (initialising the set with the words of the string rather than the letters). However when I want to do the same with the immutable version of set, the __init__ method seems to be ignored: class MySet(frozenset): def __init__(self, arg=None): if isinstance(arg, basestring): arg = arg.split() frozenset.__init__(self, arg) Can I achieve something similar with __new__ ?
[ "Yes, you need to override __new__ special method:\nclass MySet(frozenset):\n\n def __new__(cls, *args):\n if args and isinstance (args[0], basestring):\n args = (args[0].split (),) + args[1:]\n return super (MySet, cls).__new__(cls, *args)\n\nprint MySet ('foo bar baz')\n\nAnd the output is:\nMySet(['baz', 'foo', 'bar'])\n\n" ]
[ 14 ]
[]
[]
[ "immutability", "python", "set" ]
stackoverflow_0003120562_immutability_python_set.txt
Q: How to copy matplotlib figure? I have FigureCanvasWxAgg instance with a figure displayed on a frame. If user clicks on the canvas another frame with a new FigureCanvasWxAgg containing the same figure will be shown. By now closing the new frame can result in destroying the C++ part of the figure so that it won't be available for the first frame. How can I save the figure? Python deepcopy from copy module does't work in this case. Thanks in advance. A: I'm not familiar with the inner workings, but could easily imagine how disposing of a frame damages the figure data. Is it expensive to draw? Otherwise I'd take the somewhat chickenish approach of simply redrawing it ;)
How to copy matplotlib figure?
I have FigureCanvasWxAgg instance with a figure displayed on a frame. If user clicks on the canvas another frame with a new FigureCanvasWxAgg containing the same figure will be shown. By now closing the new frame can result in destroying the C++ part of the figure so that it won't be available for the first frame. How can I save the figure? Python deepcopy from copy module does't work in this case. Thanks in advance.
[ "I'm not familiar with the inner workings, but could easily imagine how disposing of a frame damages the figure data. Is it expensive to draw? Otherwise I'd take the somewhat chickenish approach of simply redrawing it ;)\n" ]
[ 1 ]
[]
[]
[ "copy", "matplotlib", "python", "wxpython" ]
stackoverflow_0002513786_copy_matplotlib_python_wxpython.txt
Q: How to improve performance through Python multithreading I'm new to Python and multithreading, so please bear with me. I'm writing a script to process domains in a list through Web of Trust, a service that ranks websites from 1-100 on a scale of "trustworthiness", and write them to a CSV. Unfortunately Web of Trust's servers can take quite a while to respond, and processing 100k domains can take hours. My attempts at multithreading so far have been disappointing -- attempting to modify the script from this answer gave threading errors, I believe because some threads took too long to resolve. Here's my unmodified script. Can someone help me multithread it, or point me to a good multithreading resource? Thanks in advance. import urllib import re text = open("top100k", "r") text = text.read() text = re.split("\n+", text) out = open('output.csv', 'w') for element in text: try: content = urllib.urlopen("http://api.mywot.com/0.4/public_query2?target=" + element) content = content.read() content = content[content.index('<application name="0" r="'):content.index('" c')] content = element + "," + content[25] + content[26] + "\n" out.write(content) except: pass A: A quick scan through the WoT API documentation shows that as well as the public_query2 request that you are using, there is a public_query_json request that lets you get the data in batches of up to 100. I would suggest using that before you start flooding their server with lots of requests in parallel.
How to improve performance through Python multithreading
I'm new to Python and multithreading, so please bear with me. I'm writing a script to process domains in a list through Web of Trust, a service that ranks websites from 1-100 on a scale of "trustworthiness", and write them to a CSV. Unfortunately Web of Trust's servers can take quite a while to respond, and processing 100k domains can take hours. My attempts at multithreading so far have been disappointing -- attempting to modify the script from this answer gave threading errors, I believe because some threads took too long to resolve. Here's my unmodified script. Can someone help me multithread it, or point me to a good multithreading resource? Thanks in advance. import urllib import re text = open("top100k", "r") text = text.read() text = re.split("\n+", text) out = open('output.csv', 'w') for element in text: try: content = urllib.urlopen("http://api.mywot.com/0.4/public_query2?target=" + element) content = content.read() content = content[content.index('<application name="0" r="'):content.index('" c')] content = element + "," + content[25] + content[26] + "\n" out.write(content) except: pass
[ "A quick scan through the WoT API documentation shows that as well as the public_query2 request that you are using, there is a public_query_json request that lets you get the data in batches of up to 100. I would suggest using that before you start flooding their server with lots of requests in parallel.\n" ]
[ 1 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0003120438_multithreading_python.txt
Q: Why do I get TypeError: get() takes exactly 2 arguments (1 given)? Google App Engine I have been trying and trying for several hours now and there must be an easy way to retreive the url. I thought this was the way: #from data.models import Program import basehandler class ProgramViewHandler(basehandler.BaseHandler): def get(self,slug): # query = Program.all() # query.filter('slug =', fslug) self.render_template('../presentation/program.html',{}) Whenever this code gets executed I get this error on the stacktrace: appengine\ext\webapp__init__.py", line 511, in call handler.get(*groups) TypeError: get() takes exactly 2 arguments (1 given) I have done some debugging, but this kind of debugging exceeds my level of debugging. When I remove the slug from def get(self,slug) everything runs fine. This is the basehandler: import os from google.appengine.ext import webapp from google.appengine.ext.webapp import template class BaseHandler(webapp.RequestHandler): def __init__(self,**kw): webapp.RequestHandler.__init__(BaseHandler, **kw) def render_template(self, template_file, data=None, **kw): path = os.path.join(os.path.dirname(__file__), template_file) self.response.out.write(template.render(path, data)) If somebody could point me in the right direction it would be great! Thank you! It's the first time for me to use stackoverflow to post a question, normally I only read it to fix the problems I have. A: You are getting this error because ProgramViewHandler.get() is being called without the slug parameter. Most likely, you need to fix the URL mappings in your main.py file. Your URL mapping should probably look something like this: application = webapp.WSGIApplication([(r'/(.*)', ProgramViewHandler)]) The parenthesis indicate a regular expression grouping. These matched groups are passed to your handler as arguments. So in the above example, everything in the URL following the initial "/" will be passed to ProgramViewHandler.get()'s slug parameter. Learn more about URL mappings in webapp here. A: If you do this: obj = MyClass() obj.foo(3) The foo method on MyClass is called with two arguments: def foo(self, number) The object on which it is called is passed as the first parameter. Maybe you are calling get() statically (i.e. doing ProgramViewHandler.get() instead of myViewHandlerVariable.get()), or you are missing a parameter.
Why do I get TypeError: get() takes exactly 2 arguments (1 given)? Google App Engine
I have been trying and trying for several hours now and there must be an easy way to retreive the url. I thought this was the way: #from data.models import Program import basehandler class ProgramViewHandler(basehandler.BaseHandler): def get(self,slug): # query = Program.all() # query.filter('slug =', fslug) self.render_template('../presentation/program.html',{}) Whenever this code gets executed I get this error on the stacktrace: appengine\ext\webapp__init__.py", line 511, in call handler.get(*groups) TypeError: get() takes exactly 2 arguments (1 given) I have done some debugging, but this kind of debugging exceeds my level of debugging. When I remove the slug from def get(self,slug) everything runs fine. This is the basehandler: import os from google.appengine.ext import webapp from google.appengine.ext.webapp import template class BaseHandler(webapp.RequestHandler): def __init__(self,**kw): webapp.RequestHandler.__init__(BaseHandler, **kw) def render_template(self, template_file, data=None, **kw): path = os.path.join(os.path.dirname(__file__), template_file) self.response.out.write(template.render(path, data)) If somebody could point me in the right direction it would be great! Thank you! It's the first time for me to use stackoverflow to post a question, normally I only read it to fix the problems I have.
[ "You are getting this error because ProgramViewHandler.get() is being called without the slug parameter.\nMost likely, you need to fix the URL mappings in your main.py file. Your URL mapping should probably look something like this:\napplication = webapp.WSGIApplication([(r'/(.*)', ProgramViewHandler)])\n\nThe parenthesis indicate a regular expression grouping. These matched groups are passed to your handler as arguments. So in the above example, everything in the URL following the initial \"/\" will be passed to ProgramViewHandler.get()'s slug parameter.\nLearn more about URL mappings in webapp here.\n", "If you do this:\nobj = MyClass()\nobj.foo(3)\n\nThe foo method on MyClass is called with two arguments:\ndef foo(self, number)\n\nThe object on which it is called is passed as the first parameter.\nMaybe you are calling get() statically (i.e. doing ProgramViewHandler.get() instead of myViewHandlerVariable.get()), or you are missing a parameter.\n" ]
[ 9, 1 ]
[]
[]
[ "google_app_engine", "python", "web_applications" ]
stackoverflow_0003119562_google_app_engine_python_web_applications.txt
Q: How can I use common code in python? I'm currently maintaining two of my own applications. They both share some common aspects, and as a result, share some code. So far, I've just copied the modules from one project to the other, but now it's becoming a maintenance issue. I'd rather have the common code in one place, outside of both of the projects, which they can both import. Then, any changes to the common code would be reflected in both project. My question is: how can I do this? Do I create a library out of this code? If so, how do the dependent projects use the library? I think one thing I struggle with here is that the common code isn't really useful to anyone else, or at least, I don't want to make it a supported modules that other people can use. If my question isn't clear, please let me know. A: There is nothing special you have to do, Python just needs to find your module. This means that you have to put your common module into your PYTHONPATH, or you add their location to sys.path. See this. Say you have ~/python/project1 ~/python/project2 ~/python/libs/stuff.py ~/python/libs/other.py You can either set PYTHONPATH='~/python/libs' in your os enviroment, or you can do import sys, os sys.path.append(os.path.expanduser('~/python/libs')) # or give the full path After that you can do import stuff, other anywhere. You can also package your stuff, then you need a layout like this: ~/python/project1 ~/python/project2 ~/python/libs/mylibname/__init__.py ~/python/libs/mylibname/stuff.py ~/python/libs/mylibname/other.py ~/python/libs/mylibname/__init__.py must exist, but it can be a empty file. It turns mylibname into a package. After adding the libs folder to your path as above, you can do from mylibname import stuff, other. A: There are a lot of ways to factor code so it is reusable. It really depends on your specific situation as far as what will work best. Factoring your code into separate packages and modules is always a good idea, so related code stays bundled together and can be reused from other packages and modules. Factoring your code into classes within a module can also help in keeping related code grouped together. I would say that putting common code into a module or package that is on your PYTHONPATH and available to both applications would probably be your best solution. A: Here's how I would do it: make an EGG archive of your common project: ~:zip common.egg common make the egg file part of your libraries cp common.egg PROJECT_PATH/lib/ in your projects: import glob import os def main(): path_lib=os.path.abspath(os.path.split(os.path.abspath(sys.modules['__main__'].__file__))[0] + '/../lib') sys.path += glob.glob(path_lib + '/*.egg') from common import stuff stuff.doCommonStuff()
How can I use common code in python?
I'm currently maintaining two of my own applications. They both share some common aspects, and as a result, share some code. So far, I've just copied the modules from one project to the other, but now it's becoming a maintenance issue. I'd rather have the common code in one place, outside of both of the projects, which they can both import. Then, any changes to the common code would be reflected in both project. My question is: how can I do this? Do I create a library out of this code? If so, how do the dependent projects use the library? I think one thing I struggle with here is that the common code isn't really useful to anyone else, or at least, I don't want to make it a supported modules that other people can use. If my question isn't clear, please let me know.
[ "There is nothing special you have to do, Python just needs to find your module. This means that you have to put your common module into your PYTHONPATH, or you add their location to sys.path. See this.\nSay you have \n~/python/project1\n~/python/project2\n~/python/libs/stuff.py\n~/python/libs/other.py\n\nYou can either set PYTHONPATH='~/python/libs' in your os enviroment, or you can do \nimport sys, os\nsys.path.append(os.path.expanduser('~/python/libs')) # or give the full path\n\nAfter that you can do import stuff, other anywhere.\nYou can also package your stuff, then you need a layout like this:\n~/python/project1\n~/python/project2\n~/python/libs/mylibname/__init__.py\n~/python/libs/mylibname/stuff.py\n~/python/libs/mylibname/other.py\n\n~/python/libs/mylibname/__init__.py must exist, but it can be a empty file. It turns mylibname into a package.\nAfter adding the libs folder to your path as above, you can do from mylibname import stuff, other.\n", "There are a lot of ways to factor code so it is reusable. It really depends on your specific situation as far as what will work best. Factoring your code into separate packages and modules is always a good idea, so related code stays bundled together and can be reused from other packages and modules. Factoring your code into classes within a module can also help in keeping related code grouped together.\nI would say that putting common code into a module or package that is on your PYTHONPATH and available to both applications would probably be your best solution.\n", "Here's how I would do it: \n\nmake an EGG archive of your common project: \n~:zip common.egg common\n\nmake the egg file part of your libraries\ncp common.egg PROJECT_PATH/lib/\n\nin your projects:\nimport glob\nimport os\n\ndef main():\n path_lib=os.path.abspath(os.path.split(os.path.abspath(sys.modules['__main__'].__file__))[0] + '/../lib')\n sys.path += glob.glob(path_lib + '/*.egg')\n from common import stuff\n stuff.doCommonStuff()\n\n\n" ]
[ 18, 4, 0 ]
[]
[]
[ "module", "python" ]
stackoverflow_0003118008_module_python.txt
Q: How to enable custom string in Django.po for Localization? I use this code to create a zh-CN: django-admin.py makemessages -l zh-CN I add some string to Django.po: msgid "zjm1126" msgstr "哈哈哈!!!" And then compile it: django-admin.py compilemessages But I don't find it become chinese words. Why? A: You need to also take two more steps: Mark the string "zjm1126" for translation in your template, for example with {% trans "zjm1126" %}. Activate Chinese as the current language. This is often done for you by Django, but you can do it explicitly if you need to. A: use django-admin.py makemessages -l zh_CN not user django-admin.py makemessages -l zh-CN zh_CN is different from zh-CN
How to enable custom string in Django.po for Localization?
I use this code to create a zh-CN: django-admin.py makemessages -l zh-CN I add some string to Django.po: msgid "zjm1126" msgstr "哈哈哈!!!" And then compile it: django-admin.py compilemessages But I don't find it become chinese words. Why?
[ "You need to also take two more steps:\n\nMark the string \"zjm1126\" for translation in your template, for example with {% trans \"zjm1126\" %}.\nActivate Chinese as the current language. This is often done for you by Django, but you can do it explicitly if you need to.\n\n", "use django-admin.py makemessages -l zh_CN\nnot user django-admin.py makemessages -l zh-CN\nzh_CN is different from zh-CN\n" ]
[ 0, 0 ]
[]
[]
[ "django", "localization", "python" ]
stackoverflow_0003116871_django_localization_python.txt
Q: How do I send an email from a non-gmail account using the appengine I have successfully sent an email using the Google App Engine. However the only email address I can get to work is the gmail address I have listed as the admin of the site. I'm running the app on my own domain (bought and maintained using Google Apps). I would like to send the email from my own domain. Here's the code (or something similar to it): from google.appengine.api import mail sender = "myaddress@google.com" sender_i_want = "myaddress@mygoogleapp.com" mail.send_mail(sender=sender, to="Albert Johnson <Albert.Johnson@example.com>", subject="Your account has been approved", body=some_string_variable) And the error I get when I try to send it from my own domain is "InvalidSenderError: Unauthorized sender". I own the domain, I do in fact authorize using my domain to send the mail, I just need to know how to convince the App Engine that this is true. A: That's a restriction of App Engine's mail API: The sender address can be either the email address of a registered administrator for the application, or the email address of the current signed-in user (the user making the request that is sending the message). If you've got Google Apps running on that domain, you should have (or be able to create) an @thatdomain.com email addresses that you can register as an administrator of the App Engine app in question, which will then let you send email "from" that address.
How do I send an email from a non-gmail account using the appengine
I have successfully sent an email using the Google App Engine. However the only email address I can get to work is the gmail address I have listed as the admin of the site. I'm running the app on my own domain (bought and maintained using Google Apps). I would like to send the email from my own domain. Here's the code (or something similar to it): from google.appengine.api import mail sender = "myaddress@google.com" sender_i_want = "myaddress@mygoogleapp.com" mail.send_mail(sender=sender, to="Albert Johnson <Albert.Johnson@example.com>", subject="Your account has been approved", body=some_string_variable) And the error I get when I try to send it from my own domain is "InvalidSenderError: Unauthorized sender". I own the domain, I do in fact authorize using my domain to send the mail, I just need to know how to convince the App Engine that this is true.
[ "That's a restriction of App Engine's mail API:\n\nThe sender address can be either the email address of a registered administrator for the application, or the email address of the current signed-in user (the user making the request that is sending the message).\n\nIf you've got Google Apps running on that domain, you should have (or be able to create) an @thatdomain.com email addresses that you can register as an administrator of the App Engine app in question, which will then let you send email \"from\" that address.\n" ]
[ 7 ]
[]
[]
[ "email", "google_app_engine", "python" ]
stackoverflow_0003120941_email_google_app_engine_python.txt
Q: Check if some game is currently running and on top I am creating a keybind program for one game. So far it works perfectly but I constantly minimize this game to IM or do something else. So.. How do I make my program work when I got this game on top and when the game is minimized the program shouldn't work. A: If you're talking about the app that currently has the focus (like, WOW when it is full screen and you're playing, for example), then you should check out this tutorial. It's a tutorial on how to build an app that keeps track of what applications have been actively used. In the tutorial it explains how to use "user32.dll" to get the title of the active window. You could then, in your app, just check to see if the active title is the app that you want to have your app function or not, and then proceed or cancel accordingly.
Check if some game is currently running and on top
I am creating a keybind program for one game. So far it works perfectly but I constantly minimize this game to IM or do something else. So.. How do I make my program work when I got this game on top and when the game is minimized the program shouldn't work.
[ "If you're talking about the app that currently has the focus (like, WOW when it is full screen and you're playing, for example), then you should check out this tutorial. It's a tutorial on how to build an app that keeps track of what applications have been actively used. In the tutorial it explains how to use \"user32.dll\" to get the title of the active window. You could then, in your app, just check to see if the active title is the app that you want to have your app function or not, and then proceed or cancel accordingly.\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0003121095_python.txt
Q: Optimizing appengine entity key usage Should I care about locality of entities on the Google App Engine datastore? Should I use custom entity key names for that? For example, I could use "$article_uuid,$comment_id" as the key name of a Comment entity. Will it improve the speed of fetching all comments for an article? Or is it better to use shorter keys? Is it a good practice to use the key in this way? I could use the "$article_uuid,$comment_id" key name also instead of an index: def get_comments(article_uuid, limit=1000): key_prefix=db.Key.from_path('Comment', article_uuid) q = Comment.gql("where __key__ > :key_prefix and __key__ < :range_end", key_prefix=key_prefix, range_end=key_prefix+chr(ord(',')+1)) return q.fetch(limit) A: The locality of your data will be improved with your key_name scheme (ref, see slide 40) - since your key_name is prefixed with the corresponding article's ID, comments for a given article should be stored near each other. The key_name you proposed doesn't seem like it would be too long. I don't think you'll see too much difference between that and shorter keys in terms of storage space or serialization/deserialization time. I expect that the size of the Comment entity will be dominated by the rest of the entity.
Optimizing appengine entity key usage
Should I care about locality of entities on the Google App Engine datastore? Should I use custom entity key names for that? For example, I could use "$article_uuid,$comment_id" as the key name of a Comment entity. Will it improve the speed of fetching all comments for an article? Or is it better to use shorter keys? Is it a good practice to use the key in this way? I could use the "$article_uuid,$comment_id" key name also instead of an index: def get_comments(article_uuid, limit=1000): key_prefix=db.Key.from_path('Comment', article_uuid) q = Comment.gql("where __key__ > :key_prefix and __key__ < :range_end", key_prefix=key_prefix, range_end=key_prefix+chr(ord(',')+1)) return q.fetch(limit)
[ "The locality of your data will be improved with your key_name scheme (ref, see slide 40) - since your key_name is prefixed with the corresponding article's ID, comments for a given article should be stored near each other.\nThe key_name you proposed doesn't seem like it would be too long. I don't think you'll see too much difference between that and shorter keys in terms of storage space or serialization/deserialization time. I expect that the size of the Comment entity will be dominated by the rest of the entity.\n" ]
[ 1 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0003121333_google_app_engine_google_cloud_datastore_python.txt
Q: How to serve PHP together with Django? i have a Bluehost hosting account, and i manually configure django with this tutorial, but now i need to run php scripts into a subdomain or in subfolder, how can i do that? my root .htaccess look like this AddHandler fcgid-script .fcgi # For security reasons, Option followsymlinks cannot be overridden. #Options +FollowSymLinks Options +SymLinksIfOwnerMatch RewriteEngine On RewriteBase / RewriteRule ^(media/.*)$ - [L] RewriteRule ^(django\.fcgi/.*)$ - [L] RewriteRule ^(.*)$ django.fcgi/$1 [L] Thanks! A: I got it, just change a little htaccess and ready, stay this way for those who have the same problem: AddHandler fcgid-script .fcgi AddHandler application/x-httpd-php5s .php # For security reasons, Option followsymlinks cannot be overridden. #Options +FollowSymLinks Options +SymLinksIfOwnerMatch RewriteEngine On RewriteBase / RewriteRule ^(subfolder/.*)$ - [L] RewriteRule ^(media/.*)$ - [L] RewriteRule ^(django\.fcgi/.*)$ - [L] RewriteRule ^(.*)$ django.fcgi/$1 [L] Thanks! A: It would actually be easier to serve from a subdomain, configured in its own VirtualHost block.
How to serve PHP together with Django?
i have a Bluehost hosting account, and i manually configure django with this tutorial, but now i need to run php scripts into a subdomain or in subfolder, how can i do that? my root .htaccess look like this AddHandler fcgid-script .fcgi # For security reasons, Option followsymlinks cannot be overridden. #Options +FollowSymLinks Options +SymLinksIfOwnerMatch RewriteEngine On RewriteBase / RewriteRule ^(media/.*)$ - [L] RewriteRule ^(django\.fcgi/.*)$ - [L] RewriteRule ^(.*)$ django.fcgi/$1 [L] Thanks!
[ "I got it, just change a little htaccess and ready, stay this way for those who have the same problem:\nAddHandler fcgid-script .fcgi\nAddHandler application/x-httpd-php5s .php\n# For security reasons, Option followsymlinks cannot be overridden.\n#Options +FollowSymLinks\nOptions +SymLinksIfOwnerMatch\nRewriteEngine On\nRewriteBase /\nRewriteRule ^(subfolder/.*)$ - [L]\nRewriteRule ^(media/.*)$ - [L]\nRewriteRule ^(django\\.fcgi/.*)$ - [L]\nRewriteRule ^(.*)$ django.fcgi/$1 [L]\n\nThanks!\n", "It would actually be easier to serve from a subdomain, configured in its own VirtualHost block.\n" ]
[ 1, 1 ]
[]
[]
[ ".htaccess", "django", "fastcgi", "php", "python" ]
stackoverflow_0003121259_.htaccess_django_fastcgi_php_python.txt
Q: Invoke make from different directory with python script I need to invoke make (build a makefile) in a directory different from the one I'm in, from inside a Python script. If I simply do: build_ret = subprocess.Popen("../dir1/dir2/dir3/make", shell = True, stdout = subprocess.PIPE) I get the following: /bin/sh: ../dir1/dir2/dir3/make: No such file or directory I've tried: build_ret = subprocess.Popen("(cd ../dir1/dir2/dir3/; make)", shell = True, stdout = subprocess.PIPE) but the make command is ignored. I don't even get the "Nothing to build for" message. I've also tried using "communicate" but without success. This is running on Red Hat Linux. A: I'd go with @Philipp's solution of using cwd, but as a side note you could also use the -C option to make: make -C ../dir1/dir2/dir3/make -C dir, --directory=dir Change to directory dir before reading the makefiles or doing anything else. If multiple -C options are specified, each is interpreted relative to the previous one: -C / -C etc is equivalent to -C /etc. This is typically used with recursive invocations of make. A: Use the cwd argument, and use the list form of Popen: subprocess.Popen(["make"], stdout=subprocess.PIPE, cwd="../dir1/dir2/dir3") Invoking the shell is almost never required and is likely to cause problems because of the additional complexity involved. A: Try to use the full path, you can get the location of the python script by calling sys.argv[0] to just get the path: os.path.dirname(sys.argv[0]) You'll find quite some path manipulations in the os.path module
Invoke make from different directory with python script
I need to invoke make (build a makefile) in a directory different from the one I'm in, from inside a Python script. If I simply do: build_ret = subprocess.Popen("../dir1/dir2/dir3/make", shell = True, stdout = subprocess.PIPE) I get the following: /bin/sh: ../dir1/dir2/dir3/make: No such file or directory I've tried: build_ret = subprocess.Popen("(cd ../dir1/dir2/dir3/; make)", shell = True, stdout = subprocess.PIPE) but the make command is ignored. I don't even get the "Nothing to build for" message. I've also tried using "communicate" but without success. This is running on Red Hat Linux.
[ "I'd go with @Philipp's solution of using cwd, but as a side note you could also use the -C option to make:\nmake -C ../dir1/dir2/dir3/make\n\n-C dir, --directory=dir\n\nChange to directory dir before reading the makefiles or doing anything else. If multiple -C options are specified, each is interpreted relative to the previous one: -C / -C etc is equivalent to -C /etc. This is typically used with recursive invocations of make.\n\n", "Use the cwd argument, and use the list form of Popen:\nsubprocess.Popen([\"make\"], stdout=subprocess.PIPE, cwd=\"../dir1/dir2/dir3\")\n\nInvoking the shell is almost never required and is likely to cause problems because of the additional complexity involved.\n", "Try to use the full path, you can get the location of the python script by calling \nsys.argv[0]\n\nto just get the path:\nos.path.dirname(sys.argv[0])\n\nYou'll find quite some path manipulations in the os.path module\n" ]
[ 11, 9, 0 ]
[]
[]
[ "linux", "python" ]
stackoverflow_0003121555_linux_python.txt
Q: Which Python should I use? Possible Duplicates: Is it advisable to go with Python 3.1 for a beginner? What version of Python should I use if I’m a new to Python? Haven't really made anything in Python... Which Python should I take ahold of? 2.X or 3.X? A: 2.X still offers a far wider variety of third-party libraries / frameworks, instructional websites and books, and experts to help you out -- I expect this will continue for a few years until 3.X gradually overtakes it. Right now, therefore, I would still recommend 2.X despite 3.x's even-greater "clean-ness" and simplicity (because some cruft which 2.x has to keen around for backwards compatibility was finally wiped out in 3.x). Very few new features of 3.x are not backported in 2.x, by the way -- e..g, if you want print to be a function, like in 3.x, in your 2.6 or 2.7 module, just put, at the start of the module, the statement from __future__ import print_function "Importing from the future" is a typical Python way to make new features available when explicitly requested, without breaking backwards compatibility. A: You are in luck! Due to a lot of confusion about this people have put together a wiki page in the last few days: Should I use Python 2 or 3? A: 2.x Quite some modules have not yet been ported to python 3 and you will find much more books, online resources for learning python 2.x You also can't rely on python 3 being preinstalled, while for most linux distributions you can rely on some version of python 2 being available. The only one I know of that already has python 3 packages is the latest Fedora 13. If that matters to you depends on your needs. A: I'd say it depends where you are going to run the code. If you have complete control over the environment, use 3.x. If your environment is controlled externally (cheap webhosting for example) then you will probably need to use 2.x. The only other reason to stick with 2.x is if a critical library you can't live without hasn't been ported to 3.x yet. Don't saddle new code with 2.x-isms if you can avoid it. A: See also this related (though not identical) thread on Python 3.0. While I think the case for 3.x is more compelling than it was a year ago, it still doesn't have the breadth of third-party library coverage of 2.x. I would suggest developing for 2.6 and making use of the migration utilities when the time finally comes (e.g. some dependency is forcing you) to move to 3.x. A: If you are just learning Python (and you don't have a specific project you need to complete), I'd suggest that you start with the newest version (3.x). Even if you start with 2.x, though, the basics will be the same, so you will be able to learn any differences in 3.x very quickly. A: Go with 2.x I ran into a lot of compatibility issues with libraries and Python 3.x, although I can't recall which ones specifically. The specific issue I was seeing had to do with unicode strings, which I understand is the default in Python 3. The library threw an exception when using unicode strings, and returned an error for normal ASCII strings. This was about 6 months ago, and I'm assuming the support hasn't drastically improved since then. If you're absolutely sure you won't use any external libraries, 3.x might not bite you. As a compromise, you could use 2.x and try to avoid the changes in 3.x to make it compatible.
Which Python should I use?
Possible Duplicates: Is it advisable to go with Python 3.1 for a beginner? What version of Python should I use if I’m a new to Python? Haven't really made anything in Python... Which Python should I take ahold of? 2.X or 3.X?
[ "2.X still offers a far wider variety of third-party libraries / frameworks, instructional websites and books, and experts to help you out -- I expect this will continue for a few years until 3.X gradually overtakes it. Right now, therefore, I would still recommend 2.X despite 3.x's even-greater \"clean-ness\" and simplicity (because some cruft which 2.x has to keen around for backwards compatibility was finally wiped out in 3.x). Very few new features of 3.x are not backported in 2.x, by the way -- e..g, if you want print to be a function, like in 3.x, in your 2.6 or 2.7 module, just put, at the start of the module, the statement\nfrom __future__ import print_function\n\n\"Importing from the future\" is a typical Python way to make new features available when explicitly requested, without breaking backwards compatibility.\n", "You are in luck! Due to a lot of confusion about this people have put together a wiki page in the last few days: Should I use Python 2 or 3?\n", "2.x\nQuite some modules have not yet been ported to python 3 and you will find much more books, online resources for learning python 2.x\nYou also can't rely on python 3 being preinstalled, while for most linux distributions you can rely on some version of python 2 being available. The only one I know of that already has python 3 packages is the latest Fedora 13. If that matters to you depends on your needs. \n", "I'd say it depends where you are going to run the code. If you have complete control over the environment, use 3.x. If your environment is controlled externally (cheap webhosting for example) then you will probably need to use 2.x. The only other reason to stick with 2.x is if a critical library you can't live without hasn't been ported to 3.x yet. Don't saddle new code with 2.x-isms if you can avoid it.\n", "See also this related (though not identical) thread on Python 3.0.\nWhile I think the case for 3.x is more compelling than it was a year ago, it still doesn't have the breadth of third-party library coverage of 2.x. I would suggest developing for 2.6 and making use of the migration utilities when the time finally comes (e.g. some dependency is forcing you) to move to 3.x.\n", "If you are just learning Python (and you don't have a specific project you need to complete), I'd suggest that you start with the newest version (3.x). Even if you start with 2.x, though, the basics will be the same, so you will be able to learn any differences in 3.x very quickly.\n", "Go with 2.x\nI ran into a lot of compatibility issues with libraries and Python 3.x, although I can't recall which ones specifically. The specific issue I was seeing had to do with unicode strings, which I understand is the default in Python 3. The library threw an exception when using unicode strings, and returned an error for normal ASCII strings. This was about 6 months ago, and I'm assuming the support hasn't drastically improved since then.\nIf you're absolutely sure you won't use any external libraries, 3.x might not bite you. As a compromise, you could use 2.x and try to avoid the changes in 3.x to make it compatible.\n" ]
[ 7, 2, 1, 1, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003121693_python.txt
Q: How do I count the number of occurrences of a list of items in another .txt file? I have a list of words and I want to find how many times they occur in a .txt file. The word list is something like as follows: wordlist = ['cup', 'bike', 'run'] I want to be able to not only pick up these words, but also things like CUP, biker, running, Cups, etc. So I think I need a regular expression. Here is what I was thinking but it doesn't work: len(re.findall(wordlist, filename, re.I)) Thanks in advance! A: You're close. But re.findall takes a pattern and a string, not a wordlist and a filename. But, if you read your file into a string and turn your wordlist into a pattern, then you'll get it. The pattern you need will look like this: r"cup|bike|run". You could do "|".join(wordlist) to get this. That's a very loose way of counting all these instances. Note that if your file has the words "My truncheon has been scuppered" in it, then re.findall will find "run" and "cup" inside the bigger words. So you may want to tweak your pattern to catch the beginnings and ends of words. To get whole words only, use this pattern: r"\b(cup|bike|run)\b". Of course, you'll need to fill in all the word varieties that you are looking for. A: The regex needs work, but this should get you started: from __future__ import with_statement # only if < 2.6 from collections import defaultdict import re matches = defaultdict(int) with open(filename) as f: for mtch in re.findall(r'\b(cup|bike|run)', f.read(), re.I): matches[mtch.lower()] += 1 A: You will have first to guess all forms of the words and that seems a PITA. But here is a simplified fn i wrote after reading http://www.theenglishspace.com/spelling/ : def getWordForms(word): ''' Given an English word, return list of possible forms ''' l = [word] if len(word)>1: l.extend([word + 's', word + 'ing', word + 'ed']) wor, d = word[:-1], word[-1:] if d == 'e': l.append(word + 'd') l.append(wor + 'ing') if wor[-1:] == 'f': l.append(wor[:-1] + 'ves') elif d == 'y': l.append(wor + 'ied') l.append(wor + 'ies') elif d == 'z': l.append(word + 'zes') # double Z elif d == 'f': l.append(wor + 'ves') elif d in 'shox': l.append(word + 'es') if re.match('[^aeiou][aeiou][^aeiou]', word): l.append(word + d + 'ing') # double consonant l.append(word + d + 'ed') return l It is overly generous in the variants of words it guesses - but that is ok because this is not a spell checker and you will be using \b for word boundaries on both sides.
How do I count the number of occurrences of a list of items in another .txt file?
I have a list of words and I want to find how many times they occur in a .txt file. The word list is something like as follows: wordlist = ['cup', 'bike', 'run'] I want to be able to not only pick up these words, but also things like CUP, biker, running, Cups, etc. So I think I need a regular expression. Here is what I was thinking but it doesn't work: len(re.findall(wordlist, filename, re.I)) Thanks in advance!
[ "You're close. But re.findall takes a pattern and a string, not a wordlist and a filename. \nBut, if you read your file into a string and turn your wordlist into a pattern, then you'll get it.\nThe pattern you need will look like this: r\"cup|bike|run\". You could do \"|\".join(wordlist) to get this.\nThat's a very loose way of counting all these instances. Note that if your file has the words \"My truncheon has been scuppered\" in it, then re.findall will find \"run\" and \"cup\" inside the bigger words. So you may want to tweak your pattern to catch the beginnings and ends of words.\nTo get whole words only, use this pattern: r\"\\b(cup|bike|run)\\b\". Of course, you'll need to fill in all the word varieties that you are looking for.\n", "The regex needs work, but this should get you started:\nfrom __future__ import with_statement # only if < 2.6\nfrom collections import defaultdict\nimport re\n\nmatches = defaultdict(int)\nwith open(filename) as f:\n for mtch in re.findall(r'\\b(cup|bike|run)', f.read(), re.I):\n matches[mtch.lower()] += 1\n\n", "You will have first to guess all forms of the words and that seems a PITA. But here is a simplified fn i wrote after reading http://www.theenglishspace.com/spelling/ :\ndef getWordForms(word):\n ''' Given an English word, return list of possible forms\n '''\n l = [word]\n if len(word)>1:\n l.extend([word + 's', word + 'ing', word + 'ed'])\n wor, d = word[:-1], word[-1:]\n if d == 'e':\n l.append(word + 'd')\n l.append(wor + 'ing')\n if wor[-1:] == 'f':\n l.append(wor[:-1] + 'ves')\n elif d == 'y':\n l.append(wor + 'ied')\n l.append(wor + 'ies')\n elif d == 'z':\n l.append(word + 'zes') # double Z\n elif d == 'f':\n l.append(wor + 'ves')\n elif d in 'shox':\n l.append(word + 'es')\n if re.match('[^aeiou][aeiou][^aeiou]', word):\n l.append(word + d + 'ing') # double consonant\n l.append(word + d + 'ed')\n return l\n\nIt is overly generous in the variants of words it guesses - but that is ok because this is not a spell checker and you will be using \\b for word boundaries on both sides.\n" ]
[ 2, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003120388_python.txt
Q: Byte precision of value in Python? I have a hash function in Python. It returns a value. How do I see the byte-size of this return value? I want to know if it is 4-bytes or 8 or what. Reason: I want to make sure that the min value is 0 and the max value is 2**32, otherwise my calculations are incorrect. I want to make sure that packing it to a I struct (unsigned int) is correct. More specifically, I am calling murmur.string_hash(`x`). I want to know sanity-check that I am getting a 4-byte unsigned return value. If I have a value of a different size, them my calculations get messed up. So I want to sanity check it. A: If it's an arbitrary function that returns a number, there are only 4 standard types of numbers in Python: small integers (C long, at least 32 bits), long integers ("unlimited" precision), floats (C double), and complex numbers. If you are referring to the builtin hash, it returns a standard integer (C long): >>> hash(2**31) -2147483648 If you want different hashes, check out hashlib. A: Generally, thinking of a return value as a particular byte precision in Python is not the best way to go, especially with integers. For most intents and purposes, Python "short" integers are seamlessly integrated with "long" (unlimited) integers. Variables are promoted from the smaller to the larger type as necessary to hold the required value. Functions are not required to return any particular type (the same function could return different data types depending on the input, for example). When a function is provided by a third-party package (as this one is), you can either just trust the documentation (which for Murmur indicates 4-byte ints as far as I can tell) or test the return value yourself before using it (whether by if, assert, or try, depending on your preference).
Byte precision of value in Python?
I have a hash function in Python. It returns a value. How do I see the byte-size of this return value? I want to know if it is 4-bytes or 8 or what. Reason: I want to make sure that the min value is 0 and the max value is 2**32, otherwise my calculations are incorrect. I want to make sure that packing it to a I struct (unsigned int) is correct. More specifically, I am calling murmur.string_hash(`x`). I want to know sanity-check that I am getting a 4-byte unsigned return value. If I have a value of a different size, them my calculations get messed up. So I want to sanity check it.
[ "If it's an arbitrary function that returns a number, there are only 4 standard types of numbers in Python: small integers (C long, at least 32 bits), long integers (\"unlimited\" precision), floats (C double), and complex numbers.\nIf you are referring to the builtin hash, it returns a standard integer (C long):\n >>> hash(2**31)\n -2147483648\n\nIf you want different hashes, check out hashlib.\n", "Generally, thinking of a return value as a particular byte precision in Python is not the best way to go, especially with integers. For most intents and purposes, Python \"short\" integers are seamlessly integrated with \"long\" (unlimited) integers. Variables are promoted from the smaller to the larger type as necessary to hold the required value. Functions are not required to return any particular type (the same function could return different data types depending on the input, for example).\nWhen a function is provided by a third-party package (as this one is), you can either just trust the documentation (which for Murmur indicates 4-byte ints as far as I can tell) or test the return value yourself before using it (whether by if, assert, or try, depending on your preference).\n" ]
[ 1, 1 ]
[]
[]
[ "byte", "precision", "python" ]
stackoverflow_0003120868_byte_precision_python.txt
Q: Python Performance - have you ever had to rewrite in something else? Has anyone ever had code in Python, that turned out not to perform fast enough? I mean, you were forced to choose another language because of it? We are investigating using Python for a couple of larger projects, and my feeling is that in most cases, Python is plenty fast enough for most scenarios (compared to say, Java) because it relies on optimized C routines. I wanted to see if people had instances where they started out in Python, but ended up having to go with something else because of performance. Thanks. A: Yes, I have. I wrote a row-count program for a binary (length-prefixed rather than delimited) bcp output file once and ended up having to redo it in C because the python one was too slow. This program was quite small (it only took a couple of days to re-write it in C), so I didn't bother to try and build a hybrid application (python glue with central routines written in C) but this would also have been a viable route. A larger application with performance critical bits can be written in a combination of C and a higher level language. You can write the performance-critical parts in C with an interface to Python for the rest of the system. SWIG, Pyrex or Boost.Python (if you're using C++) all provide good mechanisms to do the plumbing for your Python interface. The C API for python is more complex than that for Tcl or Lua, but isn't infeasible to build by hand. For an example of a hand-built Python/C API, check out cx_Oracle. This approach has been used on quite a number of successful applications going back as far as the 1970s (that I am aware of). Mozilla was substantially written in Javascript around a core engine written in C. Several CAD packages, Interleaf (a technical document publishing system) and of course EMACS are substantially written in LISP with a central C, assembly language or other core. Quite a few commercial and open-source applications (e.g. Chandler or Sungard Front Arena) use embedded Python interpreters and implement substantial parts of the application in Python. EDIT: In rsponse to Dutch Masters' comment, keeping someone with C or C++ programming skills on the team for a Python project gives you the option of writing some of the application for speed. The areas where you can expect to get a significant performance gain are where the application does something highly iterative over a large data structure or large volume of data. In the case of the row-counter above it had to inhale a series of files totalling several gigabytes and go through a process where it read a varying length prefix and used that to determine the length of the data field. Most of the fields were short (just a few bytes long). This was somewhat bit-twiddly and very low level and iterative, which made it a natural fit for C. Many of the python libraries such as numpy, cElementTree or cStringIO make use of an optimised C or FORTRAN core with a python API that facilitates working with data in aggregate. For example, numpy has matrix data structures and operations written in C which do all the hard work and a Python API that provides services at the aggregate level. A: This is a much more difficult question to answer than people are willing to admit. For example, it may be that I am able to write a program that performs better in Python than it does in C. The fallacious conclusion from that statement is "Python is therefore faster than C". In reality, it may be because I have much more recent experience in Python and its best practices and standard libraries. In fact no one can really answer your question unless they are certain that they can create an optimal solution in both languages, which is unlikely. In other words "My C solution was faster than my Python solution" is not the same as "C is faster than Python" I'm willing to bet that Guido Van Rossum could have written Python solutions for adam and Dustin's problems that performed quite well. My rule of thumb is that unless you are writing the sort of application that requires you to count clock cycles, you can probably achieve acceptable performance in Python. A: Adding my $0.02 for the record. My work involves developing numeric models that run over 100's of gigabytes of data. The hard problems are in coming up with a revenue-generating solution quickly (i.e. time-to-market). To be commercially successful the solution also has to execute quickly (compute the solution in minimal amounts of time). For us Python has proven to be an excellent choice to develop solutions for the reasons commonly cited: fast development time, language expressiveness, rich libraries, etc. But to meet the execution speed needs we've adopted the 'Hybrid' approach that several responses have already mentioned. Using numpy for computationally intense parts. We get within 1.1x to 2.5x the speed of a 'native' C++ solution with numpy with less code, fewer bugs, and shorter development times. Pickling (Python's object serialization) intermediate results to minimize re-computation. The nature of our system requires multiple steps over the same data, so we 'memorize' the results and re-use them where possible. Profiling and choosing better algorithms. It's been said in other responses, but I'll repeat it: we whip-out cProfile and try to replace hot-spots with a better algorithm. Not applicable in all cases. Going to C++. If the above fails then we call a C++ library. We use PyBindGen to write our Python/C++ wrappers. We found it far superior to SWIG, SIP, and Boost.Python as it produces direct Python C API code without an intermediate layer. Reading this list you might think "What a lot of re-work! I'll just do it in [C/C++/Java/assembler] the first time around and be done with it." Let me put it into perspective. Using Python we were able to produce a working revenue-generating application in 5 weeks that, in other languages, had previously required 3 months for projects of similar scope. This includes the time needed to optimize the Python parts we found to be slow. A: While at uni we were writing a computer vision system for analysing human behaviour based on video clips. We used python because of the excellent PIL, to speed up development and let us get easy access to the image frames we'd extracted from the video for converting to arrays etc. For 90% of what we wanted it was fine and since the images were reasonably low resolution the speed wasn't bad. However, a few of the processes required some complex pixel-by-pixel computations as well as convolutions which are notoriously slow. For these particular areas we re-wrote the innermost parts of the loops in C and just updated the old Python functions to call the C functions. This gave us the best of both worlds. We had the ease of data access that python provides, which enabled to develop fast, and then the straight-line speed of C for the most intensive computations. A: Not so far. I work for a company that has a molecular simulation engine and a bunch of programs written in python for processing the large multi-gigabyte datasets. All of our analysis software is now being written in Python because of the huge advantages in development flexibility and time. If something is not fast enough we profile it with cProfile and find the bottlenecks. Usually there are one or two functions which take up 80 or 90% of the runtime. We then take those functions and rewrite them in C, something which Python makes dead easy with its C API. In many cases this results in an order of magnitude or more speedup. Problem gone. We then go on our merry way continuing to write everything else in Python. Rinse and repeat... For entire modules or classes we tend to use Boost.python, it can be a bit of a bear but ultimately works well. If it's just a function or two, we sometimes inline it with scipy.weave if the project is already using scipy. A: Whenever I find a Python bottleneck, I rewrite that code in C as a Python module. For example, I have some hardware that sends image pixels as 4-byte 0RGB. Converting 8M from 0RGB to RGB in Python takes too long so I rewrote it as a Python module. Writing Python (or other higher level languages) is much faster than writing in C so I use Python until I can't. A: This kind of question is likely to start a religious war among language people so let me answer it a little bit differently. For most cases in today's computing environments your choice of programming language should be based on what you can program efficiently, program well and what makes you happy not the performance characteristics of the language. Also, optimization should generally be the last concern when programming any system. The typical python way to do things is to start out writing your program in python and then if you notice the performance suffering profile the application and attempt to optimize the hot-spots in python first. If optimizing the python code still isn't good enough the areas of the code that are weighing you down should be re-written as a python module in C. If even after all of that your program isn't fast enough you can either change languages or look at scaling up in hardware or concurrency. That's the long answer, to answer your question directly; no, python (sometimes with C extensions) has been fast enough for everything I need it to do. The only time I really dip into C is to get access to stuff that donesn't have python bindings. Edit: My background is a python programmer at a large .com where we use python for everything from the front-end of our websites all the way down to all the back-office systems. Python is very much an enterprise-grade language. A: While implementing a specialized memcache server for a certain datatype, storage backend would be more memory efficient and lookup time could be decreased by bit wise lookup operations (i.e: O(1) lookups). I wrote all the protocol implementation and event driven daemon part with Python within 2 days, giving us enough time to test on functionality and focusing on performance while team was validating protocol conformance and other bits. Given the the tools like Pyrex, implementing C extensions for Python is next to trivial for any developer a bit experienced in C. I rewrote the Radix Tree based storage backend in C and made it a Python module with Pyrex within a day. Memory usage for 475K prefixes went down from 90MB to 8MB. We got a 1200% jump in the query performance. Today, this application is running with pyevent (Python interface for libevent) and the new storage backend handles 8000 queries per second on a modest single core server, running as a single process daemon (thanks to libevent) consuming less than 40MB of memory (including the Python interpreter) while handling 300+ simultaneous connections. That's a project designed and implemented to production quality in less than 5 days. Without Python and Pyrex, it would take longer. We could have troubleshoot the performance problem by just using more powerful servers and switch to a multiprocess/multi-instance model while complicating the code and administration tasks, accompanied with much larger memory footprint. I think you're on the right track to go with Python. A: I used to prototype lots of things in python for doing things like log processing. When they didn't run fast enough, I'd rewrite them in ocaml. In many cases, the python was fine and I was happy with it. In some cases, as it started approaching 23 hours to do a days' logs, I'd get to rewriting. :) I would like to point out that even in those cases, I may have been better off just profiling the python code and finding a happier python implementation. A: You can always write parts of your application in Python. Not every component is equally important for performance. Python integrates easily with C++ natively, or with Java via Jython, or with .NET via IronPython. By the way, IronPython is more efficient than the C implementation of Python on some benchmarks. A: I've been working for a while now, developing an application that operate on large structured data, stored in several-gigabytes-thick-database and well, Python is good enough for that. The application has GUI client with a multitude of controls (lists, trees, notebooks, virtual lists and more), and a console server. We had some performance issues, but those were mostly related more to poor algorithm design or database engine limitations (we use Oracle, MS-SQL, MySQL and had short romance with BerkeleyDB used for speed optimizations) than to Python itself. Once you know how to use standard libraries (written in C) properly you can make your code really quick. As others say - any computation intensive algorithm, code that depends on bit-stuffing, some memory constrained computation - can be done in raw C/C++ for CPU/memory saving (or any other tricks), but the whole user interaction, logging, database handling, error handling - all that makes the application actually run, can be written in Python and it will maintain responsiveness and decent overall performance. A: I am developing in python for several years now. Recently i had to list all files in a directory and build a struct with filename, size, attributes and modification date. I did this with os.listdir and os.stat. The code was quite fast, but the more entries in the directories, the slower my code became comapred to other filemanagers listing the same directory, so i rewrote the code using SWIG/C++ and was really surprised how much faster the code was. A: Yes, twice: An audio DSP application I wound up completely rewriting in C++ because I couldn't get appropriate performance in Python; I don't consider the Python implementation wasted because it let me prototype the concept very easily, and the C++ port went smoothly because I had a working reference implementaton. A procedural graphic rendering project, where generating large 2D texture maps in Python was taking a long time; I wrote a C++ DLL and used ctypes/windll to use it from Python. A: No, I've never had to rewrite. In fact, I started using Python in Maya 8.5. Before Maya 8, the only scripting language available was the built in MEL (Maya Expression Language). Python is actually faster than the built in language that it wraps. Python's ability to work with complex data types also made it faster because MEL can only store single dimensional arrays (and no pointers). This would require multi-dimensional arrays be faked by either using multiple parallel arrays, or by using slow string concatenation. A: A month ago i had this little program written in Python (for work) that analyzes logs. When then number of log files grew, the program begun to be very slow and i thought i could rewrite it in Java. I was very interesting. It took a whole day to migrate the same algorithm from Python to Java. At the end of the day, a few benchmark trials showed me clearly that the Java program was some 20% / 25% slower than its Python counterpart. It was a surprise to me. Writing for the second time the algorithm also showed me that some optimization was possible. So in two hours i completely rewrote the whole thing in Python and it was some 40% faster than the original Python implementation (hence orders of time faster than the Java version I had). So: Python is a slow language but still it can be faster, for certain tasks, that other supposedly faster languages If you have to spend time writing something in a language whose execution is faster but whose development time is slower (most languages), consider using the same time to analyze the problem, search for libraries, profile and then write better Python code. A: I once had to write a pseudo-random number generator for a simulator. I wrote it in Python first, but Python proved to be way too slow; I ended up rewriting it in C, and even that was slow, but not nearly as slow as Python. Luckily, it's fairly easy to bridge Python and C, so I was able to write the PRNG as a C module and still write the rest of the simulator in Python. A: The following link provides an on going comparison between a number of computer languages. It should give you an idea of some of Python's strengths and weaknesses across different problem domains. Computer Language Benchmarks Game A: I'm in the process of rewriting the Perl program OpenKore in Python under the name Erok (reverse of the original Kore). So far, Python is proving to be an overall better language, especially because of its powerful string parsing functions that don't require the use of regular expressions, which really speeds up a lot of its file parsing. A: I generally don't rewrite to C before I : profile rewrite with bette algorithms (generally this is enough) rewrite python code with low level performance in mind (but never to the point of having non pythonic / non readable code) spend some time rechecking a library cannot do this (first in stdlib, or an external lib) tried psyco / other implementations (rarely achieves to get a REAL speed boost in my case) Then sometimes I created a shared library to do heavy matrix computation code (which couldn't be done with numarray) and called it with ctypes : simple to write/build/test a .so / dll in pure C, simple to encapsulate the C to python function (ie. you don't if you use basic datatypes since ctypes does all the work of calling the right arguments for you) and certainly fast enough then .
Python Performance - have you ever had to rewrite in something else?
Has anyone ever had code in Python, that turned out not to perform fast enough? I mean, you were forced to choose another language because of it? We are investigating using Python for a couple of larger projects, and my feeling is that in most cases, Python is plenty fast enough for most scenarios (compared to say, Java) because it relies on optimized C routines. I wanted to see if people had instances where they started out in Python, but ended up having to go with something else because of performance. Thanks.
[ "Yes, I have. I wrote a row-count program for a binary (length-prefixed rather than delimited) bcp output file once and ended up having to redo it in C because the python one was too slow. This program was quite small (it only took a couple of days to re-write it in C), so I didn't bother to try and build a hybrid application (python glue with central routines written in C) but this would also have been a viable route.\nA larger application with performance critical bits can be written in a combination of C and a higher level language. You can write the performance-critical parts in C with an interface to Python for the rest of the system. SWIG, Pyrex or Boost.Python (if you're using C++) all provide good mechanisms to do the plumbing for your Python interface. The C API for python is more complex than that for Tcl or Lua, but isn't infeasible to build by hand. For an example of a hand-built Python/C API, check out cx_Oracle.\nThis approach has been used on quite a number of successful applications going back as far as the 1970s (that I am aware of). Mozilla was substantially written in Javascript around a core engine written in C. Several CAD packages, Interleaf (a technical document publishing system) and of course EMACS are substantially written in LISP with a central C, assembly language or other core. Quite a few commercial and open-source applications (e.g. Chandler or Sungard Front Arena) use embedded Python interpreters and implement substantial parts of the application in Python.\nEDIT: In rsponse to Dutch Masters' comment, keeping someone with C or C++ programming skills on the team for a Python project gives you the option of writing some of the application for speed. The areas where you can expect to get a significant performance gain are where the application does something highly iterative over a large data structure or large volume of data. In the case of the row-counter above it had to inhale a series of files totalling several gigabytes and go through a process where it read a varying length prefix and used that to determine the length of the data field. Most of the fields were short (just a few bytes long). This was somewhat bit-twiddly and very low level and iterative, which made it a natural fit for C.\nMany of the python libraries such as numpy, cElementTree or cStringIO make use of an optimised C or FORTRAN core with a python API that facilitates working with data in aggregate. For example, numpy has matrix data structures and operations written in C which do all the hard work and a Python API that provides services at the aggregate level.\n", "This is a much more difficult question to answer than people are willing to admit. \nFor example, it may be that I am able to write a program that performs better in Python than it does in C. The fallacious conclusion from that statement is \"Python is therefore faster than C\". In reality, it may be because I have much more recent experience in Python and its best practices and standard libraries. \nIn fact no one can really answer your question unless they are certain that they can create an optimal solution in both languages, which is unlikely. In other words \"My C solution was faster than my Python solution\" is not the same as \"C is faster than Python\"\nI'm willing to bet that Guido Van Rossum could have written Python solutions for adam and Dustin's problems that performed quite well.\nMy rule of thumb is that unless you are writing the sort of application that requires you to count clock cycles, you can probably achieve acceptable performance in Python.\n", "Adding my $0.02 for the record.\nMy work involves developing numeric models that run over 100's of gigabytes of data. The hard problems are in coming up with a revenue-generating solution quickly (i.e. time-to-market). To be commercially successful the solution also has to execute quickly (compute the solution in minimal amounts of time).\nFor us Python has proven to be an excellent choice to develop solutions for the reasons commonly cited: fast development time, language expressiveness, rich libraries, etc. But to meet the execution speed needs we've adopted the 'Hybrid' approach that several responses have already mentioned. \n\nUsing numpy for computationally intense parts. We get within 1.1x to 2.5x the speed of a 'native' C++ solution with numpy with less code, fewer bugs, and shorter development times.\nPickling (Python's object serialization) intermediate results to minimize re-computation. The nature of our system requires multiple steps over the same data, so we 'memorize' the results and re-use them where possible.\nProfiling and choosing better algorithms. It's been said in other responses, but I'll repeat it: we whip-out cProfile and try to replace hot-spots with a better algorithm. Not applicable in all cases.\nGoing to C++. If the above fails then we call a C++ library. We use PyBindGen to write our Python/C++ wrappers. We found it far superior to SWIG, SIP, and Boost.Python as it produces direct Python C API code without an intermediate layer. \n\nReading this list you might think \"What a lot of re-work! I'll just do it in [C/C++/Java/assembler] the first time around and be done with it.\" \nLet me put it into perspective. Using Python we were able to produce a working revenue-generating application in 5 weeks that, in other languages, had previously required 3 months for projects of similar scope. This includes the time needed to optimize the Python parts we found to be slow.\n", "While at uni we were writing a computer vision system for analysing human behaviour based on video clips. We used python because of the excellent PIL, to speed up development and let us get easy access to the image frames we'd extracted from the video for converting to arrays etc.\nFor 90% of what we wanted it was fine and since the images were reasonably low resolution the speed wasn't bad. However, a few of the processes required some complex pixel-by-pixel computations as well as convolutions which are notoriously slow. For these particular areas we re-wrote the innermost parts of the loops in C and just updated the old Python functions to call the C functions.\nThis gave us the best of both worlds. We had the ease of data access that python provides, which enabled to develop fast, and then the straight-line speed of C for the most intensive computations.\n", "Not so far. I work for a company that has a molecular simulation engine and a bunch of programs written in python for processing the large multi-gigabyte datasets. All of our analysis software is now being written in Python because of the huge advantages in development flexibility and time. \nIf something is not fast enough we profile it with cProfile and find the bottlenecks. Usually there are one or two functions which take up 80 or 90% of the runtime. We then take those functions and rewrite them in C, something which Python makes dead easy with its C API. In many cases this results in an order of magnitude or more speedup. Problem gone. We then go on our merry way continuing to write everything else in Python. Rinse and repeat...\nFor entire modules or classes we tend to use Boost.python, it can be a bit of a bear but ultimately works well. If it's just a function or two, we sometimes inline it with scipy.weave if the project is already using scipy.\n", "Whenever I find a Python bottleneck, I rewrite that code in C as a Python module.\nFor example, I have some hardware that sends image pixels as 4-byte 0RGB. Converting 8M from 0RGB to RGB in Python takes too long so I rewrote it as a Python module.\nWriting Python (or other higher level languages) is much faster than writing in C so I use Python until I can't.\n", "This kind of question is likely to start a religious war among language people so let me answer it a little bit differently.\nFor most cases in today's computing environments your choice of programming language should be based on what you can program efficiently, program well and what makes you happy not the performance characteristics of the language. Also, optimization should generally be the last concern when programming any system. \nThe typical python way to do things is to start out writing your program in python and then if you notice the performance suffering profile the application and attempt to optimize the hot-spots in python first. If optimizing the python code still isn't good enough the areas of the code that are weighing you down should be re-written as a python module in C. If even after all of that your program isn't fast enough you can either change languages or look at scaling up in hardware or concurrency.\nThat's the long answer, to answer your question directly; no, python (sometimes with C extensions) has been fast enough for everything I need it to do. The only time I really dip into C is to get access to stuff that donesn't have python bindings.\nEdit: My background is a python programmer at a large .com where we use python for everything from the front-end of our websites all the way down to all the back-office systems. Python is very much an enterprise-grade language.\n", "While implementing a specialized memcache server for a certain datatype, storage backend would be more memory efficient and lookup time could be decreased by bit wise lookup operations (i.e: O(1) lookups).\nI wrote all the protocol implementation and event driven daemon part with Python within 2 days, giving us enough time to test on functionality and focusing on performance while team was validating protocol conformance and other bits. \nGiven the the tools like Pyrex, implementing C extensions for Python is next to trivial for any developer a bit experienced in C. I rewrote the Radix Tree based storage backend in C and made it a Python module with Pyrex within a day. Memory usage for 475K prefixes went down from 90MB to 8MB. We got a 1200% jump in the query performance.\nToday, this application is running with pyevent (Python interface for libevent) and the new storage backend handles 8000 queries per second on a modest single core server, running as a single process daemon (thanks to libevent) consuming less than 40MB of memory (including the Python interpreter) while handling 300+ simultaneous connections.\nThat's a project designed and implemented to production quality in less than 5 days. Without Python and Pyrex, it would take longer.\nWe could have troubleshoot the performance problem by just using more powerful servers and switch to a multiprocess/multi-instance model while complicating the code and administration tasks, accompanied with much larger memory footprint. \nI think you're on the right track to go with Python.\n", "I used to prototype lots of things in python for doing things like log processing. When they didn't run fast enough, I'd rewrite them in ocaml.\nIn many cases, the python was fine and I was happy with it. In some cases, as it started approaching 23 hours to do a days' logs, I'd get to rewriting. :)\nI would like to point out that even in those cases, I may have been better off just profiling the python code and finding a happier python implementation.\n", "You can always write parts of your application in Python. Not every component is equally important for performance. Python integrates easily with C++ natively, or with Java via Jython, or with .NET via IronPython.\nBy the way, IronPython is more efficient than the C implementation of Python on some benchmarks. \n", "I've been working for a while now, developing an application that operate on large structured data, stored in several-gigabytes-thick-database and well, Python is good enough for that. The application has GUI client with a multitude of controls (lists, trees, notebooks, virtual lists and more), and a console server. \nWe had some performance issues, but those were mostly related more to poor algorithm design or database engine limitations (we use Oracle, MS-SQL, MySQL and had short romance with BerkeleyDB used for speed optimizations) than to Python itself. Once you know how to use standard libraries (written in C) properly you can make your code really quick. \nAs others say - any computation intensive algorithm, code that depends on bit-stuffing, some memory constrained computation - can be done in raw C/C++ for CPU/memory saving (or any other tricks), but the whole user interaction, logging, database handling, error handling - all that makes the application actually run, can be written in Python and it will maintain responsiveness and decent overall performance.\n", "I am developing in python for several years now. Recently i had to list all files in a directory and build a struct with filename, size, attributes and modification date. I did this with os.listdir and os.stat. The code was quite fast, but the more entries in the directories, the slower my code became comapred to other filemanagers listing the same directory, so i rewrote the code using SWIG/C++ and was really surprised how much faster the code was. \n", "Yes, twice:\n\nAn audio DSP application I wound up completely rewriting in C++ because I couldn't get appropriate performance in Python; I don't consider the Python implementation wasted because it let me prototype the concept very easily, and the C++ port went smoothly because I had a working reference implementaton.\nA procedural graphic rendering project, where generating large 2D texture maps in Python was taking a long time; I wrote a C++ DLL and used ctypes/windll to use it from Python.\n\n", "No, I've never had to rewrite. In fact, I started using Python in Maya 8.5. Before Maya 8, the only scripting language available was the built in MEL (Maya Expression Language). Python is actually faster than the built in language that it wraps.\nPython's ability to work with complex data types also made it faster because MEL can only store single dimensional arrays (and no pointers). This would require multi-dimensional arrays be faked by either using multiple parallel arrays, or by using slow string concatenation.\n", "A month ago i had this little program written in Python (for work) that analyzes logs.\nWhen then number of log files grew, the program begun to be very slow and i thought i could rewrite it in Java.\nI was very interesting. It took a whole day to migrate the same algorithm from Python to Java. At the end of the day, a few benchmark trials showed me clearly that the Java program was some 20% / 25% slower than its Python counterpart. It was a surprise to me.\nWriting for the second time the algorithm also showed me that some optimization was possible. So in two hours i completely rewrote the whole thing in Python and it was some 40% faster than the original Python implementation (hence orders of time faster than the Java version I had).\nSo:\n\nPython is a slow language but still it can be faster, for certain tasks, that other supposedly faster languages\nIf you have to spend time writing something in a language whose execution is faster but whose development time is slower (most languages), consider using the same time to analyze the problem, search for libraries, profile and then write better Python code.\n\n", "I once had to write a pseudo-random number generator for a simulator. I wrote it in Python first, but Python proved to be way too slow; I ended up rewriting it in C, and even that was slow, but not nearly as slow as Python.\nLuckily, it's fairly easy to bridge Python and C, so I was able to write the PRNG as a C module and still write the rest of the simulator in Python.\n", "The following link provides an on going comparison between a number of computer languages. It should give you an idea of some of Python's strengths and weaknesses across different problem domains.\nComputer Language Benchmarks Game \n", "I'm in the process of rewriting the Perl program OpenKore in Python under the name Erok (reverse of the original Kore). So far, Python is proving to be an overall better language, especially because of its powerful string parsing functions that don't require the use of regular expressions, which really speeds up a lot of its file parsing.\n", "I generally don't rewrite to C before I :\n\nprofile\nrewrite with bette algorithms (generally this is enough)\nrewrite python code with low level performance in mind (but never to the point of having non pythonic / non readable code)\nspend some time rechecking a library cannot do this (first in stdlib, or an external lib)\ntried psyco / other implementations (rarely achieves to get a REAL speed boost in my case)\n\nThen sometimes I created a shared library to do heavy matrix computation code (which couldn't be done with numarray) and called it with ctypes : \n\nsimple to write/build/test a .so / dll in pure C, \nsimple to encapsulate the C to python function (ie. you don't if you use basic datatypes since ctypes does all the work of calling the right arguments for you) and certainly fast enough then .\n\n" ]
[ 34, 19, 16, 7, 7, 5, 4, 4, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 0 ]
[]
[]
[ "optimization", "performance", "python", "rewrite" ]
stackoverflow_0000386655_optimization_performance_python_rewrite.txt
Q: How to define column headers when reading a csv file in Python I have a comma separated value table that I want to read in Python. What I need to do is first tell Python not to skip the first row because that contains the headers. Then I need to tell it to read in the data as a list and not a string because I need to build an array out of the data and the first column is non-integer (row headers). There are a total of 11 columns and 5 rows. Here is the format of the table (except there are no row spaces): col1,col2,col3,col4,col5,col6,col7,col8,col9,col10,col11 w0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 w1 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 w2 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 w3 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 Is there a way to do this? Any help is greatly appreciated! A: You can use the csv module for this sort of thing. It will read in each row as a list of strings representing the different fields. How exactly you'd want to use it depends on how you're going to process the data afterwards, but you might consider making a Reader object (from the csv.reader() function), calling next() on it once to get the first row, i.e. the headers, and then iterating over the remaining lines in a for loop. r = csv.reader(...) headers = r.next() for fields in r: # do stuff If you're going to wind up putting the fields into a dict, you'd use DictReader instead (and that class will automatically take the field names from the first row, so you can just construct it an use it in a loop).
How to define column headers when reading a csv file in Python
I have a comma separated value table that I want to read in Python. What I need to do is first tell Python not to skip the first row because that contains the headers. Then I need to tell it to read in the data as a list and not a string because I need to build an array out of the data and the first column is non-integer (row headers). There are a total of 11 columns and 5 rows. Here is the format of the table (except there are no row spaces): col1,col2,col3,col4,col5,col6,col7,col8,col9,col10,col11 w0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 w1 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 w2 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 w3 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 Is there a way to do this? Any help is greatly appreciated!
[ "You can use the csv module for this sort of thing. It will read in each row as a list of strings representing the different fields.\nHow exactly you'd want to use it depends on how you're going to process the data afterwards, but you might consider making a Reader object (from the csv.reader() function), calling next() on it once to get the first row, i.e. the headers, and then iterating over the remaining lines in a for loop.\nr = csv.reader(...)\nheaders = r.next()\nfor fields in r:\n # do stuff\n\nIf you're going to wind up putting the fields into a dict, you'd use DictReader instead (and that class will automatically take the field names from the first row, so you can just construct it an use it in a loop).\n" ]
[ 27 ]
[]
[]
[ "csv", "python" ]
stackoverflow_0003122206_csv_python.txt
Q: How can I fix this multithreaded Python script? I'm writing a python script to read through a list of domains, find out what rating Mcafee's Siteadvisor service gives, then output the domain and result to a CSV. I've based my script off this previous answer. It uses the urllib to scrape Siteadvisor's page for the domain in question (not the best method, I know, but Siteadvisor provides no alternative). Unfortunately, it fails to produce anything - I consistently get this error: Traceback (most recent call last): File "multi.py", line 55, in <module> main() File "multi.py", line 44, in main resolver_thread.start() File "/usr/lib/python2.6/threading.py", line 474, in start _start_new_thread(self.__bootstrap, ()) thread.error: can't start new thread Here is my script: import threading import urllib class Resolver(threading.Thread): def __init__(self, address, result_dict): threading.Thread.__init__(self) self.address = address self.result_dict = result_dict def run(self): try: content = urllib.urlopen("http://www.siteadvisor.com/sites/" + self.address).read(12000) search1 = content.find("didn't find any significant problems.") search2 = content.find('yellow') search3 = content.find('web reputation analysis found potential security') search4 = content.find("don't have the results yet.") if search1 != -1: result = "safe" elif search2 != -1: result = "caution" elif search3 != -1: result = "warning" elif search4 != -1: result = "unknown" else: result = "" self.result_dict[self.address] = result except: pass def main(): infile = open("domainslist", "r") intext = infile.readlines() threads = [] results = {} for address in [address.strip() for address in intext if address.strip()]: resolver_thread = Resolver(address, results) threads.append(resolver_thread) resolver_thread.start() for thread in threads: thread.join() outfile = open('final.csv', 'w') outfile.write("\n".join("%s,%s" % (address, ip) for address, ip in results.iteritems())) outfile.close() if __name__ == '__main__': main() Any help would be greatly appreciated. A: It looks like you are trying to start too many threads. You can check how many items are in [address.strip() for address in intext if address.strip()] list. I quess this is a problem here. Basically there is a limit of available resources that allows to start new threads. The solution for this is to chunk your list to pieces of let's say 20 elements, do the stuff (in 20 threads), wait for threads to finish their jobs, and then pick up next chunk. Do this until all elements from your list are processed. You can also use some thread pool for better threads management. (I recently used this implementation). A: There's probably an upper limit to the number of threads you can create, and you're probably exceeding it. Suggestion: Create a small, fixed number of Resolvers - under 10 will probably get you 90% of the possible parallelism benefit possible - and a (threadsafe) Queue from python's queue lib. Have the main thread dump all the domains into the queue, and have each Resolver take one domain at a time from the queue and work on it.
How can I fix this multithreaded Python script?
I'm writing a python script to read through a list of domains, find out what rating Mcafee's Siteadvisor service gives, then output the domain and result to a CSV. I've based my script off this previous answer. It uses the urllib to scrape Siteadvisor's page for the domain in question (not the best method, I know, but Siteadvisor provides no alternative). Unfortunately, it fails to produce anything - I consistently get this error: Traceback (most recent call last): File "multi.py", line 55, in <module> main() File "multi.py", line 44, in main resolver_thread.start() File "/usr/lib/python2.6/threading.py", line 474, in start _start_new_thread(self.__bootstrap, ()) thread.error: can't start new thread Here is my script: import threading import urllib class Resolver(threading.Thread): def __init__(self, address, result_dict): threading.Thread.__init__(self) self.address = address self.result_dict = result_dict def run(self): try: content = urllib.urlopen("http://www.siteadvisor.com/sites/" + self.address).read(12000) search1 = content.find("didn't find any significant problems.") search2 = content.find('yellow') search3 = content.find('web reputation analysis found potential security') search4 = content.find("don't have the results yet.") if search1 != -1: result = "safe" elif search2 != -1: result = "caution" elif search3 != -1: result = "warning" elif search4 != -1: result = "unknown" else: result = "" self.result_dict[self.address] = result except: pass def main(): infile = open("domainslist", "r") intext = infile.readlines() threads = [] results = {} for address in [address.strip() for address in intext if address.strip()]: resolver_thread = Resolver(address, results) threads.append(resolver_thread) resolver_thread.start() for thread in threads: thread.join() outfile = open('final.csv', 'w') outfile.write("\n".join("%s,%s" % (address, ip) for address, ip in results.iteritems())) outfile.close() if __name__ == '__main__': main() Any help would be greatly appreciated.
[ "It looks like you are trying to start too many threads.\nYou can check how many items are in [address.strip() for address in intext if address.strip()] list. I quess this is a problem here. Basically there is a limit of available resources that allows to start new threads.\nThe solution for this is to chunk your list to pieces of let's say 20 elements, do the stuff (in 20 threads), wait for threads to finish their jobs, and then pick up next chunk. Do this until all elements from your list are processed.\nYou can also use some thread pool for better threads management. (I recently used this implementation).\n", "There's probably an upper limit to the number of threads you can create, and you're probably exceeding it. \nSuggestion: Create a small, fixed number of Resolvers - under 10 will probably get you 90% of the possible parallelism benefit possible - and a (threadsafe) Queue from python's queue lib. Have the main thread dump all the domains into the queue, and have each Resolver take one domain at a time from the queue and work on it.\n" ]
[ 1, 1 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0003122209_multithreading_python.txt
Q: how to init binary buffer in python so, I read from DB binary field i.e. 'field1' to var Buf1, and then do something like: unpack_from('I', Buf1, 0) so, all is ok. but question is how can I ini Buf1 without going to DB? I can get value from DB manually and init my var statically, but how? in DB field 'field1' I see something like '0x7B0500000100000064000000B80100006'. and how can I init valid binary buffer from it? A: Just use pack or pack_into it's the python's opposite of unpack_from. See also that answer. But you should elaborate on your question and give more sample code. The value you say you see from field is too large to read it into an integer. I wonder if you get the complete value.
how to init binary buffer in python
so, I read from DB binary field i.e. 'field1' to var Buf1, and then do something like: unpack_from('I', Buf1, 0) so, all is ok. but question is how can I ini Buf1 without going to DB? I can get value from DB manually and init my var statically, but how? in DB field 'field1' I see something like '0x7B0500000100000064000000B80100006'. and how can I init valid binary buffer from it?
[ "Just use pack or pack_into it's the python's opposite of unpack_from.\nSee also that answer.\nBut you should elaborate on your question and give more sample code. The value you say you see from field is too large to read it into an integer. I wonder if you get the complete value.\n" ]
[ 0 ]
[]
[]
[ "binary", "buffer", "init", "python" ]
stackoverflow_0002907012_binary_buffer_init_python.txt
Q: GUI layout -how? I've been working with a few RAD gui builders lately. I absolutely despise CSS ( camel is a horse designed by committee etc.) What algorithms are used by packing managers(java/tk). Most GUI toolkits I've used have some alternative to absolute positioning, sorry for the ambiguity but how do you start thinking about implementing a packing manger in language X. Thanks for the replies, to clarify - I want to create a generic text file that defines a 'form' this form file can then be used to generated a native(ish) GUI form (eg tk) and also an HTML form. What I'm looking for is some pointers on how a grid based packing manager is implemented so I can formulate my generic text file based on some form of established logic. If this doesn't make sense to you then you understand me:). Some notes 1. XML lives in the same stable as the zebra and the camel but not the horse. 2. Think lightweight markup languages (Markdown/ReStructuredText) but for simple forms. 3. This has probably already been implemented, do you know where? 4. Yes, I have Googled it (many,many times),answer was not between G1 and o2 Thks A: Tk has three methods. One is absolute positioning, the other two are called "grid" and "pack". grid is just what it sounds like: you lay out your widgets in a grid. There are options for spanning rows and columns, expanding (or not) to fill a cell, designating rows or columns which can grow, etc. You can accomplish probably 90% of all layout issues with the grid geometry manager. The other manager is "pack" and it works by requesting that widgets be placed on one side or another (top, bottom, left, right). It is remarkably powerful, and with the use of nested containers (called frames in tk) you can accomplish pretty much any layout as well. Pack is particularly handy when you have things stacked in a single direction, such as horizontally for a toolbar, vertically for a main app (toolbar, main area, statusbar). Both grid and pack are remarkably powerful and simple to use, and between them can solve any layout problem you have. It makes me wonder why Java and wxPython have so many and such complicated geometry managers when its possible to get by with no more than three.
GUI layout -how?
I've been working with a few RAD gui builders lately. I absolutely despise CSS ( camel is a horse designed by committee etc.) What algorithms are used by packing managers(java/tk). Most GUI toolkits I've used have some alternative to absolute positioning, sorry for the ambiguity but how do you start thinking about implementing a packing manger in language X. Thanks for the replies, to clarify - I want to create a generic text file that defines a 'form' this form file can then be used to generated a native(ish) GUI form (eg tk) and also an HTML form. What I'm looking for is some pointers on how a grid based packing manager is implemented so I can formulate my generic text file based on some form of established logic. If this doesn't make sense to you then you understand me:). Some notes 1. XML lives in the same stable as the zebra and the camel but not the horse. 2. Think lightweight markup languages (Markdown/ReStructuredText) but for simple forms. 3. This has probably already been implemented, do you know where? 4. Yes, I have Googled it (many,many times),answer was not between G1 and o2 Thks
[ "Tk has three methods. One is absolute positioning, the other two are called \"grid\" and \"pack\". \ngrid is just what it sounds like: you lay out your widgets in a grid. There are options for spanning rows and columns, expanding (or not) to fill a cell, designating rows or columns which can grow, etc. You can accomplish probably 90% of all layout issues with the grid geometry manager.\nThe other manager is \"pack\" and it works by requesting that widgets be placed on one side or another (top, bottom, left, right). It is remarkably powerful, and with the use of nested containers (called frames in tk) you can accomplish pretty much any layout as well. Pack is particularly handy when you have things stacked in a single direction, such as horizontally for a toolbar, vertically for a main app (toolbar, main area, statusbar). \nBoth grid and pack are remarkably powerful and simple to use, and between them can solve any layout problem you have. It makes me wonder why Java and wxPython have so many and such complicated geometry managers when its possible to get by with no more than three. \n" ]
[ 3 ]
[]
[]
[ "grid", "python", "rad", "tcl" ]
stackoverflow_0003122291_grid_python_rad_tcl.txt
Q: Python Unicode ajax form posting error i got a n00b problem with python and i've been searching here for a while and i couldnt find a proper solution... i got a utf8 form that i ajax post to a python page. i read the json simplejson with utf-8 charset. the text is fine as long as there is no mixed utf8 and latin chars like ?!;, etc... UnicodeDecodeError: 'ascii' codec can't decode byte 0xd7 in position 0: ordinal not in range(128) commentjsonarray = simplejson.loads(commentjson, encoding='utf-8') i tried a bunch of things but i cant get it to work. help. just an update for you with more code for help, thanks commentjson = request.POST['commentObj'] commentjsonarray = simplejson.loads(commentjson, encoding='utf-8') program = get_object(Program, commentjsonarray['programid']) userget = get_object(User, commentjsonarray['userid']) #get user avatar from usermeta usermeta = get_object(UserMeta, 'user_id = ',userget.key()) commenttext = commentjsonarray['walltext'] from django.utils.encoding import smart_unicode,force_unicode,smart_str commenttext = smart_str(commenttext) newcomment = db_create(Wall, user_avatarurl=str(usermeta.avatarurlsmall),user_fullname=str(''+userget.first_name+' '+userget.last_name),user_idstring=str(userget.key()),text = str(commenttext) , program_id = program.key() , user_id = userget.key()) above is the python part. here is the javascript: var walltext = $('walltext').value var commentObj = {"walltext": ""+walltext+"", "programid": programid, "userid": userid}; var commentJSON = encodeURIComponent(Object.toJSON(commentObj)); if (walltext != '' || walltext == 'type here' || walltext.length > 0) { new Ajax.Request('/wall/new', { method: 'post', encoding: 'UTF-8', parameters: 'commentObj=' + commentJSON, onSuccess: function(request){ var msg = request.responseText.evalJSON(); if (msg) { var structure = '<div id="' + msg.msgid + '"><img src="' + msg.avatarurl + '" width="18" height="18"> ' + msg.username + ':' + msg.text + '<div id="frontSepLine"></div></div>'; //$('programwall').insert({bottom:structure}); refreshWall(msg.programid); $('walltext').value = 'type here'; var objDiv = document.getElementById("programwall"); objDiv.scrollTop = objDiv.scrollHeight; } } }); A: The situation you've described works fine for me (with the standard library json on Python 2.6), either with or without the explicit encoding (which is not needed for a utf-8 encoded bytestring, as utf-8 is the default here): >> s = u'{"valá":"macché?!"}'.encode('utf8') >>> json.loads(s) {u'val\xe1': u'macch\xe9?!'} >>> json.loads(s, encoding='utf-8') {u'val\xe1': u'macch\xe9?!'} and also with simplejson 2.1.1 (really redundant on 2.6, but, oh well;-): >>> import simplejson >>> s = u'{"valá":"macché?!"}'.encode('utf8') >>> simplejson.loads(s) {u'val\xe1': u'macch\xe9?!'} >>> simplejson.loads(s, encoding='utf-8') {u'val\xe1': u'macch\xe9?!'} Can you describe your problem more accurately? Your description of what triggers your error, i.e. the reverse of "as long as there is no mixed utf8 and latin chars like ?!;, etc", doesn't cause any problem -- so what about showing us the tiniest example that does reproduce your problem?
Python Unicode ajax form posting error
i got a n00b problem with python and i've been searching here for a while and i couldnt find a proper solution... i got a utf8 form that i ajax post to a python page. i read the json simplejson with utf-8 charset. the text is fine as long as there is no mixed utf8 and latin chars like ?!;, etc... UnicodeDecodeError: 'ascii' codec can't decode byte 0xd7 in position 0: ordinal not in range(128) commentjsonarray = simplejson.loads(commentjson, encoding='utf-8') i tried a bunch of things but i cant get it to work. help. just an update for you with more code for help, thanks commentjson = request.POST['commentObj'] commentjsonarray = simplejson.loads(commentjson, encoding='utf-8') program = get_object(Program, commentjsonarray['programid']) userget = get_object(User, commentjsonarray['userid']) #get user avatar from usermeta usermeta = get_object(UserMeta, 'user_id = ',userget.key()) commenttext = commentjsonarray['walltext'] from django.utils.encoding import smart_unicode,force_unicode,smart_str commenttext = smart_str(commenttext) newcomment = db_create(Wall, user_avatarurl=str(usermeta.avatarurlsmall),user_fullname=str(''+userget.first_name+' '+userget.last_name),user_idstring=str(userget.key()),text = str(commenttext) , program_id = program.key() , user_id = userget.key()) above is the python part. here is the javascript: var walltext = $('walltext').value var commentObj = {"walltext": ""+walltext+"", "programid": programid, "userid": userid}; var commentJSON = encodeURIComponent(Object.toJSON(commentObj)); if (walltext != '' || walltext == 'type here' || walltext.length > 0) { new Ajax.Request('/wall/new', { method: 'post', encoding: 'UTF-8', parameters: 'commentObj=' + commentJSON, onSuccess: function(request){ var msg = request.responseText.evalJSON(); if (msg) { var structure = '<div id="' + msg.msgid + '"><img src="' + msg.avatarurl + '" width="18" height="18"> ' + msg.username + ':' + msg.text + '<div id="frontSepLine"></div></div>'; //$('programwall').insert({bottom:structure}); refreshWall(msg.programid); $('walltext').value = 'type here'; var objDiv = document.getElementById("programwall"); objDiv.scrollTop = objDiv.scrollHeight; } } });
[ "The situation you've described works fine for me (with the standard library json on Python 2.6), either with or without the explicit encoding (which is not needed for a utf-8 encoded bytestring, as utf-8 is the default here):\n>> s = u'{\"valá\":\"macché?!\"}'.encode('utf8')\n>>> json.loads(s)\n{u'val\\xe1': u'macch\\xe9?!'}\n>>> json.loads(s, encoding='utf-8')\n{u'val\\xe1': u'macch\\xe9?!'}\n\nand also with simplejson 2.1.1 (really redundant on 2.6, but, oh well;-):\n>>> import simplejson\n>>> s = u'{\"valá\":\"macché?!\"}'.encode('utf8')\n>>> simplejson.loads(s)\n{u'val\\xe1': u'macch\\xe9?!'}\n>>> simplejson.loads(s, encoding='utf-8')\n{u'val\\xe1': u'macch\\xe9?!'}\n\nCan you describe your problem more accurately? Your description of what triggers your error, i.e. the reverse of \"as long as there is no mixed utf8 and latin chars like ?!;, etc\", doesn't cause any problem -- so what about showing us the tiniest example that does reproduce your problem?\n" ]
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003122404_django_python.txt
Q: python implementation of patricia tries Looking around for python implementations of tries just so that I can understand what they are and how they work, I came across Justin Peel's patricia trie and found it very instructive: it's straightforward enough for one as new as I am to play around with it and learn from it. However there's something I think I'm not understanding: using Justin's class patricia() thus: >>> p = patricia() >>> words = ['foo','bar','baz'] >>> for x in words: ... p.addWord(x) I get a trie as a dictionary looking like this: >>> p._d {'b': ['a', {'r': ['', {}], 'z': ['', {}]}], 'f': ['oo', {}]} addWord() and isWord() work as expected, but isPrefix() shows the following behavior which puzzles me: >>> p.isPrefix('b') True >>> p.isPrefix('f') True >>> p.isPrefix('e') False good, as expected; and then >>> p.isPrefix('ba') True also good, but then: >>> p.isPrefix('bal') True and furthermore: >>> p.isPrefix('ballance') True >>> p.isPrefix('ballancing act') True Something here I'm not understanding? A: I believe the bug is in the following snippet of the code you're looking at: if w.startswith(node[0][:wlen-i],i): if wlen - i > len(node[0]): i += len(node[0]) d = node[1] return True it should actually be: if w.startswith(node[0][:wlen-i],i): if wlen - i > len(node[0]): i += len(node[0]) d = node[1] else: return True
python implementation of patricia tries
Looking around for python implementations of tries just so that I can understand what they are and how they work, I came across Justin Peel's patricia trie and found it very instructive: it's straightforward enough for one as new as I am to play around with it and learn from it. However there's something I think I'm not understanding: using Justin's class patricia() thus: >>> p = patricia() >>> words = ['foo','bar','baz'] >>> for x in words: ... p.addWord(x) I get a trie as a dictionary looking like this: >>> p._d {'b': ['a', {'r': ['', {}], 'z': ['', {}]}], 'f': ['oo', {}]} addWord() and isWord() work as expected, but isPrefix() shows the following behavior which puzzles me: >>> p.isPrefix('b') True >>> p.isPrefix('f') True >>> p.isPrefix('e') False good, as expected; and then >>> p.isPrefix('ba') True also good, but then: >>> p.isPrefix('bal') True and furthermore: >>> p.isPrefix('ballance') True >>> p.isPrefix('ballancing act') True Something here I'm not understanding?
[ "I believe the bug is in the following snippet of the code you're looking at:\n if w.startswith(node[0][:wlen-i],i):\n if wlen - i > len(node[0]):\n i += len(node[0])\n d = node[1]\n return True\n\nit should actually be:\n if w.startswith(node[0][:wlen-i],i):\n if wlen - i > len(node[0]):\n i += len(node[0])\n d = node[1]\n else:\n return True\n\n" ]
[ 4 ]
[]
[]
[ "patricia_trie", "python" ]
stackoverflow_0003121916_patricia_trie_python.txt
Q: Using urllib2 with Jython 2.2 I'm working with a product that has a built-in Jython 2.2 instance. It comes with none of the Python standard libraries. When I run this instance of Jython, the default path is ['./run/Jython/Lib', './run/Jython', '__classpath__'] I added all of the .py module files from Python 2.2 to the ./run/Jython/Lib directory, and I am able to import them. But I want to use urllib2 and I get this error: Traceback (innermost last): File "<string>", line 2, in ? File "./run/Jython/Lib/urllib2.py", line 90, in ? File "./run/Jython/Lib/socket.py", line 41, in ? ImportError: no module named _socket As far as I can tell, the _socket module is part of the Python lib-dynload libraries (_socket.so). Can Jython use this file? I tried putting it in my path, but it had no effect. A Google search seems to tell me that others are able to use urllib and urllib2 with Jython 2.2, but I'm stuck I have tried module libraries from older and newer versions of Python as well. Thanks! A: Andy, I got a clean Jython 2.2.1 install and ran the following script successfully. $ ./jython Jython 2.2.1 on java1.6.0_17 Type "copyright", "credits" or "license" for more information. >>> import urllib2 >>> f = urllib2.urlopen('http://www.python.org/') >>> print f.read(100) <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtm >>> I went back and checked the Meandre infrastructure code base. I have found that a minor modification was introduced into the path of the embedded Jython. However, that is not the main problem. The main issue is that I just realized that the Jython's system modules are missing on the Meandre distribution bundles. You could fix it by manually copying the contents on the <JYTHON_HOME>/lib to <MEANDRE_HOME>/run/Jython/Lib and restart the server instance. Now the default modules should be available to the components of the infrastructure. Just let me know if that gets you going and I will work on getting that fixed soon.
Using urllib2 with Jython 2.2
I'm working with a product that has a built-in Jython 2.2 instance. It comes with none of the Python standard libraries. When I run this instance of Jython, the default path is ['./run/Jython/Lib', './run/Jython', '__classpath__'] I added all of the .py module files from Python 2.2 to the ./run/Jython/Lib directory, and I am able to import them. But I want to use urllib2 and I get this error: Traceback (innermost last): File "<string>", line 2, in ? File "./run/Jython/Lib/urllib2.py", line 90, in ? File "./run/Jython/Lib/socket.py", line 41, in ? ImportError: no module named _socket As far as I can tell, the _socket module is part of the Python lib-dynload libraries (_socket.so). Can Jython use this file? I tried putting it in my path, but it had no effect. A Google search seems to tell me that others are able to use urllib and urllib2 with Jython 2.2, but I'm stuck I have tried module libraries from older and newer versions of Python as well. Thanks!
[ "Andy,\nI got a clean Jython 2.2.1 install and ran the following script successfully.\n$ ./jython\nJython 2.2.1 on java1.6.0_17\nType \"copyright\", \"credits\" or \"license\" for more information.\n>>> import urllib2\n>>> f = urllib2.urlopen('http://www.python.org/')\n>>> print f.read(100)\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtm\n>>>\n\nI went back and checked the Meandre infrastructure code base. I have found that a minor modification was introduced into the path of the embedded Jython. However, that is not the main problem. The main issue is that I just realized that the Jython's system modules are missing on the Meandre distribution bundles. \nYou could fix it by manually copying the contents on the \n<JYTHON_HOME>/lib\n\nto \n<MEANDRE_HOME>/run/Jython/Lib\n\nand restart the server instance. Now the default modules should be available to the components of the infrastructure. \nJust let me know if that gets you going and I will work on getting that fixed soon.\n" ]
[ 2 ]
[]
[]
[ "jython", "libraries", "python", "urllib2" ]
stackoverflow_0003121446_jython_libraries_python_urllib2.txt
Q: python modules appearing out of no where Today one peculiar thing happened to me .I was trying to get a hang of appengine and Django on www.shell.appspot.com when i entered dir(django) the o/p i got was ['VERSION', '__builtins__', '__doc__', '__file__', '__name__', '__path__', 'conf', 'core', 'template', 'utils'] but still i tried from django import forms and it worked to my surprise , while there was no trances of this on the o/p of dir().so out of curiosity i again entered dir(django) and the o/p i got was ['VERSION', '__builtins__', '__doc__', '__file__', '__name__', '__path__', 'conf', 'core', 'forms', 'oldforms', 'template', 'utils'] note the forms element here .So can any one explain to me where this forms come from ? A: The statement from package import module loads (if it had not been previously loaded) package/module.py (after first loading package/__init__.py if it hadn't previously loaded it already) and adds 'module' as an entry in the package (as well as a variable in the current scope). So dir(package) will show a 'module' entry after the import, but not before. A package can contain unbounded numbers of modules and subpackages (recursively) so it would be very slow to load everything in the package (just to fill out its dir!-) until specific modules and subpackages are specifically imported -- so, the loading of the latter is "just in time", when they're imported for the first time (and only then do they show up in the paren package's dir).
python modules appearing out of no where
Today one peculiar thing happened to me .I was trying to get a hang of appengine and Django on www.shell.appspot.com when i entered dir(django) the o/p i got was ['VERSION', '__builtins__', '__doc__', '__file__', '__name__', '__path__', 'conf', 'core', 'template', 'utils'] but still i tried from django import forms and it worked to my surprise , while there was no trances of this on the o/p of dir().so out of curiosity i again entered dir(django) and the o/p i got was ['VERSION', '__builtins__', '__doc__', '__file__', '__name__', '__path__', 'conf', 'core', 'forms', 'oldforms', 'template', 'utils'] note the forms element here .So can any one explain to me where this forms come from ?
[ "The statement from package import module loads (if it had not been previously loaded) package/module.py (after first loading package/__init__.py if it hadn't previously loaded it already) and adds 'module' as an entry in the package (as well as a variable in the current scope). So dir(package) will show a 'module' entry after the import, but not before.\nA package can contain unbounded numbers of modules and subpackages (recursively) so it would be very slow to load everything in the package (just to fill out its dir!-) until specific modules and subpackages are specifically imported -- so, the loading of the latter is \"just in time\", when they're imported for the first time (and only then do they show up in the paren package's dir).\n" ]
[ 8 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0003122638_google_app_engine_python.txt
Q: Python how to read and split a line to several integers For input file separate by space/tab like: 1 2 3 4 5 6 7 8 9 How to read the line and split the integers, then save into either lists or tuples? Thanks. data = [[1,2,3], [4,5,6], [7,8,9]] data = [(1,2,3), (4,5,6), (7,8,9)] A: One way to do this, assuming the sublists are on separate lines: with open("filename.txt", 'r') as f: data = [map(int, line.split()) for line in f] Note that the with statement didn't become official until Python 2.6. If you are using an earlier version, you'll need to do from __future__ import with_statement A: If you find yourself dealing with matrices or tables of numbers, may I suggest numpy package? import numpy as np data = np.loadtxt(input_filename) A: tuples = [tuple(int(s) for s in line.split()) for line in open("file.txt").readlines()] I like Jeff's map(int, line.split()), instead of the inner generator. A: You mean, like this? update Just convert each string into int string = """1 2 3 4 5 6 7 8 9""" data = [] for line in string.split("\n"): #split by new line data.append( map( int, line.split(" ") ) ) # split by spaces and add print( data ) Output: [['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']] [[1, 2, 3], [4, 5, 6], [7, 8, 9]] Da daaaa!!! A: def getInts(ln): return [int(word) for word in ln.split()] f = open('myfile.dat') dat = [getInts(ln) for ln in f]
Python how to read and split a line to several integers
For input file separate by space/tab like: 1 2 3 4 5 6 7 8 9 How to read the line and split the integers, then save into either lists or tuples? Thanks. data = [[1,2,3], [4,5,6], [7,8,9]] data = [(1,2,3), (4,5,6), (7,8,9)]
[ "One way to do this, assuming the sublists are on separate lines:\nwith open(\"filename.txt\", 'r') as f:\n data = [map(int, line.split()) for line in f]\n\nNote that the with statement didn't become official until Python 2.6. If you are using an earlier version, you'll need to do\nfrom __future__ import with_statement\n\n", "If you find yourself dealing with matrices or tables of numbers, may I suggest numpy package?\nimport numpy as np\ndata = np.loadtxt(input_filename)\n\n", "tuples = [tuple(int(s) for s in line.split()) for line in open(\"file.txt\").readlines()]\nI like Jeff's map(int, line.split()), instead of the inner generator.\n", "\nYou mean, like this?\n\nupdate\nJust convert each string into int\nstring = \"\"\"1 2 3\n4 5 6\n7 8 9\"\"\"\n\ndata = []\nfor line in string.split(\"\\n\"): #split by new line\n data.append( map( int, line.split(\" \") ) ) # split by spaces and add \n\nprint( data )\n\nOutput: \n[['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']]\n[[1, 2, 3], [4, 5, 6], [7, 8, 9]]\n\nDa daaaa!!!\n", "def getInts(ln):\n return [int(word) for word in ln.split()]\n\nf = open('myfile.dat')\ndat = [getInts(ln) for ln in f]\n\n" ]
[ 11, 3, 2, 1, 1 ]
[]
[]
[ "file_io", "python" ]
stackoverflow_0003122121_file_io_python.txt