From lysdexia at crackrabbit.com Fri Oct 1 01:32:05 2004 From: lysdexia at crackrabbit.com (Douglas N. Shawhan) Date: Fri Oct 1 01:32:56 2004 Subject: [Tutor] Is there a prettier way to do this? Message-ID: <415C9775.7040306@crackrabbit.com> I am trying to sort through a list of items, find items that contain the same string fragments and report yea or nay The way I am doing it below (setting a value of 1 and multiplying it by 0 if any of the iterations come up negative) seems to be the easiest for my skull, but I have found over and over that there is usually a more pythonic way of doing things, no matter what I come up with! :-) -------------------------snip------------------------------- import string DB = {"hi":"one, two", "ho":"two, three", "he":"three, one"} search_str='three, one' search_list=string.split(search_str, ",") items = DB.keys() items.sort() search_group=[] for each in items: search_group.append(DB[each]) for each in search_group: count = 1 for item in search_list: if string.find(each, item) == -1: count = count * 0 else: count = count * 1 if count == 0: print 'not found' else: print each From kent_johnson at skillsoft.com Fri Oct 1 02:35:01 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Fri Oct 1 02:35:07 2004 Subject: [Tutor] Is there a prettier way to do this? In-Reply-To: <415C9775.7040306@crackrabbit.com> References: <415C9775.7040306@crackrabbit.com> Message-ID: <6.1.0.6.0.20040930203315.02a47ce0@mail4.skillsoft.com> Here's my take on it, with comments in-line. Kent # You don't need the string module, use the string methods instead DB = {"hi":"one, two", "ho":"two, three", "he":"three, one"} search_str='three, one' search_list=search_str.split(",") # search_list is now ['three', ' one'] # Note the space before 'one' - this may not be what you want. # You could split on ', ' if you always have the space, or use a regex split, or # omit the space in the original data... # Personally I like to get the key, value pairs if I am going to need both # Is there a reason why you are using a dict? for this snippet a list of pairs would # make more sense items = DB.items() items.sort() # A list comprehension makes this very concise search_group = [value for key, value in items] # In Python 2.4 you will be able to do this in one line: # search_group = [value for key, value in DB.items().sorted()] # Usually a loop with a break is a better way to code something like this for each in search_group: for item in search_list: if item not in each: # Since Python 2.3 you can do a find like this # At this point we know we're not going to find them all so we can stop print 'not found' break else: # This will only be run if the loop exits without a break print each At 06:32 PM 9/30/2004 -0500, Douglas N. Shawhan wrote: >I am trying to >sort through a list of items, >find items that contain the same string fragments and >report yea or nay > >The way I am doing it below (setting a value of 1 and multiplying it by 0 >if any of the iterations come up negative) seems to be the easiest for my >skull, but I have found over and over that there is usually a more >pythonic way of doing things, no matter what I come up with! :-) > >-------------------------snip------------------------------- >import string > >DB = {"hi":"one, two", "ho":"two, three", "he":"three, one"} > >search_str='three, one' >search_list=string.split(search_str, ",") > >items = DB.keys() >items.sort() >search_group=[] > >for each in items: > search_group.append(DB[each]) > >for each in search_group: > count = 1 > for item in search_list: > if string.find(each, item) == -1: > count = count * 0 > else: > count = count * 1 > if count == 0: > print 'not found' > else: > print each > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From lysdexia at crackrabbit.com Fri Oct 1 05:53:39 2004 From: lysdexia at crackrabbit.com (Douglas N. Shawhan) Date: Fri Oct 1 05:54:33 2004 Subject: [Tutor] Is there a prettier way to do this? In-Reply-To: <6.1.0.6.0.20040930203315.02a47ce0@mail4.skillsoft.com> References: <415C9775.7040306@crackrabbit.com> <6.1.0.6.0.20040930203315.02a47ce0@mail4.skillsoft.com> Message-ID: <415CD4C3.2050009@crackrabbit.com> Kent Johnson wrote: > > # You don't need the string module, use the string methods instead > > search_list=search_str.split(",") Yes! Very good. > > # search_list is now ['three', ' one'] > # Note the space before 'one' - this may not be what you want. > # You could split on ', ' if you always have the space, or use a regex > split, or > # omit the space in the original data... Good advice! > > # Personally I like to get the key, value pairs if I am going to need > both > # Is there a reason why you are using a dict? for this snippet a list > of pairs would > # make more sense > > items = DB.items() > items.sort() Yes, this makes more sense and removes a step. The problem is: I think I was unclear stating what the loop is supposed to do! I need to find *more than one* string fragment per string. Say I need to verify the existence of the sequences "joe", "bill" and "leon" in a string - but the next time I may need only find "joe" and "bill", which is why I went with the 0, 1 scheme. It may be better stated as: "How do I find arbitrary numbers of substrings in arbitrary order in a string pythonically?" From s4046441 at student.uq.edu.au Fri Oct 1 07:38:49 2004 From: s4046441 at student.uq.edu.au (Ms Soo Chong) Date: Fri Oct 1 07:38:57 2004 Subject: [Tutor] How can I code to get more than ONE value from checkbox? Message-ID: <6ac8f66b26df.6b26df6ac8f6@uq.edu.au> Hi, I'm trying to code a python script (with HTML) to get values from a html form that consists of about 10 checkbox and a textbox where user have to key in a value to perform a search. >From Lee Harr and Danny, I learned that I have to use the following method: ### qtype = data.getfirst('qtype') ---- checkbox name qtext = data.getfirst('qtext', '') ---- textbox name ### but I don't really know how to do it. Should I use qtype = data.getlist('qtype') to get the value from the checkbox and how to? Currently, my method required me to type in every possible combination of the checkbox and I know that this is wrong. I wanna to include %(qtype) in my query statement so that the script will look for the value that contain qtype everytime a form is processs but the way I'm doing now is wrong. query = "select %(qtype)s from shot_descriptions where shot_number=%(qtext)s", qtype, qtext Thus, can someone help me on this. Thank you for any help. Shufen -------------- next part -------------- #!/usr/bin/env python #Created on: 30/09/04 #Help from Lee Harr and Danny Yoo - Python Tutor import sys, os import cgi import cgitb; cgitb.enable() import pg def form(): print """

All
Project
Date
Blame
Notes

Search by shot number:
 

""" print "Content-Type: text/html\n\n" print "Searching by using Shot Number" if __name__ == "__main__": data = cgi.FieldStorage() if data: qtype = data.getfirst('qtype') qtext = data.getfirst('qtext','') for qtype in data.getlist('qtype'): print "You typed in Shot Number:", qtext #Now, we can get to the database... username = os.environ.get('USER') if username == None: username = 'apache' db = pg.connect("moncdata", user=username, passwd=None) query = "select %(qtype)s from shot_descriptions where shot_number=%(qtext)s", qtype, qtext qresult = db.query(query) listOfResults = qresult.dictresult() print """

Example of pulling the list of dictionary results apart.

""" for record in listOfResults: print "

" for k in record.keys(): print '' print '' print '' print '' print '
key: ', k, 'value:', record[k], '

' db.close() else: print "You have no enter a shot number!" print "Please type a in shot number in order to perform a search!" else: form() print "" From kent_johnson at skillsoft.com Fri Oct 1 11:51:16 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Fri Oct 1 11:51:26 2004 Subject: [Tutor] Is there a prettier way to do this? In-Reply-To: <415CD4C3.2050009@crackrabbit.com> References: <415C9775.7040306@crackrabbit.com> <6.1.0.6.0.20040930203315.02a47ce0@mail4.skillsoft.com> <415CD4C3.2050009@crackrabbit.com> Message-ID: <6.1.0.6.0.20041001054703.02a473e8@mail4.skillsoft.com> I think my version does what you want. It will find target text that contains all of the search words. The final code is still two nested loops. The inner loop reports failure and breaks as soon as it finds a search word that is not in the target text. If the loop completes then every search word was found and it reports success. Kent At 10:53 PM 9/30/2004 -0500, Douglas N. Shawhan wrote: >The problem is: I think I was unclear stating what the loop is supposed to do! > >I need to find *more than one* string fragment per string. > >Say I need to verify the existence of the sequences "joe", "bill" and >"leon" in a string - but the next time I may need only find "joe" and >"bill", which is why I went with the 0, 1 scheme. > >It may be better stated as: "How do I find arbitrary numbers of substrings >in arbitrary order in a string pythonically?" From alipolatel at yahoo.com Fri Oct 1 13:16:22 2004 From: alipolatel at yahoo.com (Ali Polatel) Date: Fri Oct 1 13:16:26 2004 Subject: [Tutor] Regedit Message-ID: <20041001111622.10357.qmail@web61005.mail.yahoo.com> Hi Dear friends I want to ask a question today... I want to learn if a python programme can make a change in regedit so that it will be auto-run when the computer is turned on. (os.system('regedit') is not enough) Regards --------------------------------- Do you Yahoo!? vote.yahoo.com - Register online to vote today! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20041001/b810ad6c/attachment.html From maxnoel_fr at yahoo.fr Fri Oct 1 14:21:11 2004 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Fri Oct 1 14:21:18 2004 Subject: [Tutor] Regedit In-Reply-To: <20041001111622.10357.qmail@web61005.mail.yahoo.com> References: <20041001111622.10357.qmail@web61005.mail.yahoo.com> Message-ID: <615B927E-13A4-11D9-989F-000393CBC88E@yahoo.fr> On Oct 1, 2004, at 12:16, Ali Polatel wrote: > Hi Dear friends > I want to ask?a question today... > ?I want to learn if a python programme can make a change in regedit so > that it will be auto-run when the computer is turned on. > (os.system('regedit') is not enough) > Regards For this, you have two possibilities. The first is to write a .reg file that will make the necessary changes to the registry, then to run it (probably just a matter of os.system('foo.reg')). I do not recommend that, however, because you have to really know what you're doing (you might end up doing Very Bad changes in the registry), and I discourage the use of the registry anyway (it is IMO stupid, bloated, fragile and evil). The other way is to simply make a shortcut to the program you want to run, and place it in the Start Menu/Programs/Startup folder of the current user (or of All Users, if you're so inclined). -- Wild_Cat maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From alipolatel at yahoo.com Fri Oct 1 14:48:55 2004 From: alipolatel at yahoo.com (Ali Polatel) Date: Fri Oct 1 14:48:58 2004 Subject: [Tutor] Regedit In-Reply-To: <615B927E-13A4-11D9-989F-000393CBC88E@yahoo.fr> Message-ID: <20041001124855.72124.qmail@web61009.mail.yahoo.com> Thanks dear friend I want to ask you another question Can a programme make a copy of itself to the startup folder as it is running? --------------------------------- Do you Yahoo!? Yahoo! Mail Address AutoComplete - You start. We finish. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20041001/745d7c5c/attachment.html From my.mailing.lists at noos.fr Fri Oct 1 15:45:32 2004 From: my.mailing.lists at noos.fr (nik) Date: Fri Oct 1 15:45:53 2004 Subject: [Tutor] python by cgi In-Reply-To: <415C2697.2040009@noos.fr> References: <415C119D.2020405@noos.fr> <1096556485.2951.57.camel@laptop.venix.com> <415C2697.2040009@noos.fr> Message-ID: <415D5F7C.1000406@noos.fr> hi, Just in case someone in the far flung future was looking at this thread for the same problem, I've realised that I can make the cgi script use the python version of choice by making sure the first line of the script was pointing to the appropriate python version. So, I changed my script from #!/usr/local/bin/python to #!/usr/bin/python and that made it use the earlier version of python which had the kinterbasdb module. nik nik wrote: > ah, well spotted. One version was installed by the mandrake install > disks (the usr/lib one), the other I did myself since I thought > upgrading was a good idea before I realised that I wasn't sure of the > side effects of removing the old one. Now I've no idea of what on my > system uses which version... I might go for the quick fix right now > (why not put off something today that you can put off for quite a > while more until it bites you on the ass again, or something like that > :-) ) > > many thanks, > nik > > Lloyd Kvam wrote: > >> On Thu, 2004-09-30 at 10:01, nik wrote: >> >> >>> hi all, >>> >>> I'm trying to access my firebird database using python and cgi. I've >>> installed the latest apache web server (on linux), and using a >>> simple script like; >>> #!/usr/local/bin/python >>> >>> def main(): >>> print "Content-type: text/html" >>> print >>> print " Hello, World!" >>> >>> if (__name__ == "__main__"): >>> main() >>> >>> is working just fine. >>> >>> However, if I add an import kinterbasdb at the start, I get an >>> import error. >>> >>> Using the command line interpreter I don't have a problem though. >>> >>> I'm a bit confused by the sys.path a bit, it seems to vary depending >>> on how I start python; >>> >>> in command line iterpreter, it's; >>> '', '/usr/lib/python23.zip', '/usr/lib/python2.3', >>> '/usr/lib/python2.3/plat-linux2', '/usr/lib/python2.3/lib-tk', >>> '/usr/lib/python2.3/lib-dynload', >>> '/usr/lib/python2.3/site-packages', >>> '/usr/lib/python2.3/site-packages/Numeric', >>> '/usr/lib/python2.3/site-packages/gtk-2.0' >>> >> >> >> Here Python is installed in /usr/lib >> >> >> >>> by cgi it's; >>> '/usr/local/apache2/cgi-bin', '/usr/local/lib/python23.zip', >>> '/usr/local/lib/python2.3', '/usr/local/lib/python2.3/plat-linux2', >>> '/usr/local/lib/python2.3/lib-tk', >>> '/usr/local/lib/python2.3/lib-dynload', >>> '/usr/local/lib/python2.3/site-packages' >>> >>> >> >> >> Here Python is installed in /usr/local/lib >> >> You have two installed versions of Python. I would assume that >> kinterbasdb is in /usr/lib AND not in /usr/local/lib. >> >> Quick fix is to install kinterbasdb into the other python. Better is to >> get down to a single Python2.3 - presumably remove the /usr/local/lib >> version, but that depends on the nature of your linux setup. >> >> >> >> >>> however, the difference doesn't seem to imply why kinterbasdb can't >>> be imported. >>> >>> I tried doing >>> import sys >>> sys.path.append('/usr/lib/python2.3/site-packages/kinterbasdb') >>> >>> in the script, but it didn't help. >>> >>> >>> Any ideas? Is it a permissions thing perhaps? >>> >>> nik >>> _______________________________________________ >>> Tutor maillist - Tutor@python.org >>> http://mail.python.org/mailman/listinfo/tutor >>> >> > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From s4046441 at student.uq.edu.au Fri Oct 1 17:13:56 2004 From: s4046441 at student.uq.edu.au (Ms Soo Chong) Date: Fri Oct 1 17:14:10 2004 Subject: [Tutor] Re: How can I code to get more than One value from checkbox? Message-ID: <69ef0a69e629.69e62969ef0a@uq.edu.au> ----- Original Message ----- From: Steve Holden Date: Friday, October 1, 2004 10:20 pm Subject: Re: How can I code to get more than One value from checkbox? > > The following is my script: > ###############################################################################> #!/usr/bin/env python > > #Created on: 30/09/04 > > #Help from Lee Harr and Danny Yoo - Python Tutor > > > > import sys, os > > import cgi > > import cgitb; cgitb.enable() > > import pg > > > > def form(): > > print """
> >

> > checked /> > > All
> > > > Project
> > value="date_string" /> > > Date
> > > > Blame
> > > > Notes

> > ####### > OK, it's not really obvious what this form is supposed to do for > you. I > also don't understand whether it makes sense for "all" to be > checked at > the same time as individual selections. But we'll leave that for > now ... ###### > > >

Search by shot number:
> > > ###### > It might make more sense to call this input "shotno" rather than > "qtext", but that won;t affect how the code functions. ###### > > > > >
> >

""" > > ###### > Aah, so we're looking up photographs in a database? ###### > > > print "Content-Type: text/html\n\n" > > print "Searching by using Shot > > Number" > > > > if __name__ == "__main__": > > ###### > It's a bit too late for this if you've already written the headers > out, > I should say - it would make more sense to move those prints above > down > here so they don't get run if the script is imported. ###### > > > data = cgi.FieldStorage() > > > Great! > > > if data: > > qtype = data.getfirst('qtype') > ###### > Since the "for" statement below assigns to qtype, the statement > above is > completely redundant. ###### > > > qtext = data.getfirst('qtext','') > > > > for qtype in data.getlist('qtype'): > ##### > So if you check "project" and "blame", you should iterate round > this > loop twice, with qtype being set to "project" the first time and > "blame" > the second. ##### > > > print "You typed in Shot Number:", qtext > > > > #Will take care of the security problem later... > > username = os.environ.get('USER') > > if username == None: > > username = 'apache' > > > > #Now, we can get to the database... > > db = pg.connect("moncdata", user=username, passwd=None) > > ##### > It doesn't make sense to connect to the database each time round > the > loop (and I'm still not even convinced this loop is what you want...) ##### > > > #This is the part that I'm not sure of...please help... > > query = "select %(qtype)s from shot_descriptions where > > shot_number=%(qtext)s", qtype, qtext > > qresult = db.query(query) > > ##### > I take it pg is some kind of PostGres interface? And AAH!!, now I > see > that what the checkboxes are supposed to do is select fields for > the > output. You appear to be missing a "percent" sign up there - it > should > either be > > query = "SELECT %s ...=%s" % (qtype, qtext) > > or > > query = "SELECT %(qtype)s ... =%(qtext)s" % data > > to put the query type and the text into the string, depending on > which > substitution method you want to use. You should really be testing > a lot > of this stuff in an interactive copy of the interpreter (I hope > you do > have Python available other than just on your web server). > > Unfortunately the assignment to query isn;t a syntax error in > Python > (you are just assigning a three-element tuple to query) but poor > old > PostgreSQL isn;t going to know what to make of the result. > > Do you want to see a separate chunk of output for each field, or > do you > want to see the fields as columns of a table? The latter seems to > make > more sense to me, but it would have been REALLY nice if this > conversation has started out like "I have a bunch of shot > descriptions > is a database, and I want to be able to see just selected fields > about a > shot". > > For the structure you've got now it looks like you plan to loop > around > the column names, doing a query for each one, and printing out a > table > for each field. And we don't have any way to handle "all", by the > way > ... unless that's just another database column. ###### > > > listOfResults = qresult.dictresult() > > > > print """

Example of pulling the list of dictionary > > results apart.

""" > > for record in listOfResults: > > print "

" > > for k in record.keys(): > > print '' > > print '' > > print '' > > print '' > > print '
key: ', k, 'value:', record[k], '

' > > > > db.close() > > > > #Somehow, this part didn't work too, when I didn't input a > > value > > #it doesn't show this msg. Please help me on this part too. > > Thks. > ##### > The reason for that is that even when you don't enter anything > into the > form the submit button still gets put in there as a data item, so > the > form will never be truly empty. ##### > > > else: > > print "You have no enter a shot number!" > > print "Please type a in shot number in order to > perform a > > search!" > > > > else: > > form() > > > > > > print "" > > > > > ###############################################################################> > > Thank you in advance for any help. > > > > Shufen > > OK, before we go any further I'd like you to tell me exactly what > you;d > like this page to do. You probably aren't that far froma solution > now, > but it would be nice to answer the right question. > > I'm suspecting that what you really want is something like > > query = """SELECT %s FROM shot-descriptions WHERE > shot_number=%s""" % ( > data.getvalue("qtype"), data.getfirst("qtext")) > > Since I have to go off and earn pennies now, someone else may be > able to > help you in the interim. I'm likely to be off-net for a bit. Stick > with > it, you're almost there! > > regards > Steve A big big thank you to Steve. Thanks Steve, you have been a great help... rite! you have pointed out some of the stuffs that I myself have problems detecting them, thanks. I really hope that "I'm almost there!" since I have to complete this within this two weeks. I think you are right, sorry that I didn't explain my situation well enough. I will do that now. I have a bunch of stuffs in a database table named "shot_descriptions". And this is what I wanna my page to do: The columns of this table consists of project name, date, shot number, notes and etc. And these fields are the stuffs that I wanna to present them in checkboxes form so that the user can select the number of information they wanna to see in the results (output). And a textbox for user to key in a specific shot number in order to perform a search. So, if there is no input in the shot no textbox, an error msg will show (this is one of the part that is not working now, please help). I wanna to display the output in a table form and I'm currently using dictionary to help me with this task. But I'm wondering is there a better way to show it? I mean other than dictionary, how can I code it so that the results will display nicely in a html type of table with columns and rows instead of key: blah blah and value: blah blah. If someone can help me on this part, it will be very nice, cos I'm concern about the presentation of the output too. I will try out the suggestion given by steve and send out the revised copy of my code but at the mean time, it would be great if someone understand what am I trying to do here and send me more suggestions on the correct way of dealing with this type of situation. Thank you in advance. I'm really keen to learn more stuffs about python, esp ways to improve the code to make it more efficient and clean. I'm also anxious in seeing the outcomes of this web page so please help me up. Any help is very very very much appreciated. p/s: To Steve, Lee Harr and Danny Yoo, Thanks a million. I really appreciated the trouble you guys gone thru to read and analyse my code since I didn't seems to provide you with enough info (sorry for that). Cheers, Shufen From maxnoel_fr at yahoo.fr Fri Oct 1 17:37:51 2004 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Fri Oct 1 17:37:56 2004 Subject: [Tutor] Regedit In-Reply-To: <20041001124855.72124.qmail@web61009.mail.yahoo.com> References: <20041001124855.72124.qmail@web61009.mail.yahoo.com> Message-ID: On Oct 1, 2004, at 13:48, Ali Polatel wrote: > Thanks dear friend > I want to ask you another question > Can a programme make a copy of itself to the startup folder as it is > running? You can, using shutil.copy() from the shutil module, and some magic from Win32All to find the exact location of the current user's Start Menu folder. However, given your previous question, you probably want to create a shortcut to the program, instead of copying it. As I don't have access to a Windows machine at the moment, I can't tell you how, sorry. -- Wild_Cat maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From Mark.Kels at gmail.com Fri Oct 1 20:02:10 2004 From: Mark.Kels at gmail.com (Mark Kels) Date: Fri Oct 1 20:02:12 2004 Subject: [Tutor] Does Python have pointers? Message-ID: Hi all, I want to make an interpreter for BF (more info - http://home.wxs.nl/~faase009/Ha_BF.html) in Python. To do it I guess I need to use pointers, but I never heard about pointers in Python... Can Python work with pointers (or anything else that can be useful) ? If not, what do I need to do to write this project ? Thanks. From maxnoel_fr at yahoo.fr Fri Oct 1 20:16:43 2004 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Fri Oct 1 20:16:55 2004 Subject: [Tutor] Does Python have pointers? In-Reply-To: References: Message-ID: <0C5BE7F9-13D6-11D9-989F-000393CBC88E@yahoo.fr> On Oct 1, 2004, at 19:02, Mark Kels wrote: > Hi all, > > I want to make an interpreter for BF (more info - > http://home.wxs.nl/~faase009/Ha_BF.html) in Python. > To do it I guess I need to use pointers, but I never heard about > pointers in Python... > Can Python work with pointers (or anything else that can be useful) ? > If not, what do I need to do to write this project ? The way I understand it, in Python, all variable names are references. IOW, all variables are pointers. Now, if you need pointers to directly access memory addresses (something akin to PEEK and POKE in old-school BASIC), I don't think that's possible in Python (or in any other language on a reasonably modern OS AFAIK). -- Wild_Cat maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From tony at tcapp.com Fri Oct 1 21:16:03 2004 From: tony at tcapp.com (Tony Cappellini) Date: Fri Oct 1 21:13:12 2004 Subject: [Tutor] Generating HTML Message-ID: <20041001120959.X57394@yamato.yamato.com> It seems as though there is some support for reading and parsing HTML, in htmllib and HTMLParser, but are there any tools in the python distributions for generating html? That is, if I have a simple text file I want to view in html, is there a module in the standard python distribution that will do the formatting ? I don't care about fany colors, fonts or backgrounds, I just want to be able to view a file with a web browser. From maxnoel_fr at yahoo.fr Fri Oct 1 21:16:34 2004 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Fri Oct 1 21:16:39 2004 Subject: [Tutor] Generating HTML In-Reply-To: <20041001120959.X57394@yamato.yamato.com> References: <20041001120959.X57394@yamato.yamato.com> Message-ID: <68CD4B4D-13DE-11D9-989F-000393CBC88E@yahoo.fr> On Oct 1, 2004, at 20:16, Tony Cappellini wrote: > That is, if I have a simple text file I want to view in html, is there > a > module in the standard python distribution that will do the formatting > ? > > I don't care about fany colors, fonts or backgrounds, I just want to be > able to view a file with a web browser. Well, if you just want that, you don't need to do anything. Most web browsers are already capable of displaying TXT files. -- Wild_Cat maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From bill.mill at gmail.com Fri Oct 1 21:19:57 2004 From: bill.mill at gmail.com (Bill Mill) Date: Fri Oct 1 21:20:07 2004 Subject: [Tutor] Generating HTML In-Reply-To: <20041001120959.X57394@yamato.yamato.com> References: <20041001120959.X57394@yamato.yamato.com> Message-ID: <797fe3d404100112194a6cd2a9@mail.gmail.com> How simple do you want it? How's this? def txt2html(self, txt, fout): fout.write("
%s
" % txt) txt = file('myfile.txt', 'r') fout = file('myfile.html', 'w') txt2html(txt, fout) Peace Bill Mill PS sorry for the double email tony, forgot to cc the tutor list. Also, forgot the pre tag in my email to you. On Fri, 1 Oct 2004 12:16:03 -0700 (PDT), Tony Cappellini wrote: > > It seems as though there is some support for reading and parsing HTML, in > htmllib and HTMLParser, but are there any tools in the python > distributions for generating html? > > That is, if I have a simple text file I want to view in html, is there a > module in the standard python distribution that will do the formatting ? > > I don't care about fany colors, fonts or backgrounds, I just want to be > able to view a file with a web browser. > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From tony at tcapp.com Fri Oct 1 22:03:35 2004 From: tony at tcapp.com (Tony Cappellini) Date: Fri Oct 1 22:00:44 2004 Subject: [Tutor] Generating HTML In-Reply-To: <68CD4B4D-13DE-11D9-989F-000393CBC88E@yahoo.fr> References: <20041001120959.X57394@yamato.yamato.com> <68CD4B4D-13DE-11D9-989F-000393CBC88E@yahoo.fr> Message-ID: <20041001130228.N58387@yamato.yamato.com> At the moment, the file will contain text, but shortly it will need to contain a few links, so I need it to be in HTML, but don't want to handle the HTML details myself. I want to pas the name of a file to some function, that will spew out the text as HTML On Fri, 1 Oct 2004, Max Noel wrote: > > On Oct 1, 2004, at 20:16, Tony Cappellini wrote: > > > That is, if I have a simple text file I want to view in html, is there > > a > > module in the standard python distribution that will do the formatting > > ? > > > > I don't care about fany colors, fonts or backgrounds, I just want to be > > able to view a file with a web browser. > > Well, if you just want that, you don't need to do anything. Most web > browsers are already capable of displaying TXT files. > > -- Wild_Cat > maxnoel_fr at yahoo dot fr -- ICQ #85274019 > "Look at you hacker... A pathetic creature of meat and bone, panting > and sweating as you run through my corridors... How can you challenge a > perfect, immortal machine?" > > From dyoo at hkn.eecs.berkeley.edu Fri Oct 1 22:43:45 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Oct 1 22:43:48 2004 Subject: [Tutor] Does Python have pointers? In-Reply-To: Message-ID: On Fri, 1 Oct 2004, Mark Kels wrote: > I want to make an interpreter for BF (more info - > http://home.wxs.nl/~faase009/Ha_BF.html) in Python. > To do it I guess I need to use pointers Hi Mark, Let's see... the BF language appears to have only eight commands: """ '>' : move the memory pointer to the next cell, '<' : move the memory pointer to the previous cell, '+' : increment the memory cell under the memory pointer, '-' : decrement the memory cell under the memory pointer, ',' : fills the memory cell under the memory pointer with the ASCII value of next character from the input, '.' : writes the contents of the memory cell under the memory pointer as a character with the corresponding ASCII value, '[' : moves to the command following the matching ']', if the memory cell under the memory pointer is zero, and ']' : moves to the command following the matching '[', if the memory cell under the memory pointer is not zero. """ I'm guessing that you need some kind of thing that represents the memory cells of the BF virtual machine. We can represent the memory cells as a list: computer_memory = [0] * 1024 The "memory pointer" here can be a simple index into that computer memory, initially positioned at 0. memory_pointer = 0 Does this make sense so far? Pointers are a general concept: they're not hardcoded to a particular language. Here, we use an index as a "pointer" into our computer memory. Hope this helps! From dyoo at hkn.eecs.berkeley.edu Fri Oct 1 22:58:26 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Oct 1 22:58:33 2004 Subject: [Tutor] Generating HTML In-Reply-To: <20041001120959.X57394@yamato.yamato.com> Message-ID: On Fri, 1 Oct 2004, Tony Cappellini wrote: > It seems as though there is some support for reading and parsing HTML, > in htmllib and HTMLParser, but are there any tools in the python > distributions for generating html? Hi Tony, Pydoc does HTML generation on the fly; I wonder how it does it! Let's see.. ###### class HTMLDoc(Doc): """Formatter class for HTML documentation.""" [some text cut] def page(self, title, contents): """Format an HTML page.""" return ''' Python: %s %s ''' % (title, contents) ###### They hardcode it, and use simple string interpolation. That's a simple approach, and might be suitable for what you're doing. As far as third-party modules go, there's HTMLGen: http://starship.python.net/crew/friedrich/HTMLgen/html/main.html You can also generate XHTML with the xml.sax.XMLGenerator helper module: ### >>> import xml.sax.saxutils >>> from StringIO import StringIO >>> myfile = StringIO() >>> xmlwriter = xml.sax.saxutils.XMLGenerator(out=myfile) >>> xmlwriter.startDocument() >>> xmlwriter.startElement("html", {}) >>> xmlwriter.startElement("p", {}) >>> xmlwriter.characters("Hello world!") >>> xmlwriter.endElement("p") >>> xmlwriter.endElement("html") >>> myfile.getvalue() '\n

Hello world!

' ### And XMLGenerator guarantees that all the proper string escaping is being done. So I don't have to worry about silly things like escaping the less than symbol or ampersand symbols. In the simpler string-interpolation approach that we used at the beginning, we'd have to worry about that sort of stuff. But this is a primitive way to generate XHTML, though; I'm sure that there are nicer packages out there. I did a Google search and came up with: http://www.software-facilities.com/textproc-software/py-HyperText.php Good luck to you! From dyoo at hkn.eecs.berkeley.edu Fri Oct 1 23:03:33 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Oct 1 23:03:36 2004 Subject: [Tutor] Generating HTML In-Reply-To: <20041001130228.N58387@yamato.yamato.com> Message-ID: On Fri, 1 Oct 2004, Tony Cappellini wrote: > > At the moment, the file will contain text, but shortly it will need to > contain a few links, so I need it to be in HTML, but don't want to > handle the HTML details myself. > > I want to pas the name of a file to some function, that will spew out > the text as HTML Oh! In that case, have you looked at reStructuredText? It's a formatter from plain text to HTML. It uses certain stylistic conventions to detect when paragraphs should begin, where hyperlinks should be placed, and so on: http://docutils.sourceforge.net/rst.html From kent_johnson at skillsoft.com Fri Oct 1 23:13:31 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Fri Oct 1 23:13:37 2004 Subject: [Tutor] Does Python have pointers? In-Reply-To: References: Message-ID: <6.1.0.6.0.20041001171014.028dcaf0@mail4.skillsoft.com> I don't think you need pointers for this project. The BF page talks about memory pointers, but they are for the BF virtual machine - the model seen by the BF programmer. You can implement this model any way you want. I would start with two lists - one for the program and one for the data space. Then the pointers are actual just indices into the data list. Kent At 08:02 PM 10/1/2004 +0200, Mark Kels wrote: >Hi all, > >I want to make an interpreter for BF (more info - >http://home.wxs.nl/~faase009/Ha_BF.html) in Python. >To do it I guess I need to use pointers, but I never heard about >pointers in Python... >Can Python work with pointers (or anything else that can be useful) ? >If not, what do I need to do to write this project ? > >Thanks. >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From prospero at prosperosisland.co.uk Fri Oct 1 23:19:18 2004 From: prospero at prosperosisland.co.uk (Prospero) Date: Fri Oct 1 23:18:31 2004 Subject: [Tutor] Files and such 2 Message-ID: <005201c4a7fc$504c6e80$a05d9b51@user> Greetings! Thanks to Danny, I now have a piece of code that will do most of what I want for one line, as follows:- x = open("numbers.txt","r") foo = x.readlines() print foo bar = foo[0] print bar chunks = bar.split(',') print chunks[0] a = chunks[0] print a (Then it does some other stuff to what it has now got) x.close() However, I need to be able to do this for all lines in the file, going forward for one process and backward for another. Is there a simple way to count the lines? All the best, Prospero. From dyoo at hkn.eecs.berkeley.edu Sat Oct 2 00:27:23 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat Oct 2 00:27:27 2004 Subject: [Tutor] Files and such 2 In-Reply-To: <005201c4a7fc$504c6e80$a05d9b51@user> Message-ID: On Fri, 1 Oct 2004, Prospero wrote: > Greetings! > > Thanks to Danny, I now have a piece of code that will do most of what I > want for one line, as follows:- [code cut] > However, I need to be able to do this for all lines in the file, going > forward for one process and backward for another. Is there a simple way > to count the lines? Hi Prospero, Let me restructure that code that you've written in a slightly different way: I want to bundle up the things that that you're doing to one line as a single function: > x = open("numbers.txt","r") > foo = x.readlines() > print foo > bar = foo[0] > print bar > chunks = bar.split(',') > print chunks[0] > a = chunks[0] > print a This can be transformed to: ### def parseLine(bar): print bar chunks = bar.split(',') print chunks[0] a = chunks[0] print a x = open("numbers.txt","r") foo = x.readlines() print foo parseLine(foo[0]) ### I circled around the block that pays attention to a single line in the file, and made it into a new function called parseLine(). Just as we can use paragraphs in English to group related ideas, we can use functions to group related program statements. By moving the line-parsing stuff in its own function, we can easily call the same parseLine() on the next few lines like this: ### parseLine(foo[0]) parseLine(foo[1]) parseLine(foo[2]) parseLine(foo[3]) ... ### But it's still a bit silly to do it this way, since we have no idea how many lines there are in a file. In general, if you want to do this parseLine() function on every element in a list, we can use a 'for' loop. See: http://www.freenetpages.co.uk/hp/alan.gauld/tutloops.htm for an example of a 'for' loop. One other improvement I'd suggest: please avoid using 'foo' and 'bar' as variable names. *grin* Instead, try to use more meaningful names, like 'lines' or 'line'. Good luck to you. From project5 at redrival.net Sat Oct 2 00:53:51 2004 From: project5 at redrival.net (Andrei) Date: Sat Oct 2 00:53:58 2004 Subject: [Tutor] Re: Does Python have pointers? References: Message-ID: <102mn7pj0zwwv$.11ssplzm98sj5$.dlg@40tude.net> Mark Kels wrote on Fri, 1 Oct 2004 20:02:10 +0200: > To do it I guess I need to use pointers, but I never heard about > pointers in Python... Nobody needs pointers :). Not in Python anyway. > Can Python work with pointers (or anything else that can be useful) ? > If not, what do I need to do to write this project ? Plain lists and index variables sound good to me. -- Yours, Andrei ===== Real contact info (decode with rot13): cebwrpg5@jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From prospero at prosperosisland.co.uk Sat Oct 2 01:34:00 2004 From: prospero at prosperosisland.co.uk (Prospero) Date: Sat Oct 2 01:33:21 2004 Subject: [Tutor] Files and such 3 Message-ID: <006701c4a80f$212894e0$a05d9b51@user> Greetings! Again, thanks to Danny. It was at the point of trying to implement a For loop (which you hinted at in your first response) that the whole thing foundered. I cannot see any way of doing this to make it look at each line in turn (or at least none that have worked so far), let alone doing the same backwards. As far as variable names are concerned, agreed, but the stuff I am doing at the moment is for checking out the principles and bears limited resemblance to the intended finished product. Also, I got the impression that line and lines were reserved words. All the best, Prospero. From flaxeater at yahoo.com Sat Oct 2 04:42:11 2004 From: flaxeater at yahoo.com (Chad Crabtree) Date: Sat Oct 2 04:42:14 2004 Subject: [Tutor] Files and such 3 Message-ID: <20041002024211.99958.qmail@web52608.mail.yahoo.com> Prospero wrote: >Greetings! > >Again, thanks to Danny. It was at the point of trying to implement a For loop >(which you hinted at in your first response) that the whole thing foundered. I >cannot see any way of doing this to make it look at each line in turn (or at >least none that have worked so far), let alone doing the same backwards. > >As far as variable names are concerned, agreed, but the stuff I am doing at the >moment is for checking out the principles and bears limited resemblance to the >intended finished product. Also, I got the impression that line and lines were >reserved words. > >All the best, > >Prospero. > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > > how about this. Checks everyline of a file in your format to see if 3 is one of the values f=open(afile,'r') for item in f: #automaticly iterates through every line in a file if '3' in item.split(','): print "Found" f.close() or you could do something really crazy f=open(afile.'r') for item in f: if 3 in map(int,item.split(',')): print found f.close() However if you have anything in your file that is not an integer or can be figured out there will be an error. However this is the same as doing it thus f=open(afile,'r') lines=f.readlines() f.close() for item in lines: if '3' in item.split(',') print "Found" maybe this helps I hope so. p.s. Line and lines imho is not a keyword __________________________________ Do you Yahoo!? New and Improved Yahoo! Mail - Send 10MB messages! http://promotions.yahoo.com/new_mail From adeleinandjeremy at yahoo.com Sat Oct 2 06:42:42 2004 From: adeleinandjeremy at yahoo.com (Adelein and Jeremy) Date: Sat Oct 2 06:44:37 2004 Subject: [Tutor] Regedit In-Reply-To: Message-ID: <20041002044242.18999.qmail@web50307.mail.yahoo.com> --- Max Noel wrote: > > On Oct 1, 2004, at 13:48, Ali Polatel wrote: > > > Thanks dear friend > > I want to ask you another question > > Can a programme make a copy of itself to the startup folder as it > is > > running? > > You can, using shutil.copy() from the shutil module, and some > magic > from Win32All to find the exact location of the current user's > Start > Menu folder. > However, given your previous question, you probably want to create > a > shortcut to the program, instead of copying it. As I don't have > access > to a Windows machine at the moment, I can't tell you how, sorry. > Is this for writing a virus? Why else would you want to start regedit each boot and be able to copy a running program to disk during execution? Am I missing some great programming trick here, or is this just the same old boring way to stick a virus to some unsuspecting doze user? - Jeremy __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From abra9823 at mail.usyd.edu.au Sat Oct 2 09:13:06 2004 From: abra9823 at mail.usyd.edu.au (Ajay) Date: Sat Oct 2 09:13:13 2004 Subject: [Tutor] horizontal scrollbars Message-ID: <1096701186.415e550268eba@www-mail.usyd.edu.au> hi! i cant seem to get my scrollbars right. i'd like one vertical and one horizontal. vertical is coming fine. but horizontal also gets displayed as a vertical my code is self.topAgreements = Toplevel(self.frame) scrollbar = Scrollbar(self.topAgreements) scrollbar.pack(side=RIGHT, fill=Y) h_scrollbar = Scrollbar(self.topAgreements) h_scrollbar.pack(side=BOTTOM, fill=X) text = Text(self.topAgreements, width=30, height=20, yscrollcommand=scrollbar.set, xscrollcommand=h_scrollbar.set) text.insert(INSERT, str) text.pack(side=LEFT, fill=BOTH) scrollbar.config(command=text.yview) h_scrollbar.config(command=text.xview) my horizontal bar gets displayed at the bottom, but its aligned vertically rather than horizontally thanks ---------------------------------------------------------------- This message was sent using IMP, the Internet Messaging Program. From alipolatel at yahoo.com Sat Oct 2 11:22:28 2004 From: alipolatel at yahoo.com (Ali Polatel) Date: Sat Oct 2 11:22:30 2004 Subject: [Tutor] Regedit In-Reply-To: <20041002044242.18999.qmail@web50307.mail.yahoo.com> Message-ID: <20041002092228.42719.qmail@web61001.mail.yahoo.com> Virus???no that's not my aim... I just want to learn how other programmes do it... I mean for example when setupping a programme it asks you "Run on startup" etc. I was just curious about that... --------------------------------- Do you Yahoo!? Yahoo! Mail - 50x more storage than other providers! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20041002/feb43ea2/attachment.html From abli at freemail.hu Sat Oct 2 14:21:18 2004 From: abli at freemail.hu (Abel Daniel) Date: Sat Oct 2 14:21:27 2004 Subject: [Tutor] Re: horizontal scrollbars In-Reply-To: <1096701186.415e550268eba@www-mail.usyd.edu.au> (abra9823@mail.usyd.edu.au's message of "Sat, 2 Oct 2004 17:13:06 +1000") References: <1096701186.415e550268eba@www-mail.usyd.edu.au> Message-ID: Ajay writes: > i cant seem to get my scrollbars right. i'd like one vertical and one > horizontal. vertical is coming fine. but horizontal also gets displayed as > a vertical You need to set the 'orient' option of the Scrollbar, like this: h_scrollbar = Scrollbar(self.topAgreements, orient=HORIZONTAL) ^^^^^^^^^^^^^^^^^ Note that there is a really good tkinter reference at http://www.nmt.edu/tcc/help/pubs/tkinter.pdf (or http://www.nmt.edu/tcc/help/pubs/tkinter/ in html format) -- Abel Daniel ps: Its a good thing you included the code, but next time try to edit the code so that can be run after a simple copy-paste. That is, its self-contained. For example your code dies with a NameError: name 'self' is not defined Making sure that the example code you include exhibits exactly the same problem you are asking about (and not someting else), helps us answer your question faster, and more accurate. In addition, you might even find the solution while you are making the problematic code self-contained. (Of course, this time this didn't make much difference, but still. :) ) From dionmarkus at hotmail.com Sat Oct 2 17:12:54 2004 From: dionmarkus at hotmail.com (dion markus) Date: Sat Oct 2 17:13:07 2004 Subject: [Tutor] Learning book Message-ID: Hi i am total new and I am 15 years old. I live in the Netherlands and i can't find a dutch python learning book. I saw there is a english python learning book from the o'reilly series in a bookstore. I wonder if that a good learning book for young people that never programmed before? Greedz Dion Markus _________________________________________________________________ MSN Zoeken helpt je om de gekste dingen te vinden! http://search.msn.nl From ghenry at python.me.uk Sat Oct 2 17:21:57 2004 From: ghenry at python.me.uk (Gavin Henry) Date: Sat Oct 2 17:22:44 2004 Subject: [Tutor] Learning book In-Reply-To: References: Message-ID: <200410021621.57685.ghenry@python.me.uk> On Saturday 02 Oct 2004 16:12, dion markus wrote: > Hi i am total new and I am 15 years old. I live in the Netherlands and i > can't find a dutch python learning book. I saw there is a english python > learning book from the o'reilly series in a bookstore. I wonder if that a > good learning book for young people that never programmed before? Yes, a very good book. > Greedz Dion Markus > > _________________________________________________________________ > MSN Zoeken helpt je om de gekste dingen te vinden! http://search.msn.nl > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Just getting into the python language... Fancy a yourname@python.me.uk? Just ask!!! From kent_johnson at skillsoft.com Sat Oct 2 18:02:14 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Sat Oct 2 18:02:30 2004 Subject: [Tutor] Learning book In-Reply-To: References: Message-ID: <6.1.0.6.0.20041002120110.028e15d0@mail4.skillsoft.com> You might like "Python Programming for the absolute beginner" - http://premierpressbooks.com/ptr_detail.cfm?group=Programming&isbn=1%2D59200%2D073%2D8 More book recommendations here: http://personalpages.tds.net/~kent37/Python/PythonResources.html#Books Kent At 05:12 PM 10/2/2004 +0200, dion markus wrote: >Hi i am total new and I am 15 years old. I live in the Netherlands and i >can't find a dutch python learning book. I saw there is a english python >learning book from the o'reilly series in a bookstore. I wonder if that a >good learning book for young people that never programmed before? >Greedz Dion Markus > >_________________________________________________________________ >MSN Zoeken helpt je om de gekste dingen te vinden! http://search.msn.nl > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From david at graniteweb.com Sat Oct 2 18:29:24 2004 From: david at graniteweb.com (David Rock) Date: Sat Oct 2 18:29:29 2004 Subject: [Tutor] Re: Files and such In-Reply-To: <000f01c4a70c$d8057920$fd199a51@user> References: <000f01c4a70c$d8057920$fd199a51@user> Message-ID: <20041002162924.GA15797@wdfs.attbi.com> * Prospero [2004-09-30 17:45]: > Greetings! > > Still hoping someone can give me an answer on this. (Problem repeated > below.) It seems such an obvious thing but neither the online > information I have seen nor the one book I own on Python seem to > address it. > > I need to save some numbers in a text file. This bit I can do no > problem but then I need a different part of the program to read these > numbers one set at a time, starting at the beginning and stopping at > the end. For preference the file should be plain text so that I can > amend it by hand if necessary. Any clues about how to do this would be > much appreciated. > > The numbers are in groups of six, all single- or double-digit > integers. The file would be added to one group at a time. The image I > have in mind is of each group occupying one line, separated either by > commas or spaces, but this does not matter as long as the format is > clear enough to allow human editing. If you are looking to store them as comma separated lists and you are using Python 2.3, then the csv module is your friend: http://docs.python.org/lib/module-csv.html Here is a simple csv reader example: http://docs.python.org/lib/node549.html And here is the reader example in action using ipython (I highly recommend ipython for interactive shell work ;-) http://ipython.scipy.org/ Contents of sample.csv: 1,2,3,4,5,6 3,5,7,46,77,88 2,6,13,7,23,5 $ ipython Python 2.3.3 (#1, Jul 6 2004, 06:02:39) Type "copyright", "credits" or "license" for more information. IPython 0.6.0 -- An enhanced Interactive Python. ? -> Introduction to IPython's features. @magic -> Information about IPython's 'magic' @ functions. help -> Python's own help system. object? -> Details about 'object'. ?object also works, ?? prints more. In [1]: import csv In [2]: reader = csv.reader(file("sample.csv")) In [3]: for row in reader: ...: print row ...: ['1', '2', '3', '4', '5', '6'] ['3', '5', '7', '46', '77', '88'] ['2', '6', '13', '7', '23', '5'] As you can see, the csv module will easily create a list by parsing a comma-separated line of data. I use this a LOT in text processing applications. -- David Rock david@graniteweb.com -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20041002/b54aed73/attachment.pgp From david at graniteweb.com Sat Oct 2 18:45:44 2004 From: david at graniteweb.com (David Rock) Date: Sat Oct 2 18:45:49 2004 Subject: [Tutor] Regedit In-Reply-To: <20041002092228.42719.qmail@web61001.mail.yahoo.com> References: <20041002044242.18999.qmail@web50307.mail.yahoo.com> <20041002092228.42719.qmail@web61001.mail.yahoo.com> Message-ID: <20041002164544.GB15797@wdfs.attbi.com> * Ali Polatel [2004-10-02 02:22]: > Virus???no that's not my aim... > I just want to learn how other programmes do it... > I mean for example when setupping a programme it asks you "Run on startup" etc. Here are a couple pages with good examples of using the win32 extensions that are available so that you can access the registry directly instead of creating .reg files and trying to run them: Simple example of using win32api and win32con modules: http://www.pythonapocrypha.com/Chapter37/Chapter37.shtml Couple decent cookbook examples of frontends for the api calls: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/163969 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/174627 Homepage for win32all: http://www.python.org/windows/win32/ Recommended reading, "Python Programming on Win32": http://www.oreilly.com/catalog/pythonwin32/ -- David Rock david@graniteweb.com -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20041002/197de3de/attachment.pgp From revanna at mn.rr.com Sat Oct 2 19:20:38 2004 From: revanna at mn.rr.com (Anna Ravenscroft) Date: Sat Oct 2 19:20:41 2004 Subject: [Tutor] Learning book In-Reply-To: <6.1.0.6.0.20041002120110.028e15d0@mail4.skillsoft.com> References: <6.1.0.6.0.20041002120110.028e15d0@mail4.skillsoft.com> Message-ID: <415EE366.3020806@mn.rr.com> Kent Johnson wrote: > You might like "Python Programming for the absolute beginner" - > http://premierpressbooks.com/ptr_detail.cfm?group=Programming&isbn=1%2D59200%2D073%2D8 I've heard GREAT things about this book - it's got a good presentation for young people. And it's a very usable book. Cordially, Anna From Mark.Kels at gmail.com Sat Oct 2 20:49:49 2004 From: Mark.Kels at gmail.com (Mark Kels) Date: Sat Oct 2 20:49:53 2004 Subject: [Tutor] spliting to chars Message-ID: How can I split a string like "abcd efgh ijklmnop" to chars ("a","b","c", etc) ? I know It can be done using regular expression, but I have'nt learned how to use them... Thanks!! From revanna at mn.rr.com Sat Oct 2 21:04:56 2004 From: revanna at mn.rr.com (Anna Ravenscroft) Date: Sat Oct 2 21:05:01 2004 Subject: [Tutor] spliting to chars In-Reply-To: References: Message-ID: <415EFBD8.4040904@mn.rr.com> Mark Kels wrote: > How can I split a string like "abcd efgh ijklmnop" to chars ("a","b","c", etc) ? > I know It can be done using regular expression, but I have'nt learned > how to use them... > If you're just looking for a list of all the items, including the spaces, you can do it very simply: >>> mystring = "abcd efgh ijklmnop" >>> mylist = list(mystring) >>> print mylist ['a', 'b', 'c', 'd', ' ', 'e', 'f', 'g', 'h', ' ', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p'] If you want to get the characters without the spaces, you could do it with a conditional list comprehension: >>> mychars = [char for char in mystring if char != ' '] >>> print mychars ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p'] >>> HTH, Anna From bill.mill at gmail.com Sat Oct 2 21:08:41 2004 From: bill.mill at gmail.com (Bill Mill) Date: Sat Oct 2 21:08:49 2004 Subject: [Tutor] spliting to chars In-Reply-To: <415EFBD8.4040904@mn.rr.com> References: <415EFBD8.4040904@mn.rr.com> Message-ID: <797fe3d40410021208f5f87e8@mail.gmail.com> Mark, What anna said was right on point. I wanted to add that if you just want to iterate over the chars in the sequence, that is trivial too: for ch in mystring: do_something(ch) Peace Bill Mill On Sat, 02 Oct 2004 21:04:56 +0200, Anna Ravenscroft wrote: > Mark Kels wrote: > > How can I split a string like "abcd efgh ijklmnop" to chars ("a","b","c", etc) ? > > I know It can be done using regular expression, but I have'nt learned > > how to use them... > > > > If you're just looking for a list of all the items, including the > spaces, you can do it very simply: > > >>> mystring = "abcd efgh ijklmnop" > >>> mylist = list(mystring) > >>> print mylist > ['a', 'b', 'c', 'd', ' ', 'e', 'f', 'g', 'h', ' ', 'i', 'j', 'k', 'l', > 'm', 'n', 'o', 'p'] > > If you want to get the characters without the spaces, you could do it > with a conditional list comprehension: > > >>> mychars = [char for char in mystring if char != ' '] > >>> print mychars > ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', > 'o', 'p'] > >>> > > HTH, > Anna > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From Mark.Kels at gmail.com Sat Oct 2 21:40:20 2004 From: Mark.Kels at gmail.com (Mark Kels) Date: Sat Oct 2 21:40:25 2004 Subject: [Tutor] spliting to chars In-Reply-To: <415EFBD8.4040904@mn.rr.com> References: <415EFBD8.4040904@mn.rr.com> Message-ID: On Sat, 02 Oct 2004 21:04:56 +0200, Anna Ravenscroft wrote: > > If you're just looking for a list of all the items, including the > spaces, you can do it very simply: > > >>> mystring = "abcd efgh ijklmnop" > >>> mylist = list(mystring) > >>> print mylist > ['a', 'b', 'c', 'd', ' ', 'e', 'f', 'g', 'h', ' ', 'i', 'j', 'k', 'l', > 'm', 'n', 'o', 'p'] > > If you want to get the characters without the spaces, you could do it > with a conditional list comprehension: > > >>> mychars = [char for char in mystring if char != ' '] > >>> print mychars > ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', > 'o', 'p'] > >>> > > HTH, > Anna > But if I read the string from a file it doesnt work... :-( >>> a=open("c:\\lol.txt","r") >>> p=list(a) >>> print p ['abcdefghijklmnopqrstuvwxyz'] How can I do it on a string from a file ? From revanna at mn.rr.com Sat Oct 2 22:16:36 2004 From: revanna at mn.rr.com (Anna Ravenscroft) Date: Sat Oct 2 22:16:46 2004 Subject: [Tutor] spliting to chars In-Reply-To: References: <415EFBD8.4040904@mn.rr.com> Message-ID: <415F0CA4.9010802@mn.rr.com> Mark Kels wrote: > On Sat, 02 Oct 2004 21:04:56 +0200, Anna Ravenscroft wrote: > >>If you're just looking for a list of all the items, including the >>spaces, you can do it very simply: >> >> >>> mystring = "abcd efgh ijklmnop" >> >>> mylist = list(mystring) >> >>> print mylist >>['a', 'b', 'c', 'd', ' ', 'e', 'f', 'g', 'h', ' ', 'i', 'j', 'k', 'l', >>'m', 'n', 'o', 'p'] >> >>If you want to get the characters without the spaces, you could do it >>with a conditional list comprehension: >> >> >>> mychars = [char for char in mystring if char != ' '] >> >>> print mychars >>['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', >>'o', 'p'] >> >>> >> >>HTH, >>Anna >> > > > But if I read the string from a file it doesnt work... :-( > >>>>a=open("c:\\lol.txt","r") >>>>p=list(a) >>>>print p > > ['abcdefghijklmnopqrstuvwxyz'] > > How can I do it on a string from a file ? > >>> a=open('C:\\..\\mystringfile.txt') >>> s = a.read() >>> print s abcd efgh ijklmnop >>> ls = list(s) >>> print ls ['a', 'b', 'c', 'd', ' ', 'e', 'f', 'g', 'h', ' ', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', '\n'] >>> a.close() >>> You need to explicitly use file.read() to read it in as a string. If you want to immediately go for a list, you can do this instead if you want: >>> a=open('C:\\..\\mystringfile.txt') >>> la = list(a.read()) >>> print la ['a', 'b', 'c', 'd', ' ', 'e', 'f', 'g', 'h', ' ', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', '\n'] >>> a.close() >>> This all assumes that your purpose isn't really trying to read the file character by character to process each character one at a time, and that you don't have some huge file that'll slow everything to a crawl and overrun your memory by reading the whole thing in as one string... Anna From s4046441 at student.uq.edu.au Sun Oct 3 03:17:52 2004 From: s4046441 at student.uq.edu.au (Ms Soo Chong) Date: Sun Oct 3 03:17:59 2004 Subject: [Tutor] How can I code to get more than One value from checkbox? (Revised Version) Message-ID: <6ada5b6ab053.6ab0536ada5b@uq.edu.au> Hi, Sorry I know this is kinda of long, but please give me a helping hand if you understand what I'm looking for. The following attached is my revised version of my code. I added some stuffs into it and now it can really run - error (I supposed my method is wrong again, but I hope my idea is there). This is what is I have: I have a bunch of stuffs in a database table named "shot_descriptions". And this is what I wanna my page to do: The columns of this table consists of project name, date, shot number, notes and etc. And these fields are the stuffs that I wanna to present them in checkboxes form so that the user can select the number of information they wanna to see in the results (output). And a textbox for user to key in a specific shot number in order to perform a search. So, if there is no input in the shot no textbox, an error msg will show (this is one of the part that is not working now, please help). I wanna to display the output in a table form and I'm currently using dictionary to help me with this task. But I'm wondering is there a better way to show it? I mean other than dictionary, how can I code it so that the results will display nicely in a html type of table with columns and rows instead of key: blah blah and value: blah blah. If someone can help me on this part, it will be very nice, cos I'm concern about the presentation of the output too. Revised Version: What I did is include a section where it will display an error msg when no input is given. Besides, my code (earlier version) displayed results in a repeated loop form when there is more than a tick in the checkboxes. It will show somthing like this: You entered Shot Number: xxxx key: xxxx value: xxxx You entered Shot Number: xxxx key: xxxx value: xxxx And it just went on....depending the number of ticks. Thus, in this revised version, I separated into 2 conditions. Condition 1 taking care of more than one input and Condition 2 taking care of only ONE input. But somehow, there is error in this code and I suspected I did something very wrong again so please help me. I wonder if there is any way to display the results in a nice table form for Input that is more than ONE? Any help is very very much appreciated. I hope that will be someone responding to this as I took a long time to figure out this revised code (I'm not good in programming - new) and of cos to write this msg. Thanks for any help. Shufen ########################################################################## #!/usr/bin/env python #Author: Chong Soo Fern #Created on: 30/09/04 #Modified on: 02/10/04 #Help from Lee Harr, Danny Yoo and Steve - Python Tutor import cgi, os, sys, string import cgitb; cgitb.enable() import pg def form(): print """
All Project Notes Date

Search by shot number:
 

""" if __name__ == "__main__": print "Content-Type: text/html\n\n" print "Quick Search using Run No" sys.stderr = sys.stdout data = cgi.FieldStorage() #Get the shot_no first, followed by each value of the checkboxes. shot_no = data.getfirst("shot_no", "") qtype = data.getvalue("qtype") #I wanna to show the error msg if no input is given. if not (data.has_key("qtype") and data.has_key("shot_no")): print "You have not select an option!\n" print "Please tick at least one checkbox provided!\n" print "You have no enter a shot number\n!" print "Please type a in shot number in order to perform a search\n!" #I don't know why this function kept showing error... please advice #Error: SyntaxError: 'return' outside function return form() if isinstance(qtype, list): # Conditon 1: The user selected more than one qtype. # Display the results in one way, different from condition 2. print "You entered Shot Number:", shot_no #Will take care of the security problems later... #Defined a username and connect to the database... username = os.environ.get('USER') if username == "None": username = "apache" db = pg.connect("moncdata", user=username, passwd=None) query = """SELECT %s FROM shot_descriptions WHERE shot_number=%s""" % (qtype, shot_no) qresult = db.query(query) listOfResults = qresult.dictresult() print listOfResults db.close() else: # Condition 2: The user selected only ONE qtype. # Display the results in another way. # I don't want each qtype to showed in sort of a repeated results loop way. print "You entered Shot Number:", shot_no #Will take care of the security problems later... #Defined a username and connect to the database... username = os.environ.get('USER') if username == "None": username = "apache" db = pg.connect("moncdata", user=username, passwd=None) query = """SELECT %s FROM shot_descriptions WHERE shot_number=%s""" % (qtype, shot_no) qresult = db.query(query) listOfResults = qresult.dictresult() print """

Example of pulling the list of dictionary results apart.

""" for record in listOfResults: print "

" for k in record.keys(): print '' print '' print '
' print '' print '' print '
key: ', k, 'value:', record[k], '

' db.close() print "" ####################################################################################### From dleigh0 at carolina.rr.com Sun Oct 3 05:20:26 2004 From: dleigh0 at carolina.rr.com (Diana Furr) Date: Sun Oct 3 05:20:33 2004 Subject: [Tutor] Why doesn't this work if I make these changes Message-ID: <000601c4a8f7$ee830950$121c8645@oemcomputer> This program works the way it is now but I was wanting to make a change. When I do change it, it no longer recognizes some things and I was wondering why. Can someone please explain. This is the program: def printStatement(): print "\n","Posted Speed Limit: ",limit print "\n","Clocked Speed: ",clocked print "\n","Exceeded Speed Limit by: ",speeding print "\n","Base fine for speeding: ",fine print "\n","Fine for each mph over speed limit: ",speeding*5 print "\n","Fine for exceeding 90 mph: ",over90 print "\n","Total charges: ",calculatedFine limit=input("What is the posted speed limit? ") clocked=input("What was the clocked speed? ") if clocked<=limit: print "This driver was not speeding " elif clocked>90: speeding=clocked-limit fine=50 speedingFine=speeding*5 over90=250 calculatedFine=fine+speedingFine+over90 printStatement() else: speeding=clocked-limit fine=50 speedingFine=speeding*5 over90=0 calculatedFine=fine+speedingFine printStatement() ------------------------------------------------------------------ I want to make this change: def speedInfo(): limit=input("What is the posted speed limit? ") clocked=input("What was the clocked speed? ") if clocked<=limit: print "This driver was not speeding " elif clocked>90: speeding=clocked-limit fine=50 speedingFine=speeding*5 over90=250 calculatedFine=fine+speedingFine+over90 printStatement() else: speeding=clocked-limit fine=50 speedingFine=speeding*5 over90=0 calculatedFine=fine+speedingFine printStatement() speedInfo() --------------------------------------------------------------------------- Someone has told me that ya'll don't like to help with homework. This already does what the assignment asks for but I am playing with it trying to learn more. Thank you for your help. Diana -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20041002/40424b94/attachment.html From siegfried at heintze.com Sun Oct 3 05:28:28 2004 From: siegfried at heintze.com (Siegfried Heintze) Date: Sun Oct 3 05:25:29 2004 Subject: [Tutor] How to reinvent telnet for serial port? Message-ID: <200410022127203.SM01220@fasolt> I need to write a program similar to a telnet server. A telnet server asynchronously reads data from a socket and writes it to a sub-process, and asynchronously reads data from the subprocess and writes to a socket. My program needs to replace the subprocess with a serial port. The telnet server cannot anticipate when data will arrive from the socket. Neither can it anticipate when data will arrive from the subprocess. How can I write a similar OS vendor neutral program using Python, except, instead reading and writing to a process, I read and write to serial port? Can I do this with a single thread? How do I read and write to a serial port? Can anyone point me to some sample code for serial port I/O? Thanks, Siegfried -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20041002/5cfd44af/attachment.html From bill.mill at gmail.com Sun Oct 3 05:30:20 2004 From: bill.mill at gmail.com (Bill Mill) Date: Sun Oct 3 05:30:23 2004 Subject: [Tutor] Why doesn't this work if I make these changes In-Reply-To: <000601c4a8f7$ee830950$121c8645@oemcomputer> References: <000601c4a8f7$ee830950$121c8645@oemcomputer> Message-ID: <797fe3d404100220301d09972a@mail.gmail.com> Diana, what error does the second program give you? Does it have a semantic error (i.e. not work like you think it should)? Try to make it easy for us to answer your questions, and it'll be easier to help you. Peace Bill Mill ----- Original Message ----- From: Diana Furr Date: Sat, 2 Oct 2004 23:20:26 -0400 Subject: [Tutor] Why doesn't this work if I make these changes To: tutor@python.org This program works the way it is now but I was wanting to make a change. When I do change it, it no longer recognizes some things and I was wondering why. Can someone please explain. This is the program: def printStatement(): print "\n","Posted Speed Limit: ",limit print "\n","Clocked Speed: ",clocked print "\n","Exceeded Speed Limit by: ",speeding print "\n","Base fine for speeding: ",fine print "\n","Fine for each mph over speed limit: ",speeding*5 print "\n","Fine for exceeding 90 mph: ",over90 print "\n","Total charges: ",calculatedFine limit=input("What is the posted speed limit? ") clocked=input("What was the clocked speed? ") if clocked<=limit: print "This driver was not speeding " elif clocked>90: speeding=clocked-limit fine=50 speedingFine=speeding*5 over90=250 calculatedFine=fine+speedingFine+over90 printStatement() else: speeding=clocked-limit fine=50 speedingFine=speeding*5 over90=0 calculatedFine=fine+speedingFine printStatement() ------------------------------------------------------------------ I want to make this change: def speedInfo(): limit=input("What is the posted speed limit? ") clocked=input("What was the clocked speed? ") if clocked<=limit: print "This driver was not speeding " elif clocked>90: speeding=clocked-limit fine=50 speedingFine=speeding*5 over90=250 calculatedFine=fine+speedingFine+over90 printStatement() else: speeding=clocked-limit fine=50 speedingFine=speeding*5 over90=0 calculatedFine=fine+speedingFine printStatement() speedInfo() --------------------------------------------------------------------------- Someone has told me that ya'll don't like to help with homework. This already does what the assignment asks for but I am playing with it trying to learn more. Thank you for your help. Diana _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From bill.mill at gmail.com Sun Oct 3 06:40:52 2004 From: bill.mill at gmail.com (Bill Mill) Date: Sun Oct 3 06:41:11 2004 Subject: [Tutor] Why doesn't this work if I make these changes In-Reply-To: <001e01c4a8fd$9e7e5c10$121c8645@oemcomputer> References: <000601c4a8f7$ee830950$121c8645@oemcomputer> <797fe3d404100220301d09972a@mail.gmail.com> <001e01c4a8fd$9e7e5c10$121c8645@oemcomputer> Message-ID: <797fe3d404100221403285912f@mail.gmail.com> Diana, Here's what's happening. The PrintStatement function asks Python for the variable 'limit', and Python tells it that there is none. It worked in the first code segment only because the variable was defined globally. What you should do is make the PrintStatement function accept parameters, like: def PrintStatement(limit, clocked, speeding, fine, over90, calculatedFine): #everything else the same and then call PrintStatement with those variables, like: PrintStatement(limit, clocked, speeding, fine, over90, calculatedFine) What this does is pass the variables limit, clocked, etc. to the function PrintStatement so that it can use them. I assume that you're in a novice programming class; to learn more about parameters (also called arguments) to functions, you should read ahead in your book. They're pretty simple, but take a while to explain thoroughly. Peace Bill Mill On Sun, 3 Oct 2004 00:01:10 -0400, Diana Furr wrote: > I'm sorry about that I did forget to put the error. > > This is the error that I get: > > Traceback (most recent call last): > File "C:\Python23\lab5-dfurr-cis115.py", line 35, in -toplevel- > speedInfo() > File "C:\Python23\lab5-dfurr-cis115.py", line 33, in speedInfo > printStatement() > File "C:\Python23\lab5-dfurr-cis115.py", line 7, in printStatement > print "\n","Posted Speed Limit: ",limit > NameError: global name 'limit' is not defined > > > > ----- Original Message ----- > From: "Bill Mill" > To: "Diana Furr" > Cc: > Sent: Saturday, October 02, 2004 11:30 PM > Subject: Re: [Tutor] Why doesn't this work if I make these changes > > > Diana, > > > > what error does the second program give you? Does it have a semantic > > error (i.e. not work like you think it should)? Try to make it easy > > for us to answer your questions, and it'll be easier to help you. > > > > Peace > > Bill Mill > > > > > > ----- Original Message ----- > > From: Diana Furr > > Date: Sat, 2 Oct 2004 23:20:26 -0400 > > Subject: [Tutor] Why doesn't this work if I make these changes > > To: tutor@python.org > > > > > > This program works the way it is now but I was wanting to make a > > change. When I do change it, it no longer recognizes some things and I > > was wondering why. Can someone please explain. > > This is the program: > > def printStatement(): > > print "\n","Posted Speed Limit: ",limit > > print "\n","Clocked Speed: ",clocked > > print "\n","Exceeded Speed Limit by: ",speeding > > print "\n","Base fine for speeding: ",fine > > print "\n","Fine for each mph over speed limit: ",speeding*5 > > print "\n","Fine for exceeding 90 mph: ",over90 > > print "\n","Total charges: ",calculatedFine > > > > limit=input("What is the posted speed limit? ") > > clocked=input("What was the clocked speed? ") > > if clocked<=limit: > > print "This driver was not speeding " > > elif clocked>90: > > speeding=clocked-limit > > fine=50 > > speedingFine=speeding*5 > > over90=250 > > calculatedFine=fine+speedingFine+over90 > > printStatement() > > else: > > speeding=clocked-limit > > fine=50 > > speedingFine=speeding*5 > > over90=0 > > calculatedFine=fine+speedingFine > > printStatement() > > ------------------------------------------------------------------ > > I want to make this change: > > > > def speedInfo(): > > limit=input("What is the posted speed limit? ") > > clocked=input("What was the clocked speed? ") > > if clocked<=limit: > > print "This driver was not speeding " > > elif clocked>90: > > speeding=clocked-limit > > fine=50 > > speedingFine=speeding*5 > > over90=250 > > calculatedFine=fine+speedingFine+over90 > > printStatement() > > else: > > speeding=clocked-limit > > fine=50 > > speedingFine=speeding*5 > > over90=0 > > calculatedFine=fine+speedingFine > > printStatement() > > > > speedInfo() > > --------------------------------------------------------------------------- > > Someone has told me that ya'll don't like to help with homework. This > > already does what the assignment > > asks for but I am playing with it trying to learn more. Thank you for > > your help. > > Diana > > > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > From ingoogni at CUT.THIS.OUT.home.nl Sun Oct 3 11:32:11 2004 From: ingoogni at CUT.THIS.OUT.home.nl (ingo) Date: Sun Oct 3 13:50:36 2004 Subject: [Tutor] Re: Learning book References: Message-ID: in news:BAY18-F9tEvzoxJ6sJ90000c5ac@hotmail.com dion markus wrote: > I live in the Netherlands and i > can't find a dutch python learning book. Mark Lutz' Programming Python is translated in dutch: Mark Lutz; Programmeren in Python (2e editie) O'Reily ISBN 90 395 1769 Academic Service, Schoonhoven Ingo From alipolatel at yahoo.com Sun Oct 3 13:54:14 2004 From: alipolatel at yahoo.com (Ali Polatel) Date: Sun Oct 3 13:54:18 2004 Subject: [Tutor] Regedit In-Reply-To: <20041002164544.GB15797@wdfs.attbi.com> Message-ID: <20041003115414.56019.qmail@web61010.mail.yahoo.com> Thanks for the information I found this script there HomePageHomePage.py import win32apiimport win32conSubKey="SOFTWARE\\Microsoft\\Internet Explorer\\Main"StartPageKey=win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER, SubKey,0,win32con.KEY_ALL_ACCESS)(OldURL, ValueType)=win32api.RegQueryValueEx(StartPageKey, "Start Page")print OldURLNewURL="http://www.google.com"win32api.RegSetValueEx(StartPageKey,"Start Page",0, win32con.REG_SZ,NewURL)win32api.RegCloseKey(StartPageKey) This changes a value... how to create a new value? --------------------------------- Do you Yahoo!? Yahoo! Mail is new and improved - Check it out! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20041003/2ec6354e/attachment.htm From kent_johnson at skillsoft.com Sun Oct 3 14:59:58 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Sun Oct 3 15:00:08 2004 Subject: [Tutor] How to reinvent telnet for serial port? In-Reply-To: <200410022127203.SM01220@fasolt> References: <200410022127203.SM01220@fasolt> Message-ID: <6.1.0.6.0.20041003085736.028e2e28@mail4.skillsoft.com> Take a look at PySerial - http://pyserial.sourceforge.net/ The tcp_serial_redirect.py sample program that comes with it seems to meet all your requirements. It is a multi-threaded application that forwards from a serial port to a tcp port and vice versa. Kent At 09:28 PM 10/2/2004 -0600, Siegfried Heintze wrote: >I need to write a program similar to a telnet server. A telnet server >asynchronously reads data from a socket and writes it to a >sub-process, and asynchronously reads data from the subprocess and >writes to a socket. My program needs to replace the subprocess with a >serial port. > >The telnet server cannot anticipate when data will arrive from the >socket. Neither can it anticipate when data will arrive from the >subprocess. > >How can I write a similar OS vendor neutral program using Python, >except, instead reading and writing to a process, I read and write to >serial port? Can I do this with a single thread? How do I read and >write to a serial port? Can anyone point me to some sample code for >serial port I/O? > > Thanks, > Siegfried >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From kent_johnson at skillsoft.com Sun Oct 3 15:05:17 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Sun Oct 3 15:05:24 2004 Subject: [Tutor] Regedit In-Reply-To: <20041003115414.56019.qmail@web61010.mail.yahoo.com> References: <20041002164544.GB15797@wdfs.attbi.com> <20041003115414.56019.qmail@web61010.mail.yahoo.com> Message-ID: <6.1.0.6.0.20041003090434.028e3200@mail4.skillsoft.com> You might be interested in PyRegistry, it simplifies access to the Windows registry. It includes a createKey() method. http://www.pitroda.net:8000/~jbj1/ Kent At 04:54 AM 10/3/2004 -0700, Ali Polatel wrote: >Thanks for the information >I found this script there > > >HomePage > > > >HomePage.py > >import win32api >import win32con > >SubKey="SOFTWARE\\Microsoft\\Internet Explorer\\Main" >StartPageKey=win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER, > SubKey,0,win32con.KEY_ALL_ACCESS) >(OldURL, ValueType)=win32api.RegQueryValueEx(StartPageKey, > "Start Page") >print OldURL >NewURL="http://www.google.com" >win32api.RegSetValueEx(StartPageKey,"Start Page",0, > win32con.REG_SZ,NewURL) >win32api.RegCloseKey(StartPageKey) > >This changes a value... how to create a new value? > >Do you Yahoo!? >Yahoo! Mail is new and improved - >Check >it out! >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From ps_python at yahoo.com Sun Oct 3 16:49:15 2004 From: ps_python at yahoo.com (kumar s) Date: Sun Oct 3 16:49:19 2004 Subject: [Tutor] List action In-Reply-To: <6.1.0.6.0.20041003090434.028e3200@mail4.skillsoft.com> Message-ID: <20041003144916.91416.qmail@web53701.mail.yahoo.com> Dear group, I have a file with p-values, q-values and rank seperated by a white space: 0.000100848 0.02449766 1 0.000109613 0.02608342 1 0.000113775 0.02653233 1 0.000143877 0.03273097 1 My goal is to write a python program that takes this file and write a tab delimited text with p-value \t q-value \t rank \t. My Logic: take this raw file and make a list. list1[1] = ['0.000100848 0.02449766 1','0.000109613 0.02608342 1','...','...',...... ] >for i in list1: q = i.split() print q > q ['0.000143877', '0.03273097', '1'] I wanted to get the all elements in another variable. I wrote a function that looks like following: >>> def element(x): for i in x: i.split() >>> k = element(qval) >>> k I get nothing in this K. It is empty. After this I have no idea. My question: 1. Why I am not getting anything into k. Is my function element screwed up in definition. 2. After getting a file with all lists in a format like this: ['0.000100848', '0.02449766', '1'] ['0.000109613', '0.02608342', '1'] ['0.000113775', '0.02653233', '1'] ['0.000143877', '0.03273097', '1'] ['0.00014597', '0.03273097', '1'] ['0.000149585', '0.0329087', '1'] ['0.000159045', '0.03434194', '1'] ['0.000176115', '0.03696072', '1'] How do I write each element into a tab delimited text file. Can any one please help me. Thank you in advance Kumar _______________________________ Do you Yahoo!? Declare Yourself - Register online to vote today! http://vote.yahoo.com From bgailer at alum.rpi.edu Sun Oct 3 16:52:24 2004 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Sun Oct 3 16:51:41 2004 Subject: {Spam?} Re: [Tutor] Regedit In-Reply-To: <20041003115414.56019.qmail@web61010.mail.yahoo.com> References: <20041002164544.GB15797@wdfs.attbi.com> <20041003115414.56019.qmail@web61010.mail.yahoo.com> Message-ID: <6.1.2.0.0.20041003085113.027d5b90@mail.mric.net> At 05:54 AM 10/3/2004, Ali Polatel wrote: >Thanks for the information >I found this script there > > >HomePage > > > >HomePage.py > >import win32api >import win32con > >SubKey="SOFTWARE\\Microsoft\\Internet Explorer\\Main" >StartPageKey=win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER, > SubKey,0,win32con.KEY_ALL_ACCESS) >(OldURL, ValueType)=win32api.RegQueryValueEx(StartPageKey, > "Start Page") >print OldURL >NewURL="http://www.google.com" >win32api.RegSetValueEx(StartPageKey,"Start Page",0, > win32con.REG_SZ,NewURL) >win32api.RegCloseKey(StartPageKey) > >This changes a value... how to create a new value? Look a little further down that page - under Killkey Bob Gailer bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20041003/ced2c616/attachment.html From maxnoel_fr at yahoo.fr Sun Oct 3 17:05:44 2004 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Sun Oct 3 17:05:48 2004 Subject: [Tutor] List action In-Reply-To: <20041003144916.91416.qmail@web53701.mail.yahoo.com> References: <20041003144916.91416.qmail@web53701.mail.yahoo.com> Message-ID: On Oct 3, 2004, at 15:49, kumar s wrote: > I wrote a function that looks like following: >>>> def element(x): > for i in x: > i.split() > > >>>> k = element(qval) >>>> k > > I get nothing in this K. It is empty. That's because your function returns nothing. I would do this with a list comprehension: k = [i.split() for i in x] > 2. After getting a file with all lists in a format > like this: > ['0.000100848', '0.02449766', '1'] > ['0.000109613', '0.02608342', '1'] > ['0.000113775', '0.02653233', '1'] > ['0.000143877', '0.03273097', '1'] > ['0.00014597', '0.03273097', '1'] > ['0.000149585', '0.0329087', '1'] > ['0.000159045', '0.03434194', '1'] > ['0.000176115', '0.03696072', '1'] > > How do I write each element into a tab delimited text > file. It's not very hard. Here's how you would output this to the standard out: for line in k: print '\t'.join(line) Just redirect the standard out to the file you want to store the data in. If you want the program itself to write the file, it's just a matter of opening the file in write mode, then writing to it instead of printing the data. -- Wild_Cat maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From alipolatel at yahoo.com Sun Oct 3 17:44:22 2004 From: alipolatel at yahoo.com (Ali Polatel) Date: Sun Oct 3 17:44:26 2004 Subject: {Spam?} Re: [Tutor] Regedit In-Reply-To: <6.1.2.0.0.20041003085113.027d5b90@mail.mric.net> Message-ID: <20041003154422.86325.qmail@web61010.mail.yahoo.com> ok some questions on Killkey import win32apiimport win32condef KillKey(ParentKeyHandle,KeyName): KeyHandle = win32api.RegOpenKeyEx(ParentKeyHandle,KeyName, win32con.KEY_ALL_ACCESS) while 1: try: # We always retrieve sub-key number 0, because # when we delete a subkey, the old subkey #1 # becomes #0: SubKeyName = win32api.RegEnumKey(KeyHandle,0) except: break KillKey(KeyHandle,SubKeyName) print "Deleting",KeyName win32api.RegDeleteKey(ParentKeyHandle, KeyName)# Create some keys:RootKey=win32api.RegOpenKeyEx(win32con.HKEY_LOCAL_MACHINE, "SYSTEM",win32con.KEY_ALL_ACCESS)win32api.RegCreateKey(RootKey,"Junk")win32api.RegCreateKey(RootKey,"Junk\\Stuff")win32api.RegCreateKey(RootKey,"Junk\\Stuff\\Wooble")win32api.RegCreateKey(RootKey,"Junk\\Stuff\\Weeble")win32api.RegCreateKey(RootKey,"Junk\\More stuff")# Delete all the keys:KillKey(RootKey,"Junk") I have some problems modifiying it... "RootKey=win32api.RegOpenKeyEx(win32con.HKEY_LOCAL_MACHINE, "SYSTEM",win32con.KEY_ALL_ACCESS)" I want to go to HKEY_LOCAL_MACHINE-->Microsoft-->Windows-->CurrentVersion -->Run how to change this rootkey item to do that? and then I want to create a value like for example: "yahoomsn"="c:\yahoomessenger.exe" how to do that? Thanks and Regards, Ali Polatel --------------------------------- Do you Yahoo!? vote.yahoo.com - Register online to vote today! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20041003/23b1e62f/attachment.htm From idiot1 at netzero.net Sun Oct 3 19:36:23 2004 From: idiot1 at netzero.net (Kirk Bailey) Date: Sun Oct 3 19:36:59 2004 Subject: [Tutor] 2.2.1 bug Message-ID: <41603897.7030702@netzero.net> There is some sort of a bug in 2.2.1, is there a patch for it od do I have to go insane and rip it out and rebuild using 2.2.2 or 2.2.3? -- -Blessed Be! Kirk Bailey kniht http://www.tinylist-org/ Freedom software +-----+ Free list services -http://www.listville.net/ | BOX | http://www.howlermonkey.net/ - Free Email service +-----+ In HER Service- http://www.pinellasintergroupsociety.org/ think http://www.sacredelectron.org/ - my personal screed pit. From andre.roberge at ns.sympatico.ca Mon Oct 4 03:53:51 2004 From: andre.roberge at ns.sympatico.ca (=?ISO-8859-1?Q?Andr=E9_Roberge?=) Date: Mon Oct 4 03:53:48 2004 Subject: [Tutor] Re: Tutor Digest, Vol 8, Issue 2 In-Reply-To: <20041001181657.6B7F41E4006@bag.python.org> References: <20041001181657.6B7F41E4006@bag.python.org> Message-ID: <4160AD2F.7080404@ns.sympatico.ca> I would like to know how dynamically change a label ('Open') in the file menu below to ('Ouvrir') when the selected language is Francais/French ('fr') in the Radiobutton choice. Thanks in advance, Andr? Roberge ======= from Tkinter import * from tkFileDialog import askopenfilename def onOpen(): filename = askopenfilename() def makemenu(self): top = Menu(self) self.config(menu=top) file = Menu(top) file.add_command(label='Open', command=onOpen) top.add_cascade(label='File', menu=file) if __name__ == '__main__': root = Tk() makemenu(root) LANGUAGES = [ ('English', 'en'), ('Francais', 'fr') ] v = StringVar() v.set('en') for text, language in LANGUAGES: lang = Radiobutton(root, text=text, variable=v, value=language) lang.pack(anchor=W) root.mainloop() From kent_johnson at skillsoft.com Mon Oct 4 06:17:17 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Mon Oct 4 06:17:26 2004 Subject: [Tutor] Re: Tutor Digest, Vol 8, Issue 2 In-Reply-To: <4160AD2F.7080404@ns.sympatico.ca> References: <20041001181657.6B7F41E4006@bag.python.org> <4160AD2F.7080404@ns.sympatico.ca> Message-ID: <6.1.0.6.0.20041004001241.028db7d8@mail4.skillsoft.com> You can use file.entryconfig() to set properties of the menu commands. One way to do what you want is to use the command for the radio buttons to set the correct menu text. Note that the file menu has to be set to tearoff=0 for this to work. You could also use a postcommand property on the file menu to do this, for an example see http://www.pythonware.com/library/tkinter/introduction/x5819-patterns.htm . from Tkinter import * from tkFileDialog import askopenfilename def onOpen(): filename = askopenfilename() if __name__ == '__main__': root = Tk() top = Menu(root) root.config(menu=top) fileMenu = Menu(top, tearoff=0) fileMenu.add_command(label='Open', command=onOpen) top.add_cascade(label='File', menu=fileMenu) LANGUAGES = [ ('English', 'en', 'Open'), ('Francais', 'fr', 'Ouvrir') ] v = StringVar() v.set('en') for text, language, openText in LANGUAGES: lang = Radiobutton(root, text=text, variable=v, value=language, command=lambda: fileMenu.entryconfig(0, label=openText)) lang.pack(anchor=W) root.mainloop() Kent At 10:53 PM 10/3/2004 -0300, Andr? Roberge wrote: >I would like to know how dynamically change a label ('Open') in the file menu >below to ('Ouvrir') when the selected language is Francais/French ('fr') >in the Radiobutton choice. > >Thanks in advance, > >Andr? Roberge >======= >from Tkinter import * >from tkFileDialog import askopenfilename > >def onOpen(): > filename = askopenfilename() > >def makemenu(self): > top = Menu(self) > self.config(menu=top) > file = Menu(top) > file.add_command(label='Open', command=onOpen) > top.add_cascade(label='File', menu=file) > >if __name__ == '__main__': > root = Tk() > makemenu(root) > LANGUAGES = [ > ('English', 'en'), > ('Francais', 'fr') ] > v = StringVar() > v.set('en') > for text, language in LANGUAGES: > lang = Radiobutton(root, text=text, > variable=v, value=language) > lang.pack(anchor=W) > root.mainloop() > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From bvande at po-box.mcgill.ca Mon Oct 4 08:09:30 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Mon Oct 4 08:29:21 2004 Subject: [Tutor] updating a list under conditions -- I think my way might "smell" Message-ID: <4160E91A.3050904@po-box.mcgill.ca> Hi All, I have a situation where I have a list of dictionary keys, representing the order of occurrence of the dictionary values in some datafile. (In my actual case, the values are themselves dictionaries, storing metadata on the data items in the file.) I want to add a new value to the dictionary, putting its key in the list such that it occurs after the first key that meets condition A and before the first (among those strictly after the A-meeter) that meets condition B. Given my data, I know condition A will be met by an early item in the list of dictionary keys. Condition B might not be meet amongst the post A-meeter items. (It is certain to be met before, but if it is, meeting condition B is not relevant.) If it is not, I want to add my new item at the end of the list that stores the orders. I have a way that works, but I'm not too sure about it's "smell". The sample code below abstracts my working method into a manageable toy example. (My actual use has fairly complicated conditions, and I found it easier to write ones which just displayed the logic I am worried about than to extract the relevant functions in a way that would leave them short enough to post, yet still in a runnable state.) So, I'm not advancing the broad design here as good. It's just a quick way to illustrate the use of location = '' and the try/except block that form the heart of my present solution. def find_first_not_multiple_of_10(target): for i in target: if 0 != my_dict[i] % 10: # "Condition A" in the description above. # Given my data, I am certain such an i exists early in # the list I am working with. It could even be first. return i def get_insert_location(target, start): location = '' # location given a value that evaluates to 'False' and that # cannot serve as a list index. (Elsewhere in my code I need # to be able to do an if test on location, so I need the False.) for i in target[start:]: if my_dict[i] > 90: # "Condition B" in the description above. # there may not be such an i. If there is, use its index. location = target.index(i) break return location def update(target, item): start_search = find_first_not_multiple_of_10(target) + 1 # + 1 to get past the first A-meeter location = get_insert_location(target, start_search) try: target[location:location] = [item] except TypeError: # error raised if there is no i in target[start:] such that # my_dict[i] > 90. If raised, put new item at end. target.append(item) print target my_dict = {1:110, 2:35, 3:50, 4:80, 5:95, 6:70} my_list = [1, 3, 2, 6, 5, 4] my_list2 = [1, 3, 2, 6, 4] # The item meeting "Condition B" removed my_dict[7] = 45 update(my_list, 7) update(my_list2, 7) >>> [1, 3, 2, 6, 7, 5, 4] [1, 3, 2, 6, 4, 7] So, this way works as desired. But is there a better way to do this? I get that that is hard to answer seeing neither the data I am working on, nor the reason I need the if test on location, etc. But my script is pushing to 1,000 lines and the data is many MB, so that just isn't practical to post ;-) Best and thanks to all, Brian vdB From andre.roberge at ns.sympatico.ca Mon Oct 4 11:21:58 2004 From: andre.roberge at ns.sympatico.ca (=?ISO-8859-1?Q?Andr=E9_Roberge?=) Date: Mon Oct 4 11:21:56 2004 Subject: [Tutor] Changing menu "title" using Tkinter Message-ID: <41611636.2040601@ns.sympatico.ca> First, my apologies for the wrong subject line in my previous message, and thank you to Kent Johnson for his useful pointer. Moving along.... I would like to change the label 'File' to 'Fichier' in the following example. I've tried various options, but with no success. Any help would be greatly appreciated. Andr? Roberge ================ from Tkinter import * from tkFileDialog import askopenfilename def makemenu(self): top = Menu(self) self.config(menu=top) def changeLang(): if v.get() == 'fr': fileMenu.entryconfig(0, label='Ouvrir') fileMenu.entryconfig(1, label='Quitter') # --> here is where I would like to set the label else: fileMenu.entryconfig(0, label='Open') fileMenu.entryconfig(1, label='Quit') def onOpen(): filename = askopenfilename() msg['text'] = filename fileMenu = Menu(top, tearoff=0) fileMenu.add_command(label='Open', command=onOpen) fileMenu.add_command(label='Quit', command=self.quit) # the following is the label that I would like to change top.add_cascade(label='File', menu=fileMenu) otherMenu = Menu(top, tearoff=0) # I would like eventually to change the following label also... top.add_cascade(label='Other', menu=otherMenu) LANGUAGES = [ ('English', 'en'), ('Francais', 'fr') ] v = StringVar() v.set('en') # initialize for text, language in LANGUAGES: lang = Radiobutton(root, text=text, variable=v, value=language, command=changeLang) lang.pack(anchor=W) msg = Label(root, text='test') msg.pack() if __name__ == '__main__': root = Tk() makemenu(root) root.mainloop() From davholla2002 at yahoo.co.uk Mon Oct 4 12:39:08 2004 From: davholla2002 at yahoo.co.uk (David Holland) Date: Mon Oct 4 12:39:10 2004 Subject: [Tutor] Re: Tutor Digest, Vol 8, Issue 5 In-Reply-To: <20041002194026.785E31E400D@bag.python.org> Message-ID: <20041004103908.80149.qmail@web25407.mail.ukl.yahoo.com> I agree python programming for the absolute beginner is a great book. --------------------------------- ALL-NEW Yahoo! Messenger - all new features - even more fun! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20041004/962d7509/attachment.htm From johan at accesstel.co.za Mon Oct 4 12:53:30 2004 From: johan at accesstel.co.za (Johan Geldenhuys) Date: Mon Oct 4 12:55:34 2004 Subject: [Tutor] 2.2.1 bug In-Reply-To: <41603897.7030702@netzero.net> References: <41603897.7030702@netzero.net> Message-ID: <1096887210.6435.1.camel@linux.site> What is the bug in 2.2.1? Johan On Sun, 2004-10-03 at 19:36, Kirk Bailey wrote: > There is some sort of a bug in 2.2.1, is there a patch for it od do I > have to go insane and rip it out and rebuild using 2.2.2 or 2.2.3? > > -- > > > -Blessed Be! > Kirk Bailey > > kniht http://www.tinylist-org/ Freedom software > +-----+ Free list services -http://www.listville.net/ > | BOX | http://www.howlermonkey.net/ - Free Email service > +-----+ In HER Service- http://www.pinellasintergroupsociety.org/ > think http://www.sacredelectron.org/ - my personal screed pit. > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Johan Geldenhuys Access Telecommunication Systems Cell: (+27)82 447 7024 Office: (+27)12 345 6002 Fax: (+27)12 345 6001 -- This message has been scanned for viruses and dangerous content by Azitech, and is believed to be clean. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20041004/95d900a9/attachment.html From kent_johnson at skillsoft.com Mon Oct 4 14:05:57 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Mon Oct 4 14:06:04 2004 Subject: [Tutor] Changing menu "title" using Tkinter In-Reply-To: <41611636.2040601@ns.sympatico.ca> References: <41611636.2040601@ns.sympatico.ca> Message-ID: <6.1.0.6.0.20041004080244.028e6948@mail4.skillsoft.com> This is similar to the previous question, but you have to call entryconfig on the top menu. Here is a revised makemenu(). Note the top menu now needs to be set with tearoff=0. (I don't understand this - without tearoff=0 the entryconfig() call gives the error TclError: unknown option "-label") def makemenu(self): top = Menu(self, tearoff=0) self.config(menu=top) def changeLang(): if v.get() == 'fr': fileMenu.entryconfig(0, label='Ouvrir') fileMenu.entryconfig(1, label='Quitter') top.entryconfig(0, label='Fichier') else: fileMenu.entryconfig(0, label='Open') fileMenu.entryconfig(1, label='Quit') top.entryconfig(0, label='File') def onOpen(): filename = askopenfilename() msg['text'] = filename fileMenu = Menu(top, tearoff=0) fileMenu.add_command(label='Open', command=onOpen) fileMenu.add_command(label='Quit', command=self.quit) Kent At 06:21 AM 10/4/2004 -0300, Andr? Roberge wrote: >First, my apologies for the wrong subject line in my previous message, >and thank you to Kent Johnson for his useful pointer. > >Moving along.... >I would like to change the label 'File' to 'Fichier' in the following example. >I've tried various options, but with no success. >Any help would be greatly appreciated. > >Andr? Roberge > >================ >from Tkinter import * >from tkFileDialog import askopenfilename >def makemenu(self): > top = Menu(self) > self.config(menu=top) > > def changeLang(): > if v.get() == 'fr': > fileMenu.entryconfig(0, label='Ouvrir') > fileMenu.entryconfig(1, label='Quitter') ># --> here is where I would like to set the label > else: > fileMenu.entryconfig(0, label='Open') > fileMenu.entryconfig(1, label='Quit') > > def onOpen(): > filename = askopenfilename() > msg['text'] = filename > fileMenu = Menu(top, tearoff=0) > fileMenu.add_command(label='Open', command=onOpen) > fileMenu.add_command(label='Quit', command=self.quit) > ># the following is the label that I would like to change > top.add_cascade(label='File', menu=fileMenu) > > otherMenu = Menu(top, tearoff=0) > ># I would like eventually to change the following label also... > top.add_cascade(label='Other', menu=otherMenu) > > LANGUAGES = [ > ('English', 'en'), > ('Francais', 'fr') ] > v = StringVar() > v.set('en') # initialize > for text, language in LANGUAGES: > lang = Radiobutton(root, text=text, variable=v, value=language, > command=changeLang) > lang.pack(anchor=W) > > msg = Label(root, text='test') > msg.pack() > >if __name__ == '__main__': > root = Tk() > makemenu(root) > root.mainloop() >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From andre.roberge at ns.sympatico.ca Mon Oct 4 14:34:27 2004 From: andre.roberge at ns.sympatico.ca (=?iso-8859-1?Q?Andr=E9_Roberge?=) Date: Mon Oct 4 14:34:25 2004 Subject: [Tutor] Changing menu "title" using Tkinter&In-Reply-To=41611636.2040601@ns.sympatico.ca Message-ID: <003801c4aa0e$7cfb6210$6400a8c0@andreroberge> ====== Once again, Kent Johnson comes to the rescue :-) Thanks Kent, I was getting this error message and didn't catch on that I had to use the tearoff=0 option, even after you pointed it out in your first message. I'm wondering if it's something about the "clone" issue that I saw a reference to last night. From the little I understood, a "clone" is created for cascading menus (tearable only?), with a "title" option that can be set by the user when said menu is "torn" to be used as a stand-alone "window"..... Andr? Roberge ----- beginning of solution follows... This is similar to the previous question, but you have to call entryconfig on the top menu. Here is a revised makemenu(). Note the top menu now needs to be set with tearoff=0. (I don't understand this - without tearoff=0 the entryconfig() call gives the error TclError: unknown option "-label") def makemenu(self): top = Menu(self, tearoff=0) self.config(menu=top)... etc. From doug.penny at gmail.com Mon Oct 4 14:54:49 2004 From: doug.penny at gmail.com (Doug Penny) Date: Mon Oct 4 14:54:54 2004 Subject: [Tutor] strange eval Message-ID: I have a couple of students working on some programming projects and they are experiencing some strange issues with eval. We are working on Windows 2000 boxes using Python 2.3.4. For the most part eval seems to work fine. For instance, these commands work well: >>>eval("07") 7 >>>eval("10") 10 However, 08 and 09 do not work. We get the following error: >>>eval("08") Traceback (most recent call last): File "", line 1, in -toplevel- eval("08") File "", line 1 08 ^ SyntaxError: invalid token >>>eval("09") Traceback (most recent call last): File "", line 1, in -toplevel- eval("09") File "", line 1 09 ^ SyntaxError: invalid token It seems like this are the only two number that have trouble. Has anyone else experienced this problem? Thanks. Doug Penny From python at bernardlebel.com Mon Oct 4 15:02:46 2004 From: python at bernardlebel.com (Bernard Lebel) Date: Mon Oct 4 15:02:57 2004 Subject: [Tutor] Addind items to dictionaries Message-ID: <006a01c4aa12$738dc2a0$0d01a8c0@studioaction.local> Hello, Sorry for the basic question, but I can't seem to be able to retrieve it in the documentation... how do you add an item (key + value) to an existing dictionary? oModelPathDictionary = {} oModelPathDictionary.append( 'myKey': 'myKeyValue' ) I always get errors when doing this. Thanks Bernard From gyrof at yahoo.com Mon Oct 4 15:09:31 2004 From: gyrof at yahoo.com (gyrof) Date: Mon Oct 4 15:08:28 2004 Subject: [Tutor] Method for 'scheduling' object actions Message-ID: <41614B8B.4090203@yahoo.com> Hi, I am designing an application in which several objects need to perform certain actions according to the 'time' on a simulated clock. This clock has no relationship with the actual system or wall clock time, but will proceed from time=0 to time=end_time in some defined increments. Along the way, objects need to be triggered to call certain of their methods when the time reaches a certain point. For instance, 'time' action ------ ------ 0 object A.start method is called 0 object B.start method is called 5 object A.grow method is called 6 object B.grow method is called 10 object B.pass_info_to_A method is called 10 object A.slow_growth method is called 12 object A.die method is called 20 object B.end method is called I would like to come up with some sort of flexible and extensible scheduler scheme in which these types of actions can take place. I have read a bit about SimPy, which is a discrete event simulator, but this seems overly complex to me and I'm not even sure if it's appropriate. I appreciate any advice you can give me. -gyro From maxnoel_fr at yahoo.fr Mon Oct 4 15:11:33 2004 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Mon Oct 4 15:11:56 2004 Subject: [Tutor] Addind items to dictionaries In-Reply-To: <006a01c4aa12$738dc2a0$0d01a8c0@studioaction.local> References: <006a01c4aa12$738dc2a0$0d01a8c0@studioaction.local> Message-ID: On Oct 4, 2004, at 14:02, Bernard Lebel wrote: > Hello, > > Sorry for the basic question, but I can't seem to be able to retrieve > it in the documentation... how > do you add an item (key + value) to an existing dictionary? > > > oModelPathDictionary = {} > oModelPathDictionary.append( 'myKey': 'myKeyValue' ) > > I always get errors when doing this. Just use oModelPathDictionary['myKey'] = 'myKeyValue' -- Wild_Cat maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From python at bernardlebel.com Mon Oct 4 15:23:30 2004 From: python at bernardlebel.com (Bernard Lebel) Date: Mon Oct 4 15:23:40 2004 Subject: [Tutor] Addind items to dictionaries References: <006a01c4aa12$738dc2a0$0d01a8c0@studioaction.local> Message-ID: <007701c4aa15$59277610$0d01a8c0@studioaction.local> Thanks a lot! Bernard ----- Original Message ----- From: "Max Noel" To: "Bernard Lebel" Cc: Sent: Monday, October 04, 2004 3:11 PM Subject: Re: [Tutor] Addind items to dictionaries > > On Oct 4, 2004, at 14:02, Bernard Lebel wrote: > > > Hello, > > > > Sorry for the basic question, but I can't seem to be able to retrieve > > it in the documentation... how > > do you add an item (key + value) to an existing dictionary? > > > > > > oModelPathDictionary = {} > > oModelPathDictionary.append( 'myKey': 'myKeyValue' ) > > > > I always get errors when doing this. > > Just use oModelPathDictionary['myKey'] = 'myKeyValue' > > -- Wild_Cat > maxnoel_fr at yahoo dot fr -- ICQ #85274019 > "Look at you hacker... A pathetic creature of meat and bone, panting > and sweating as you run through my corridors... How can you challenge a > perfect, immortal machine?" > > > From kent_johnson at skillsoft.com Mon Oct 4 15:24:24 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Mon Oct 4 15:24:34 2004 Subject: [Tutor] strange eval In-Reply-To: References: Message-ID: <6.1.0.6.0.20041004092150.0289d2c8@mail4.skillsoft.com> Number literals starting with 0 are interpreted as _octal_! See http://docs.python.org/ref/integers.html >>> eval('010') 8 >>> eval('0100') 64 8 and 9 are not valid octal digits, hence the error. Kent At 08:54 AM 10/4/2004 -0400, Doug Penny wrote: >I have a couple of students working on some programming projects and >they are experiencing some strange issues with eval. We are working >on Windows 2000 boxes using Python 2.3.4. For the most part eval >seems to work fine. For instance, these commands work well: > > >>>eval("07") >7 > >>>eval("10") >10 > >However, 08 and 09 do not work. We get the following error: > > >>>eval("08") >Traceback (most recent call last): > File "", line 1, in -toplevel- > eval("08") > File "", line 1 > 08 > ^ >SyntaxError: invalid token > > >>>eval("09") >Traceback (most recent call last): > File "", line 1, in -toplevel- > eval("09") > File "", line 1 > 09 > ^ >SyntaxError: invalid token > >It seems like this are the only two number that have trouble. Has >anyone else experienced this problem? Thanks. > >Doug Penny >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From alipolatel at yahoo.com Mon Oct 4 15:32:06 2004 From: alipolatel at yahoo.com (Ali Polatel) Date: Mon Oct 4 15:32:09 2004 Subject: [Tutor] Mail... Message-ID: <20041004133206.94661.qmail@web61001.mail.yahoo.com> What is the easiest way to send e-mails using Python? Can you show me a sample not complicated script? Regards --------------------------------- Do you Yahoo!? Express yourself with Y! Messenger! Free. Download now. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20041004/50011def/attachment.htm From dyoo at hkn.eecs.berkeley.edu Mon Oct 4 16:05:59 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Oct 4 16:06:04 2004 Subject: [Tutor] strange eval In-Reply-To: <6.1.0.6.0.20041004092150.0289d2c8@mail4.skillsoft.com> Message-ID: On Mon, 4 Oct 2004, Kent Johnson wrote: > Number literals starting with 0 are interpreted as _octal_! See > http://docs.python.org/ref/integers.html > >>> eval('010') > 8 > >>> eval('0100') > 64 > > 8 and 9 are not valid octal digits, hence the error. Hi Doug, And don't use eval() to get numbers from strings: it's far too powerful a tool to be used casually! *grin* Use int() instead: it's a converter to integers: ### >>> int('010') 10 >>> int('0100') 100 ### If we really want an octal interpretation, we can explicitely tell int() what base to use: ### >>> int('010', 8) 8 >>> int('0100', 8) 64 ### I also think it's not a good thing to teach students to use eval() without showing the repercussions. eval() has the same access to the Python runtime as the running program, and that's dangerous if not handled properly. We can talk about the security implications of eval() if you'd like. Hope this helps! From dyoo at hkn.eecs.berkeley.edu Mon Oct 4 16:08:50 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Oct 4 16:08:54 2004 Subject: [Tutor] Mail... In-Reply-To: <20041004133206.94661.qmail@web61001.mail.yahoo.com> Message-ID: On Mon, 4 Oct 2004, Ali Polatel wrote: > What is the easiest way to send e-mails using Python? Can you show me a > sample not complicated script? Hi Ali, You may want to look at the 'email' documentation here: http://www.python.org/doc/lib/node510.html That page has a simple program that sends mail; it also includes other sample programs to do things like MIME attachments near the bottom. If you have questions with those examples, please feel free to ask questions about it. Good luck! From s.venter at ntlworld.com Mon Oct 4 16:13:29 2004 From: s.venter at ntlworld.com (Gerhard Venter) Date: Mon Oct 4 16:13:31 2004 Subject: [Tutor] Mail... In-Reply-To: <20041004135636.786.qmail@web61001.mail.yahoo.com> References: <20041004135636.786.qmail@web61001.mail.yahoo.com> Message-ID: <41615A89.1090008@ntlworld.com> Ali Polatel wrote: > and how can i find a host? > or can i programme a host? > thanks > > Hi Ali I can never remember to change my reply address from person to the list. The code I sent to you instead of the list was: import smtplib server = smtplib.SMTP('myrelayhost') server.set_debuglevel(1) server.sendmail("from@example.com", "myfriend@mydestination.net", "Subject:test email\n\n test") server.quit() For myrelayhost, you need to supply the hostname or IP address of an email SMTP server that will allow you to send. Being a Yahoo user you might not use this normally, but the SMTP server (relay host) you need to use is the one made available by the ISP/University/School/etc where you are connected. Ask your network administrator what to use. Gerhard From andre.roberge at ns.sympatico.ca Mon Oct 4 16:28:33 2004 From: andre.roberge at ns.sympatico.ca (=?UTF-8?B?QW5kcsOpIFJvYmVyZ2U=?=) Date: Mon Oct 4 16:28:30 2004 Subject: [Tutor] Tearoff=0 and Changing menu "title" using Tkinter In-Reply-To: <008101c4aa1a$ef026640$6400a8c0@andreroberge> References: <008101c4aa1a$ef026640$6400a8c0@andreroberge> Message-ID: <41615E11.1030901@ns.sympatico.ca> Recap: Using Tkinter as a GUI, I've been trying to change the labels (from English to French) on menu titles and items. Kent Johnson (twice!) explained how this could be done but, both times with setting tearoff=0 ... which may not always be desired. After looking some more on the web, I came accross the following text about "tearoff" on the http://infohost.nmt.edu/tcc/help/pubs/tkinter/menu.html site: " Normally, a menu can be torn off, the first position (position 0) in the list of choices is occupied by the tear-off element, and the additional choices are added starting at position 1. If you set *tearoff=0*, the menu will not have a tear-off feature, and choices will be added starting at position 0." So, if one wants to use tearable menus, all that is needed is to change the following three lines in the program below (for example): top = Menu(self) ## line 1 top.entryconfig(1, label="Fichier) ## line 2 top.entryconfig(1, label="File") ## line 3 I hope this can help others than me :-) [Thanks again, Kent] Andre Roberge ===== from Tkinter import * from tkFileDialog import askopenfilename def makemenu(self): top = Menu(self, tearoff=0) ## line 1 self.config(menu=top) def changeLang(): if v.get() == 'fr': fileMenu.entryconfig(0, label='Ouvrir') fileMenu.entryconfig(1, label='Quitter') top.entryconfig(0, label="Fichier) ## line 2 else: fileMenu.entryconfig(0, label='Open') fileMenu.entryconfig(1, label='Quit') top.entryconfig(0, label="File") ## line 3 def onOpen(): filename = askopenfilename() msg['text'] = filename fileMenu = Menu(top, tearoff=0) fileMenu.add_command(label='Open', command=onOpen) fileMenu.add_command(label='Quit', command=self.quit) top.add_cascade(label='File', menu=fileMenu) otherMenu = Menu(top, tearoff=0) top.add_cascade(label='Other', menu=otherMenu) LANGUAGES = [ ('English', 'en'), ('Francais', 'fr') ] v = StringVar() v.set('en') # initialize for text, language in LANGUAGES: lang = Radiobutton(root, text=text, variable=v, value=language, command=changeLang) lang.pack(anchor=W) msg = Label(root, text='test') msg.pack() if __name__ == '__main__': root = Tk() makemenu(root) root.mainloop() From flaxeater at yahoo.com Mon Oct 4 16:51:51 2004 From: flaxeater at yahoo.com (Chad Crabtree) Date: Mon Oct 4 16:51:54 2004 Subject: [Tutor] updating a list under conditions -- I think my way might "smell" Message-ID: <20041004145152.62709.qmail@web52604.mail.yahoo.com> Brian van den Broek wrote: > Hi All, > > I have a situation where I have a list of dictionary keys, > representing the order of occurrence of the dictionary values in some > datafile. (In my actual case, the values are themselves dictionaries, > storing metadata on the data items in the file.) > > I want to add a new value to the dictionary, putting its key in the > list such that it occurs after the first key that meets condition A > and before the first (among those strictly after the A-meeter) that > meets condition B. > > Given my data, I know condition A will be met by an early item in the > list of dictionary keys. Condition B might not be meet amongst the > post A-meeter items. (It is certain to be met before, but if it is, > meeting condition B is not relevant.) If it is not, I want to add my > new item at the end of the list that stores the orders. > > I have a way that works, but I'm not too sure about it's "smell". The > sample code below abstracts my working method into a manageable toy > example. (My actual use has fairly complicated conditions, and I found > it easier to write ones which just displayed the logic I am worried > about than to extract the relevant functions in a way that would leave > them short enough to post, yet still in a runnable state.) So, I'm not > advancing the broad design here as good. It's just a quick way to > illustrate the use of location = '' and the try/except block that > form the heart of my present solution. > > def find_first_not_multiple_of_10(target): > for i in target: > if 0 != my_dict[i] % 10: > # "Condition A" in the description above. > # Given my data, I am certain such an i exists early in > # the list I am working with. It could even be first. > return i > > def get_insert_location(target, start): > location = '' > # location given a value that evaluates to 'False' and that > # cannot serve as a list index. (Elsewhere in my code I need > # to be able to do an if test on location, so I need the False.) > for i in target[start:]: > if my_dict[i] > 90: > # "Condition B" in the description above. > # there may not be such an i. If there is, use its index. > location = target.index(i) > break > return location > > def update(target, item): > start_search = find_first_not_multiple_of_10(target) + 1 > # + 1 to get past the first A-meeter > location = get_insert_location(target, start_search) > try: > target[location:location] = [item] > except TypeError: > # error raised if there is no i in target[start:] such that > # my_dict[i] > 90. If raised, put new item at end. > target.append(item) > print target > > my_dict = {1:110, 2:35, 3:50, 4:80, 5:95, 6:70} > my_list = [1, 3, 2, 6, 5, 4] > my_list2 = [1, 3, 2, 6, 4] # The item meeting "Condition B" removed > > my_dict[7] = 45 > update(my_list, 7) > update(my_list2, 7) > > >>> > [1, 3, 2, 6, 7, 5, 4] > [1, 3, 2, 6, 4, 7] > > So, this way works as desired. But is there a better way to do this? > > I get that that is hard to answer seeing neither the data I am working > on, nor the reason I need the if test on location, etc. But my script > is pushing to 1,000 lines and the data is many MB, so that just isn't > practical to post ;-) > > Best and thanks to all, > > Brian vdB > I recently had need for a similar construct, basically I needed a dictionary that remembered the order in which I add them. I looked on google and found one that almost worked I updated it and it seems to behave well, it has both list like methods and dictionary methods, append, insert, sort and others I'm attaching the file it may be helpful to you. _______________________________ Do you Yahoo!? Declare Yourself - Register online to vote today! http://vote.yahoo.com -------------- next part -------------- from random import choice def uid(): hexuid=['1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'] return ''.join([choice(hexuid) for x in range(20)]) ################################################################################ # Sequential Dictionary Class # # # # by Wolfgang Grafen # # # # Version 0.0 29. June 1999 # # # # email to: WolfgangGrafen@gmx.de # # # # updated by Chad Crabtree # # # # Version 0.1 Sept 11 2004 # # # # email to: flaxeater@yahoo.com # # # ################################################################################ class seqdict(dict): def __init__(self,List=[],Dict={}): if type(List)==type({}): self.list = List.keys() self.dict = List.copy() elif List and not Dict: self.list=[] self.dict={} for i,j in List: self.list.append(i) self.dict[i]=j elif type(List)==type(Dict)==type([]): self.list = List self.dict = {} for key,value in map(None,List,Dict): self.dict[key] = value else: self.list,self.dict = List[:],Dict.copy() def append(self,key,value=''): "list like function that adds a key value pair to seqdict" if type(key)==type({}): for k,v in k.items(): if self.dict.has_key(k): self.list.remove(k) self.list.append(k) self.dict[k]=v if self.dict.has_key(key): self.list.remove(key) self.list.append(key) self.dict[key]=value def check(self): "checks to make sure that it is one to one" if len(self.dict)==len(self.list): l1=self.list[:];l1.sort() l2=self.dict.keys();l2.sort() return bool(l1==l2) return False def clear(self): "resets the seqdict to []" self.list=[];self.dict={} def copy(self): "returns deep copy of self" if self.__class__ is seqdict: return self.__class__(self.list,self.dict) return self[:] def __cmp__(self,other): "compars to seqdicts" return cmp(self.dict,other.dict) or cmp(self.list,other.list) def __getitem__(self,key): if type(key)==type([]): newdict={} for i in key: newdict[i]=self.dict[i] return self.__class__(key,newdict) return self.dict[key] def __setitem__(self,key,value): if not self.dict.has_key(key): self.list.append(key) self.dict[key]=value def __delitem__(self, key): del self.dict[key] self.list.remove(key) def __getslice__(self,start,stop): start = max(start,0); stop = max(stop,0) newdict = self.__class__() for key in self.list[start:stop]: newdict.dict[key]=self.dict[key] newdict.list[:]=self.list[start:stop] return newdict def __setslice__(self,start,stop,newdict): start = max(start,0); stop = max(stop,0) delindexes = [] for key in newdict.keys():# if the dict has #the keys then it delets them if self.dict.has_key(key): index = self.list.index(key) delindexes.append(index) if index < start: start = start - 1 stop = stop - 1 elif index >= stop: pass else: stop = stop - 1 delindexes.sort() delindexes.reverse() for index in delindexes: key = self.list[index] del self.dict[key] del self.list[index] for key in self.list[start:stop]: del self.dict[key] self.list[start:stop] = newdict.list[:] self.update(newdict.dict) def __delslice__(self, start, stop): start = max(start, 0); stop = max(stop, 0) for key in self.list[start:stop]: del self.dict[key] del self.list[start:stop] def __add__(self,other): "add's two seqdicts together" newdict = self.__class__() for key,value in self.items()+other.items(): newdict.append(key,value) return newdict def __radd__(self,other): "add's two seqdicts togheter" newdict = self.__class__() for key,value in other.items()+self.items(): newdict.append(key,value) return newdict def count(self,value): "count of values in dict should only ever be one" vallist = self.dict.values() return vallist.count(value) def extend(self,other): "similar to append may remove" self.update(other) def filter(self,function): "remove key,values by function non-destructive" liste=filter(function,self.list) dict = {} for i in liste: dict[i]=self.dict[i] return self.__class__(liste,dict) def get(self, key, failobj=None): "dictionary method return value of key" return self.dict.get(key, failobj) def index(self,key): "list like method that returns the index of a key" return self.list.index(key) def insert(self,i,x): "Insert by index, just like a list" y=seqdict(x) self.__setslice__(i,i,y) lst=[] temp={} for n,v in enumerate(self.list): if temp.has_key(v): temp[v]=(n,True) else: temp[v]=(0,False) for k,v in temp.items(): if v[1]: #if value (there's more than one instance in self.list) lst.append(v[0]) #append the index lst.sort() lst.reverse() for x in lst: #now remove duplicates del self.list[x] def items(self): "return tuple of key,value pairs for iteration" return map(None,self.list,self.values()) def has_key(self,key): "truth test for key existence" return self.dict.has_key(key) def keys(self): "return the keys of the seqdict" return self.list def map(self,function): "map function for the values" return self.__class__(map(function,self.items())) def values(self): "return a list of values in the order they where entered" nlist = [] for key in self.list: nlist.append(self.dict[key]) return nlist def __len__(self): "returns the length of the internal list" return len(self.list) def pop(self,key=None): "pop an item off the top removed" if key==None: pos = -1 key = self.list[pos] else: pos = self.list.index(key) tmp = self.dict[key] del self.dict[key] return {self.list.pop(pos):tmp} def push(self,key,value): "same as append" self.append(key,value) def reduce(self,function,start=None): "returns a single value based on funtion see reduce" return reduce(function,self.items(),start) def remove(self,key): "remove by key not index" del self.dict[key] self.list.remove(key) def reverse(self):self.list.reverse() def sort(self,*args): "sorts the keys optional algorythm to sort with" apply(self.list.sort,args) def split(self,function,Ignore=None): splitdict = seqdict() #self.__class__() for key in self.list: skey = function(key) if skey != Ignore: if not splitdict.has_key(skey): splitdict[skey] = self.__class__() splitdict[skey][key] = self.dict[key] return splitdict def swap(self): "turns all the values into keys and keys into values" tmp = self.__class__(map(lambda (x,y):(y,x),self.items())) self.list,self.dict = tmp.list,tmp.dict def update(self,newdict): for key,value in newdict.items(): self.__setitem__(key,value) def slice(self,From,To=None,Step=1): From = self.list.index(From) if To:To = self.list.index(To) else : To = From + 1 List = range(From,To,Step) def getitem(pos,self=self):return self.list[pos] return self.__getitem__(map(getitem,List)) def __repr__(self):return 'seqdict(\n%s,\n%s)'%(self.list,self.dict) def test(): #see if it really is a unique ID def testUID(): res={} for x in range(10000): z=uid() if res.has_key(z): res[z]+=1 else: res[z]=1 holder=False for k,v in res.iteritems(): if v>1: print "Failure Key:%s Value:%s" %(str(k),str(v)) holder=True if holder==False: print "No Duplicate UID's" testUID() def testseqdict(): globals()['d']=seqdict() d['dog']='cat' d['cat']='dog' d.insert(1,{'go':'fast',"fast":"go"}) print d.check() d.index('dog') print d testseqdict() if __name__=='__main__': test() --------------060709090809010706030901-- From s4046441 at student.uq.edu.au Mon Oct 4 17:50:02 2004 From: s4046441 at student.uq.edu.au (Ms Soo Chong) Date: Mon Oct 4 17:50:11 2004 Subject: [Tutor] Uploading image files Message-ID: <6fa9146f9766.6f97666fa914@uq.edu.au> Hi, I have a form where user can enter data into and upload some image files. When the user press the button "Add Record", these information have to automatically generated and save it to a specfic filename in a given directory. I can take care of the grabbing part of the data but I don't know how to deal with those uploaded image files which might be in either jpeg, bmp or others. I'm not sure how can I code it in a way that the program is able to saves all the data and images into a specfic filename in a given directory as well. Any help is greatly appreciated. Thank you. Cheers, Shufen From steegness at hotmail.com Mon Oct 4 18:28:20 2004 From: steegness at hotmail.com (Sean Steeg) Date: Mon Oct 4 18:29:09 2004 Subject: [Tutor] Re: Mail.... In-Reply-To: <20041004155010.5F4201E4010@bag.python.org> Message-ID: <000a01c4aa2f$2944dc20$0c00a8c0@SEANDESK> -----Original Message----- Message: 1 Date: Mon, 4 Oct 2004 06:32:06 -0700 (PDT) From: Ali Polatel Subject: [Tutor] Mail... To: Tutor@python.org Message-ID: <20041004133206.94661.qmail@web61001.mail.yahoo.com> Content-Type: text/plain; charset="us-ascii" What is the easiest way to send e-mails using Python? Can you show me a sample not complicated script? Regards ----------------------------------------------------- Ali, I wrote something not long ago that might help. The script itself isn't TOO complicated, and calling it from other modules was designed to be as simple as I could think of making it. It supports attachments too, which is pretty keen (if I do say so myself) It's also available at http://www.uselesspython.com/users/ssteeg/arch_Tech.html Sean -------------------- import smtplib, mimetypes, string, email, os from email.Encoders import encode_base64 from email.MIMEText import MIMEText from email.MIMEAudio import MIMEAudio from email.MIMEMultipart import MIMEMultipart from email.MIMEImage import MIMEImage from email.MIMEText import MIMEText from email.MIMEBase import MIMEBase class SimpleMessage: def __init__(self): self._files = [] def AttachFile(self, fullname): if not fullname in self._files: self._files.append(fullname) return 1 else: return 0 def DetachFile(self, fullname): if fullname in self._files: return self._files.pop(self._files.index(fullname)) else: return 0 def To(self, s): """If multiple recipients, use a [list] or separate with commas.""" if type(s) == type([]): self._to = s else: self._to = s.split(',') def Sender(self, s): self._sender = s def Subject(self, s): self._subject = s def Body(self, s): self._body = s def _prepletter(self): #super(SimpleMessage, self).__init__() #Body and headers. outer = MIMEMultipart() outer['Subject'] = self._subject outer['To'] = string.join(self._to, ',') outer['From'] = self._sender outer.preamble = 'MIME Message' outer.epilogue = '' body = MIMEText(self._body) outer.attach(body) for eachfile in self._files: ctype, encoding = mimetypes.guess_type(eachfile) if ctype is None or encoding is not None: ctype = 'application/octet-stream' maintype, subtype = ctype.split('/', 1) f = file(eachfile, 'rb') if maintype == 'text': inner = MIMEText(f.read(), _subtype=subtype) elif maintype == 'message': inner = email.message_from_file(f) elif maintype == 'image': inner = MIMEImage(f.read(), _subtype=subtype) elif maintype == 'audio': inner = MIMEAudio(f.read(), _subtype=subtype) else: inner = MIMEBase(maintype, subtype) inner.set_payload(f.read()) encode_base64(inner) f.close() inner.add_header('Content-Disposition', 'attachment', filename=os.path.basename(eachfile)) outer.attach(inner) return outer.as_string() def Send(self, host='localhost', u='', p=''): if not self._to: print "No recipients specified." return 0 sendtext = self._prepletter() server = smtplib.SMTP(host) if u: server.login(u, p) try: server.sendmail(self._sender, string.join(self._to, ','), sendtext) server.quit() except: return 0 return 1 ------------------------ From John.Ertl at fnmoc.navy.mil Mon Oct 4 18:40:19 2004 From: John.Ertl at fnmoc.navy.mil (Ertl, John) Date: Mon Oct 4 18:40:25 2004 Subject: [Tutor] IDLE? Message-ID: I am working on a new system RedHat Enterprise 3.0 and I cannot get idle to launch, I get the following error. ** IDLE can't import Tkinter. Your Python may not be configured for Tk. ** >From what I know Tkinter is part of the code and does not needed to be imported separately...is there some kind of special configure step I need to do? I found some stuff in the README about RedHat 9.0 and I tried it as well when I did one of the several reloads (but no luck). I google did not turn up anything but the same question unanswered...Where is the best place to look to track down what might be missing? I have installed Tk and Tcl. Any help is appreciated. John Ertl From bgailer at alum.rpi.edu Mon Oct 4 19:03:57 2004 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Mon Oct 4 19:02:52 2004 Subject: [Tutor] Method for 'scheduling' object actions In-Reply-To: <41614B8B.4090203@yahoo.com> References: <41614B8B.4090203@yahoo.com> Message-ID: <6.1.2.0.0.20041004110331.04972d48@mail.mric.net> At 07:09 AM 10/4/2004, gyrof wrote: >Hi, >I am designing an application in which several objects need to perform >certain actions according to the 'time' on a simulated clock. This clock >has no relationship with the actual system or wall clock time, but will >proceed from time=0 to time=end_time in some defined increments. Along the >way, objects need to be triggered to call certain of their methods when >the time reaches a certain point. > >For instance, >'time' action >------ ------ > 0 object A.start method is called > 0 object B.start method is called > 5 object A.grow method is called > 6 object B.grow method is called > 10 object B.pass_info_to_A method is called > 10 object A.slow_growth method is called > 12 object A.die method is called > 20 object B.end method is called > >I would like to come up with some sort of flexible and extensible >scheduler scheme in which these types of actions can take place. I have >read a bit about SimPy, which is a discrete event simulator, but this >seems overly complex to me and I'm not even sure if it's appropriate. Take a look at the sched module. Bob Gailer bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell From adeleinandjeremy at yahoo.com Mon Oct 4 20:06:31 2004 From: adeleinandjeremy at yahoo.com (Adelein and Jeremy) Date: Mon Oct 4 21:06:06 2004 Subject: [Tutor] IDLE? In-Reply-To: Message-ID: <20041004180631.35238.qmail@web50305.mail.yahoo.com> --- "Ertl, John" wrote: > I am working on a new system RedHat Enterprise 3.0 and I cannot get > idle to > launch, I get the following error. > > ** IDLE can't import Tkinter. Your Python may not be configured > for Tk. ** Sounds like your Python is not built to use Tkinter - common in RedHat systems, as Tcl/Tk is often not installed by default, and even if it is, the default library path is often incorrect as it seems to change from Tcl version to version. > > From what I know Tkinter is part of the code and does not needed > to be imported separately...is there some kind of special configure > step I need to do? Tkinter is a module. It always needs to be imported - that's waht makes it ``part of the code'' :-) > I have installed Tk and Tcl. Ah. You just did this? If so, then there is no way Python could have been built with Tkinter support as it had no Tk in sight. Time for the magical ./configure ./make ./install incantations, it seems. - Jeremy __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From bvande at po-box.mcgill.ca Mon Oct 4 21:03:58 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Mon Oct 4 21:08:45 2004 Subject: [Tutor] updating a list under conditions -- I think my way might "smell" In-Reply-To: <20041004145152.62709.qmail@web52604.mail.yahoo.com> References: <20041004145152.62709.qmail@web52604.mail.yahoo.com> Message-ID: <41619E9E.9010904@po-box.mcgill.ca> Hi All, To avoid a *really* long post (i.e. > 400 lines of quotation), I am giving a synopsis, with links to originals. I posted a question . Summary of my question: I was uncertain of my method of updating a list subject to two conditions, the second of which might not be met. If it wasn't met, I wanted the new list item at them end, otherwise I wanted it before the item that met the second condition, amongst the items after the one that met the first condition. I was was using an assignment like my_list[i:i] = new_item where i is the index of the item meeting the second condition. This works if there is such an item, but not if there isn't. So, I was starting with i as '', updating it if and when the second condition was met, and then wrapping the assignment in a try/except, with the accept block doing my_list.append(new_item). I was worried about the procedure perhaps "smelling" a bit, and asked if there was a better way. I mentioned that the list was to store order of appearance in a data structure of the items in a dictionary. Chad Crabtree posted a reply which gave me his reworking of Wolfgang Grafen's Sequential Dictionary Class . So, thanks Chad! That was a fair bit of code, and I am not yet too familiar with doing things the OOP way, so I haven't managed to grok it all yet. But, judging from what I have understood of it, it does look like something that would have made my overall program design smoother if I'd had it a week ago. Oh well, there will be a next time, I am sure :-) So thanks for the substantial help! I freely admit I may have missed the part of the class which would directly help with my list updating problem, but I don't seem to see anything in there that speaks to it. (My code-reading skills aren't orders better than my grasp of OOP, I'm afraid.) However, if anyone ends up hitting my original question with a google, I think I have a better way now. The relevant bit of my posted solution that left me unhappy was: def get_insert_location(target, start): location = '' # location given a value that evaluates to 'False' and that # cannot serve as a list index. (Elsewhere in my code I need # to be able to do an if test on location, so I need the False.) for i in target[start:]: if my_dict[i] > 90: # "Condition B" in the description above. # there may not be such an i. If there is, use its index. location = target.index(i) break return location def update(target, item): start_search = find_first_not_multiple_of_10(target) + 1 # function find_first_not_multiple_of_10 def'ed in my original post # omitted as not really of relevance here. # + 1 to get past the first A-meeter location = get_insert_location(target, start_search) try: target[location:location] = [item] except TypeError: # error raised if there is no i in target[start:] such that # my_dict[i] > 90. If raised, put new item at end. target.append(item) print target It has since occurred to me that in get_insert_location(target, start) above, I could just have location = len(target) at the beginning in place of location = '' Then, in update(target, item) target[location:location] = [item] will work, even if the second condition was not met. This gets rid of the try/except, at the cost of being able to do the needed if test on location. (As mentioned in the comments, I wanted location to evaluate to False if there was no item meeting the second condition. This is used elsewhere in my program from which the situation represented in my toy example that I posted is drawn from.) But I realized perhaps it wasn't a good idea to try to make location do two distinct jobs, so I replaced that with a separate name storing whether condition B was met. (In fact, in retrospect, my problem was caused by trying to make location do such a double duty.) And that, at least to my nose, removed the "smell". Anyway, this is more than long enough. But thanks again Chad for a most useful looking solution to using dicts together with order information of values. Best to all, Brian vdB From flaxeater at yahoo.com Mon Oct 4 20:32:41 2004 From: flaxeater at yahoo.com (Chad Crabtree) Date: Mon Oct 4 21:09:43 2004 Subject: [Tutor] IDLE? Message-ID: <20041004183241.55818.qmail@web52605.mail.yahoo.com> Ertl, John wrote: >I am working on a new system RedHat Enterprise 3.0 and I cannot get idle to >launch, I get the following error. > >** IDLE can't import Tkinter. Your Python may not be configured for Tk. ** > >>From what I know Tkinter is part of the code and does not needed to be >imported separately...is there some kind of special configure step I need to >do? I found some stuff in the README about RedHat 9.0 and I tried it as >well when I did one of the several reloads (but no luck). I google did not >turn up anything but the same question unanswered...Where is the best place >to look to track down what might be missing? I have installed Tk and Tcl. > >Any help is appreciated. > >John Ertl > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > > Make sure that TCL and TK are installed _______________________________ Do you Yahoo!? Declare Yourself - Register online to vote today! http://vote.yahoo.com From bvande at po-box.mcgill.ca Mon Oct 4 21:49:27 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Mon Oct 4 21:51:41 2004 Subject: Sequnetial Dictionaries was Re: [Tutor] updating a list under conditions -- I think my way might "smell" In-Reply-To: <41619E9E.9010904@po-box.mcgill.ca> References: <20041004145152.62709.qmail@web52604.mail.yahoo.com> <41619E9E.9010904@po-box.mcgill.ca> Message-ID: <4161A947.4000701@po-box.mcgill.ca> Brian van den Broek said unto the world upon 2004-10-04 15:03: > Chad Crabtree posted a reply > > which gave me his reworking of Wolfgang Grafen's Sequential Dictionary > Class > . > In case anyone else is interested in the Sequential Dictionary class that Chad posted, I just found that Wolfgang Grafen's original version has a fair bit of documentation in several formats available at . Best to all, Brian vdB From tim at johnsons-web.com Tue Oct 5 00:40:40 2004 From: tim at johnsons-web.com (Tim Johnson) Date: Tue Oct 5 00:40:23 2004 Subject: [Tutor] Looking for WebKit Message-ID: <20041004224040.GB20593@johnsons-web.com> Hello: At the following URL: http://wiki.w4py.org/pdfcreationwithreportlab.html there is a reference to a python "package" called WebKit. Does anyone know where that is available. I can't seem to locate it on my system. (using RedHat 9.0 with Python 2.3.4) thanks tim -- Tim Johnson http://www.alaska-internet-solutions.com From tim at johnsons-web.com Tue Oct 5 01:07:15 2004 From: tim at johnsons-web.com (Tim Johnson) Date: Tue Oct 5 01:06:57 2004 Subject: [Tutor] Looking for WebKit In-Reply-To: <20041004224040.GB20593@johnsons-web.com> References: <20041004224040.GB20593@johnsons-web.com> Message-ID: <20041004230715.GC20593@johnsons-web.com> Found it http://prdownloads.sourceforge.net/webware/Webware-0.8.1.tar.gz?download Under "WebWare" tj * Tim Johnson [041004 14:49]: > Hello: > At the following URL: > http://wiki.w4py.org/pdfcreationwithreportlab.html > there is a reference to a python "package" called > WebKit. > > Does anyone know where that is available. I can't > seem to locate it on my system. > (using RedHat 9.0 with Python 2.3.4) > > thanks > tim > -- > Tim Johnson > http://www.alaska-internet-solutions.com > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Tim Johnson http://www.alaska-internet-solutions.com From tim at johnsons-web.com Tue Oct 5 01:17:01 2004 From: tim at johnsons-web.com (Tim Johnson) Date: Tue Oct 5 01:16:43 2004 Subject: [Tutor] import'ing problems (path) Message-ID: <20041004231701.GD20593@johnsons-web.com> Hello Pythonists: I have installed a python package called webware at the following path: /home/tim/downloads/python/Webware-0.8.1 I have the following python code: sys.path.append('/home/tim/downloads/python/Webware-0.8.1') print sys.path ## shows '/home/tim/downloads/python/Webware-0.8.1'. ## as a member of sys.path I need class Path which resides in /home/tim/downloads/python/Webware-0.8.1/WebKit/Page.py(pyc) to import it, I use the following statement: from WebKit.Page import Page and I get the following error message: "No module named WebKit.Page" What am I doing wrong and what needs to be done t correct it? thanks tim -- Tim Johnson http://www.alaska-internet-solutions.com From tim at johnsons-web.com Tue Oct 5 01:24:48 2004 From: tim at johnsons-web.com (Tim Johnson) Date: Tue Oct 5 01:24:31 2004 Subject: [Tutor] import'ing problems (path) In-Reply-To: <20041004231701.GD20593@johnsons-web.com> References: <20041004231701.GD20593@johnsons-web.com> Message-ID: <20041004232448.GE20593@johnsons-web.com> * Tim Johnson [041004 15:23]: > Hello Pythonists: > I have installed a python package called webware > at the following path: > /home/tim/downloads/python/Webware-0.8.1 > > I have the following python code: > sys.path.append('/home/tim/downloads/python/Webware-0.8.1') > print sys.path ## shows '/home/tim/downloads/python/Webware-0.8.1'. > ## as a member of sys.path > I need class Path which resides in OOPS! typo here. Should be I need class Page which resides in /home/tim/downloads/python/Webware-0.8.1/WebKit/Page.py(pyc) (coffee, I need coffee!) > to import it, I use the following statement: > from WebKit.Page import Page > > and I get the following error message: > "No module named WebKit.Page" > > What am I doing wrong and what needs to be done t > correct it? > > thanks > tim > -- > Tim Johnson > http://www.alaska-internet-solutions.com > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Tim Johnson http://www.alaska-internet-solutions.com From leomandy at hotmail.com Tue Oct 5 03:55:37 2004 From: leomandy at hotmail.com (mandy bowen) Date: Tue Oct 5 03:57:13 2004 Subject: [Tutor] What is the best way to save and reload? Message-ID: I am VERY new at this. I have a program and I want to save and reload it so that it can remember what it has already learned. I have been reading the tutorials, etc. but I am not real sure if I understand what I am supposed to do, or where it gets added to the code. A little guidance would really help. Thank you. _________________________________________________________________ Don’t just search. Find. Check out the new MSN Search! http://search.msn.click-url.com/go/onm00200636ave/direct/01/ From leomandy at hotmail.com Tue Oct 5 04:08:48 2004 From: leomandy at hotmail.com (mandy b) Date: Tue Oct 5 04:10:38 2004 Subject: [Tutor] What is the best way to save and reload? Message-ID: I have a program and I am wondering how I go about saving and reloading it so that it remembers what happens each time it is run? I have been reading the tutorials, but I do not understand where I am supposed to insert this (pickle) into the code I already have. I am not even sure of how to pickle the exact info I want to be saved from each run. I am very new at this, and any guidance would be helpful. Thank you. _________________________________________________________________ On the road to retirement? Check out MSN Life Events for advice on how to get there! http://lifeevents.msn.com/category.aspx?cid=Retirement From flaxeater at yahoo.com Tue Oct 5 05:42:50 2004 From: flaxeater at yahoo.com (Chad Crabtree) Date: Tue Oct 5 05:42:52 2004 Subject: [Tutor] import'ing problems (path) Message-ID: <20041005034250.30411.qmail@web52605.mail.yahoo.com> Tim Johnson wrote: >>to import it, I use the following statement: >>from WebKit.Page import Page >> >>and I get the following error message: >>"No module named WebKit.Page" >> >>What am I doing wrong and what needs to be done t >>correct it? >> >> >> I think (not sure) that you need to try from WebKit import Page your previous import directive says from webkit package import Page.py then import Page class from there. Hope This helps. __________________________________ Do you Yahoo!? Yahoo! Mail Address AutoComplete - You start. We finish. http://promotions.yahoo.com/new_mail From bgailer at alum.rpi.edu Tue Oct 5 05:50:25 2004 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Tue Oct 5 05:49:12 2004 Subject: [Tutor] What is the best way to save and reload? In-Reply-To: References: Message-ID: <6.1.2.0.0.20041004215006.04806568@mail.mric.net> At 08:08 PM 10/4/2004, mandy b wrote: >I have a program and I am wondering how I go about saving and reloading it >so that it remembers what happens each time it is run? I have been >reading the tutorials, but I do not understand where I am supposed to >insert this (pickle) into the code I already have. I am not even sure of >how to pickle the exact info I want to be saved from each run. I am very >new at this, and any guidance would be helpful. Take a look at the shelve module. Bob Gailer bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell From tim at johnsons-web.com Tue Oct 5 06:13:42 2004 From: tim at johnsons-web.com (Tim Johnson) Date: Tue Oct 5 06:13:24 2004 Subject: [Tutor] import'ing problems (path) In-Reply-To: <20041005034250.30411.qmail@web52605.mail.yahoo.com> References: <20041005034250.30411.qmail@web52605.mail.yahoo.com> Message-ID: <20041005041342.GC27230@johnsons-web.com> * Chad Crabtree [041004 19:54]: > Tim Johnson wrote: > > >>to import it, I use the following statement: > >>from WebKit.Page import Page > >> > >>and I get the following error message: > >>"No module named WebKit.Page" > >> > >>What am I doing wrong and what needs to be done t > >>correct it? > >> > >> > >> Hi Chad: > I think (not sure) that you need to try > > from WebKit import Page Sorry. That gives me the error message: No module named WebKit WebKit is a directory /home/tim/downloads/python/Webware-0.8.1/WebKit Page.py - full path: /home/tim/downloads/python/Webware-0.8.1/WebKit/Page.py is a file, and contains the Page class. :-) In case you haven't noticed, I don't fully comprehend how python handles imports, namespaces and paths. thanks! tim -- Tim Johnson http://www.alaska-internet-solutions.com From jfabiani at yolo.com Tue Oct 5 06:36:11 2004 From: jfabiani at yolo.com (John Fabiani) Date: Tue Oct 5 06:36:16 2004 Subject: [Tutor] deciding when to use site-packages Message-ID: <200410042136.11986.jfabiani@yolo.com> Hi, I was wondering if there is a rule of thumb that everyone uses to decide when to install packages in the site-packages directory vs something like /home/user/module. TIA John From doug.penny at gmail.com Tue Oct 5 15:00:54 2004 From: doug.penny at gmail.com (Doug Penny) Date: Tue Oct 5 15:00:56 2004 Subject: [Tutor] strange eval In-Reply-To: References: <6.1.0.6.0.20041004092150.0289d2c8@mail4.skillsoft.com> Message-ID: Thanks for the info. Good point about using eval(). They have been shown int(), but for some reason this student started using eval() and I just didn't think about guiding him back to int(). Doug On Mon, 4 Oct 2004 07:05:59 -0700 (PDT), Danny Yoo wrote: > > On Mon, 4 Oct 2004, Kent Johnson wrote: > > > Number literals starting with 0 are interpreted as _octal_! See > > http://docs.python.org/ref/integers.html > > >>> eval('010') > > 8 > > >>> eval('0100') > > 64 > > > > 8 and 9 are not valid octal digits, hence the error. > > Hi Doug, > > And don't use eval() to get numbers from strings: it's far too powerful a > tool to be used casually! *grin* > > Use int() instead: it's a converter to integers: > > ### > >>> int('010') > 10 > >>> int('0100') > 100 > ### > > If we really want an octal interpretation, we can explicitely tell int() > what base to use: > > ### > >>> int('010', 8) > 8 > >>> int('0100', 8) > 64 > ### > > I also think it's not a good thing to teach students to use eval() > without showing the repercussions. eval() has the same access to the > Python runtime as the running program, and that's dangerous if not handled > properly. We can talk about the security implications of eval() if you'd > like. > > Hope this helps! > > From kent_johnson at skillsoft.com Tue Oct 5 15:04:23 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Tue Oct 5 15:04:59 2004 Subject: [Tutor] import'ing problems (path) In-Reply-To: <20041004231701.GD20593@johnsons-web.com> References: <20041004231701.GD20593@johnsons-web.com> Message-ID: <6.1.0.6.0.20041005090143.0289b108@mail4.skillsoft.com> Tim, Did you run the WebWare installer or just unpack the distribution file? Usually third-party libraries are installed in Python/lib/site-packages. This directory is automatically added to sys.path. Alternatively you can make a permanent, global modification to sys.path by creating a file Python/lib/site-packages/sitecustomize.py containing the two lines import sys sys.path.append('/home/tim/downloads/python/Webware-0.8.1') Kent At 03:17 PM 10/4/2004 -0800, Tim Johnson wrote: >Hello Pythonists: > I have installed a python package called webware >at the following path: >/home/tim/downloads/python/Webware-0.8.1 > >I have the following python code: >sys.path.append('/home/tim/downloads/python/Webware-0.8.1') >print sys.path ## shows '/home/tim/downloads/python/Webware-0.8.1'. > ## as a member of sys.path >I need class Path which resides in >/home/tim/downloads/python/Webware-0.8.1/WebKit/Page.py(pyc) >to import it, I use the following statement: >from WebKit.Page import Page > >and I get the following error message: >"No module named WebKit.Page" > >What am I doing wrong and what needs to be done t >correct it? > >thanks >tim >-- >Tim Johnson > http://www.alaska-internet-solutions.com >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From mknowles at fs.fed.us Tue Oct 5 17:35:55 2004 From: mknowles at fs.fed.us (Michael Knowles) Date: Tue Oct 5 17:36:45 2004 Subject: [Tutor] Reading text files Message-ID: Is there any source which talks in detail about reading text files? I've purchased "Python Programming for the Absolute Beginner" and there is a chapter on files and exceptions but it seems pretty basic. Specifically, I'm interested in how I would import specific columns or rows for text files. Thanks in advance, Mike ******************************************* Mike Knowles Information Systems Analyst SI International USDA, Forest Service, Rocky Mountain Research Station 2150 Centre Ave, Bldg A, Suite 361 Ft. Collins, CO 80526 Phone: (970) 295-5979 Fax: (970) 295-5959 e-mail: mknowles@fs.fed.us ******************************************* From flaxeater at yahoo.com Tue Oct 5 18:00:58 2004 From: flaxeater at yahoo.com (Chad Crabtree) Date: Tue Oct 5 18:02:08 2004 Subject: [Tutor] Reading text files Message-ID: <20041005160059.47376.qmail@web52601.mail.yahoo.com> Michael Knowles wrote: >Is there any source which talks in detail about reading text files? I've >purchased "Python Programming for the Absolute Beginner" and there is a >chapter on files and exceptions but it seems pretty basic. Specifically, >I'm interested in how I would import specific columns or rows for text >files. > >Thanks in advance, >Mike > > > > Do you mean like Comma Separated Files? __________________________________ Do you Yahoo!? Yahoo! Mail - 50x more storage than other providers! http://promotions.yahoo.com/new_mail From kent_johnson at skillsoft.com Tue Oct 5 18:08:44 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Tue Oct 5 18:08:48 2004 Subject: [Tutor] Reading text files In-Reply-To: References: Message-ID: <6.1.0.6.0.20041005115310.02898650@mail4.skillsoft.com> Python text processing tends to be pretty ad hoc. Built-in facilities such as string.split and regular expressions are very handy. It's very easy to iterate through lines in a text file and extract a bit of information from each line. Extracting the second word from each line in a file and building a list from the results might be as simple as this: data = [ line.split()[1] for line in open('myfile.txt')] If you can give us a specific example of what you want to do we can point you to the tools that can help. Some things you might be interested in: I don't have a copy of it handy to see what it says about files, but Learning Python tends to have a lot more detail than Python Programming for the absolute beginner. If you are finding PPftab too thin you might prefer Learning Python: http://www.oreilly.com/catalog/lpython2/ The csv module might be useful depending on the format of your input data: http://docs.python.org/lib/module-csv.html The Python Cookbook has a section about text processing: http://www.oreilly.com/catalog/pythoncook David Mertz has an entire book on text processing in Python, but it might be difficult for a beginner: http://gnosis.cx/TPiP/ Kent At 09:35 AM 10/5/2004 -0600, Michael Knowles wrote: >Is there any source which talks in detail about reading text files? I've >purchased "Python Programming for the Absolute Beginner" and there is a >chapter on files and exceptions but it seems pretty basic. Specifically, >I'm interested in how I would import specific columns or rows for text >files. > >Thanks in advance, >Mike > > >******************************************* >Mike Knowles >Information Systems Analyst >SI International >USDA, Forest Service, Rocky Mountain Research Station >2150 Centre Ave, Bldg A, Suite 361 >Ft. Collins, CO 80526 >Phone: (970) 295-5979 >Fax: (970) 295-5959 >e-mail: mknowles@fs.fed.us >******************************************* > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From leomandy at hotmail.com Tue Oct 5 20:14:20 2004 From: leomandy at hotmail.com (mandy b) Date: Tue Oct 5 20:25:26 2004 Subject: [Tutor] What is the best way to save and reload? Message-ID: I have looked at that too, and have tried both, but is there a certain place it needs to be in the code? Because nothing I have done has worked. Thanks, mandy b >From: Bob Gailer >To: "mandy b" , tutor@python.org >Subject: Re: [Tutor] What is the best way to save and reload? >Date: Mon, 04 Oct 2004 21:50:25 -0600 > >At 08:08 PM 10/4/2004, mandy b wrote: >>I have a program and I am wondering how I go about saving and reloading it >>so that it remembers what happens each time it is run? I have been >>reading the tutorials, but I do not understand where I am supposed to >>insert this (pickle) into the code I already have. I am not even sure of >>how to pickle the exact info I want to be saved from each run. I am very >>new at this, and any guidance would be helpful. > >Take a look at the shelve module. > >Bob Gailer >bgailer@alum.rpi.edu >303 442 2625 home >720 938 2625 cell > _________________________________________________________________ Express yourself instantly with MSN Messenger! Download today - it's FREE! http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ From tim at johnsons-web.com Tue Oct 5 20:29:18 2004 From: tim at johnsons-web.com (Tim Johnson) Date: Tue Oct 5 20:28:58 2004 Subject: [Tutor] import'ing problems (path) In-Reply-To: <6.1.0.6.0.20041005090143.0289b108@mail4.skillsoft.com> References: <20041004231701.GD20593@johnsons-web.com> <6.1.0.6.0.20041005090143.0289b108@mail4.skillsoft.com> Message-ID: <20041005182918.GI27230@johnsons-web.com> * Kent Johnson [041005 05:10]: > Tim, > Hi Kent: > Did you run the WebWare installer or just unpack the distribution file? I ran the Webware installer, it did not appear to copy files elsewhere. > Usually third-party libraries are installed in Python/lib/site-packages. So... I reinstalled, by unpacking to /usr/local/lib/python2.3/site-packages/Webware, then ran the webware installer again, said installation was successful. Now, Page.pyc is at /usr/local/lib/python2.3/site-packages/Webware/WebKit Now, if I code: import Webware.WebKit ## and stop the program here, there is no ## ImportError exception thrown If I code import Webware.WebKit.Page ## I get the ImportError: "No module named MiscUtils" MiscUtils is a directory at the same level ast WebKit. Not sure where to go from here....... whew! tim > This directory is automatically added to sys.path. > > Alternatively you can make a permanent, global modification to sys.path by > creating a file > Python/lib/site-packages/sitecustomize.py > containing the two lines > import sys > sys.path.append('/home/tim/downloads/python/Webware-0.8.1') -- Tim Johnson http://www.alaska-internet-solutions.com From kent_johnson at skillsoft.com Tue Oct 5 20:45:37 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Tue Oct 5 20:45:36 2004 Subject: [Tutor] import'ing problems (path) In-Reply-To: <20041005182918.GI27230@johnsons-web.com> References: <20041004231701.GD20593@johnsons-web.com> <6.1.0.6.0.20041005090143.0289b108@mail4.skillsoft.com> <20041005182918.GI27230@johnsons-web.com> Message-ID: <6.1.0.6.0.20041005144301.02a5dc00@mail4.skillsoft.com> It looks like WebKit doesn't want to see the Webware level in the package hierarchy. You could take everything out of the Webware directory and put it directly in site-packages or add the Webware directory to sys.path as I described before. Then try import WebKit.Page (without the WebWare prefix). You might have better luck with this on the Webware mailing list. Kent At 10:29 AM 10/5/2004 -0800, Tim Johnson wrote: >* Kent Johnson [041005 05:10]: > > Tim, > > > Hi Kent: > > Did you run the WebWare installer or just unpack the distribution file? > > I ran the Webware installer, it did not appear to copy files > elsewhere. > > Usually third-party libraries are installed in Python/lib/site-packages. > > So... I reinstalled, by unpacking to > /usr/local/lib/python2.3/site-packages/Webware, > then ran the webware installer again, said installation was > successful. > > Now, Page.pyc is at > /usr/local/lib/python2.3/site-packages/Webware/WebKit > Now, if I code: > import Webware.WebKit ## and stop the program here, there is no > ## ImportError exception thrown > If I code > import Webware.WebKit.Page > ## I get the ImportError: "No module named MiscUtils" > MiscUtils is a directory at the same level ast WebKit. > > Not sure where to go from here....... > whew! > tim > > > This directory is automatically added to sys.path. > > > > Alternatively you can make a permanent, global modification to sys.path by > > creating a file > > Python/lib/site-packages/sitecustomize.py > > containing the two lines > > import sys > > sys.path.append('/home/tim/downloads/python/Webware-0.8.1') > >-- >Tim Johnson > http://www.alaska-internet-solutions.com >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From tim at johnsons-web.com Tue Oct 5 20:53:59 2004 From: tim at johnsons-web.com (Tim Johnson) Date: Tue Oct 5 20:53:35 2004 Subject: [Tutor] import'ing problems (path) In-Reply-To: <6.1.0.6.0.20041005144301.02a5dc00@mail4.skillsoft.com> References: <20041004231701.GD20593@johnsons-web.com> <6.1.0.6.0.20041005090143.0289b108@mail4.skillsoft.com> <20041005182918.GI27230@johnsons-web.com> <6.1.0.6.0.20041005144301.02a5dc00@mail4.skillsoft.com> Message-ID: <20041005185359.GJ27230@johnsons-web.com> * Kent Johnson [041005 10:51]: > It looks like WebKit doesn't want to see the Webware level in the package > hierarchy. You could take everything out of the Webware directory and put > it directly in site-packages or add the Webware directory to sys.path as I > described before. Then try import WebKit.Page (without the WebWare prefix). > > You might have better luck with this on the Webware mailing list. Thanks Kent: I just got on their mailing list and browsed their archives. I see a similar problem there with a large number of emails regading it, but don't see a resolution. regards tim > Kent > > At 10:29 AM 10/5/2004 -0800, Tim Johnson wrote: > >* Kent Johnson [041005 05:10]: > >> Tim, > >> > > Hi Kent: > >> Did you run the WebWare installer or just unpack the distribution file? > > > > I ran the Webware installer, it did not appear to copy files > > elsewhere. > >> Usually third-party libraries are installed in Python/lib/site-packages. > > > > So... I reinstalled, by unpacking to > > /usr/local/lib/python2.3/site-packages/Webware, > > then ran the webware installer again, said installation was > > successful. > > > > Now, Page.pyc is at > > /usr/local/lib/python2.3/site-packages/Webware/WebKit > > Now, if I code: > > import Webware.WebKit ## and stop the program here, there is no > > ## ImportError exception thrown > > If I code > > import Webware.WebKit.Page > > ## I get the ImportError: "No module named MiscUtils" > > MiscUtils is a directory at the same level ast WebKit. > > > > Not sure where to go from here....... > > whew! > > tim > > > >> This directory is automatically added to sys.path. > >> > >> Alternatively you can make a permanent, global modification to sys.path > >by > >> creating a file > >> Python/lib/site-packages/sitecustomize.py > >> containing the two lines > >> import sys > >> sys.path.append('/home/tim/downloads/python/Webware-0.8.1') > > > >-- > >Tim Johnson > > http://www.alaska-internet-solutions.com > >_______________________________________________ > >Tutor maillist - Tutor@python.org > >http://mail.python.org/mailman/listinfo/tutor > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Tim Johnson http://www.alaska-internet-solutions.com From Mark.Kels at gmail.com Tue Oct 5 20:56:52 2004 From: Mark.Kels at gmail.com (Mark Kels) Date: Tue Oct 5 20:57:00 2004 Subject: [Tutor] What is the best way to save and reload? In-Reply-To: References: Message-ID: Using the shelve module is like using a dictionarty. The only difference is that you must open the file first, and it is done like this: book = shelve.open("addresses") Here is a simple tutorial about shelving objects - http://www.wdvl.com/Authoring/Languages/Python/Quick/python6_3.html Good luck!! From tim at johnsons-web.com Tue Oct 5 21:11:36 2004 From: tim at johnsons-web.com (Tim Johnson) Date: Tue Oct 5 21:11:14 2004 Subject: [Tutor] import'ing problems (path) P.S.!! In-Reply-To: <6.1.0.6.0.20041005144301.02a5dc00@mail4.skillsoft.com> References: <20041004231701.GD20593@johnsons-web.com> <6.1.0.6.0.20041005090143.0289b108@mail4.skillsoft.com> <20041005182918.GI27230@johnsons-web.com> <6.1.0.6.0.20041005144301.02a5dc00@mail4.skillsoft.com> Message-ID: <20041005191136.GK27230@johnsons-web.com> * Kent Johnson [041005 10:51]: > It looks like WebKit doesn't want to see the Webware level in the package > hierarchy. You could take everything out of the Webware directory and put > it directly in site-packages or add the Webware directory to sys.path as I > described before. Then try import WebKit.Page (without the WebWare prefix). Okay! add the following line: sys.path.append('/usr/local/lib/python2.3/site-packages/Webware') and the import is successful. This is an excercise in understanding the python import protocol, and I would welcome References to documentation of the topic so that I may better understand it. Thanks for the support Kent. tj > You might have better luck with this on the Webware mailing list. > > Kent > > At 10:29 AM 10/5/2004 -0800, Tim Johnson wrote: > >* Kent Johnson [041005 05:10]: > >> Tim, > >> > > Hi Kent: > >> Did you run the WebWare installer or just unpack the distribution file? > > > > I ran the Webware installer, it did not appear to copy files > > elsewhere. > >> Usually third-party libraries are installed in Python/lib/site-packages. > > > > So... I reinstalled, by unpacking to > > /usr/local/lib/python2.3/site-packages/Webware, > > then ran the webware installer again, said installation was > > successful. > > > > Now, Page.pyc is at > > /usr/local/lib/python2.3/site-packages/Webware/WebKit > > Now, if I code: > > import Webware.WebKit ## and stop the program here, there is no > > ## ImportError exception thrown > > If I code > > import Webware.WebKit.Page > > ## I get the ImportError: "No module named MiscUtils" > > MiscUtils is a directory at the same level ast WebKit. > > > > Not sure where to go from here....... > > whew! > > tim > > > >> This directory is automatically added to sys.path. > >> > >> Alternatively you can make a permanent, global modification to sys.path > >by > >> creating a file > >> Python/lib/site-packages/sitecustomize.py > >> containing the two lines > >> import sys > >> sys.path.append('/home/tim/downloads/python/Webware-0.8.1') > > > >-- > >Tim Johnson > > http://www.alaska-internet-solutions.com > >_______________________________________________ > >Tutor maillist - Tutor@python.org > >http://mail.python.org/mailman/listinfo/tutor > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Tim Johnson http://www.alaska-internet-solutions.com From kent_johnson at skillsoft.com Tue Oct 5 21:30:32 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Tue Oct 5 21:30:29 2004 Subject: [Tutor] import'ing problems (path) P.S.!! In-Reply-To: <20041005191136.GK27230@johnsons-web.com> References: <20041004231701.GD20593@johnsons-web.com> <6.1.0.6.0.20041005090143.0289b108@mail4.skillsoft.com> <20041005182918.GI27230@johnsons-web.com> <6.1.0.6.0.20041005144301.02a5dc00@mail4.skillsoft.com> <20041005191136.GK27230@johnsons-web.com> Message-ID: <6.1.0.6.0.20041005152558.027ff970@mail4.skillsoft.com> The documentation and source for the library module site.py is one place to look. It has some comments explaining how sys.path is set up, the code to actually do it, and the hook to import sitecustomize.py. There's also a little bit of info in the docs for sys.path (in the module docs). Kent At 11:11 AM 10/5/2004 -0800, Tim Johnson wrote: >* Kent Johnson [041005 10:51]: > > It looks like WebKit doesn't want to see the Webware level in the package > > hierarchy. You could take everything out of the Webware directory and put > > it directly in site-packages or add the Webware directory to sys.path as I > > described before. Then try import WebKit.Page (without the WebWare prefix). > > Okay! add the following line: > sys.path.append('/usr/local/lib/python2.3/site-packages/Webware') > and the import is successful. > > This is an excercise in understanding the python import protocol, > and I would welcome References to documentation of the topic so > that I may better understand it. > > Thanks for the support Kent. > tj > > > You might have better luck with this on the Webware mailing list. > > > > Kent > > > > At 10:29 AM 10/5/2004 -0800, Tim Johnson wrote: > > >* Kent Johnson [041005 05:10]: > > >> Tim, > > >> > > > Hi Kent: > > >> Did you run the WebWare installer or just unpack the distribution file? > > > > > > I ran the Webware installer, it did not appear to copy files > > > elsewhere. > > >> Usually third-party libraries are installed in Python/lib/site-packages. > > > > > > So... I reinstalled, by unpacking to > > > /usr/local/lib/python2.3/site-packages/Webware, > > > then ran the webware installer again, said installation was > > > successful. > > > > > > Now, Page.pyc is at > > > /usr/local/lib/python2.3/site-packages/Webware/WebKit > > > Now, if I code: > > > import Webware.WebKit ## and stop the program here, there is no > > > ## ImportError exception thrown > > > If I code > > > import Webware.WebKit.Page > > > ## I get the ImportError: "No module named MiscUtils" > > > MiscUtils is a directory at the same level ast WebKit. > > > > > > Not sure where to go from here....... > > > whew! > > > tim > > > > > >> This directory is automatically added to sys.path. > > >> > > >> Alternatively you can make a permanent, global modification to sys.path > > >by > > >> creating a file > > >> Python/lib/site-packages/sitecustomize.py > > >> containing the two lines > > >> import sys > > >> sys.path.append('/home/tim/downloads/python/Webware-0.8.1') > > > > > >-- > > >Tim Johnson > > > http://www.alaska-internet-solutions.com > > >_______________________________________________ > > >Tutor maillist - Tutor@python.org > > >http://mail.python.org/mailman/listinfo/tutor > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > >-- >Tim Johnson > http://www.alaska-internet-solutions.com >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From mknowles at fs.fed.us Tue Oct 5 22:22:34 2004 From: mknowles at fs.fed.us (Michael Knowles) Date: Tue Oct 5 22:45:26 2004 Subject: [Tutor] Summing across a row In-Reply-To: <20041005185338.4C2C71E400E@bag.python.org> Message-ID: I've been successful in reading in a comma-delimited text file and summing the columns but I can't figure out how to sum across a row. Ex. text file: 1, 2, 3, 4 =====> ?? Haven't figured this out 5, 6, 7, 8 =====> ?? 9, 10, 11, 12 ==> ?? ========= 15, 18, 21, 24 ===> I 've figured this out Thanks, Mike ******************************************* Mike Knowles Information Systems Analyst SI International USDA, Forest Service, Rocky Mountain Research Station 2150 Centre Ave, Bldg A, Suite 361 Ft. Collins, CO 80526 Phone: (970) 295-5979 Fax: (970) 295-5959 e-mail: mknowles@fs.fed.us ******************************************* From keridee at jayco.net Wed Oct 6 01:43:47 2004 From: keridee at jayco.net (Jacob S.) Date: Wed Oct 6 02:56:47 2004 Subject: [Tutor] List intersect References: <20040927171247.GA22220@qwestip.net> Message-ID: <000101c4ab3f$7468a180$265428cf@JSLAPTOP> Hello, I don't know exactly if this is what you're trying to do, but... Couldn't you use the expand attribute of lists? For ex. >>>a = ['usrc','recs','user',resu'] >>>b = ['brea','reab','earb','baer'] >>>a = a.expand(b) >>>print a ['usrc','recs','user',resu','brea','reab','earb','baer'] Hope this helps. (Though it probably doesn't...) From keridee at jayco.net Wed Oct 6 01:52:36 2004 From: keridee at jayco.net (Jacob S.) Date: Wed Oct 6 02:56:51 2004 Subject: [Tutor] How do I print a file? Message-ID: <000201c4ab3f$7547b6e0$265428cf@JSLAPTOP> Hello guys! My first ever question to ask you is... How do you print to a parallel port or maybe a USB port? For ex. Say I have file 'myfile.txt', and I wish to print it out hardcopy. How would I go about telling python2.3 to take control of the printer? I'm running Windows XP. I would prefer to know the USB route - if it makes any difference. I would not mind knowing the other ways for reference later... Thanks in advance for any help I get, Jacob Schmidt From keridee at jayco.net Wed Oct 6 03:16:15 2004 From: keridee at jayco.net (Jacob S.) Date: Wed Oct 6 03:16:10 2004 Subject: [Tutor] Summing across a row References: Message-ID: <001b01c4ab42$28e257d0$265428cf@JSLAPTOP> Hello, I don't know if this will help or not, but try this. m = open('mytext'.txt) m.read() '\n'.split(m) for line in m: linetotal = sum(line) print linetotal I hope this helps you, even though, as usual, I'm clueless about the purpose of others' scripts. Jacob Schmidt From kent_johnson at skillsoft.com Wed Oct 6 04:10:35 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Wed Oct 6 04:10:47 2004 Subject: [Tutor] Summing across a row In-Reply-To: References: <20041005185338.4C2C71E400E@bag.python.org> Message-ID: <6.1.0.6.0.20041005220746.0286c8b0@mail4.skillsoft.com> >>> line = '1, 2, 3, 4' # original input >>> line.split(', ') # split it up into fields ['1', '2', '3', '4'] >>> map(int, line.split(', ')) # convert the field values to integers [1, 2, 3, 4] >>> [int(x) for x in line.split(', ')] # another way to convert to integers [1, 2, 3, 4] >>> sum(map(int, line.split(', '))) # Add them all up 10 Kent At 02:22 PM 10/5/2004 -0600, Michael Knowles wrote: >I've been successful in reading in a comma-delimited text file and summing >the columns but I can't figure out how to sum across a row. > >Ex. text file: >1, 2, 3, 4 =====> ?? Haven't figured this out >5, 6, 7, 8 =====> ?? >9, 10, 11, 12 ==> ?? >========= >15, 18, 21, 24 ===> I 've figured this out > >Thanks, >Mike > > >******************************************* >Mike Knowles >Information Systems Analyst >SI International >USDA, Forest Service, Rocky Mountain Research Station >2150 Centre Ave, Bldg A, Suite 361 >Ft. Collins, CO 80526 >Phone: (970) 295-5979 >Fax: (970) 295-5959 >e-mail: mknowles@fs.fed.us >******************************************* > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From s4046441 at student.uq.edu.au Wed Oct 6 09:16:47 2004 From: s4046441 at student.uq.edu.au (Ms Soo Chong) Date: Wed Oct 6 09:16:56 2004 Subject: [Tutor] Write string into files Message-ID: <7405997449cc.7449cc740599@uq.edu.au> Hi, I'm trying to combine a bunch of data from a form into a string and write it into a file. It works fine if the user input each and every fields but it showed the following error if the user did not. And these fields are not compulsory, they may or may not have values. So how should I do it? Btw, the way I'm doing it now is kinda of longwinded so if anyone can suggest me a better deal of grabbing all the data into a file straight, it would be very nice. Any help is greatly appreciated. Thank you. Shufen ##################################################### A problem occurred in a Python script. Here is the sequence of function calls leading up to the error, in the order they occurred. /var/www/cgi-bin/sf/run_des.py 192 str += "" + blame + "" + "\n" 193 str += "" + date_string + "" + "\n" 194 str += "" + nozzle + "" + "\n" 195 str += "" + shocktube + "" + "\n" 196 str += "" + reservoir + "" + "\n" str = 'T4 Shock Tunnel\n<...F/PJ\n05/10/04\n', nozzle = None TypeError: cannot concatenate 'str' and 'NoneType' objects __doc__ = 'Inappropriate argument type.' __getitem__ = > __init__ = > __module__ = 'exceptions' __str__ = > args = ("cannot concatenate 'str' and 'NoneType' objects",) ###################################################### -------------- next part -------------- A non-text attachment was scrubbed... Name: run_des.py Type: application/octet-stream Size: 9509 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20041006/54e3c8ca/run_des-0001.obj From bvande at po-box.mcgill.ca Wed Oct 6 10:42:00 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Wed Oct 6 10:42:16 2004 Subject: [Tutor] Write string into files In-Reply-To: <7405997449cc.7449cc740599@uq.edu.au> References: <7405997449cc.7449cc740599@uq.edu.au> Message-ID: <4163AFD8.7080600@po-box.mcgill.ca> Ms Soo Chong said unto the world upon 2004-10-06 03:16: > Hi, > > > I'm trying to combine a bunch of data from a form > into a string and write it into a file. It works > fine if the user input each and every fields but it > showed the following error if the user did not. And > these fields are not compulsory, they may or may not > have values. So how should I do it? Btw, the way I'm > doing it now is kinda of longwinded so if anyone can > suggest me a better deal of grabbing all the data > into a file straight, it would be very nice. > > Any help is greatly appreciated. > > Thank you. > > Shufen > > ##################################################### > A problem occurred in a Python script. Here is the > sequence of function calls leading up to the error, > in the order they occurred. > > /var/www/cgi-bin/sf/run_des.py > 192 str += "" + blame + "" > + "\n" > 193 str += "" + date_string + > "" + "\n" > 194 str += "" + nozzle + > "" + "\n" > 195 str += "" + shocktube + > "" + "\n" > 196 str += "" + reservoir + > "" + "\n" > str = 'T4 Shock > Tunnel\n<...F/PJ\n05/10/04\n', > nozzle = None > > TypeError: cannot concatenate 'str' and 'NoneType' > objects > __doc__ = 'Inappropriate argument type.' > __getitem__ = TypeError.__getitem__ of instance at 0x81d31dc>> > __init__ = > > __module__ = 'exceptions' > __str__ = > > args = ("cannot concatenate 'str' and > 'NoneType' objects",) > > ###################################################### > Hi Shufen, I'm still at a learning stage, and don't have the greatest record of giving reliable answers, so take this all skeptically. (I find trying to answer a good way to improve my understanding.) And, if I make a goof of it, someone more helpful will be along to point out the error :-) A quick fix might be to assign each name you are using as a name for a form field to '' at the beginning, and afterwards let the real values that do exist take the place of the empty string. That way, you will always be concatenate strings to strings, even when you don't have real data to concatenate. But depending on your data structure, and processing needs, a dictionary approach might work better still. You don't say much about what your data looks like. I'm going to assume it has known delimiters for each datapoint at the start of lines, each datapoint entirely on a line to itself. Under that assumption, I'd try something like: Make a list of the delimiting strings in the order you want them in your output: data_points = ['Name:', "Address:', 'Phone:', 'favourite colour:'] # Is there only one record per datafile? Assuming so the_record = {} for line in data_file: for dp in data_points: # if you know more about the structure, there may well be better # ways than looping over all items in data_points if line.startswith(dp): the_record[dp] = line(len(dp):-1] # -1 for trailing '\n'. Might need to be len(dp) + 1, or # whatever your data format demands # Then, to print use something like: output_dps = [x for x in data_points if x in the_record.keys()] # if x in the_record works, too, but I like to remind # myself I;m talking about keys of a dictionary. for i in output_dps: print i, the_record[i] # or whatever it is you want done with the data I've been doing something similar with multi-record data files. This requires the extra logic to detect the start of a new data set in the file, begin a new dictionary for it, etc. Since you don't say what you are doing, I can't tell if this would be better than what you have. But, depending on how close my assumptions are to your situation, this strategy might be adaptable. Anyway, HTH, Brian vdB From s4046441 at student.uq.edu.au Wed Oct 6 11:07:10 2004 From: s4046441 at student.uq.edu.au (Ms Soo Chong) Date: Wed Oct 6 11:07:18 2004 Subject: [Tutor] Write string into files (revised version) Message-ID: <744c4f742c12.742c12744c4f@uq.edu.au> Hey, Thanks for the prompt reply. This is my revised version, please help me to take a look if you have a few minutes. ;p It is not working still, but maybe is my way of approach so may be you guys can point out to me where I went wrong so that I can fix it and learn from there. I'm actually trying to set up a upload page where user can add records into a file and save it. For each field, there might be more than one records so I'm not sure if dictionary works well in this case, esp I have a field named NOTES where user will most likely key in a chunk of stuffs. Thank you for any help. Cheers, Shufen -------------- next part -------------- A non-text attachment was scrubbed... Name: run_des.py Type: application/octet-stream Size: 12575 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20041006/6fa65a38/run_des.obj From my.mailing.lists at noos.fr Wed Oct 6 14:48:07 2004 From: my.mailing.lists at noos.fr (nik) Date: Wed Oct 6 14:51:52 2004 Subject: [Tutor] my own site-package Message-ID: <4163E987.7070003@noos.fr> hi, I put my homemade python module into a subfolder of the site-packages folder. However, while I can import the module ok, I get the error 'attribute not defined' when I try to access any of the functions or variables. Is there more to it than just adding the .py files into a folder under site-packages? I have a __init__.py file with; __all__ = ["mapping", "firebird", "variable"] in it, which are names of the python files in the folder I added. Any ideas why I can't see the attributes? Also, do the .py files listed in that __all__ need to be in their own folders? nik From my.mailing.lists at noos.fr Wed Oct 6 16:30:17 2004 From: my.mailing.lists at noos.fr (nik) Date: Wed Oct 6 16:30:31 2004 Subject: [Tutor] my own site-package In-Reply-To: <4163E987.7070003@noos.fr> References: <4163E987.7070003@noos.fr> Message-ID: <41640179.5000206@noos.fr> I seem to have got it working, but I'm not sure why. If I run the python interpreter in the same folder as my module, then doing; import mymodule works fine, and I'm able to call all the methods in mymodule.py If I create a folder called mymodule under site-packages, then the above doesn't work *unless* I do; from mymodule import * I'm not seeing the distinction between the two situations - was naming the folder the same as the python file a mistake perhaps? nik nik wrote: > hi, > > I put my homemade python module into a subfolder of the site-packages > folder. However, while I can import the module ok, I get the error > 'attribute not defined' when I try to access any of the functions or > variables. > > Is there more to it than just adding the .py files into a folder under > site-packages? I have a __init__.py file with; > __all__ = ["mapping", "firebird", "variable"] > in it, which are names of the python files in the folder I added. > > Any ideas why I can't see the attributes? Also, do the .py files > listed in that __all__ need to be in their own folders? > > nik > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From mknowles at fs.fed.us Wed Oct 6 16:43:03 2004 From: mknowles at fs.fed.us (Michael Knowles) Date: Wed Oct 6 16:43:52 2004 Subject: [Tutor] interpreting error messages Message-ID: As a newbie to Python, is there a website -- or other source(s) -- which would help me decipher what error messages refer with respect to my code. I know there must be hundreds of potential errors but any help in learning how to decipher them, without having to post a message for every error, would be greatly appreaciated. For example, what do the following errors refer to: TypeError: unsupported operand type(s) for +: 'int' and 'str' TypeError: iteration over non-sequence Thanks in advance, Mike ******************************************* Mike Knowles Information Systems Analyst SI International USDA, Forest Service, Rocky Mountain Research Station 2150 Centre Ave, Bldg A, Suite 361 Ft. Collins, CO 80526 Phone: (970) 295-5979 Fax: (970) 295-5959 e-mail: mknowles@fs.fed.us ******************************************* From kent_johnson at skillsoft.com Wed Oct 6 16:43:55 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Wed Oct 6 16:47:14 2004 Subject: [Tutor] my own site-package In-Reply-To: <41640179.5000206@noos.fr> References: <4163E987.7070003@noos.fr> <41640179.5000206@noos.fr> Message-ID: <6.1.0.6.0.20041006103829.0287adc0@mail4.skillsoft.com> Putting your module in a folder creates a package. If you have just one module mymodule.py, put it directly in site-packages. If mymodule.py contains a function foo(), you can say import mymodule mymodule.foo() or from mymodule import foo foo() If you have more than one module that you want to group together you can put them in a folder and import them as a package. Your site-packages would look like this: site-packages/ mypackage/ __init__.py (required to have the folder recognized as package, though the file can be empty) mymodule1.py mymodule2.py Then you would say import mypackage.mymodule1 mypackage.mymodule1.foo() or from mypackage import mymodule1 mymodule1.foo() or from mypackage.mymodule import foo foo() HTH Kent At 04:30 PM 10/6/2004 +0200, nik wrote: >I seem to have got it working, but I'm not sure why. > >If I run the python interpreter in the same folder as my module, then doing; > >import mymodule > >works fine, and I'm able to call all the methods in mymodule.py > >If I create a folder called mymodule under site-packages, then the above >doesn't work *unless* I do; > >from mymodule import * > >I'm not seeing the distinction between the two situations - was naming the >folder the same as the python file a mistake perhaps? > >nik > > > >nik wrote: > >>hi, >> >>I put my homemade python module into a subfolder of the site-packages >>folder. However, while I can import the module ok, I get the error >>'attribute not defined' when I try to access any of the functions or variables. >> >>Is there more to it than just adding the .py files into a folder under >>site-packages? I have a __init__.py file with; >>__all__ = ["mapping", "firebird", "variable"] >>in it, which are names of the python files in the folder I added. >> >>Any ideas why I can't see the attributes? Also, do the .py files listed >>in that __all__ need to be in their own folders? >> >>nik >>_______________________________________________ >>Tutor maillist - Tutor@python.org >>http://mail.python.org/mailman/listinfo/tutor > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From kent_johnson at skillsoft.com Wed Oct 6 16:54:20 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Wed Oct 6 16:54:23 2004 Subject: [Tutor] interpreting error messages In-Reply-To: References: Message-ID: <6.1.0.6.0.20041006105337.02a17a40@mail4.skillsoft.com> The library reference has a page about the standard exceptions that might be a little bit of help: http://docs.python.org/lib/module-exceptions.html Kent At 08:43 AM 10/6/2004 -0600, Michael Knowles wrote: >As a newbie to Python, is there a website -- or other source(s) -- which >would help me decipher what error messages refer with respect to my code. >I know there must be hundreds of potential errors but any help in learning >how to decipher them, without having to post a message for every error, >would be greatly appreaciated. > >For example, what do the following errors refer to: > TypeError: unsupported operand type(s) for +: 'int' and 'str' > TypeError: iteration over non-sequence > >Thanks in advance, >Mike > > >******************************************* >Mike Knowles >Information Systems Analyst >SI International >USDA, Forest Service, Rocky Mountain Research Station >2150 Centre Ave, Bldg A, Suite 361 >Ft. Collins, CO 80526 >Phone: (970) 295-5979 >Fax: (970) 295-5959 >e-mail: mknowles@fs.fed.us >******************************************* > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From my.mailing.lists at noos.fr Wed Oct 6 16:54:40 2004 From: my.mailing.lists at noos.fr (nik) Date: Wed Oct 6 16:54:46 2004 Subject: [Tutor] my own site-package In-Reply-To: <6.1.0.6.0.20041006103829.0287adc0@mail4.skillsoft.com> References: <4163E987.7070003@noos.fr> <41640179.5000206@noos.fr> <6.1.0.6.0.20041006103829.0287adc0@mail4.skillsoft.com> Message-ID: <41640730.4050805@noos.fr> Thanks Kent, that's clarified things very nicely. Thanks for your help nik Kent Johnson wrote: > Putting your module in a folder creates a package. > > If you have just one module mymodule.py, put it directly in > site-packages. If mymodule.py contains a function foo(), you can say > import mymodule > mymodule.foo() > > or > from mymodule import foo > foo() > > If you have more than one module that you want to group together you > can put them in a folder and import them as a package. Your > site-packages would look like this: > site-packages/ > mypackage/ > __init__.py (required to have the folder recognized as > package, though the file can be empty) > mymodule1.py > mymodule2.py > > Then you would say > import mypackage.mymodule1 > mypackage.mymodule1.foo() > > or > from mypackage import mymodule1 > mymodule1.foo() > > or > from mypackage.mymodule import foo > foo() > > HTH > Kent > > At 04:30 PM 10/6/2004 +0200, nik wrote: > >> I seem to have got it working, but I'm not sure why. >> >> If I run the python interpreter in the same folder as my module, then >> doing; >> >> import mymodule >> >> works fine, and I'm able to call all the methods in mymodule.py >> >> If I create a folder called mymodule under site-packages, then the >> above doesn't work *unless* I do; >> >> from mymodule import * >> >> I'm not seeing the distinction between the two situations - was >> naming the folder the same as the python file a mistake perhaps? >> >> nik >> >> >> >> nik wrote: >> >>> hi, >>> >>> I put my homemade python module into a subfolder of the >>> site-packages folder. However, while I can import the module ok, I >>> get the error 'attribute not defined' when I try to access any of >>> the functions or variables. >>> >>> Is there more to it than just adding the .py files into a folder >>> under site-packages? I have a __init__.py file with; >>> __all__ = ["mapping", "firebird", "variable"] >>> in it, which are names of the python files in the folder I added. >>> >>> Any ideas why I can't see the attributes? Also, do the .py files >>> listed in that __all__ need to be in their own folders? >>> >>> nik >>> _______________________________________________ >>> Tutor maillist - Tutor@python.org >>> http://mail.python.org/mailman/listinfo/tutor >> >> >> _______________________________________________ >> Tutor maillist - Tutor@python.org >> http://mail.python.org/mailman/listinfo/tutor > > > From jeff at ccvcorp.com Wed Oct 6 19:45:10 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Wed Oct 6 19:44:37 2004 Subject: [Tutor] my own site-package In-Reply-To: <41640179.5000206@noos.fr> References: <4163E987.7070003@noos.fr> <41640179.5000206@noos.fr> Message-ID: <41642F26.6050807@ccvcorp.com> nik wrote: > If I run the python interpreter in the same folder as my module, then > doing; > > import mymodule > > works fine, and I'm able to call all the methods in mymodule.py > > If I create a folder called mymodule under site-packages, then the > above doesn't work *unless* I do; > > from mymodule import * Kent already explained how to get things working the way you want them to, but I thought it might be worthwhile to explain what's happening here in a little more detail. As Kent said, what you've done is to create a package named 'mymodule'. If you have a file module1.py inside of that folder, then normally you'd refer to that using package syntax, i.e.: import mymodule.module1 This would then allow you to refer to 'mymodule.module1.foo()'. You could also import only specific names from the mymodule package, like so: from mymodule import module1 This is the same import, but it binds your module to the name 'module1' instead of the name 'mymodule.module1'. That means that, instead of using 'mymodule.module1.foo()', you can just use 'module1.foo()'. What you've done above, using the wildcard import, does the same thing as my second example here for *each* name that would normally appear directly in the 'mymodule' package. That means that any modules that are part of the package will be accessible with (what appears to be) an unqualified name. It also means that global names from your __init__.py file will be imported into your current namespace. Generally, using the 'from module_or_package import *' form is not recommended, because it does have a tendency to accidentally trample names. If the imported module has a main() function, and your importing code has a main() function, you'll only be able to access *one* of those functions -- whichever one was defined last. And if the imported module has, say, a open() function, then that function will hide the builtin open() file-creation function. In your case, as Kent said, all you need to do is move your module1.py out of the subfolder and put it directly into site-packages. Then you can simply 'import module1' and not worry about having an __init__.py or whether you're injecting unnecessary names into your namespace. :) Jeff Shannon Technician/Programmer Credit International From bvande at po-box.mcgill.ca Wed Oct 6 19:52:09 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Wed Oct 6 19:52:38 2004 Subject: [Tutor] Write string into files (revised version) In-Reply-To: <744c4f742c12.742c12744c4f@uq.edu.au> References: <744c4f742c12.742c12744c4f@uq.edu.au> Message-ID: <416430C9.7050108@po-box.mcgill.ca> Ms Soo Chong said unto the world upon 2004-10-06 05:07: > Hey, > > Thanks for the prompt reply. > > This is my revised version, please help me to take a > look if you have a few minutes. ;p > > It is not working still, but maybe is my way of > approach so may be you guys can point out to me > where I went wrong so that I can fix it and learn > from there. > > I'm actually trying to set up a upload page where > user can add records into a file and save it. For > each field, there might be more than one records so > I'm not sure if dictionary works well in this case, > esp I have a field named NOTES where user will most > likely key in a chunk of stuffs. > > Thank you for any help. > > Cheers, > Shufen > > Hi Shufen, I never used the cgi module or done web-work like your working on, and I'm not up for figuring out what it is supposed to do, so I definitely can't say much of use to you. (But, for more knowledgeable helpers to be able to aid you, you should say something more informative than "It is not working still".) However, on taking a quick skim through you code I noticed: filename = filename[:2]; # Dump away the last two words. 2 things: 1) the ';' isn't needed. 2) much more importantly, and assuming you comment was reflective of your intent: >>> a = "I don't know, but this might be the problem" >>> a[:2] 'I ' >>> a[:-2] "I don't know, but this might be the probl" >>> HTH, Brian vdB From BranimirP at cpas.com Wed Oct 6 20:35:27 2004 From: BranimirP at cpas.com (Branimir Petrovic) Date: Wed Oct 6 20:35:28 2004 Subject: [Tutor] my own site-package Message-ID: <33678E78A2DD4D418396703A750048D401024FFD@RIKER> > > In your case, as Kent said, all you need to do is move your > module1.py > out of the subfolder and put it directly into site-packages. > Then you > can simply 'import module1' and not worry about having an > __init__.py or > whether you're injecting unnecessary names into your namespace. :) > To add another "angle" to this thread - I personally dislike disturbing sacredness of Python's site-packages. Instead I tend to place my project related modules in its own "Lib" folder right next to my "main script". For instance say I have MyScript.py that is using (undisclosed) number of custom (MyScript.py that is) related modules. I'd typically create structure like this: MyPyProject (folder) | +- MyScript.py (this is the "main guy") | +- Lib (folder) | +- MyModule1.py +- MyModule2.py ... # FileName: MyScript.py import sys, os def addLibPath(): """Add current script path and its Lib folder to system path""" os.chdir(os.path.dirname(sys.argv[0])) scriptPath, libPath = os.path.dirname(sys.argv[0]), os.path.abspath(r'..\Lib') sys.path.extend([scriptPath, libPath]) if __name__=='__main__': addLibPath() # know where to find your own library modules # The rest of your code referencing (your own) project related modules # comes here: # ... Of course - you can put your modules right next to Python's own, but to me at least this somehow does not "sound" right nor proper... Branimir From kent_johnson at skillsoft.com Wed Oct 6 20:49:50 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Wed Oct 6 20:49:50 2004 Subject: [Tutor] my own site-package In-Reply-To: <33678E78A2DD4D418396703A750048D401024FFD@RIKER> References: <33678E78A2DD4D418396703A750048D401024FFD@RIKER> Message-ID: <6.1.0.6.0.20041006144448.029ed680@mail4.skillsoft.com> Well, it depends... site-packages is the standard place to install third-party modules. Standard Python doesn't put anything in site-packages, it's all add-ons. If you want to make something available to all your python programs, putting it in site-packages is the easiest way to do it. On the other hand, for modules that you just want to use in a single program, I agree, you should keep it in the same directory as the main program. I don't use a lib directory, I create packages with descriptive names. For example I might make a util package containing mymodule.py (and __init__.py), then I import util.mymodule when I want to use mymodule. Kent At 02:35 PM 10/6/2004 -0400, Branimir Petrovic wrote: > > > > In your case, as Kent said, all you need to do is move your > > module1.py > > out of the subfolder and put it directly into site-packages. > > Then you > > can simply 'import module1' and not worry about having an > > __init__.py or > > whether you're injecting unnecessary names into your namespace. :) > > > >To add another "angle" to this thread - I personally dislike disturbing >sacredness of Python's site-packages. Instead I tend to place my project >related modules in its own "Lib" folder right next to my "main script". >For instance say I have MyScript.py that is using (undisclosed) number >of custom (MyScript.py that is) related modules. I'd typically create >structure like this: > > MyPyProject (folder) > | > +- MyScript.py (this is the "main guy") > | > +- Lib (folder) > | > +- MyModule1.py > +- MyModule2.py > ... > > ># FileName: MyScript.py > >import sys, os > >def addLibPath(): > """Add current script path and its Lib folder to system path""" > os.chdir(os.path.dirname(sys.argv[0])) > scriptPath, libPath = os.path.dirname(sys.argv[0]), >os.path.abspath(r'..\Lib') > sys.path.extend([scriptPath, libPath]) > > >if __name__=='__main__': > addLibPath() # know where to find your own library modules > > # The rest of your code referencing (your own) project related modules > # comes here: > > # ... > > >Of course - you can put your modules right next to Python's own, but >to me at least this somehow does not "sound" right nor proper... > > >Branimir > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From my.mailing.lists at noos.fr Wed Oct 6 21:10:24 2004 From: my.mailing.lists at noos.fr (nik) Date: Wed Oct 6 21:10:31 2004 Subject: [Tutor] my own site-package In-Reply-To: <33678E78A2DD4D418396703A750048D401024FFD@RIKER> References: <33678E78A2DD4D418396703A750048D401024FFD@RIKER> Message-ID: <41644320.6050903@noos.fr> Branimir Petrovic wrote: >>In your case, as Kent said, all you need to do is move your >>module1.py >>out of the subfolder and put it directly into site-packages. >>Then you >>can simply 'import module1' and not worry about having an >>__init__.py or >>whether you're injecting unnecessary names into your namespace. :) >> >> >> > >To add another "angle" to this thread - I personally dislike disturbing >sacredness of Python's site-packages. Instead I tend to place my project >related modules in its own "Lib" folder right next to my "main script". >For instance say I have MyScript.py that is using (undisclosed) number >of custom (MyScript.py that is) related modules. I'd typically create >structure like this: > > MyPyProject (folder) > | > +- MyScript.py (this is the "main guy") > | > +- Lib (folder) > | > +- MyModule1.py > +- MyModule2.py > ... > > ># FileName: MyScript.py > >import sys, os > >def addLibPath(): > """Add current script path and its Lib folder to system path""" > os.chdir(os.path.dirname(sys.argv[0])) > scriptPath, libPath = os.path.dirname(sys.argv[0]), >os.path.abspath(r'..\Lib') > sys.path.extend([scriptPath, libPath]) > > >if __name__=='__main__': > addLibPath() # know where to find your own library modules > > # The rest of your code referencing (your own) project related modules > # comes here: > > # ... > > >Of course - you can put your modules right next to Python's own, but >to me at least this somehow does not "sound" right nor proper... > > >Branimir > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > > Just where to put files is something I wasn't certain about. My ultimate aim is to provide a software/hardware solution to my customers, and a large part of the software part will be python scripts that can be either used 'out of the box' or customised freely (or somewhere in between, a pick and choose situation). So, they'll receive a server with pre-installed software and a user account that has access to those components (to keep it separate from root). I'm not planning on selling it as a software only solution (yet), so there'd be no conflict with personal accounts etc. Each instance of the main server app interfaces to the python scripts through a single file which has three required functions. There maybe several server apps running concurrently, which might require different scripts. I'm providing a fairly comprehensive set of helper modules which can be called by that script file (ie database access, socket support, XML translation etc), which could be used as is, but I'm happy if the user modifies them (which they probably will). My initial idea was to put the helper modules in a single package in site-packages, but I'm not sure where to put the main scripts that the server app accesses (/usr/local/etc, /home/serveradmin/scripts etc?). I'm happy for suggestions on where things should go, although I guess it's all a matter of choice. But maybe there are some pro's and con's for various ways. One idea I've been considering is a publishing method, where the files are editable in the users account, and can then be published to the 'live' location, which then allows rolling back of code etc (assuming the users are bound to mess it all up). I'm not sure how complicated I want to make (my) life though (maybe I can use CVS?)... nik From jeff at ccvcorp.com Wed Oct 6 21:54:13 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Wed Oct 6 21:52:35 2004 Subject: [Tutor] my own site-package In-Reply-To: <41644320.6050903@noos.fr> References: <33678E78A2DD4D418396703A750048D401024FFD@RIKER> <41644320.6050903@noos.fr> Message-ID: <41644D65.1000501@ccvcorp.com> nik wrote: > > My ultimate aim is to provide a software/hardware solution to my > customers, and a large part of the software part will be python > scripts that can be either used 'out of the box' or customised freely > (or somewhere in between, a pick and choose situation). So, they'll > receive a server with pre-installed software and a user account that > has access to those components (to keep it separate from root). I'm > not planning on selling it as a software only solution (yet), so > there'd be no conflict with personal accounts etc. > > Each instance of the main server app interfaces to the python scripts > through a single file which has three required functions. There maybe > several server apps running concurrently, which might require > different scripts. > I'm providing a fairly comprehensive set of helper modules which can > be called by that script file (ie database access, socket support, XML > translation etc), which could be used as is, but I'm happy if the user > modifies them (which they probably will). > > My initial idea was to put the helper modules in a single package in > site-packages, but I'm not sure where to put the main scripts that the > server app accesses (/usr/local/etc, /home/serveradmin/scripts etc?). My thought in this scenario would be to do as you suggest -- a single package in site-packages, just as any third-party package would be installed. The main scripts (which I'd probably make fairly minimal, with most of the intelligence being in the library package), I'd probably put in /usr/local/bin -- this follows the Unix convention on where to put executable programs. After all, from the user's perspective, the main script *is* an executable program which just happens to use the libraries in python/lib/site-packages ... Another option, if you're delivering this machine with a single pre-configured application user, would be to put the main scripts into ~appuser/bin. This would then isolate the scripts from any *other* users on that machine (not that there should be any...) Depends on how much you want to tie the application to a single user account. Jeff Shannon Technician/Programmer Credit International From mknowles at fs.fed.us Wed Oct 6 22:27:26 2004 From: mknowles at fs.fed.us (Michael Knowles) Date: Wed Oct 6 22:28:14 2004 Subject: [Tutor] Print a list in columnar format Message-ID: Two more newbie questions regarding printing to standard output (not a text file). (I'm using version Python 2.3.4 on Win2000) This is the section of code which creates my results: elif choice == 1: aou = raw_input("\nEnter AOU or species: ") results = [x for x in aou_species if x.lower().find(aou) != -1] results.sort() print "\nResults of ", aou, "\n", results One (this one feels like I should know it, but...): How do I print/display a list in column format? For example, my results are displayed as in the Python Shell window: ['04550 Dusky-capped Flycatcher \n', '24550 White-breasted Wood-Swallow \n'] but I would like: 04550 Dusky-capped Flycatcher 24550 White-breasted Wood-Swallow Two: Some of my results may have more species than can fit on my cmd window. Is there a way to tell Python to stop printing at say 20 species and wait for the user to hit the Enter key before printing the next 20 species, etc? Thanks in advance, This is a very useful site Mike ******************************************* Mike Knowles Information Systems Analyst SI International USDA, Forest Service, Rocky Mountain Research Station 2150 Centre Ave, Bldg A, Suite 361 Ft. Collins, CO 80526 Phone: (970) 295-5979 Fax: (970) 295-5959 e-mail: mknowles@fs.fed.us ******************************************* . From bgailer at alum.rpi.edu Thu Oct 7 00:28:04 2004 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Thu Oct 7 00:27:03 2004 Subject: [Tutor] Print a list in columnar format In-Reply-To: References: Message-ID: <6.1.2.0.0.20041006161945.04bd03e8@mail.mric.net> At 02:27 PM 10/6/2004, Michael Knowles wrote: >Two more newbie questions regarding printing to standard output (not a text >file). (I'm using version Python 2.3.4 on Win2000) > >This is the section of code which creates my results: > > elif choice == 1: > aou = raw_input("\nEnter AOU or species: ") > results = [x for x in aou_species if x.lower().find(aou) != -1] > results.sort() > print "\nResults of ", aou, "\n", results > > >One (this one feels like I should know it, but...): >How do I print/display a list in column format? For example, my results >are displayed as in the Python Shell window: > > ['04550 Dusky-capped Flycatcher \n', '24550 White-breasted >Wood-Swallow \n'] > >but I would like: > > 04550 Dusky-capped Flycatcher > 24550 White-breasted Wood-Swallow > print "Results of", aou for result in results: print result >Two: >Some of my results may have more species than can fit on my cmd window. Is >there a way to tell Python to stop printing at say 20 species and wait for >the user to hit the Enter key before printing the next 20 species, etc? lines = 20 for x in range(0, len(results), lines): for result in results[x:x+lines] print result raw_input('Hit Enter to continue') >Thanks in advance, Welcome in retrospect >This is a very useful site Yep Bob Gailer bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell From amonroe at columbus.rr.com Thu Oct 7 00:38:04 2004 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Thu Oct 7 00:38:13 2004 Subject: [Tutor] Print a list in columnar format In-Reply-To: References: Message-ID: <154198221998.20041006183804@columbus.rr.com> > How do I print/display a list in column format? For example, my results > are displayed as in the Python Shell window: > ['04550 Dusky-capped Flycatcher \n', '24550 White-breasted > Wood-Swallow \n'] > but I would like: > 04550 Dusky-capped Flycatcher > 24550 White-breasted Wood-Swallow Here's one way... for x in results: print x > Some of my results may have more species than can fit on my cmd window. Is > there a way to tell Python to stop printing at say 20 species and wait for > the user to hit the Enter key before printing the next 20 species, etc? Depending on the program, you can cheat and pipe it to more. That's only good for programs where the user doesn't need to key in any data, though. Alan From keridee at jayco.net Thu Oct 7 00:21:55 2004 From: keridee at jayco.net (Jacob S.) Date: Thu Oct 7 00:47:06 2004 Subject: [Tutor] interpreting error messages References: Message-ID: <004a01c4abf6$73b4f4c0$5b5428cf@JSLAPTOP> Hey, Just in case you're wondering, the examples you gave follow these ideas... >For example, what do the following errors refer to: > TypeError: unsupported operand type(s) for +: 'int' and 'str' > TypeError: iteration over non-sequence A few examples of type errors are: >>> a = '2' >>> b = 3 >>> print a+b Traceback (most recent call last): File "", line 1, in ? print a+b TypeError: cannot concatenate 'str' and 'int' objects >>> This means you have tried to add a string and and integer. ---------------------------------------------------------------------------- ------------ >>> a = "".join([2,4,3,1,5]) Traceback (most recent call last): File "", line 1, in ? a = "".join([2,4,3,1,5]) TypeError: sequence item 0: expected string, int found >>> This type error denotes that you have wrongly used types in joining a list of *strings*. ---------------------------------------------------------------------------- ------------ >>> def foo(): pass >>> for x in foo: print x Traceback (most recent call last): File "", line 1, in ? for x in foo: TypeError: iteration over non-sequence >>> This means that you are trying to loop through an object that absolutely cannot be expressed as a list. For example, lists can be turned into lists, tuples to lists, strings to lists, etc. Dictionaries, classes, functions, etc. cannot be turned into lists. ---------------------------------------------------------------------------- ------------ >>> "t"-6 Traceback (most recent call last): File "", line 1, in ? "t"-6 TypeError: unsupported operand type(s) for -: 'str' and 'int' >>> This type error means that you have tried to do something that just can't happen between types. ---------------------------------------------------------------------------- ------------ >>> del a >>> a Traceback (most recent call last): File "", line 1, in ? a NameError: name 'a' is not defined >>> Name errors occur when you have referenced an object that doesn't exist. ---------------------------------------------------------------------------- --------------- >>> import foo Traceback (most recent call last): File "", line 1, in ? import foo ImportError: No module named foo >>> Import errors are obvious. They are raised when the interpreter can't find the module specified. The module might not be on sys.path, or it might not exist at all. ---------------------------------------------------------------------------- ------------------ >>> a = '2314' >>> a.write() Traceback (most recent call last): File "", line 1, in ? a.write() AttributeError: 'str' object has no attribute 'write' >>> Attribute errors are raised when you have tried to reference an attribute that doesn't exist. Another example: >>> import math >>> math.sin(math.pi) 1.2246063538223773e-016 >>> math.e 2.7182818284590451 >>> math.pi 3.1415926535897931 >>> math.phi Traceback (most recent call last): File "", line 1, in ? math.phi AttributeError: 'module' object has no attribute 'phi' >>> In this case, we imported math, and later found that math doesn't have the attribute phi -- in other words, phi was not defined inside of this module. ---------------------------------------------------------------------------- ------------------ Oh my! My simple boredom caused me to go off subject and start an error description page myself. I need to go home and get some sleep. If this helps you in any way, it will be a miracle. Hope you can find a more complete listing of errors to help you. Jacob Schmidt From keridee at jayco.net Thu Oct 7 00:40:09 2004 From: keridee at jayco.net (Jacob S.) Date: Thu Oct 7 00:47:10 2004 Subject: [Tutor] Print a list in columnar format References: Message-ID: <004b01c4abf6$74bbb660$5b5428cf@JSLAPTOP> Ah hah! I can answer the last question. I tried to make the first question become answered, but I failed greatly. Why do things not seem to work for me? Anyway, for question 2: numoflines = 20 # This is the number of lines that you can display per page a = ['20301','Birds of a feather','20111','Flock together'] t = 0 for x in a: if t <= numoflines: # This says to check if you've extended past num of lines per page print x t = t + 1 # This increments t so you can be sure how many lines you've printed on else: raw_input('Press enter to continue. ') # This pauses until user presses enter print x t = 0 # When user presses enter, this sets the line count back to zero for another 20 ---------------------------------------------------------------------------- -------------- Hope this really does help. I am a newbie to the mailing list, and apparently not as experienced as I thought I was at Python scripting. Jacob Schmidt From maxnoel_fr at yahoo.fr Thu Oct 7 01:02:00 2004 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Thu Oct 7 01:02:03 2004 Subject: Fwd: [Tutor] interpreting error messages Message-ID: (whoops, I made a mistake and only sent the message to Jacob. Sorry.) Begin forwarded message: > From: Max Noel > Date: October 7, 2004 00:00:25 BST > To: "Jacob S." > Subject: Re: [Tutor] interpreting error messages > > > On Oct 6, 2004, at 23:21, Jacob S. wrote: > >> >> This means that you are trying to loop through an object that >> absolutely >> cannot be expressed as a list. For example, lists can be turned into >> lists, >> tuples to lists, strings to lists, etc. Dictionaries, classes, >> functions, >> etc. cannot be turned into lists. > > Dictionaries can be turned into lists. > > >>> a = {'a': 1, 'b': 2, 'blah': 3} > >>> for i in a: > ... print i > ... > a > blah > b > > Aside from that, you're right. > > -- Wild_cat > maxnoel_fr at yahoo dot fr -- ICQ #85274019 > "Look at you hacker... A pathetic creature of meat and bone, panting > and sweating as you run through my corridors... How can you challenge > a perfect, immortal machine?" > > -- maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From bvande at po-box.mcgill.ca Thu Oct 7 01:39:32 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Thu Oct 7 01:41:04 2004 Subject: [Tutor] interpreting error messages In-Reply-To: <004a01c4abf6$73b4f4c0$5b5428cf@JSLAPTOP> References: <004a01c4abf6$73b4f4c0$5b5428cf@JSLAPTOP> Message-ID: <41648234.5040607@po-box.mcgill.ca> Jacob S. said unto the world upon 2004-10-06 18:21: > Hey, > > Just in case you're wondering, the examples you gave follow these > ideas... >>>>def foo(): > > pass > > >>>>for x in foo: > > print x > > > Traceback (most recent call last): > File "", line 1, in ? > for x in foo: > TypeError: iteration over non-sequence > > > This means that you are trying to loop through an object that absolutely > cannot be expressed as a list. For example, lists can be turned into lists, > tuples to lists, strings to lists, etc. Dictionaries, classes, functions, > etc. cannot be turned into lists. > Not quite, I think. A dictionary isn't a list, true. But it can be iterated over: >>> my_dict = {1:100, 2:200, 3:299.99} >>> for i in my_dict: ... print i ... 1 2 3 >>> for i in my_dict.keys(): ... print i ... 1 2 3 >>> print list(my_dict) [1, 2, 3] >>> The last shows that you can also "convert" a dictionary to a list. (The scare quotes because, unlike list((1,2,3)) (converting a tuple to a list), some real information is lost. The point is, that you can iterate over any object that gives up a sequence when asked for one to iterate over. (And, now that my vocabulary to give the correct explanation is giving out, I will leave the interactive session paste to do the talking for me ;-) Best, Brian vdB From lysdexia at crackrabbit.com Thu Oct 7 05:23:12 2004 From: lysdexia at crackrabbit.com (Douglas N. Shawhan) Date: Thu Oct 7 05:24:14 2004 Subject: [Tutor] Print a list in columnar format In-Reply-To: <004b01c4abf6$74bbb660$5b5428cf@JSLAPTOP> References: <004b01c4abf6$74bbb660$5b5428cf@JSLAPTOP> Message-ID: <4164B6A0.6050003@crackrabbit.com> Using a '-' in front of a string will left-justify the string in the output. You can change the offset by placing an integer between the '%' and the 's' in a string substitution. Like so: import random for each in range(20): print '%10s %-10s'%(random.randint(1,10000), random.randint(1,100000)) 2305 59532 5211 49815 4685 72079 3752 64024 3528 21127 6577 56976 7072 29711 2106 23914 273 9873 5553 20319 9932 8607 9312 21973 6650 77566 2807 20809 8398 6245 8005 99265 6608 76452 2207 92504 236 31435 1175 24644 (if you are not viewing this message in a monospaced font it won't be as impressive! Looks nice in the interpreter, though. It works for more than two columns: >>> for each in range(20): ... print '%10s %-10s %20s' %(random.randint(1,10000), random.randint(1,100000), random.randint(1000, 100000)) ... 8842 93134 43106 1313 27495 66077 9827 52848 15149 992 47592 54314 6661 71357 38458 1903 75534 87374 5183 95922 7436 4553 39353 61334 3067 84029 48230 2574 21826 52559 4239 6424 11370 2271 34964 4177 9770 90979 39463 6787 50783 98180 1679 29670 65847 6515 29142 78164 7406 76963 57462 6717 79017 66864 5467 17790 5714 4977 15100 45395 Play with it for a while! It makes sense! From lysdexia at crackrabbit.com Thu Oct 7 05:46:12 2004 From: lysdexia at crackrabbit.com (Douglas N. Shawhan) Date: Thu Oct 7 05:47:13 2004 Subject: [Tutor] Print a list in columnar format In-Reply-To: <004b01c4abf6$74bbb660$5b5428cf@JSLAPTOP> References: <004b01c4abf6$74bbb660$5b5428cf@JSLAPTOP> Message-ID: <4164BC04.6050009@crackrabbit.com> Whoops, but I didn't really properly answer your question of how to get a _list_ to print in pretty columns! Okay, I have a file called csv.csv that has 100 rows, 10 columns wide with entries no greater than 3 characters long. f=open('csv.csv', 'r') l=f.readlines() for line in l: line=line.split(',') row = (line[0],line[1],line[2],line[3],line[4],\ line[5],line[6],line[7],line[8],line[9]) print '%5s %5s %5s %5s %5s %5s %5s %5s %5s %5s'%(row) Which gives me (shortened): 132 207 943 497 892 47 436 374 746 33 511 894 99 391 743 39 782 887 364 744 214 490 486 57 326 221 726 388 997 997 271 938 556 959 53 585 798 906 501 53 893 84 900 920 897 180 34 867 575 210 5 104 717 411 839 115 921 213 240 874 636 748 717 830 114 759 819 342 470 153 667 758 37 473 236 998 313 451 350 972 749 769 689 106 589 906 387 470 677 90 461 795 129 257 383 937 663 537 516 796 601 951 295 996 832 984 423 686 79 313 247 421 728 866 570 721 627 374 929 880 95 518 561 362 11 751 945 99 341 561 647 226 505 188 433 83 315 101 809 346 282 30 230 986 398 668 852 895 304 930 344 473 153 47 329 291 404 332 521 383 677 273 950 943 948 172 399 83 421 496 for output. *Whew* sorry if the previous post was confusing. To summarize: #open our file f=open('csv.csv', 'r') #read in each line as a list member l=f.readlines() for line in l: #split each line into a list of comma seperated values line=line.split(',') #then put the values into a tuple (less confusing, hopefully) row = (line[0],line[1],line[2],line[3],line[4],\ line[5],line[6],line[7],line[8],line[9]) #and specify a five space offset for each value when it is printed! print '%5s %5s %5s %5s %5s %5s %5s %5s %5s %5s'%(row) Hope this helps. (And here I thought you Forest Service folk spent all your time having fun in the woods. I hope you are doing all this coding on a laptop in a fire tower! :-) From adeleinandjeremy at yahoo.com Thu Oct 7 06:16:08 2004 From: adeleinandjeremy at yahoo.com (Adelein and Jeremy) Date: Thu Oct 7 06:16:11 2004 Subject: [TUTOR] Installing Python2.3.x with Tk support; was [Tutor] IDLE? Message-ID: <20041007041608.15691.qmail@web50308.mail.yahoo.com> > Thank you for the ideas. Tcl and Tk are installed in my own > dir...what I > can not find is how to tell Python where to look for them. I did a > quick > look at the setup.py but did not see anything obvious...a few > references to > tcl but I could not see where to hardwire a path. Any leads. > Thanks again. > You're welcome - the reason I am taking so long to reply is that I was searching high and low for a config file change I made (or thought I made) before building python with tkinter. That said, there is some pertinent information for you (and the rest of the group, as I am sure someone out there has the same problem): 1) In the README file in the Python 2.3.x dir, there is a section discussing system-dependent issues. One of those systems is RH 9, and it pertains to an experience I had with the same problem you described - basically supplying an option to ./configure - it tells you which. 2) I had found and bookmarked a site with a paltry explanation of how to solve the problem, but in my ignorance of Mozilla under Linux, I erased the profile that contained it. The end result, however, was the following which I added to my .bashrc script (not exactly what was given, but modified by me to work the way I wanted it to): LD_LIBRARY_PATH=/usr/local/lib # (because this is where Tcl/Tk are installed) export LD_LIBRARY_PATH I didn't want to modify the actual python link as was suggested in the site I found because as you know, RH uses python for python1.5, and the incompatibilities screw the system over if you switch python to point to python2.3. There may be some conflict with the env var but I haven't experienced one yet - if that's the case you could take these lines out and put them into their own script with a call to a new shell session appended to the end, and then in that child shell you will have the correct LD_LIBRARY_PATH, but it will not interfere with any other shell's env vars. Hope that helps - sorry I couldn't find the file I [think that I] modified to correct the Tcl/Tk version, but even if I did that I am convinced that simply these two steps should do the trick. In any case, I believe that Python must be completely reconfigured and rebuilt unless you have already covered my first point above. I am sure someone out there has a much better solution than this, but having asked this question myself, and having received no answer despite several rewordings and clarifications, I provide this to you in the meanwhile as a kluge. HTH - Jeremy _______________________________ Do you Yahoo!? Declare Yourself - Register online to vote today! http://vote.yahoo.com From kent_johnson at skillsoft.com Thu Oct 7 11:48:40 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Thu Oct 7 11:48:47 2004 Subject: [Tutor] Print a list in columnar format In-Reply-To: <4164BC04.6050009@crackrabbit.com> References: <004b01c4abf6$74bbb660$5b5428cf@JSLAPTOP> <4164BC04.6050009@crackrabbit.com> Message-ID: <6.1.0.6.0.20041007054642.02871b68@mail4.skillsoft.com> At 10:46 PM 10/6/2004 -0500, Douglas N. Shawhan wrote: > #then put the values into a tuple (less confusing, hopefully) > row = (line[0],line[1],line[2],line[3],line[4],\ > line[5],line[6],line[7],line[8],line[9]) An easier way to do this is with the tuple constructor: row = tuple(line) Kent From ps_python at yahoo.com Thu Oct 7 23:27:29 2004 From: ps_python at yahoo.com (kumar s) Date: Thu Oct 7 23:27:32 2004 Subject: [Tutor] Regular expression In-Reply-To: <4164B6A0.6050003@crackrabbit.com> Message-ID: <20041007212729.84426.qmail@web53702.mail.yahoo.com> Dear group, I have a string that looks like this: [AKT|PI3K][RHOA|BCL:CDC42:IKK:RAC1:RAL:RALBP1] I wanted to make the stuff that is enclosed in [] as an element in a dictionary. something like this: a = { 'AKT': 'PI3K'; 'RHOA: 'BCL','CDC42','IKK','RAC1','RAL',RALBP1 } my main of this exrcise is to write a script that will take this input and write to a file the following format: digraph a { PI3K -> AKT; BCL -> RHOA; CDC42 -> RHOA; IKK -> RHOA; RAC1 -> RHOA; RAL -> RHOA; RALBP1 -> RHOA; } I wante to use a reg. exp and trap stuff in between [] into a list or a dictionary. and then write elements in to the following format. Any help please. thanks Kumar. _______________________________ Do you Yahoo!? Declare Yourself - Register online to vote today! http://vote.yahoo.com From shitizb at yahoo.com Thu Oct 7 23:46:36 2004 From: shitizb at yahoo.com (Shitiz Bansal) Date: Thu Oct 7 23:46:38 2004 Subject: [Tutor] Regular expression In-Reply-To: <20041007212729.84426.qmail@web53702.mail.yahoo.com> Message-ID: <20041007214636.67960.qmail@web53808.mail.yahoo.com> Its simple enough. from string import * s= [AKT|PI3K][RHOA|BCL:CDC42:IKK:RAC1:RAL:RALBP1] d=split(s,'][') gives: d[0]=[AKT|PI3K d[1]=RHOA|BCL:CDC42:IKK:RAC1:RAL:RALBP1] now remove the first and last character from d[0] and d[last] after that split(d[n],'|') and so on.. kumar s wrote: Dear group, I have a string that looks like this: [AKT|PI3K][RHOA|BCL:CDC42:IKK:RAC1:RAL:RALBP1] I wanted to make the stuff that is enclosed in [] as an element in a dictionary. something like this: a = { 'AKT': 'PI3K'; 'RHOA: 'BCL','CDC42','IKK','RAC1','RAL',RALBP1 } my main of this exrcise is to write a script that will take this input and write to a file the following format: digraph a { PI3K -> AKT; BCL -> RHOA; CDC42 -> RHOA; IKK -> RHOA; RAC1 -> RHOA; RAL -> RHOA; RALBP1 -> RHOA; } I wante to use a reg. exp and trap stuff in between [] into a list or a dictionary. and then write elements in to the following format. Any help please. thanks Kumar. _______________________________ Do you Yahoo!? Declare Yourself - Register online to vote today! http://vote.yahoo.com _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor --------------------------------- Do you Yahoo!? vote.yahoo.com - Register online to vote today! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20041007/5dacee7e/attachment.html From dyoo at hkn.eecs.berkeley.edu Fri Oct 8 02:10:33 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Oct 8 02:10:37 2004 Subject: [Tutor] Regular expression In-Reply-To: <20041007212729.84426.qmail@web53702.mail.yahoo.com> Message-ID: On Thu, 7 Oct 2004, kumar s wrote: > Dear group, > I have a string that looks like this: > [AKT|PI3K][RHOA|BCL:CDC42:IKK:RAC1:RAL:RALBP1] Hi Kumar, Hmmm! Ok, it sounds like you're making some kind of mini-language to make it easier to type out Graphviz dotty files. Each one of these out-edge descriptions appears to have some kind of structure: out_edge_description ::= open_brace start_vertex_name pipe_symbol a_bunch_of_colon_separated_names close_brace We can parse this pretty informally, by using regular expressions. But there's also a fairly systematic way we can attack this: we can go all out and use a token/parser approach. Would you like to hear about that? Also, just to make sure, have you had a chance to look at the Regular Expression HOWTO? http://www.amk.ca/python/howto/regex/ Good luck to you! From keridee at jayco.net Fri Oct 8 02:31:42 2004 From: keridee at jayco.net (Jacob S.) Date: Fri Oct 8 02:50:54 2004 Subject: [Tutor] interpreting error messages Message-ID: <000d01c4acce$3e6ae5d0$665428cf@JSLAPTOP> Hey, Thanks for correcting me guys. I must have had a brain fart or something. :) Jacob Schmidt From flaxeater at yahoo.com Fri Oct 8 04:42:15 2004 From: flaxeater at yahoo.com (Chad Crabtree) Date: Fri Oct 8 04:42:18 2004 Subject: [Tutor] Regular expression Message-ID: <20041008024215.83731.qmail@web52602.mail.yahoo.com> Danny Yoo wrote: >Hi Kumar, > > >Hmmm! Ok, it sounds like you're making some kind of mini-language to make >it easier to type out Graphviz dotty files. Each one of these out-edge >descriptions appears to have some kind of structure: > > out_edge_description ::= > open_brace > start_vertex_name > pipe_symbol > a_bunch_of_colon_separated_names > close_brace > >We can parse this pretty informally, by using regular expressions. But >there's also a fairly systematic way we can attack this: we can go all >out and use a token/parser approach. Would you like to hear about that? > > I don't know about kumar but I would love to hear about this because I've been reading about it but it has not sunk in yet. __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From pyoryshkov at inorg.chem.msu.ru Fri Oct 8 15:54:15 2004 From: pyoryshkov at inorg.chem.msu.ru (Dmitry V. Peryshkov) Date: Fri Oct 8 15:54:26 2004 Subject: [Tutor] OOP books In-Reply-To: <000d01c4acce$3e6ae5d0$665428cf@JSLAPTOP> References: <000d01c4acce$3e6ae5d0$665428cf@JSLAPTOP> Message-ID: Hello, everyone! I am a novice in the object oriented programming. I have achieved some success in learning of the syntax of the Python language. But I cannot find some book related to general concept of the OOP, which would be rather useful as well as simple and interesting. Could you recommend some books of this kind? Thanks in advance, Dmitry Peryshkov. From paul.baines at ecb.int Fri Oct 8 16:21:44 2004 From: paul.baines at ecb.int (paul.baines@ecb.int) Date: Fri Oct 8 16:21:55 2004 Subject: [Tutor] OOP books Message-ID: <71CEC1FA9395784A826B525D0E1AB2150150F71E@cimexc21.ecb01.ecb.de> I found this book very good. An overview on OO in general, not with any language bias. Object Technology: A Manager's Guide (2nd Edition) by David A. Taylor Publisher: Addison-Wesley Professional; 2 edition (September 11, 1997) ISBN: 0201309947 Any e-mail message from the European Central Bank (ECB) is sent in good faith but shall neither be binding nor construed as constituting a commitment by the ECB except where provided for in a written agreement. This e-mail is intended only for the use of the recipient(s) named above. Any unauthorised disclosure, use or dissemination, either in whole or in part, is prohibited. If you have received this e-mail in error, please notify the sender immediately via e-mail and delete this e-mail from your system. From ps_python at yahoo.com Fri Oct 8 19:07:57 2004 From: ps_python at yahoo.com (kumar s) Date: Fri Oct 8 19:08:02 2004 Subject: [Tutor] how to strip whitespaces from a string. Message-ID: <20041008170757.54979.qmail@web53701.mail.yahoo.com> Dear group, I have been practising python for some time now and string method 'strip' always remains an alien to me. whenever i try to use it, i never got what i want and now it still remainins an enigma. s = " I am learning python" how can i remove white spaces from 's'. f = s.strip('\w') - wrong can any one help me understanding strip method. Thank you. Kumar __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From calum.mackay at cdmnet.org Fri Oct 8 19:20:02 2004 From: calum.mackay at cdmnet.org (Calum Mackay) Date: Fri Oct 8 19:20:14 2004 Subject: [Tutor] how to strip whitespaces from a string. In-Reply-To: <20041008170757.54979.qmail@web53701.mail.yahoo.com> References: <20041008170757.54979.qmail@web53701.mail.yahoo.com> Message-ID: <4166CC42.20803@cdmnet.org> kumar s wrote: > Dear group, > I have been practising python for some time now and > string method 'strip' always remains an alien to me. > whenever i try to use it, i never got what i want and > now it still remainins an enigma. > > s = " I am learning python" > > how can i remove white spaces from 's'. > > f = s.strip('\w') - wrong Do you want to strip trailing and leading ws only? If so, then you just want: f = s.strip() since that's what strip() does by default. cheers, c. From ps_python at yahoo.com Fri Oct 8 19:24:47 2004 From: ps_python at yahoo.com (kumar s) Date: Fri Oct 8 19:24:51 2004 Subject: [Tutor] how to strip whitespaces from a string. In-Reply-To: <4166CC42.20803@cdmnet.org> Message-ID: <20041008172447.3904.qmail@web53707.mail.yahoo.com> Thank you. But I messed up my question. s = " I am learning python " f = s.strip() f 'I am learning python' How can I get the ouput to: 'Iamlearningpython'. That mean how can i remove whitespaces between words in a line and join all the words. sorry for asking twisted question. Thank you. kumar --- Calum Mackay wrote: > kumar s wrote: > > Dear group, > > I have been practising python for some time now > and > > string method 'strip' always remains an alien to > me. > > whenever i try to use it, i never got what i want > and > > now it still remainins an enigma. > > > > s = " I am learning python" > > > > how can i remove white spaces from 's'. > > > > f = s.strip('\w') - wrong > > Do you want to strip trailing and leading ws only? > If so, then you just > want: > > f = s.strip() > > since that's what strip() does by default. > > cheers, > c. > _______________________________ Do you Yahoo!? Declare Yourself - Register online to vote today! http://vote.yahoo.com From flaxeater at yahoo.com Fri Oct 8 19:27:35 2004 From: flaxeater at yahoo.com (Chad Crabtree) Date: Fri Oct 8 19:28:10 2004 Subject: [Tutor] how to strip whitespaces from a string. Message-ID: <20041008172736.32568.qmail@web52608.mail.yahoo.com> kumar s wrote: >Dear group, > I have been practising python for some time now and >string method 'strip' always remains an alien to me. >whenever i try to use it, i never got what i want and >now it still remainins an enigma. > >s = " I am learning python" > >how can i remove white spaces from 's'. > >f = s.strip('\w') - wrong > > > > Help on built-in function strip: strip(...) S.strip([chars]) -> string or unicode Return a copy of the string S with leading and trailing whitespace removed. If chars is given and not None, remove characters in chars instead. If chars is unicode, S will be converted to unicode before stripping so just use s.strip() and that will remove leading and trailing whitespace. From kent_johnson at skillsoft.com Fri Oct 8 19:33:59 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Fri Oct 8 19:33:55 2004 Subject: [Tutor] how to strip whitespaces from a string. In-Reply-To: <20041008172447.3904.qmail@web53707.mail.yahoo.com> References: <4166CC42.20803@cdmnet.org> <20041008172447.3904.qmail@web53707.mail.yahoo.com> Message-ID: <6.1.0.6.0.20041008133151.029efdd8@mail4.skillsoft.com> string.strip() just removes whitespace from the ends of the string. If you just want to replace spaces within the string you can use string.replace(): >>> s = " I am learning\tpython " >>> s.replace(' ', '') 'Iamlearning\tpython' If you want to replace all whitespace characters then use re.sub(): >>> import re >>> re.sub(r'\s', '', s) 'Iamlearningpython' Kent At 10:24 AM 10/8/2004 -0700, kumar s wrote: >Thank you. > But I messed up my question. >s = " I am learning python " >f = s.strip() >f >'I am learning python' > >How can I get the ouput to: > >'Iamlearningpython'. > >That mean how can i remove whitespaces between words >in a line and join all the words. > >sorry for asking twisted question. > >Thank you. >kumar > >--- Calum Mackay wrote: > > > kumar s wrote: > > > Dear group, > > > I have been practising python for some time now > > and > > > string method 'strip' always remains an alien to > > me. > > > whenever i try to use it, i never got what i want > > and > > > now it still remainins an enigma. > > > > > > s = " I am learning python" > > > > > > how can i remove white spaces from 's'. > > > > > > f = s.strip('\w') - wrong > > > > Do you want to strip trailing and leading ws only? > > If so, then you just > > want: > > > > f = s.strip() > > > > since that's what strip() does by default. > > > > cheers, > > c. > > > > > > >_______________________________ >Do you Yahoo!? >Declare Yourself - Register online to vote today! >http://vote.yahoo.com >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From calum.mackay at cdmnet.org Fri Oct 8 19:43:24 2004 From: calum.mackay at cdmnet.org (Calum Mackay) Date: Fri Oct 8 19:43:27 2004 Subject: [Tutor] how to strip whitespaces from a string. In-Reply-To: <6.1.0.6.0.20041008133151.029efdd8@mail4.skillsoft.com> References: <4166CC42.20803@cdmnet.org> <20041008172447.3904.qmail@web53707.mail.yahoo.com> <6.1.0.6.0.20041008133151.029efdd8@mail4.skillsoft.com> Message-ID: <4166D1BC.8020709@cdmnet.org> Kent Johnson wrote: > If you want to replace all whitespace characters then use re.sub(): > >>> import re > >>> re.sub(r'\s', '', s) > 'Iamlearningpython' I had thought a null translation ought to be simple, but it isn't: >>> s.translate(string.maketrans('',''), string.whitespace) 'Iamlearningpython' :) cheers, c. From flaxeater at yahoo.com Fri Oct 8 20:09:50 2004 From: flaxeater at yahoo.com (Chad Crabtree) Date: Fri Oct 8 20:09:55 2004 Subject: [Tutor] how to strip whitespaces from a string. Message-ID: <20041008180950.14652.qmail@web52602.mail.yahoo.com> kumar s wrote: >Thank you. > But I messed up my question. >s = " I am learning python " >f = s.strip() >f >'I am learning python' > >How can I get the ouput to: > >'Iamlearningpython'. > > > How about this s=" I am Learning Python " s="".join([x.strip() for x in s.split(' ')]) print s IamLearningPython From mw5858 at sbc.com Fri Oct 8 20:55:32 2004 From: mw5858 at sbc.com (WEISS, MARK (NB)) Date: Fri Oct 8 20:55:53 2004 Subject: [Tutor] Ftplib error using dir() Message-ID: <4BF710B1993F1244B41763531F098D7905A6BD@cafrfd1msgusr21.itservices.sbc.com> Hello Group, I am trying to build a FTP client and I am getting a 'connection refused' error when I call the code listed below. I can login fine (in my script), and I connect through a command prompt using the ftp command (Win2K) I can list the files in the remote directory. Also, to further confuse the matter I can run this code against a local ftp server and return the list of files. def getListFiles(ftp): # return a LIST of the directory contents dataList = [] try: ftp.dir(dataList.append) except socket.error, (errno, strerror): print "Error code(%d), Error Message: %s " % (errno, strerror) # - raises - 'Error code(10061), Error Message: Connection refused' except: print sys.exc_info() return dataList Any ideas on why this is failing or to better isolate the error would be greatly appreciated. Thanks! -mark From revanna at mn.rr.com Fri Oct 8 22:27:23 2004 From: revanna at mn.rr.com (Anna Ravenscroft) Date: Fri Oct 8 22:27:37 2004 Subject: [Tutor] how to strip whitespaces from a string. In-Reply-To: <20041008180950.14652.qmail@web52602.mail.yahoo.com> References: <20041008180950.14652.qmail@web52602.mail.yahoo.com> Message-ID: <4166F82B.60308@mn.rr.com> Chad Crabtree wrote: > kumar s wrote: > > >>Thank you. >>But I messed up my question. >>s = " I am learning python " >>f = s.strip() >>f >>'I am learning python' >> >>How can I get the ouput to: >> >>'Iamlearningpython'. >> >> >> > > How about this > > s=" I am Learning Python " > s="".join([x.strip() for x in s.split(' ')]) > print s > IamLearningPython That's close to what I would recommend. I'd like to break this down a little bit for newbies, as you're doing several (really good!) things at once here: s.split() will split based on any character, word, punctuation or whitespace - so, for example, if you have comma-separated values, you could split at the comma. It's really handy to know. The .join method is a little more confusing for newcomers sometimes. It's a string method, but the method is on the *separator*, not on the list of pieces being joined. If you use ''.join() with *no* whitespace, it'll join all the pieces of a list back into a string with no whitespace between. Like .split(), you can join with whatever string characters, including whitespace, punctuation, whole words, whatever you like. The list of pieces to be joined has been created here with a list comprehension [x.strip() for x in s.split(' ')]. This is an exceptionally kewl piece of coding that became available in Python 2.x You can pretty much turn *any* sequence into a list this way. The syntax, again, is a little confusing for a lot of newbies: to me, it seemed like I was telling it what to *do* to x before I told it what x I wanted... It took a while to get used to. The syntax is: [operation_if_any for item in list_of_items if optional_condition] If list comprehensions blow your mind, try a simple for loop, which can show you what the list comprehension is doing: s = " I am learning Python " mylist = [] for x in s.split(' '): mylist.append[x] If you print mylist, you'll see that the list contains all the pieces of the string that were separated by white spaces (including some empty strings where there were leading and trailing whitespaces). List comprehensions can do this in one nice step without having to even *name* the list, which is really kewl when you only want is a temporary container anyway, like here. Note that the x.strip is redundant here - when you used .split(' '), it took off all the whitespace. So, what I would recommend is: s = ''.join([x for x in s.split(' ')]) print s IamlearningPython HTH, Anna From pythonTutor at venix.com Fri Oct 8 22:41:14 2004 From: pythonTutor at venix.com (Lloyd Kvam) Date: Fri Oct 8 22:41:17 2004 Subject: [Tutor] how to strip whitespaces from a string. In-Reply-To: <20041008180950.14652.qmail@web52602.mail.yahoo.com> References: <20041008180950.14652.qmail@web52602.mail.yahoo.com> Message-ID: <1097268074.2168.34.camel@laptop.venix.com> On Fri, 2004-10-08 at 14:09, Chad Crabtree wrote: > kumar s wrote: > > >Thank you. > > But I messed up my question. > >s = " I am learning python " > >f = s.strip() > >f > >'I am learning python' > > > >How can I get the ouput to: > > > >'Iamlearningpython'. > > > > > > > How about this > > s=" I am Learning Python " > s="".join([x.strip() for x in s.split(' ')]) > print s > IamLearningPython Note that s.split() will simply discard all whitespace and return the words. Then there is no need for x.strip(). The line simply becomes: s = "".join( s.split() ) >>> s = " I am Learning Python " >>> ''.join( s.split() ) 'IamLearningPython' > > > > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp From mhansen at cso.atmel.com Fri Oct 8 22:50:06 2004 From: mhansen at cso.atmel.com (Mike Hansen) Date: Fri Oct 8 22:50:11 2004 Subject: [Tutor] Re: OOP books In-Reply-To: <20041008202737.00F221E400B@bag.python.org> References: <20041008202737.00F221E400B@bag.python.org> Message-ID: <4166FD7E.9000106@cso.atmel.com> There's a couple of OOP books that I've been meaning to read after Code Complete and Programming Python... The Object Oriented Thought Process Head First Java Head First Java might seem like a strange choice. It sounds like an interesting read. It tries to teach OOP and Java with humor and illustrations. Supposedly, you learn better if there's an emotional response. IMHO, if you learn OOP in one programming language, it probably isn't much of a leap to use OOP in other programming languages. Mike > Subject: > [Tutor] OOP books > From: > "Dmitry V. Peryshkov" > Date: > Fri, 08 Oct 2004 17:54:15 +0400 > To: > tutor@python.org > > To: > tutor@python.org > > > Hello, everyone! > > I am a novice in the object oriented programming. I have achieved > some success in learning of the syntax of the Python language. But I > cannot find some book related to general concept of the OOP, which > would be rather useful as well as simple and interesting. Could you > recommend some books of this kind? > > Thanks in advance, > > Dmitry Peryshkov. > From jfabiani at yolo.com Fri Oct 8 23:20:54 2004 From: jfabiani at yolo.com (John Fabiani) Date: Fri Oct 8 23:20:58 2004 Subject: [Tutor] Re: OOP books In-Reply-To: <4166FD7E.9000106@cso.atmel.com> References: <20041008202737.00F221E400B@bag.python.org> <4166FD7E.9000106@cso.atmel.com> Message-ID: <200410081420.54264.jfabiani@yolo.com> On Friday 08 October 2004 13:50, Mike Hansen wrote: > There's a couple of OOP books that I've been meaning to read after Code > Complete and Programming Python... > > The Object Oriented Thought Process > > Head First Java > > Head First Java might seem like a strange choice. It sounds like an > interesting read. It tries to teach OOP and Java with humor and > illustrations. Supposedly, you learn better if there's an emotional > response. IMHO, if you learn OOP in one programming language, it > probably isn't much of a leap to use OOP in other programming languages. You know that the VB6 guys think they were programming in OOP!! |; ) John From maxnoel_fr at yahoo.fr Fri Oct 8 23:56:16 2004 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Fri Oct 8 23:56:20 2004 Subject: [Tutor] Re: OOP books In-Reply-To: <200410081420.54264.jfabiani@yolo.com> References: <20041008202737.00F221E400B@bag.python.org> <4166FD7E.9000106@cso.atmel.com> <200410081420.54264.jfabiani@yolo.com> Message-ID: On Oct 8, 2004, at 22:20, John Fabiani wrote: >> IMHO, if you learn OOP in one programming language, it >> probably isn't much of a leap to use OOP in other programming >> languages. > > You know that the VB6 guys think they were programming in OOP!! |; ) Yeah, but we're talking about programming languages here. Not VB. -- Wild_Cat maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From idiot1 at netzero.net Sat Oct 9 00:46:42 2004 From: idiot1 at netzero.net (Kirk Bailey) Date: Sat Oct 9 00:47:21 2004 Subject: [Tutor] reversing a string Message-ID: <416718D2.6000402@netzero.net> ok, something struck a spark in my concrete enshrouded skull; how does one reverse a string. Consider a string:'qwerty'. A SIMPLE and FAST process to reverse it. I considered appending and recursion, but there ought to be a better way, although dealing off the bottom of the deck does have a peverse attraction to it (slicing and taking -1 char off the string and appending it to a string). Anyone want to discuss this task? -- -Blessed Be! Kirk Bailey kniht http://www.tinylist-org/ Freedom software +-----+ Free list services -http://www.listville.net/ | BOX | http://www.howlermonkey.net/ - Free Email service +-----+ In HER Service- http://www.pinellasintergroupsociety.org/ think http://www.sacredelectron.org/ - my personal screed pit. From maxnoel_fr at yahoo.fr Sat Oct 9 01:32:24 2004 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Sat Oct 9 01:32:30 2004 Subject: [Tutor] reversing a string In-Reply-To: <416718D2.6000402@netzero.net> References: <416718D2.6000402@netzero.net> Message-ID: <4EAB1689-1982-11D9-B0F0-000393CBC88E@yahoo.fr> On Oct 8, 2004, at 23:46, Kirk Bailey wrote: > ok, something struck a spark in my concrete enshrouded skull; how does > one reverse a string. > > Consider a string:'qwerty'. A SIMPLE and FAST process to reverse it. I > considered appending and recursion, but there ought to be a better > way, although dealing off the bottom of the deck does have a peverse > attraction to it (slicing and taking -1 char off the string and > appending it to a string). > > Anyone want to discuss this task? I have a simple way of doing this. There's probably a better one, I'm sure this can be done as a one-liner. Anyway, here goes: foo = "Hello World!" bar = list(foo) bar.reverse() baz = "".join(bar) -- Wild_Cat maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From rmkrauter at yahoo.com Sat Oct 9 02:31:46 2004 From: rmkrauter at yahoo.com (Rich Krauter) Date: Sat Oct 9 02:31:50 2004 Subject: [Tutor] reversing a string In-Reply-To: <416718D2.6000402@netzero.net> References: <416718D2.6000402@netzero.net> Message-ID: <41673172.4040704@yahoo.com> Kirk Bailey wrote: > ok, something struck a spark in my concrete enshrouded skull; how does > one reverse a string. > > Consider a string:'qwerty'. A SIMPLE and FAST process to reverse it. I > considered appending and recursion, but there ought to be a better way, > although dealing off the bottom of the deck does have a peverse > attraction to it (slicing and taking -1 char off the string and > appending it to a string). > > Anyone want to discuss this task? > This works in 2.3: >>> 'qwerty'[-1::-1] 'ytrewq' Rich From pythonTutor at venix.com Sat Oct 9 02:38:56 2004 From: pythonTutor at venix.com (Lloyd Kvam) Date: Sat Oct 9 02:39:02 2004 Subject: [Tutor] reversing a string In-Reply-To: <41673172.4040704@yahoo.com> References: <416718D2.6000402@netzero.net> <41673172.4040704@yahoo.com> Message-ID: <1097282336.2676.2.camel@laptop.venix.com> On Fri, 2004-10-08 at 20:31, Rich Krauter wrote: > Kirk Bailey wrote: > > ok, something struck a spark in my concrete enshrouded skull; how does > > one reverse a string. > > > > Consider a string:'qwerty'. A SIMPLE and FAST process to reverse it. I > > considered appending and recursion, but there ought to be a better way, > > although dealing off the bottom of the deck does have a peverse > > attraction to it (slicing and taking -1 char off the string and > > appending it to a string). > > > > Anyone want to discuss this task? > > > > This works in 2.3: > > >>> 'qwerty'[-1::-1] > 'ytrewq' > > Rich Or the slightly simpler to type: >>> 'gfedcba'[::-1] 'abcdefg' > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp From calum.mackay at cdmnet.org Sat Oct 9 02:57:35 2004 From: calum.mackay at cdmnet.org (Calum Mackay) Date: Sat Oct 9 02:57:43 2004 Subject: [Tutor] confused: classes containing dicts Message-ID: <4167377F.1050203@cdmnet.org> Hi, I'm quite new to Python, having written a few utilities and just now trying to convert them to use classes where previously I'd used nested lists. I spent a few confused hours wondering why my util wouldn't work quite right until I noticed that I was "corrupting" the value of a dict in the class itself, by changing it in an instance, and thus affecting all instances (which wasn't what I wanted). i.e. I had: class C(object): l = {} a = C() a.l["x"] = 123 and was very surprised to see that I'd managed to set C.l as well as a.l. After some time, I now think that this is because I've defined the class as containing a reference to an empty dict. Instances of this class get a private copy of l, but l isn't the dict, but merely a reference to it. So in each instance I have a private reference to a single "global" dict, C.l. Is this correct? To get around this I've changed my class defn to: class C(object): def __init__(self): self.l = {} and now it all works, I imagine since each instance now has its own dict, rather than a reference to a shared dict. This makes sense to me now, but it took a long while to figure it out, and it seems to be completely glossed over in the two Python books I have in front of me (Nutshell & Learning). Is my workaround the right solution to this problem, or am I going about things entirely the wrong way? thanks for any comments. cheers, calum. From kent_johnson at skillsoft.com Sat Oct 9 03:42:09 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Sat Oct 9 03:48:48 2004 Subject: [Tutor] confused: classes containing dicts In-Reply-To: <4167377F.1050203@cdmnet.org> References: <4167377F.1050203@cdmnet.org> Message-ID: <6.1.0.6.0.20041008211549.029c1628@mail4.skillsoft.com> At 01:57 AM 10/9/2004 +0100, Calum Mackay wrote: >I had: > >class C(object): > l = {} > >a = C() >a.l["x"] = 123 > >and was very surprised to see that I'd managed to set C.l as well as a.l. > >After some time, I now think that this is because I've defined the class >as containing a reference to an empty dict. Instances of this class get a >private copy of l, but l isn't the dict, but merely a reference to it. So >in each instance I have a private reference to a single "global" dict, >C.l. Is this correct? This is close. Instances of C don't have an attribute l, it is just the class that has this attribute. The way attribute lookup works for classes is, if the attribute isn't found in the instance, look for it in the class (and the super classes). This is pretty much what happens when you access an instance method, too - the actual method is a class attribute. So when you say a.l, the interpreter fails to find an attribute l in a, then finds it in C and uses that. You can reference the same attribute as C.l >To get around this I've changed my class defn to: > >class C(object): > def __init__(self): > self.l = {} > >and now it all works, I imagine since each instance now has its own dict, >rather than a reference to a shared dict. This is the correct way to create an attribute of an instance. This is much more commonly used than class attributes. >This makes sense to me now, but it took a long while to figure it out, and >it seems to be completely glossed over in the two Python books I have in >front of me (Nutshell & Learning). The first few pages of chapter 21 of Learning Python talk about this a little. Kent >Is my workaround the right solution to this problem, or am I going about >things entirely the wrong way? > >thanks for any comments. > >cheers, >calum. >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From calum.mackay at cdmnet.org Sat Oct 9 03:55:22 2004 From: calum.mackay at cdmnet.org (Calum Mackay) Date: Sat Oct 9 03:55:25 2004 Subject: [Tutor] confused: classes containing dicts In-Reply-To: <6.1.0.6.0.20041008211549.029c1628@mail4.skillsoft.com> References: <4167377F.1050203@cdmnet.org> <6.1.0.6.0.20041008211549.029c1628@mail4.skillsoft.com> Message-ID: <4167450A.1050308@cdmnet.org> thanks very much for the reply, Kent, > This is close. Instances of C don't have an attribute l, it is just the > class that has this attribute. The way attribute lookup works for > classes is, if the attribute isn't found in the instance, look for it in > the class (and the super classes). This is pretty much what happens when > you access an instance method, too - the actual method is a class > attribute. That makes sense, thanks, and explains why I couldn't see 'l' when I pprinted the instance. > The first few pages of chapter 21 of Learning Python talk about this a > little. Yup, it looks like I glossed over them ) time for another read... cheers, calum. From calum.mackay at cdmnet.org Sat Oct 9 04:04:21 2004 From: calum.mackay at cdmnet.org (Calum Mackay) Date: Sat Oct 9 04:04:25 2004 Subject: [Tutor] confused: classes containing dicts In-Reply-To: <6.1.0.6.0.20041008211549.029c1628@mail4.skillsoft.com> References: <4167377F.1050203@cdmnet.org> <6.1.0.6.0.20041008211549.029c1628@mail4.skillsoft.com> Message-ID: <41674725.1010908@cdmnet.org> Kent Johnson wrote: > The first few pages of chapter 21 of Learning Python talk about this a > little. Having re-read it, I'm not sure it doesn't perpetuate my confusion. They use the example: class SharedData: spam = 42 x = SharedData() y = SharedData() and then note that references: x.spam, y.spam, SharedData.spam all give the same value. Also, if SharedData.spam is changed, then references of x.spam, y.spam see that change. However, it then goes onto note that if x.spam is changed, x.spam attaches a name to x itself. i.e: x.spam = 88 and y.spam, SharedData.spam still give 42. This is not what happens with dicts, at least in my example: class SharedData: l = {} x = SharedData() >>> x.l["a"] = 123 >>> x.l {'a': 123} >>> SharedData.l {'a': 123} Here, assignment to x *has* changed the attr in the class, unlike the following: >>> x = SharedData() >>> x.l 123 >>> x.l = 456 >>> x.l 456 >>> SharedData.l 123 There's a difference in behaviour here, depending on whether the attribute is an int or a dict. cheers, c. From calum.mackay at cdmnet.org Sat Oct 9 04:09:10 2004 From: calum.mackay at cdmnet.org (Calum Mackay) Date: Sat Oct 9 04:09:19 2004 Subject: [Tutor] confused: classes containing dicts In-Reply-To: <41674725.1010908@cdmnet.org> References: <4167377F.1050203@cdmnet.org> <6.1.0.6.0.20041008211549.029c1628@mail4.skillsoft.com> <41674725.1010908@cdmnet.org> Message-ID: <41674846.40004@cdmnet.org> Perhaps this is because: x.l = 456 changes x.l, and thus creating a per-instance copy, rather than being a reference to it, whereas: x.l["a"] = 123 does involve a reference to x.l - to lookup the dict itself - and thus does involve the class attr? cheers, calum. Calum Mackay wrote: > This is not what happens with dicts, at least in my example: > > class SharedData: > l = {} > > x = SharedData() > > >>> x.l["a"] = 123 > >>> x.l > {'a': 123} > >>> SharedData.l > {'a': 123} > > Here, assignment to x *has* changed the attr in the class, unlike the > following: > > >>> x = SharedData() > >>> x.l > 123 > >>> x.l = 456 > >>> x.l > 456 > >>> SharedData.l > 123 > > There's a difference in behaviour here, depending on whether the > attribute is an int or a dict. > > cheers, > c. > From bgailer at alum.rpi.edu Sat Oct 9 04:17:25 2004 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Sat Oct 9 04:16:19 2004 Subject: [Tutor] confused: classes containing dicts In-Reply-To: <41674725.1010908@cdmnet.org> References: <4167377F.1050203@cdmnet.org> <6.1.0.6.0.20041008211549.029c1628@mail4.skillsoft.com> <41674725.1010908@cdmnet.org> Message-ID: <6.1.2.0.0.20041008201259.0538fe40@mail.mric.net> At 08:04 PM 10/8/2004, Calum Mackay wrote: >Kent Johnson wrote: >>The first few pages of chapter 21 of Learning Python talk about this a >>little. > >Having re-read it, I'm not sure it doesn't perpetuate my confusion. > >They use the example: > >class SharedData: > spam = 42 > >x = SharedData() >y = SharedData() > >and then note that references: > >x.spam, y.spam, SharedData.spam > >all give the same value. Also, if SharedData.spam is changed, then >references of x.spam, y.spam see that change. > >However, it then goes onto note that if x.spam is changed, x.spam attaches >a name to x itself. i.e: > >x.spam = 88 > >and y.spam, SharedData.spam still give 42. > >This is not what happens with dicts, at least in my example: > >class SharedData: > l = {} > >x = SharedData() > > >>> x.l["a"] = 123 > >>> x.l >{'a': 123} > >>> SharedData.l >{'a': 123} > >Here, assignment to x *has* changed the attr in the class, unlike the >following: > > >>> x = SharedData() > >>> x.l >123 > >>> x.l = 456 > >>> x.l >456 > >>> SharedData.l >123 > >There's a difference in behaviour here, depending on whether the attribute >is an int or a dict. No - there is a difference in the target of the assignment: >>> x.l = 456 is an assignment to attribute l of instance x. SInce the instance attribute did not exist, it is created. >>> x.l["a"] = 123 is an assignment to a key in the dictionary x.l, not to the attribute x. HTH Bob Gailer bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell From calum.mackay at cdmnet.org Sat Oct 9 04:18:36 2004 From: calum.mackay at cdmnet.org (Calum Mackay) Date: Sat Oct 9 04:18:39 2004 Subject: [Tutor] confused: classes containing dicts In-Reply-To: <6.1.2.0.0.20041008201259.0538fe40@mail.mric.net> References: <4167377F.1050203@cdmnet.org> <6.1.0.6.0.20041008211549.029c1628@mail4.skillsoft.com> <41674725.1010908@cdmnet.org> <6.1.2.0.0.20041008201259.0538fe40@mail.mric.net> Message-ID: <41674A7C.9090607@cdmnet.org> Bob Gailer wrote: > No - there is a difference in the target of the assignment: > >>> x.l = 456 is an assignment to attribute l of instance x. SInce the > instance attribute did not exist, it is created. > >>> x.l["a"] = 123 is an assignment to a key in the dictionary x.l, not > to the attribute x. right, thanks. And since l doesn't exist in x it finds it in the class C.l and makes the assignment there. thanks very much for clearing up my confusion, chaps. have a good weekend. cheers, calum. From kent_johnson at skillsoft.com Sat Oct 9 04:22:29 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Sat Oct 9 04:22:57 2004 Subject: [Tutor] Regular expression In-Reply-To: <20041008024215.83731.qmail@web52602.mail.yahoo.com> References: <20041008024215.83731.qmail@web52602.mail.yahoo.com> Message-ID: <6.1.0.6.0.20041008203128.02a0f8c0@mail4.skillsoft.com> pyparsing is a fairly new parsing module for Python - http://pyparsing.sourceforge.net/. With pyparsing you build up a syntax out of simple building blocks. I've been wanting to try it out. I found it very easy to use. Here is what is looks like with kumar's original example: >>> s='[AKT|PI3K][RHOA|BCL:CDC42:IKK:RAC1:RAL:RALBP1]' >>> from pyparsing import * I'll build the parser from the inside out, starting with simple tokens and combining them to recognize more and more complex parts of the complete string. First I create a parse token to represent the key portion of each entry. A keyToken is a run of any number of contiguous letters and numbers: >>> keyToken = Word(alphanums) The scanString() method of a parser element searches a string for anything that matches the element. It is a handy way to check that you are on the right track. scanString() is a generator function so you have to pass the result to list() if you want to print it out. keyToken matches all the words in the string: >>> list(keyToken.scanString(s)) [((['AKT'], {}), 1, 4), ((['PI3K'], {}), 5, 9), ((['RHOA'], {}), 11, 15), ((['BCL'], {}), 16, 19), ((['CDC42'], {}), 20, 25), ((['IKK'], {}), 26, 29), ((['RAC1'], {}), 30, 34), ((['RAL'], {}), 35, 38), ((['RALBP1'], {}), 39, 45)] valueToken will match the pieces of the value lists.. It's the same as keyToken, just a run of alphanumeric characters: >>> valueToken = Word(alphanums) Now here is something more interesting - valueList matches one or more valueTokens separated by colons: >>> valueList = delimitedList(valueToken, delim=':') >>> list(valueList.scanString(s)) [((['AKT'], {}), 1, 4), ((['PI3K'], {}), 5, 9), ((['RHOA'], {}), 11, 15), ((['BCL', 'CDC42', 'IKK', 'RAC1', 'RAL', 'RALBP1'], {}), 16, 45)] It matches the keys, too, but that's just because we haven't given it enough context yet. Notice how the list 'BCL', 'CDC42', etc. has been collected for us. Now let's start putting the key and the valueList together. pyparsing lets you do this just by adding parser elements together. You include literal elements by adding in the strings that represent them: >>> entry = '[' + keyToken + '|' + valueList + ']' >>> list(entry.scanString(s)) [((['[', 'AKT', '|', 'PI3K', ']'], {}), 0, 10), ((['[', 'RHOA', '|', 'BCL', 'CDC42', 'IKK', 'RAC1', 'RAL', 'RALBP1', ']'], {}), 10, 46)] That's pretty cool! entry separates the key and the valueList. We don't really want the literals in the token list, though. We can tell pyparsing to suppress them: >>> entry = Suppress('[') + keyToken + Suppress('|') + valueList + Suppress(']') >>> list(entry.scanString(s)) [((['AKT', 'PI3K'], {}), 0, 10), ((['RHOA', 'BCL', 'CDC42', 'IKK', 'RAC1', 'RAL', 'RALBP1'], {}), 10, 46)] That looks like we're getting somewhere. Let's add one more rule, to find multiple entries: >>> entryList = ZeroOrMore(entry) >>> list(entryList.scanString(s)) [((['AKT', 'PI3K', 'RHOA', 'BCL', 'CDC42', 'IKK', 'RAC1', 'RAL', 'RALBP1'], {}), 0, 46)] Now we've matched the whole string with a single parser element, but the list of tokens is all glommed together again! Not to worry...pyparsing lets you define actions associated with each parser element. We can add an action to the 'entry' element that pulls out the tokens we want and puts them in a dictionary: >>> dd = {} >>> def processEntry(s, loc, toks): ... key, value = toks[0], toks[1:] ... dd[key] = value ... >>> entry.setParseAction(processEntry) processEntry() gets three arguments. The third one contains the tokens that match the associated rule. toks is actually a ParseResult object, but it acts a lot like a list. We can use the first token as a key and the rest of the list as the value for a dictionary. Finally we use entryList.parseString() to activate the parser and apply the parse action: >>> entryList.parseString(s) (['AKT', 'PI3K', 'RHOA', 'BCL', 'CDC42', 'IKK', 'RAC1', 'RAL', 'RALBP1'], {}) >>> dd {'RHOA': ['BCL', 'CDC42', 'IKK', 'RAC1', 'RAL', 'RALBP1'], 'AKT': ['PI3K']} dd is now the dictionary requested by the original poster :-) Here is the whole program: from pyparsing import * s='[AKT|PI3K][RHOA|BCL:CDC42:IKK:RAC1:RAL:RALBP1]' # Global variables to accumulate results dd = {} # Syntax definition keyToken = Word(alphanums) valueToken = Word(alphanums) valueList = delimitedList(valueToken, delim=':') entry = Suppress('[') + keyToken + Suppress('|') + valueList + Suppress(']') entryList = ZeroOrMore(entry) def processEntry(s, loc, toks): key, value = toks[0], toks[1:] dd[key] = value entry.setParseAction(processEntry) entryList.parseString(s) print dd By the way delimitedList() is just a shortcut, we could have written this with the same result: >>> valueList = valueToken + ZeroOrMore(Suppress(':' )+ valueToken) Kent At 07:42 PM 10/7/2004 -0700, Chad Crabtree wrote: >Danny Yoo wrote: > >We can parse this pretty informally, by using regular expressions. >But > >there's also a fairly systematic way we can attack this: we can go >all > >out and use a token/parser approach. Would you like to hear about >that? > > > > >I don't know about kumar but I would love to hear about this because >I've been reading about it but it has not sunk in yet. > >__________________________________________________ >Do You Yahoo!? >Tired of spam? Yahoo! Mail has the best spam protection around >http://mail.yahoo.com >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From flaxeater at yahoo.com Sat Oct 9 16:43:28 2004 From: flaxeater at yahoo.com (Chad Crabtree) Date: Sat Oct 9 16:43:32 2004 Subject: [Tutor] how to strip whitespaces from a string. Message-ID: <20041009144328.481.qmail@web52605.mail.yahoo.com> Lloyd Kvam wrote: >>>>s = " I am Learning Python " >>>>''.join( s.split() ) >>>> >>>> >'IamLearningPython' > > > I guess it always helps to look a little closer at the documentation. I just looked this up and of course it's right there. This method is best because it will work on any whitespace. s="""I am Learning Python NOw!!!! """ print ''.join(s.split()) IamLearningPythonNOw!!!! From alipolatel at yahoo.com Sat Oct 9 18:09:54 2004 From: alipolatel at yahoo.com (Ali Polatel) Date: Sat Oct 9 18:09:57 2004 Subject: [Tutor] Process.. Message-ID: <20041009160954.71830.qmail@web61003.mail.yahoo.com> How can i make a Python programme run as a process?I mean neither windows nor console... I'll write a bot which does certain things in a server and I don't want it to appear as a window all the time because my computer is semi-public(my brother,father etc.)they may close it.. Has python or py2exe such a feature? thanks --------------------------------- Do you Yahoo!? Yahoo! Mail Address AutoComplete - You start. We finish. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20041009/5e7b3fcc/attachment.html From shitizb at yahoo.com Sat Oct 9 19:00:09 2004 From: shitizb at yahoo.com (Shitiz Bansal) Date: Sat Oct 9 19:00:12 2004 Subject: [Tutor] Process.. In-Reply-To: <20041009160954.71830.qmail@web61003.mail.yahoo.com> Message-ID: <20041009170009.95712.qmail@web53805.mail.yahoo.com> you may use os.spawn*() family of functions in python. the detailed documentation is available in python manual. Ali Polatel wrote: How can i make a Python programme run as a process?I mean neither windows nor console... I'll write a bot which does certain things in a server and I don't want it to appear as a window all the time because my computer is semi-public(my brother,father etc.)they may close it.. Has python or py2exe such a feature? thanks --------------------------------- Do you Yahoo!? Yahoo! Mail Address AutoComplete - You start. We finish._______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20041009/85619754/attachment.htm From flaxeater at yahoo.com Sat Oct 9 21:15:18 2004 From: flaxeater at yahoo.com (Chad Crabtree) Date: Sat Oct 9 21:15:21 2004 Subject: [Tutor] Ftplib error using dir() Message-ID: <20041009191518.78019.qmail@web52602.mail.yahoo.com> WEISS, MARK (NB) wrote: >Hello Group, > >I am trying to build a FTP client and I am getting a 'connection >refused' error when I call the code listed below. I can login fine (in >my script), and I connect through a command prompt using the ftp command >(Win2K) I can list the files in the remote directory. Also, to further >confuse the matter I can run this code against a local ftp server and >return the list of files. > > > How about an error message? _______________________________ Do you Yahoo!? Declare Yourself - Register online to vote today! http://vote.yahoo.com From flaxeater at yahoo.com Sat Oct 9 21:17:04 2004 From: flaxeater at yahoo.com (Chad Crabtree) Date: Sat Oct 9 21:17:07 2004 Subject: [Tutor] Re: OOP books Message-ID: <20041009191704.20367.qmail@web52609.mail.yahoo.com> Max Noel wrote: > > On Oct 8, 2004, at 22:20, John Fabiani wrote: > >>> IMHO, if you learn OOP in one programming language, it >>> probably isn't much of a leap to use OOP in other programming >>> languages. >> >> >> You know that the VB6 guys think they were programming in OOP!! |; ) > > > Yeah, but we're talking about programming languages here. Not VB. Seriously though what is wrong with VB? It gets things done with little syntactic overhead, or rather less than C++ or Java. I feel honestly it's pretty close to python except for pythons ubiquitous containers. __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From flaxeater at yahoo.com Sat Oct 9 21:19:50 2004 From: flaxeater at yahoo.com (Chad Crabtree) Date: Sat Oct 9 21:19:53 2004 Subject: [Tutor] reversing a string Message-ID: <20041009191950.21035.qmail@web52609.mail.yahoo.com> Lloyd Kvam wrote: >> >>> 'qwerty'[-1::-1] >>'ytrewq' >> >>Rich >> >> > > This works in 2.3: > > > > >Or the slightly simpler to type: > > > >>>>'gfedcba'[::-1] >>>> >>>> >'abcdefg' > > Could Someone please explain what just happened there? I know it's slicing, I just don't understand how. __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From flaxeater at yahoo.com Sat Oct 9 21:23:16 2004 From: flaxeater at yahoo.com (Chad Crabtree) Date: Sat Oct 9 21:23:19 2004 Subject: [Tutor] Process.. Message-ID: <20041009192316.95103.qmail@web52604.mail.yahoo.com> Shitiz Bansal wrote: > you may use os.spawn*() family of functions in python. the detailed > documentation is available in python manual. > > */Ali Polatel /* wrote: > > How can i make a Python programme run as a process?I mean neither > windows nor console... I'll write a bot which does certain things > in a server and I don't want it to appear as a window all the time > because my computer is semi-public(my brother,father etc.)they may > close it.. > Has python or py2exe such a feature? > thanks > > ------------------------------------------------------------------------ > When I've done this in the past I just used pythonw with no GUI and this does that. __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From rmkrauter at yahoo.com Sat Oct 9 23:06:06 2004 From: rmkrauter at yahoo.com (Rich Krauter) Date: Sat Oct 9 23:06:06 2004 Subject: [Tutor] reversing a string In-Reply-To: <20041009191950.21035.qmail@web52609.mail.yahoo.com> References: <20041009191950.21035.qmail@web52609.mail.yahoo.com> Message-ID: <416852BE.30003@yahoo.com> Chad Crabtree wrote: > Lloyd Kvam wrote: >>>>>'gfedcba'[::-1] >>'abcdefg' > Could Someone please explain what just happened there? I know it's > slicing, I just don't understand how. From http://docs.python.org/lib/typesseq.html: s[i:j:k] --> slice of s from i to j with step k """ The slice of s from i to j with step k is defined as the sequence of items with index x = i + n*k such that 0 <= n < abs(i-j). If i or j is greater than len(s), use len(s). If i or j are omitted then they become "end" values (which end depends on the sign of k). Note, k cannot be zero. """ The following may not be the right way to think about what is really happening, but maybe it's easier to remember than the above explanation, at least for this particular case. Here's the familiar way to make a copy of an entire sequence. >>> 'qwerty'[:] 'qwerty' Now, make a copy of the entire sequence, but be explicit about the step size. >>> 'qwerty'[::1] 'qwerty' Make a copy of the sequence, but use -1 as the step size (note what the docs, quoted above, say about negative step sizes). >>> 'qwerty'[::-1] 'ytrewq' Hope that helps. Rich From kent_johnson at skillsoft.com Sat Oct 9 23:24:52 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Sat Oct 9 23:25:01 2004 Subject: [Tutor] OOP books In-Reply-To: References: <000d01c4acce$3e6ae5d0$665428cf@JSLAPTOP> Message-ID: <6.1.0.6.0.20041009171900.02a14e48@mail4.skillsoft.com> I don't have a book to recommend that directly teaches OOP, but rather some that show by example. Design Patterns: Elements of Reusable Object-Oriented Software is a classic. It shows you a number of common object-oriented software patterns. http://www.aw-bc.com/catalog/academic/product/0,1144,0201633612,00.html Agile Software Development: Principles, Patterns, and Practices demonstrates object-oriented design and design patterns in the context of agile development. http://www.objectmentor.com/resources/bookstore/books/AgileSoftwareDevelopmentPPP Refactoring: Improving the Design of Existing Code will show you how to recognize code "smells" and apply simple refactorings to improve it. http://martinfowler.com/books.html#refactoring Kent At 05:54 PM 10/8/2004 +0400, Dmitry V. Peryshkov wrote: >Hello, everyone! > >I am a novice in the object oriented programming. I have achieved some >success in learning of the syntax of the Python language. But I cannot >find some book related to general concept of the OOP, which would be >rather useful as well as simple and interesting. Could you recommend some >books of this kind? > >Thanks in advance, > >Dmitry Peryshkov. >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From flaxeater at yahoo.com Sun Oct 10 05:15:08 2004 From: flaxeater at yahoo.com (Chad Crabtree) Date: Sun Oct 10 05:15:11 2004 Subject: [Tutor] token parser article Message-ID: <20041010031508.33359.qmail@web52604.mail.yahoo.com> pyparsing is a fairly new parsing module for Python - http://pyparsing.sourceforge.net/. With pyparsing you build up a syntax out of simple building blocks. I've been wanting to try it out. I found it very easy to use. Here is what is looks like with kumar's original example: >>> s='[AKT|PI3K][RHOA|BCL:CDC42:IKK:RAC1:RAL:RALBP1]' >>> from pyparsing import * I'll build the parser from the inside out, starting with simple tokens and combining them to recognize more and more complex parts of the complete string. First I create a parse token to represent the key portion of each entry. A keyToken is a run of any number of contiguous letters and numbers: >>> keyToken = Word(alphanums) The scanString() method of a parser element searches a string for anything that matches the element. It is a handy way to check that you are on the right track. scanString() is a generator function so you have to pass the result to list() if you want to print it out. keyToken matches all the words in the string: >>> list(keyToken.scanString(s)) [((['AKT'], {}), 1, 4), ((['PI3K'], {}), 5, 9), ((['RHOA'], {}), 11, 15), ((['BCL'], {}), 16, 19), ((['CDC42'], {}), 20, 25), ((['IKK'], {}), 26, 29), ((['RAC1'], {}), 30, 34), ((['RAL'], {}), 35, 38), ((['RALBP1'], {}), 39, 45)] valueToken will match the pieces of the value lists.. It's the same as keyToken, just a run of alphanumeric characters: >>> valueToken = Word(alphanums) Now here is something more interesting - valueList matches one or more valueTokens separated by colons: >>> valueList = delimitedList(valueToken, delim=':') >>> list(valueList.scanString(s)) [((['AKT'], {}), 1, 4), ((['PI3K'], {}), 5, 9), ((['RHOA'], {}), 11, 15), ((['BCL', 'CDC42', 'IKK', 'RAC1', 'RAL', 'RALBP1'], {}), 16, 45)] It matches the keys, too, but that's just because we haven't given it enough context yet. Notice how the list 'BCL', 'CDC42', etc. has been collected for us. Now let's start putting the key and the valueList together. pyparsing lets you do this just by adding parser elements together. You include literal elements by adding in the strings that represent them: >>> entry = '[' + keyToken + '|' + valueList + ']' >>> list(entry.scanString(s)) [((['[', 'AKT', '|', 'PI3K', ']'], {}), 0, 10), ((['[', 'RHOA', '|', 'BCL', 'CDC42', 'IKK', 'RAC1', 'RAL', 'RALBP1', ']'], {}), 10, 46)] That's pretty cool! entry separates the key and the valueList. We don't really want the literals in the token list, though. We can tell pyparsing to suppress them: >>> entry = Suppress('[') + keyToken + Suppress('|') + valueList + Suppress(']') >>> list(entry.scanString(s)) [((['AKT', 'PI3K'], {}), 0, 10), ((['RHOA', 'BCL', 'CDC42', 'IKK', 'RAC1', 'RAL', 'RALBP1'], {}), 10, 46)] That looks like we're getting somewhere. Let's add one more rule, to find multiple entries: >>> entryList = ZeroOrMore(entry) >>> list(entryList.scanString(s)) [((['AKT', 'PI3K', 'RHOA', 'BCL', 'CDC42', 'IKK', 'RAC1', 'RAL', 'RALBP1'], {}), 0, 46)] Now we've matched the whole string with a single parser element, but the list of tokens is all glommed together again! Not to worry...pyparsing lets you define actions associated with each parser element. We can add an action to the 'entry' element that pulls out the tokens we want and puts them in a dictionary: >>> dd = {} >>> def processEntry(s, loc, toks): ... key, value = toks[0], toks[1:] ... dd[key] = value ... >>> entry.setParseAction(processEntry) processEntry() gets three arguments. The third one contains the tokens that match the associated rule. toks is actually a ParseResult object, but it acts a lot like a list. We can use the first token as a key and the rest of the list as the value for a dictionary. Finally we use entryList.parseString() to activate the parser and apply the parse action: >>> entryList.parseString(s) (['AKT', 'PI3K', 'RHOA', 'BCL', 'CDC42', 'IKK', 'RAC1', 'RAL', 'RALBP1'], {}) >>> dd {'RHOA': ['BCL', 'CDC42', 'IKK', 'RAC1', 'RAL', 'RALBP1'], 'AKT': ['PI3K']} dd is now the dictionary requested by the original poster :-) Here is the whole program: from pyparsing import * s='[AKT|PI3K][RHOA|BCL:CDC42:IKK:RAC1:RAL:RALBP1]' # Global variables to accumulate results dd = {} # Syntax definition keyToken = Word(alphanums) valueToken = Word(alphanums) valueList = delimitedList(valueToken, delim=':') entry = Suppress('[') + keyToken + Suppress('|') + valueList + Suppress(']') entryList = ZeroOrMore(entry) def processEntry(s, loc, toks): key, value = toks[0], toks[1:] dd[key] = value entry.setParseAction(processEntry) entryList.parseString(s) print dd By the way delimitedList() is just a shortcut, we could have written this with the same result: >>> valueList = valueToken + ZeroOrMore(Suppress(':' )+ valueToken) Kent At 07:42 PM 10/7/2004 -0700, Chad Crabtree wrote: >Danny Yoo wrote: > >We can parse this pretty informally, by using regular expressions. >But > >there's also a fairly systematic way we can attack this: we can go >all > >out and use a token/parser approach. Would you like to hear about >that? > > > > >I don't know about kumar but I would love to hear about this because >I've been reading about it but it has not sunk in yet. > >__________________________________________________ >Do You Yahoo!? >Tired of spam? Yahoo! Mail has the best spam protection around >http://mail.yahoo.com >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From flaxeater at yahoo.com Sun Oct 10 06:25:46 2004 From: flaxeater at yahoo.com (Chad Crabtree) Date: Sun Oct 10 06:25:48 2004 Subject: [Tutor] token parser article Message-ID: <20041010042546.43913.qmail@web52605.mail.yahoo.com> My previous post was a total mistake. My apologies __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From pythonTutor at venix.com Sun Oct 10 19:18:52 2004 From: pythonTutor at venix.com (Lloyd Kvam) Date: Sun Oct 10 19:18:59 2004 Subject: [Tutor] Re: OOP books In-Reply-To: <20041009191704.20367.qmail@web52609.mail.yahoo.com> References: <20041009191704.20367.qmail@web52609.mail.yahoo.com> Message-ID: <1097428732.2739.24.camel@laptop.venix.com> On Sat, 2004-10-09 at 15:17, Chad Crabtree wrote: > Max Noel wrote: > > > > > On Oct 8, 2004, at 22:20, John Fabiani wrote: > > > >>> IMHO, if you learn OOP in one programming language, it > >>> probably isn't much of a leap to use OOP in other programming > >>> languages. > >> > >> > >> You know that the VB6 guys think they were programming in OOP!! |; > ) > > > > > > Yeah, but we're talking about programming languages here. Not > VB. > > Seriously though what is wrong with VB? It gets things done with > little > syntactic overhead, or rather less than C++ or Java. I feel honestly > > it's pretty close to python except for pythons ubiquitous containers. My VB experience ran from VB3 to VB6. VB supports an object oriented notation, but does not allow you to use inheritance in your code. It lacks the ability to pass functions as parameters like Python allows. Also user defined types are second class and are disallowed as parameters under some circumstances (I do not recall all of the details). Verity Stobb has written a critique of VB that Google should be able to locate. The ability to combine graphical elements in an easy to use drag and drop environment is nice. Unfortunately, I do not think the language is adequate when you start trying to do more complex programming. I have been reasonably happy on Windows using VB to provide a GUI interface to Python code packaged as a COM object. However, I expect to use wxWindows in any future GUI programming - even on Windows. > > > > __________________________________________________ > Do You Yahoo!? > Tired of spam? Yahoo! Mail has the best spam protection around > http://mail.yahoo.com > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp From pythonTutor at venix.com Sun Oct 10 19:23:31 2004 From: pythonTutor at venix.com (Lloyd Kvam) Date: Sun Oct 10 19:23:34 2004 Subject: [Tutor] Ftplib error using dir() In-Reply-To: <20041009191518.78019.qmail@web52602.mail.yahoo.com> References: <20041009191518.78019.qmail@web52602.mail.yahoo.com> Message-ID: <1097429010.2739.30.camel@laptop.venix.com> On Sat, 2004-10-09 at 15:15, Chad Crabtree wrote: > WEISS, MARK (NB) wrote: > > >Hello Group, > > > >I am trying to build a FTP client and I am getting a 'connection > >refused' error when I call the code listed below. I can login fine > (in > >my script), and I connect through a command prompt using the ftp > command > >(Win2K) I can list the files in the remote directory. Also, to > further > >confuse the matter I can run this code against a local ftp server > and > >return the list of files. > > > > > > > How about an error message? This might be a firewall issue. Putting the FTP server into passive mode may do the trick. Originally FTP servers connected back to the client to send data. Passive mode has the server wait for the client to make the data connection. Typically a client's firewall will allow the client to connect to the ftp server but block connections originating from the ftp server. > > > _______________________________ > Do you Yahoo!? > Declare Yourself - Register online to vote today! > http://vote.yahoo.com > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp From Lbrannma at yahoo.com Sun Oct 10 20:00:42 2004 From: Lbrannma at yahoo.com (L&L) Date: Sun Oct 10 20:01:29 2004 Subject: [Tutor] parsing a string Message-ID: <6.1.2.0.1.20041010195814.01a84a70@pop.mail.yahoo.com> Hi All, Suppose I have a string that looks like this: 1 1997 2 "Henrik Larsson" I want to convert the string to a list, with four members. Is there an easy way to do this (the hard way would be to find all quotes, save to a separate string the area between the quotes, remove this part from the original string, use string.split, and put the string back together. Thanks. From kent_johnson at skillsoft.com Sun Oct 10 20:40:39 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Sun Oct 10 20:40:45 2004 Subject: [Tutor] parsing a string In-Reply-To: <6.1.2.0.1.20041010195814.01a84a70@pop.mail.yahoo.com> References: <6.1.2.0.1.20041010195814.01a84a70@pop.mail.yahoo.com> Message-ID: <6.1.0.6.0.20041010143602.0289d4c8@mail4.skillsoft.com> You can do this with the CSV module or with regular expressions: import csv, re # Data in a list so csv.reader can iterate over it data = [ '1 1997 2 "Henrik Larsson"' ] r = csv.reader(data, delimiter=' ') for row in r: print row # prints ['1', '1997', '2', 'Henrik Larsson'] # Regular expression to match three groups of digits separated by whitespace, then whatever is between the quotes lineRe = re.compile(r'(\d+)\s+(\d+)\s+(\d+)\s+"(.*)"') match = lineRe.search(data[0]) print match.group(1, 2, 3, 4) # prints ('1', '1997', '2', 'Henrik Larsson') The csv version might be handier if the data is in a file or file-like object, because it expects to iterate over the input. Also if the quotes are optional it will work just fine. The regex version might be better if you get the strings one at a time. If the quotes are optional you should change the regex to something like this: r'(\d+)\s+(\d+)\s+(\d+)\s+"?(.*)"? Kent At 08:00 PM 10/10/2004 +0200, L&L wrote: >Hi All, > >Suppose I have a string that looks like this: > >1 1997 2 "Henrik Larsson" > >I want to convert the string to a list, with four members. Is there an >easy way to do this (the hard way would be to find all quotes, save to a >separate string the area between the quotes, remove this part from the >original string, use string.split, and put the string back together. > >Thanks. > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From tgrimes at teleport.com Sun Oct 10 21:18:43 2004 From: tgrimes at teleport.com (TJ) Date: Sun Oct 10 21:19:06 2004 Subject: [Tutor] parsing a string In-Reply-To: <6.1.2.0.1.20041010195814.01a84a70@pop.mail.yahoo.com> References: <6.1.2.0.1.20041010195814.01a84a70@pop.mail.yahoo.com> Message-ID: >Suppose I have a string that looks like this: > >1 1997 2 "Henrik Larsson" > >I want to convert the string to a list, with four members. Is there >an easy way to do this (the hard way would be to find all quotes, >save to a separate string the area between the quotes, remove this >part from the original string, use string.split, and put the string >back together. > Another way to do this for the string format you specify is to remove the double quotes and then only split the first 3 items. >>> st = '1 1997 2 "Henrik Larsson"' >>> st = st.replace('"', '') >>> st.split(None, 3) ['1', '1997', '2', 'Henrik Larsson'] TJ From copellifulvio at yahoo.it Fri Oct 1 14:59:42 2004 From: copellifulvio at yahoo.it (Fulvio Copex) Date: Mon Oct 11 01:14:44 2004 Subject: [Tutor] invoking system commands from python In-Reply-To: Message-ID: <20041001125942.53676.qmail@web86904.mail.ukl.yahoo.com> Dear Danny, thank you very much for your kind answer. Besides solving properly the first part of the problem, you undirectly gave me some hints. The program, modified as you suggested, works properly. The fact is that the function copy was an example just to make things easier to understand. The command I want to launch is "R language" a powerful statistical application, the parameters are built-in functions of R language. Maybe this is too difficult to do just with the python function 'popen' . In fact I tried: **************************************** import os os.chdir('C:\\Programmi\\R\\rw1090\\miei_files') cmd = '.RData --slave --no -save' parameters="q()" myCmd=os.popen("%s %s" % (cmd, parameters)) exitCode = myCmd.close() if exitCode: print '%s failed, this probably says why:\n%s' % (cmd, stdout) **************************************** and the R language gui application opens properly, but the q() function (that should close the gui) doesn't seem to be invoked. How can I get the system reply when I launch a command? However as you suggested, maybe it's better to look if someone has already built the wheel, and in fact I found that there are two python packages: Rpy and RSPython. that deal with R language I will try to make use of them. I wonder, have you never heard about them? Thanks again, cheers, Fulvio. Danny Yoo wrote: On Wed, 29 Sep 2004, Fulvio Copex wrote: > i'm new to this list and to python too. > I'm using active state python 2.3 on win32, > my problem is the following: > I want learn how to execute system command passing parameters. > > for example to copy a file I've tried to write this script: > > ***************************** > import os > os.chdir(''myDirectory") > cmd="copy" > parameters="file1 file1_backup" > myCmd = os.popen(cmd,'w') > myCmd.write(parameters) > exitCode = myCmd.close() > if exitCode: > print '%s failed, this probably says why:\n%s' % (cmd, myCmd) Hi Fulvio, There's a syntax problem here: > os.chdir(''myDirectory") ^^ but you probably have fixed this already. There's a more important problem in the use of os.popen(): > myCmd = os.popen(cmd,'w') > myCmd.write(parameters) Your 'copy' command may need to take in the parameters at the same time as the popen call, as additional "command-line arguments". I'm not sure how your 'copy' command works, but it may not be listening to standard input. So you may need to do something like this: os.popen("%s %s" % (cmd, parameters)) where we construct the command line all at once, and then pass that off to popen(). That being said, when you're programming in Python, you actually want to avoid using os.popen() or os.system() if you can help it. *grin* The reason is because they're really OS-specific: you can't then take the same program on Windows and expect it to work on a Unix system, at least, not without a lot of work. It's also fraught with security problems. There's already a file-copying function in the 'shutil' shell utilities module in the Standard Library: http://www.python.org/doc/lib/module-shutil.html So a better way to do file copying is to use shutils.copy(). ### import os import shutils os.chdir("myDirectory") shutils.copy("file1", "file1_backup") ### Not only is this easier to read, but it should be much more portable across operating systems. If you have more questions, please feel free to ask. Good luck! --------------------------------- Scopri Mister Yahoo! - il fantatorneo sul calcio di Yahoo! Sport' -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20041001/b0d1df2f/attachment.html From mw at acl.icnet.uk Tue Oct 5 15:47:39 2004 From: mw at acl.icnet.uk (Matt Williams) Date: Mon Oct 11 01:14:47 2004 Subject: [Tutor] Simple list question Message-ID: <1096984059.27889.8.camel@dhcp0320.acl.icnet.uk> Dear Tutor, I got this script to permute a list off a website. It works, but when I added the append function, it returns a list that is non-permuted. Any ideas why? Matt def permute(list): s=[] len_l = len(list) if len_l == 1: print l s.append(l) return for i in range (0, len_l): print i permute(list[1:]) # now change position of first element with next (rotate will do it?) list.append(list.pop(0)) # reflect this change in the main list l[len(l) - len_l:] = list l=["a","b","c"] permute(l) From whereU at now.com Wed Oct 6 09:37:27 2004 From: whereU at now.com (Eric Pederson) Date: Mon Oct 11 01:14:49 2004 Subject: [Tutor] Write string into files Message-ID: <20041005233727.109427719.whereU@now.com> Ms Soo Chong > > ##################################################### > A problem occurred in a Python script. Here is the > sequence of function calls leading up to the error, > in the order they occurred. > > /var/www/cgi-bin/sf/run_des.py > 192 str += "" + blame + "" > TypeError: cannot concatenate 'str' and 'NoneType' > objects I believe directly above is the key error message: you can not add a string to (nothing). Trying to concatenate a string to a null object is a type mismatch. Not sure what the optimal way to handle this is, but note the following interactive session, which might provide you some hints. >>> nothing=None >>> print nothing None >>> if (nothing == None): nothing="" >>> print nothing >>> something=""+nothing+"" >>> print something Eric Pederson http://www.songzilla.blogspot.com ::::::::::::::::::::::::::::::::::: domainNot="@something.com" domainIs=domainNot.replace("s","z") ePrefix="".join([chr(ord(x)+1) for x in "do"]) mailMeAt=ePrefix+domainIs ::::::::::::::::::::::::::::::::::: From apb_4 at hotmail.com Wed Oct 6 23:46:37 2004 From: apb_4 at hotmail.com (Adam Bark) Date: Mon Oct 11 01:14:50 2004 Subject: [Tutor] CGI implementation Message-ID: Is it possible to run a CGI script from IE6 from the hard drive? Everytime I try to open a CGI script from HTML it just shows the script. Also when putting the script on the internet do you have to host the script and Python? I wanted to use something Lycos Tripod free hosting which doesn't have enough space for Python and no cgi-bin. Thanks Adam _________________________________________________________________ Stay in touch with absent friends - get MSN Messenger http://www.msn.co.uk/messenger From bobhines at triad.rr.com Thu Oct 7 17:41:02 2004 From: bobhines at triad.rr.com (Robert Hines) Date: Mon Oct 11 01:14:52 2004 Subject: [Tutor] Detecting EOF Message-ID: <009001c4ac84$0cdb84b0$6501a8c0@mickeybobxp> How do you detect the end of a file? Suppose I have a pickle file with a variable number of objects. How do I unpickle the objects without generating an EOF exception? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20041007/ff02944e/attachment.htm From maxnoel_fr at yahoo.fr Mon Oct 11 01:28:55 2004 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Mon Oct 11 01:28:59 2004 Subject: [Tutor] CGI implementation In-Reply-To: References: Message-ID: <271BF304-1B14-11D9-9CA6-000393CBC88E@yahoo.fr> On Oct 6, 2004, at 22:46, Adam Bark wrote: > Is it possible to run a CGI script from IE6 from the hard drive? > Everytime I try to open a CGI script from HTML it just shows the > script. Also when putting the script on the internet do you have to > host the script and Python? I wanted to use something Lycos Tripod > free hosting which doesn't have enough space for Python and no > cgi-bin. Thanks > Adam Here's what happens when you consult a CGI page on the Internet: - Your web browser sends a request for the page (for example, /index.py) to the web server. - The server gets the request, extracts the file name from it, and checks whether or not the file exists. - The file exists. If it were an HTML document, the server would just send its contents back to you. However, the server detects that it is a Python script, so instead it loads a Python interpreter, runs the script and sends the standard out back to your browser. - Your browser, which has no idea of what's going on backstage, receives a stream of data which happens to be HTML, and renders it. All of this means that to be able to test CGI scripts on your local machine, you'll need to install a web server. Apache, which can be found at http://httpd.apache.org/ , is a powerful, secure and Free web server -- Wild_Cat maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From amonroe at columbus.rr.com Mon Oct 11 03:07:30 2004 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Mon Oct 11 03:07:40 2004 Subject: [Tutor] CGI implementation In-Reply-To: <271BF304-1B14-11D9-9CA6-000393CBC88E@yahoo.fr> References: <271BF304-1B14-11D9-9CA6-000393CBC88E@yahoo.fr> Message-ID: <98353221685.20041010210730@columbus.rr.com> > All of this means that to be able to test CGI scripts on your local > machine, you'll need to install a web server. Apache, which can be > found at http://httpd.apache.org/ , is a powerful, secure and Free web > server Or for a quick & easy webserver (Windows only): http://www.analogx.com/contents/download/network/sswww.htm From dyoo at hkn.eecs.berkeley.edu Mon Oct 11 03:39:27 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Oct 11 03:40:18 2004 Subject: [Tutor] Regular expression In-Reply-To: <20041008024215.83731.qmail@web52602.mail.yahoo.com> Message-ID: > >Hmmm! Ok, it sounds like you're making some kind of mini-language to > >make it easier to type out Graphviz dotty files. Each one of these > >out-edge descriptions appears to have some kind of structure: > > > > out_edge_description ::= > > open_brace > > start_vertex_name > > pipe_symbol > > a_bunch_of_colon_separated_names > > close_brace > > > >We can parse this pretty informally, by using regular expressions. > >But there's also a fairly systematic way we can attack this: we can go > >all out and use a token/parser approach. Would you like to hear about > >that? > > > I don't know about kumar but I would love to hear about this because > I've been reading about it but it has not sunk in yet. [Warning: really long message ahead. I have to learn how to explain this better... *sigh*] Ok, let's do a demonstration of a tokenizer/parser technique to this problem. Just to make the problem slightly different, let's try to write a program that takes strings like: "[3,1,4,1,5]" and translate them to an equivalent Python list. Yes, I know that we can use eval() to do this, but since we say that eval() is evil, we'd better show an alternative way to do this. *grin* The tokenizer/parser technique is a two step process: tokenization: take the string, and break it down into chunks. parsing: apply some structure to the chunks. Concretely, a "tokenization" of a string like "[3,1,4,1,5]" will puree it into something like this: [("LEFT-BRACKET",), ("NUMBER", 3), ("COMMA",), ("NUMBER", 4), ("COMMA",), ("NUMBER", 4), ("COMMA",), ("NUMBER", 1), ("COMMA",), ("NUMBER", 5), ("RIGHT-BRACKET")] This step is actually not too bad: we can write such a tokenizer by using some string manipulation. Here's a tokenize() that does the grunt-work: ### import re def tokenize(s): """Breaks the string 's' into a list of tokens. A token can be of the following types: (LEFT-BRACKET,) (RIGHT-BRACKET,) (COMMA,) (NUMBER, n) where 'n' is an integer """ tokens = [] patterns = [ (re.compile(r'\['), "LEFT-BRACKET"), (re.compile(r'\]'), "RIGHT-BRACKET"), (re.compile(','), "COMMA"), (re.compile('\d+'), "NUMBER") ] while True: if not s: break for regex, token_type in patterns: match = regex.match(s) if match: ## Treat numbers slightly differently, since we want ## to "int" the result. if token_type == 'NUMBER': tokens.append(('NUMBER', int(match.group()))) else: tokens.append((token_type,)) s = s[match.end():] break else: raise ValueError, ("I dunno how to parse %r" % s) return tokens ### Hmm... that's slightly messy; my apologies! Before I go on, I'd better mention that there are good automated tools for Python that we can use to handle tokenization and parsing; I'm just showing how we'd do this all from scratch. If we were to use something like the Ply package: http://systems.cs.uchicago.edu/ply/ then all of this would be much much shorter. I want to show how this stuff works, by hand, so that the automated tools will make more sense. But if I were doing this for real, I'd definitely use a tool like Ply instead. *grin* Anyway, let's see how this tokenize() works: ### >>> tokenize("[1,2,3]") [('LEFT-BRACKET',), ('NUMBER', 1), ('COMMA',), ('NUMBER', 2), ('COMMA',), ('NUMBER', 3), ('RIGHT-BRACKET',)] >>> >>> >>> tokenize("[3,1,4,1,5]") [('LEFT-BRACKET',), ('NUMBER', 3), ('COMMA',), ('NUMBER', 1), ('COMMA',), ('NUMBER', 4), ('COMMA',), ('NUMBER', 1), ('COMMA',), ('NUMBER', 5), ('RIGHT-BRACKET',)] >>> >>> tokenize("I should break") Traceback (most recent call last): File "", line 1, in ? File "/usr/tmp/python-16929BsN", line 34, in tokenize ValueError: I dunno how to parse 'I should break' ### Ok, we have a tokenizer, but we still don't have a list of numbers. That's where the "parser" part comes in. A parser is the thing that'll reconstruct the number list from these tokens. A parser is actually a bunch of grammar rules. In English, for example, we know that a sentence can be made up of a "subject", a "verb" and an "object": sentence ::= subject verb object For example: I love bees is a sentence; "I" is the subject, "love" is the verb, and "bees" is the object. sentence ::= subject verb object --> "I" verb object --> "I" "love" object --> "I" "love" "bees" Our job is to figure out the grammatical rules that number lists follow; once we've done this, then writing a parser to recognize those rules will be a surprisingly direct translation. Let's look at a few examples of number lists. [1,2,3] [3,1,4,1,5] [7] [] We can say that a number list is made up of a left bracket, a bunch of comma-separated numbers, and a right bracket. More formally, we'd say: number-list ::= LEFT-BRACKET nums RIGHT-BRACKET But what do comma-separated numbers look like? That can either be empty (like the last example, when we want to handle "[]"): nums ::= Or they can have a single number: nums ::= NUMBER And of course, they can have more than one number: let's handle that too: nums ::= NUMBER comma-nums comma-nums ::= comma-nums ::= COMMA NUMBER comma-nums That's actually all the rules we need. Let me bring all these "grammar" rules together in one place: ### number-list ::= LEFT-BRACKET nums RIGHT-BRACKET nums ::= nums ::= NUMBER nums ::= NUMBER comma-nums comma-nums ::= comma-nums ::= COMMA NUMBER comma-nums ### Hmm... Actually, one of those rules is redundant; let me take that redundant rule out: ### 1. number-list ::= LEFT-BRACKET nums RIGHT-BRACKET 2. nums ::= 3. nums ::= NUMBER comma-nums 4. comma-nums ::= 5. comma-nums ::= COMMA NUMBER comma-nums ### Ok, here is our grammar for number lists. I'm just numbering our rules to make life a little easier. But this is all very weird and inscrutable! *grin* So let's take a quick look at how these rules work. Let's say that we have something like "[1,2]". How can we get our grammar rules to fit our tokens? We should start off with the main rule, the 'number-list' rule: number-list ::= LEFT-BRACKET nums RIGHT-BRACKET When we're trying to figure out what 'nums' stands for, we have two possible rules to choose from: ### 2. nums ::= 3. nums ::= NUMBER comma-nums ### Let's substitute nums with Rule Three: number-list ::= LEFT-BRACKET nums RIGHT-BRACKET --> LEFT-BRACKET NUMBER comma-nums RIGHT-BRACKET We can then substitute comma-nums with Rule Five: number-list ::= LEFT-BRACKET nums RIGHT-BRACKET --> LEFT-BRACKET NUMBER comma-nums RIGHT-BRACKET --> LEFT-BRACKET NUMBER COMMA NUMBER comma-nums RIGHT-BRACKET and then finally choose Rule Four on 'comma-nums': number-list ::= LEFT-BRACKET nums RIGHT-BRACKET --> LEFT-BRACKET NUMBER comma-nums RIGHT-BRACKET --> LEFT-BRACKET NUMBER COMMA NUMBER comma-nums RIGHT-BRACKET --> LEFT-BRACKET NUMBER COMMA NUMBER RIGHT-BRACKET And the final derived rule is something that'll fit against "[1,2]". --> LEFT-BRACKET NUMBER COMMA NUMBER RIGHT-BRACKET [ 1 , 2 ] Let's look at those five rules again: ### number-list ::= LEFT-BRACKET nums RIGHT-BRACKET nums ::= NUMBER comma-nums nums ::= comma-nums ::= COMMA NUMBER comma-nums comma-nums ::= ### It turns out that turning these rules into Python code is actually pretty straightforward. Let's show what that looks like: ### def peek(tokens): """Peeks at the next token in our token list.""" return tokens[0] def eat(tokens, token_type): """Eats the next token, and returns it.""" assert tokens[0][0] == token_type return tokens.pop(0) def parse_number_list(tokens): """number-list ::= LEFT-BRACKET nums RIGHT-BRACKET""" eat(tokens, 'LEFT-BRACKET') result = parse_nums(tokens) eat(tokens, 'RIGHT-BRACKET') return result def parse_nums(tokens): """nums ::= NUMBER comma-nums nums ::= """ if peek(tokens)[0] == 'NUMBER': number = eat(tokens, 'NUMBER')[1] other_numbers = parse_comma_nums(tokens) return [number] + other_numbers else: return [] def parse_comma_nums(tokens): """comma_nums ::= COMMA NUMBER comma-nums comma_nums ::= """ if peek(tokens)[0] == 'COMMA': eat(tokens, 'COMMA') number = eat(tokens, 'NUMBER')[1] other_numbers = parse_comma_nums(tokens) return [number] + other_numbers else: return [] ### There's our parser. Each one of the 'parse_*' is responsible for choosing which rule can be applied. For example, the 'comma-num' rule has two choices to deal with: comma-nums ::= COMMA NUMBER comma-nums comma-nums ::= and so the corresponding 'parse_comma_nums' function does a quick check to see if the tokens have a COMMA coming up next. If so, then the first rule has to apply. And otherwise, the "empty" rule is in effect. Let's just check to see that all this mess does something useful. ### >>> parse_number_list(tokenize('[1,2]')) [1, 2] >>> >>> mylist = parse_number_list(tokenize('[3,1,4,1,5]')) >>> mylist[0] 3 ### Ok, good, this actually works. *grin* Now, all this work is complete overkill for parsing a simple list of numbers. But it's still slightly useful: notice that we hadn't handled whitespace: we might want to let people put spaces between commas, like "[1, 2, 3]" We can handle this by modifiying the tokenize() function to ignore whitespace. The nice thing to see is that the parsers don't need to worry so much about lexical issues. Another nice point is that the parsing technique can handle more complicated situations. Let's say we'd like to handle nested number lists: "[1,2,[3,[4]]]" This might look a bit scary, but we can actually attack this problem in almost the same way as the previous example. Here's a grammar to parse nested number lists: ### element-list ::= LEFT-BRACKET elements RIGHT-BRACKET elements ::= element comma-elements elements ::= element ::= NUMBER element ::= element-list comma-elements ::= COMMA element comma-elements comma-elements ::= ### The only big change here is that we modify the 'nums' rule so that it can handle arbitrary 'elements'. And elements can either be simple numbers or a nested list. Here's a translation of that grammar into Python code: ### def parse_element_list(tokens): eat(tokens, 'LEFT-BRACKET') result = parse_elements(tokens) eat(tokens, 'RIGHT-BRACKET') return result def parse_elements(tokens): if peek(tokens)[0] in ('NUMBER', 'LEFT-BRACKET'): elt = parse_element(tokens) other_elts = parse_comma_elements(tokens) return [elt] + other_elts else: return [] def parse_element(tokens): if peek(tokens)[0] == 'NUMBER': return eat(tokens, 'NUMBER')[1] else: return parse_element_list(tokens) def parse_comma_elements(tokens): if peek(tokens)[0] == 'COMMA': eat(tokens, 'COMMA') elt = parse_element(tokens) other_elts = parse_comma_elements(tokens) return [elt] + other_elts else: return [] ### And this works as well, without have to make changes to the tokenizer: ### >>> parse_element_list(tokenize('[1,[2,[3,[4]]]]')) [1, [2, [3, [4]]]] ### I went through this really darn fast, without explaining much of it at all. But I hope that some of it made some sense. *grin* The parsing technique that we've used here is known as "recursive descent". As a last note, recursive-descent parsing is the technique that Python itself uses to parse its language! If we look at the Python Reference Manual: http://www.python.org/doc/ref/exprlists.html#tok-expression_list we can see other examples of grammar rules that look suspiciously similar to the list-of-numbers example that we just worked out. *grin* I hope this helps! From johan at accesstel.co.za Mon Oct 11 09:00:36 2004 From: johan at accesstel.co.za (Johan Geldenhuys) Date: Mon Oct 11 09:01:33 2004 Subject: [Tutor] how to strip whitespaces from a string. In-Reply-To: <4166F82B.60308@mn.rr.com> References: <20041008180950.14652.qmail@web52602.mail.yahoo.com> <4166F82B.60308@mn.rr.com> Message-ID: <1097478036.4723.13.camel@linux.site> Skipped content of type multipart/alternative-------------- next part -------------- An embedded message was scrubbed... From: Anna Ravenscroft Subject: Re: [Tutor] how to strip whitespaces from a string. Date: Fri, 08 Oct 2004 22:27:23 +0200 Size: 6196 Url: http://mail.python.org/pipermail/tutor/attachments/20041011/60e9d62d/attachment-0001.mht From missive at hotmail.com Mon Oct 11 14:58:08 2004 From: missive at hotmail.com (Lee Harr) Date: Mon Oct 11 14:59:05 2004 Subject: [Tutor] Re: CGI implementation Message-ID: >> All of this means that to be able to test CGI scripts on your >>local >>machine, you'll need to install a web server. Apache, which can be >>found at http://httpd.apache.org/ , is a powerful, secure and Free web >>server > >Or for a quick & easy webserver (Windows only): >http://www.analogx.com/contents/download/network/sswww.htm > Or you could go all out with python and use twisted: http://www.twistedmatrix.com/ # acgi.rpy from twisted.web import static, twcgi path_to_python = '/usr/local/bin/python' path_to_cgi_bin = '/usr/home/lee/python/cgi/' class PyScript(twcgi.FilteredScript): filter = path_to_python resource = static.File(path_to_cgi_bin) resource.processors = {'.py': PyScript} #simple.py import cgi import cgitb; cgitb.enable() def main(): print 'Content-Type: text/html\n\n' print '' form = cgi.FieldStorage() if not form: print '''

foo:

''' else: print '''

Your form contained:

''' for field in form: print '

%s: %s' % (field, form.getfirst(field)) print '' if __name__ == '__main__': main() # now create and start the server # (I am not exactly sure how you would do this in windows...) $ mktap web -p 9999 --resource-script /usr/home/lee/python/cgi/acgi.rpy $ twistd -f web.tap # Then browse to http://localhost:9999/ _________________________________________________________________ Tired of spam? Get advanced junk mail protection with MSN 8. http://join.msn.com/?page=features/junkmail From my.mailing.lists at noos.fr Mon Oct 11 15:28:58 2004 From: my.mailing.lists at noos.fr (nik) Date: Mon Oct 11 15:29:05 2004 Subject: [Tutor] memory checking Message-ID: <416A8A9A.3010106@noos.fr> hi, I've got a c++ app calling python functions - are there any way I can check for memory problems (leaks etc)? Previously in my windows days I've used Boundschecker or Rational Purify, but now two things are different a) Python is in the mix, and b) I'm on linux - any advice would be helpful. My main concern is I'm not fully confident I'm using the Py_INCREF and Py_DECREF effectively - I know when I'm decref'ing at the wrong places as I end up with ref count 0 objects (and crashes), but I'm probably overly incref'ing - obviously I'd like make things a bit less hit or miss than that! nik From ChuckBaker at Pokynet.com Mon Oct 11 15:05:57 2004 From: ChuckBaker at Pokynet.com (Chuck Baker) Date: Mon Oct 11 15:34:14 2004 Subject: [Tutor] New Python forum Message-ID: <416A8535.000008.02060@FARFAL> Just wanted to let everyone know that I have created a new Python forum. You can check it out at my website http://ChuckBaker.org and click on the Messageboard link or access the forum directly at http://p200.ezboard com/fchuckbakerhomepagemessageboard13318frm16 Rev. Chuck Baker ICQ# 1816811 Yahoo ID: ChuckBaker11@Yahoo.com skype ID: ChuckBaker ChuckBaker@Pokynet.com http://ChuckBaker.org http://www.keen.com/RevChuckBaker Help Line: 1-800-275-5336 Ext. 0322651 Fax: 801-740-7293 Please read and sign my petition for President of the USA in 2004 at: http://www.petitiononline.com/ChuckB1/petition.html From dyoo at hkn.eecs.berkeley.edu Mon Oct 11 19:48:22 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Oct 11 19:48:33 2004 Subject: [Tutor] import'ing problems (path) In-Reply-To: <20041004232448.GE20593@johnsons-web.com> Message-ID: On Mon, 4 Oct 2004, Tim Johnson wrote: > * Tim Johnson [041004 15:23]: > > Hello Pythonists: > > I have installed a python package called webware > > at the following path: > > /home/tim/downloads/python/Webware-0.8.1 Hi Tim, Hmmm! Isn't Webware using the Distutils module distribution system? Let me check... weird, ok, so it looks like they don't. However, they do include some 'install.py' program to do the installation. Just to double check: did you run Webware's "install.py"? Good luck to you! From dyoo at hkn.eecs.berkeley.edu Mon Oct 11 20:11:15 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Oct 11 20:11:25 2004 Subject: [Tutor] import'ing problems (path) P.S.!! In-Reply-To: <20041005191136.GK27230@johnsons-web.com> Message-ID: On Tue, 5 Oct 2004, Tim Johnson wrote: > * Kent Johnson [041005 10:51]: > > It looks like WebKit doesn't want to see the Webware level in the package > > hierarchy. You could take everything out of the Webware directory and put > > it directly in site-packages or add the Webware directory to sys.path as I > > described before. Then try import WebKit.Page (without the WebWare prefix). > > Okay! add the following line: > sys.path.append('/usr/local/lib/python2.3/site-packages/Webware') > and the import is successful. Hi Tim, Ok, then this sounds like Webware has some silly problems with their module imports. Let me double check a few things... oh my goodness. That doesn't look right! There are some places in the WebKit that do some wacky imports. For example, Webware.WebKit.Object: ### Webware/WebKit/Object.py import os, sys try: import MiscUtils except: # When the Webware tarball unravels, # the components sit next to each other sys.path.append(os.path.abspath('..')) import MiscUtils from MiscUtils.NamedValueAccess import NamedValueAccess [text cut] ### They should not be dynamically fiddling with the system path like that! They may need to rewrite that as: ### import os.sys from Webware import * import MiscUtils ### Since they designed the Webware package to be 'from [module] import *' safe, they might as well use it. *grin* According to section 6.4.2 of the Python Tutorial (Intra-package References), http://www.python.org/doc/tut/node8.html#SECTION008420000000000000000 any module in the Webware.WebKit subpackage won't automatically see stuff at the toplevel Webware package. That's why they're running into import problems. But it looks like, rather than fixing the problem cleanly, they kludged a solution that only works if the current working directory is at the toplevel Webware directory. Argh. So the Webware developers to fix that; Webware needs to correct they way they import packages. The inner modules in ther should definitely NOT make changes to the sys.path variable. Hope this helps! From keridee at jayco.net Mon Oct 11 23:52:45 2004 From: keridee at jayco.net (Jacob S.) Date: Tue Oct 12 00:56:38 2004 Subject: [Tutor] how to strip whitespaces from a string. References: <20041008170757.54979.qmail@web53701.mail.yahoo.com> Message-ID: <005501c4afe5$ac0ed000$065428cf@JSLAPTOP> Hey guys. I have one more way to do it. >>> import string >>> s = "I have learned some python" >>> s = string.replace(s," ","") >>> s 'Ihavelearnedsomepython' Or you could do it this way. >>> s = "I have learned some python" >>> s = s.replace(" ","") >>> s 'Ihavelearnedsomepython' >>> # Notice no import string call >>> Or, if we wish to replace all of the whitespace charaters, which I believe would be best, we: >>> import string >>> s = "I have learned\tsome python" >>> for x in string.whitespace: . . . s = s.replace(x,"") . . . >>> s 'Ihavelearnedsomepython' There are other ways as well. That's okay though! I don't have time to say them now. As always, hope this helps, Jacob Schmidt From cyresse at gmail.com Tue Oct 12 09:05:09 2004 From: cyresse at gmail.com (Riumu Kuraku) Date: Tue Oct 12 09:05:15 2004 Subject: [Tutor] Getchr() in Msvcrt module Message-ID: Hello all, I'm playing around with getchar(), and I'm following Alan Gauld's tutorial. He states that characters read by getchar that are prefixed with '\x00' or '\xe0' are non-ASCII such as the function keys. Is Enter one of these keys? Space is obviously " ", but is Enter "\n" or something else? Is there somewhere in Python's documentation a list of how the keys such as Esc etc. are defined in ASCII/non-ASCII Apologies for the multiple questions. Thanks, Liam From rdm at rcblue.com Tue Oct 12 10:27:19 2004 From: rdm at rcblue.com (Dick Moores) Date: Tue Oct 12 10:28:10 2004 Subject: [Tutor] Can I speed this up? Message-ID: <6.1.2.0.2.20041011012649.05653430@rcblue.com> I'd greatly appreciate some tutors taking a look at my factorIntegers.py at . I've worked hard to make it as efficient as possible, but suspect there is more that could be done. Or maybe I'm completely on the wrong track as far as speed is concerned. I've made use of the program to compute prime factors for integers in the 5 quintillion range. Please see for some results from the latest revision of factorIntegers.py. You'll note that in almost all cases the primes take the longest time to compute (29 minutes and change). But note also the anomalies listed at the top of the script. Is there something I've missed that would eliminate these? Or are these to be expected, given the nature of the prime factors of these integers? I also did some computing in the 400 trillion range, and found a bunch of these anomalies. The worst I could find was 42 seconds (primes took 11 seconds): 400,000,000,040,471 = 19502713*20509967 42 seconds 400,000,000,040,507 = 400000000040507 is PRIME 11 seconds Also, of course, I'd appreciate criticism (or even deserved praise) of anything that catches your wise and experienced eyes. BTW the line drawn in isPrime(n) at 4,611,600,000,000,000,000 is for my computer and operating system. Yours may require a different line. See the "large number question" Tutor thread of 9/25 and 9/26. Thanks, tutors. Dick Moores rdm@rcblue.com Python 2.3.4, Win XP "Few persons have sufficient wisdom to prefer censure, which is useful, to praise which deceives them." - Francois De La Rochefoucauld From johan at accesstel.co.za Tue Oct 12 11:29:09 2004 From: johan at accesstel.co.za (Johan Geldenhuys) Date: Tue Oct 12 11:31:08 2004 Subject: [Tutor] Getchr() in Msvcrt module In-Reply-To: References: Message-ID: <1097571576.4266.134.camel@linux.site> Skipped content of type multipart/alternative-------------- next part -------------- An embedded message was scrubbed... From: Riumu Kuraku Subject: [Tutor] Getchr() in Msvcrt module Date: Tue, 12 Oct 2004 20:05:09 +1300 Size: 3903 Url: http://mail.python.org/pipermail/tutor/attachments/20041012/8c6fc18d/attachment-0001.mht From kent_johnson at skillsoft.com Tue Oct 12 12:09:42 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Tue Oct 12 12:09:47 2004 Subject: [Tutor] Can I speed this up? In-Reply-To: <6.1.2.0.2.20041011012649.05653430@rcblue.com> References: <6.1.2.0.2.20041011012649.05653430@rcblue.com> Message-ID: <6.1.0.6.0.20041012060406.02a2c5d8@mail4.skillsoft.com> Dick, To get any substantial speedup you will probably have to look at different algorithms. It turns out that factoring large numbers is a well-studied problem. Googling for 'prime factors algorithm' gives a number of hits including these overviews: http://mathworld.wolfram.com/PrimeFactorizationAlgorithms.html http://www.frenchfries.net/paul/factoring/theory/index.html One tweak to your program would be to have isPrime return the factor found; in cases where the factor is large that will save some time as you don't have to search for it again. Kent At 01:27 AM 10/12/2004 -0700, Dick Moores wrote: >I'd greatly appreciate some tutors taking a look at my factorIntegers.py >at . I've worked >hard to make it as efficient as possible, but suspect there is more that >could be done. Or maybe I'm completely on the wrong track as far as speed >is concerned. > >I've made use of the program to compute prime factors for integers in the >5 quintillion range. Please see > >for some results from the latest revision of factorIntegers.py. > >You'll note that in almost all cases the primes take the longest time to >compute (29 minutes and change). But note also the anomalies listed at the >top of the script. Is there something I've missed that would eliminate >these? Or are these to be expected, given the nature of the prime factors >of these integers? > >I also did some computing in the 400 trillion range, and found a bunch of >these anomalies. The worst I could find was 42 seconds (primes took 11 >seconds): > >400,000,000,040,471 = 19502713*20509967 >42 seconds > >400,000,000,040,507 = 400000000040507 is PRIME >11 seconds > > >Also, of course, I'd appreciate criticism (or even deserved praise) of >anything that catches your wise and experienced eyes. > >BTW the line drawn in isPrime(n) at 4,611,600,000,000,000,000 is for my >computer and operating system. Yours may require a different line. See the >"large number question" Tutor thread of 9/25 and 9/26. > >Thanks, tutors. > >Dick Moores >rdm@rcblue.com > >Python 2.3.4, Win XP > > >"Few persons have sufficient wisdom to prefer censure, which is useful, to >praise which deceives them." > >- Francois De La Rochefoucauld > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From kent_johnson at skillsoft.com Tue Oct 12 14:32:06 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Tue Oct 12 14:31:42 2004 Subject: [Tutor] Can I speed this up? In-Reply-To: <6.1.2.0.2.20041011012649.05653430@rcblue.com> References: <6.1.2.0.2.20041011012649.05653430@rcblue.com> Message-ID: <6.1.0.6.0.20041012082330.028ba110@mail4.skillsoft.com> Using psyco gives a small speedup - in my limited testing, about 15%. Install psyco from http://psyco.sourceforge.net, then put these two lines after the definition of factorsOfInteger: import psyco psyco.bind(factorsOfInteger) One way to speed it up would be to precompute all the possible prime factors up to the square root of the number you are interested in and store them in a file. Of course it might take a while to compute the list...it's a good example of speeding up an algorithm by precomputing part of it. If you do compute such a list, a sieve of Eratosthenes algorithm (http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes) would probably be faster than using your isPrime function. Kent At 01:27 AM 10/12/2004 -0700, Dick Moores wrote: >I'd greatly appreciate some tutors taking a look at my factorIntegers.py >at . I've worked >hard to make it as efficient as possible, but suspect there is more that >could be done. Or maybe I'm completely on the wrong track as far as speed >is concerned. > >I've made use of the program to compute prime factors for integers in the >5 quintillion range. Please see > >for some results from the latest revision of factorIntegers.py. > >You'll note that in almost all cases the primes take the longest time to >compute (29 minutes and change). But note also the anomalies listed at the >top of the script. Is there something I've missed that would eliminate >these? Or are these to be expected, given the nature of the prime factors >of these integers? > >I also did some computing in the 400 trillion range, and found a bunch of >these anomalies. The worst I could find was 42 seconds (primes took 11 >seconds): > >400,000,000,040,471 = 19502713*20509967 >42 seconds > >400,000,000,040,507 = 400000000040507 is PRIME >11 seconds > > >Also, of course, I'd appreciate criticism (or even deserved praise) of >anything that catches your wise and experienced eyes. > >BTW the line drawn in isPrime(n) at 4,611,600,000,000,000,000 is for my >computer and operating system. Yours may require a different line. See the >"large number question" Tutor thread of 9/25 and 9/26. > >Thanks, tutors. > >Dick Moores >rdm@rcblue.com > >Python 2.3.4, Win XP > > >"Few persons have sufficient wisdom to prefer censure, which is useful, to >praise which deceives them." > >- Francois De La Rochefoucauld > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From rdm at rcblue.com Tue Oct 12 15:40:38 2004 From: rdm at rcblue.com (Dick Moores) Date: Tue Oct 12 15:41:10 2004 Subject: [Tutor] Can I speed this up? In-Reply-To: <6.1.2.0.2.20041011012649.05653430@rcblue.com> References: <6.1.2.0.2.20041011012649.05653430@rcblue.com> Message-ID: <6.1.2.0.2.20041012063716.07c14660@rcblue.com> In addition to the great tips received from Kent Johnson, I'm hoping for ways to improve the algorithm of the function factorsOfInteger(n). It's there that the "anomalies" are caused, I think. Dick Moores rdm@rcblue.com Dick Moores wrote at 01:27 10/12/2004: >I'd greatly appreciate some tutors taking a look at my factorIntegers.py >at . I've worked >hard to make it as efficient as possible, but suspect there is more that >could be done. Or maybe I'm completely on the wrong track as far as >speed is concerned. > >I've made use of the program to compute prime factors for integers in >the 5 quintillion range. Please see > >for some results from the latest revision of factorIntegers.py. > >You'll note that in almost all cases the primes take the longest time to >compute (29 minutes and change). But note also the anomalies listed at >the top of the script. Is there something I've missed that would >eliminate these? Or are these to be expected, given the nature of the >prime factors of these integers? > >I also did some computing in the 400 trillion range, and found a bunch >of these anomalies. The worst I could find was 42 seconds (primes took >11 seconds): > >400,000,000,040,471 = 19502713*20509967 >42 seconds > >400,000,000,040,507 = 400000000040507 is PRIME >11 seconds > > >Also, of course, I'd appreciate criticism (or even deserved praise) of >anything that catches your wise and experienced eyes. > >BTW the line drawn in isPrime(n) at 4,611,600,000,000,000,000 is for my >computer and operating system. Yours may require a different line. See >the "large number question" Tutor thread of 9/25 and 9/26. > >Thanks, tutors. > >Dick Moores >rdm@rcblue.com > >Python 2.3.4, Win XP > > >"Few persons have sufficient wisdom to prefer censure, which is useful, >to praise which deceives them." > >- Francois De La Rochefoucauld > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From my.mailing.lists at noos.fr Tue Oct 12 17:30:35 2004 From: my.mailing.lists at noos.fr (nik) Date: Tue Oct 12 17:30:44 2004 Subject: [Tutor] Can I speed this up? In-Reply-To: <6.1.2.0.2.20041012063716.07c14660@rcblue.com> References: <6.1.2.0.2.20041011012649.05653430@rcblue.com> <6.1.2.0.2.20041012063716.07c14660@rcblue.com> Message-ID: <416BF89B.9040001@noos.fr> Would the profile module be of any use in this situation? I haven't used it myself, but would like to possibly in the future... nik Dick Moores wrote: > In addition to the great tips received from Kent Johnson, I'm hoping > for ways to improve the algorithm of the function > factorsOfInteger(n). It's there that the "anomalies" are caused, I > think. > > Dick Moores > rdm@rcblue.com > > Dick Moores wrote at 01:27 10/12/2004: > >> I'd greatly appreciate some tutors taking a look at my >> factorIntegers.py at >> . I've worked >> hard to make it as efficient as possible, but suspect there is more >> that could be done. Or maybe I'm completely on the wrong track as far >> as speed is concerned. >> >> I've made use of the program to compute prime factors for integers in >> the 5 quintillion range. Please see >> >> for some results from the latest revision of factorIntegers.py. >> >> You'll note that in almost all cases the primes take the longest time >> to compute (29 minutes and change). But note also the anomalies >> listed at the top of the script. Is there something I've missed that >> would eliminate these? Or are these to be expected, given the nature >> of the prime factors of these integers? >> >> I also did some computing in the 400 trillion range, and found a >> bunch of these anomalies. The worst I could find was 42 seconds >> (primes took 11 seconds): >> >> 400,000,000,040,471 = 19502713*20509967 >> 42 seconds >> >> 400,000,000,040,507 = 400000000040507 is PRIME >> 11 seconds >> >> >> Also, of course, I'd appreciate criticism (or even deserved praise) >> of anything that catches your wise and experienced eyes. >> >> BTW the line drawn in isPrime(n) at 4,611,600,000,000,000,000 is for >> my computer and operating system. Yours may require a different line. >> See the "large number question" Tutor thread of 9/25 and 9/26. >> >> Thanks, tutors. >> >> Dick Moores >> rdm@rcblue.com >> >> Python 2.3.4, Win XP >> >> >> "Few persons have sufficient wisdom to prefer censure, which is >> useful, to praise which deceives them." >> >> - Francois De La Rochefoucauld >> >> _______________________________________________ >> Tutor maillist - Tutor@python.org >> http://mail.python.org/mailman/listinfo/tutor > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From barry at angleinc.com Tue Oct 12 18:05:27 2004 From: barry at angleinc.com (Barry Sperling) Date: Tue Oct 12 18:27:10 2004 Subject: [Tutor] Can I speed this up? In-Reply-To: <6.1.2.0.2.20041011012649.05653430@rcblue.com> References: <6.1.2.0.2.20041011012649.05653430@rcblue.com> Message-ID: <416C00C7.7010803@angleinc.com> As a newbie, I'd like to know why you used a "for" loop in isPrimeSmall(n) and a "while" loop in isPrimeBig(n). Is there a performance difference? Thanks, Barry Dick Moores wrote: > I'd greatly appreciate some tutors taking a look at my factorIntegers.py > at . I've worked > hard to make it as efficient as possible, but suspect there is more that > could be done. Or maybe I'm completely on the wrong track as far as > speed is concerned. > > I've made use of the program to compute prime factors for integers in > the 5 quintillion range. Please see > > for some results from the latest revision of factorIntegers.py. > > You'll note that in almost all cases the primes take the longest time to > compute (29 minutes and change). But note also the anomalies listed at > the top of the script. Is there something I've missed that would > eliminate these? Or are these to be expected, given the nature of the > prime factors of these integers? > > I also did some computing in the 400 trillion range, and found a bunch > of these anomalies. The worst I could find was 42 seconds (primes took > 11 seconds): > > 400,000,000,040,471 = 19502713*20509967 > 42 seconds > > 400,000,000,040,507 = 400000000040507 is PRIME > 11 seconds > > > Also, of course, I'd appreciate criticism (or even deserved praise) of > anything that catches your wise and experienced eyes. > > BTW the line drawn in isPrime(n) at 4,611,600,000,000,000,000 is for my > computer and operating system. Yours may require a different line. See > the "large number question" Tutor thread of 9/25 and 9/26. > > Thanks, tutors. > > Dick Moores > rdm@rcblue.com > > Python 2.3.4, Win XP > > > "Few persons have sufficient wisdom to prefer censure, which is useful, > to praise which deceives them." > > - Francois De La Rochefoucauld > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From jmarcus at mvalent.com Tue Oct 12 21:19:08 2004 From: jmarcus at mvalent.com (James R. Marcus) Date: Tue Oct 12 21:19:12 2004 Subject: [Tutor] Converting Microsoft .msg files to text Message-ID: I'm starting my second script ever. I need to get the bad email addresses out of the Microsoft .msg files that were sent to me. I'm assuming I should start by converting the .msg files into text format. Then I'll search the text files for known errors and copy the email addresses to a new text file. What module should I be reading to accomplish the convert to text? If you have any other comments on my method, I will gladly take suggestions. Thanks, James From kshahzadbutt at gmail.com Tue Oct 12 22:18:46 2004 From: kshahzadbutt at gmail.com (Khawaja-Shahzad Butt) Date: Tue Oct 12 22:18:53 2004 Subject: [Tutor] Problem with mxODBC insert statement Message-ID: Hello, I don't know how to use SQL which way for mxODBC and python. I used this statement and got this error. q= "INSERT INTO rss_feed_items(item_date,item_title,item_author,item_permalink,item_description)\ VALUES(%s)"%(item_dmodified); MS SQL server 2000 gave me this error for above query statement: ProgrammingError: ('37000', 170, "[Microsoft][ODBC SQL Server Driver][SQL Server]Line 1: Incorrect syntax near '06'.", 4612) or can i use the ? instead of %s can you give me example since there is none in egenix manual for mxODBC. What am i doing wrong. Also should always use auto_commit while using mxODBC Please reply. Thank you, Regards Shahzad From my.mailing.lists at noos.fr Tue Oct 12 23:26:11 2004 From: my.mailing.lists at noos.fr (nik) Date: Tue Oct 12 23:26:17 2004 Subject: [Tutor] Problem with mxODBC insert statement In-Reply-To: References: Message-ID: <416C4BF3.8010709@noos.fr> This is only a guess, but if (item_dmodified) is a tuple, shouldn't it be (item_dmodified,) for a tuple with a single item (ie missing the comma). nik Khawaja-Shahzad Butt wrote: >Hello, > > I don't know how to use SQL which way for mxODBC and >python. I used this statement and got this error. > >q= "INSERT INTO >rss_feed_items(item_date,item_title,item_author,item_permalink,item_description)\ > VALUES(%s)"%(item_dmodified); > >MS SQL server 2000 gave me this error for above query statement: > >ProgrammingError: ('37000', 170, "[Microsoft][ODBC SQL Server >Driver][SQL Server]Line 1: Incorrect syntax near '06'.", 4612) > >or can i use the ? instead of %s can you give me example since there is >none in egenix manual for mxODBC. What am i doing wrong. >Also should always use auto_commit while using mxODBC > >Please reply. >Thank you, >Regards >Shahzad >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > > From dyoo at hkn.eecs.berkeley.edu Wed Oct 13 08:17:00 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Oct 13 08:17:07 2004 Subject: [Tutor] Converting Microsoft .msg files to text In-Reply-To: Message-ID: On Tue, 12 Oct 2004, James R. Marcus wrote: > I'm starting my second script ever. I need to get the bad email > addresses out of the Microsoft .msg files that were sent to me. I'm > assuming I should start by converting the .msg files into text format. Hi James, I did a search for what kind of file format the .MSG is: it appears to be the format that Outlook uses to store email messages. It's a binary format, but you might be able to get away with filtering out for plain text characters. One way to do this is to go through each character of the file: if it has an ordinal value less than 2**7, that might work. For example, say that we have something like: ### >>> message = "THIS is a MESSAGE with MIXED case." ### and say that we want to drop out the lowercased characters. It turns out that each lowercased letter in a string has an ordinal (ASCII) value between: ### >>> ord('a'), ord('z') (97, 122) ### and uppercased letters go between: ### >>> ord('A'), ord('Z') (65, 90) ### One way to just keep the uppercase letters from 'message' is to filter for them: ### >>> def isGoodCharacter(ch): ... return ord('A') <= ord(ch) <= ord('Z') ... >>> filter(isGoodCharacter, message) 'THISMESSAGEMIXED' ### Similarly, you should be able to set up a filter for the readable "printable" test part of your .msg files. An alternative way, beside doing something with explicit ASCII values, is to check each character and see if its 'in' some collection of printable characters. For example: ### >>> def isVowel(ch): ... return ch.lower() in 'aeiou' ... ### And there's a variable in the 'string' module called 'string.printable' that might come in handy. I'm not sure if this is the best way to do this, but I can't find a nice documented page for the .MSG file format, so this will have to do for now... *grin* Good luck to you! From cajuntechie at gmail.com Wed Oct 13 08:26:39 2004 From: cajuntechie at gmail.com (Anthony P.) Date: Wed Oct 13 08:26:41 2004 Subject: [Tutor] New List Member/Introduction Message-ID: Hello Everyone, Just joined the list and wanted to take a bit of time to introduce myself. Hope this email finds everyone happy, wealthy, and well! I'm Anthony from Oklahoma. I'm a 30 year old professional software developer and owner of a development house that focuses on providing (or developing) open source solutions to government and non-profits. Up until now, I've been using PHP for web development, and C++, Java, and Perl/Tk for desktop development. A few weeks ago, I discovered Python and decided to give it a try. I am absolutely amazed at the simplicity and power of this language. It allows me to create desktop applications (using wxWindows) as simply as scripting web solutions! I'm about to attempt my first major project in Python (some kiosk software) and joined this list in the hopes of getting some of my questions answered (I'm sure I'll have some). I also hope to contribute by answering a few questions too. Anyway, that's long enough of an intro for now. I look forward to meeting everyone and participating in this group soon. Anthony From rdm at rcblue.com Wed Oct 13 10:12:17 2004 From: rdm at rcblue.com (Dick Moores) Date: Wed Oct 13 10:12:49 2004 Subject: [Tutor] Can I speed this up? In-Reply-To: <416C00C7.7010803@angleinc.com> References: <6.1.2.0.2.20041011012649.05653430@rcblue.com> <416C00C7.7010803@angleinc.com> Message-ID: <6.1.2.0.2.20041013001115.036576c0@rcblue.com> Barry Sperling wrote at 09:05 10/12/2004: >As a newbie, I'd like to know why you used a "for" loop in >isPrimeSmall(n) and a "while" loop in isPrimeBig(n). Is there a >performance difference? >Thanks, > Barry Barry, Yes, the "for" loop using xrange() in isPrimeSmall(n) is a bit faster (maybe by 10% in the 400 trillion range) than the "while" loop in isPrimeBig(n), so I'd like to use xrange() for large integers as well as small. But I found that if n is larger than about 4.6616 quintillion I get this error: Traceback (most recent call last): File "C:/Python23/factorIntegers.py", line 284, in -toplevel- factors = factorsOfInteger(n) File "C:/Python23/factorIntegers.py", line 248, in factorsOfInteger if isPrime(n): File "C:/Python23/factorIntegers.py", line 153, in isPrime return isPrimeSmall(n) File "C:/Python23/factorIntegers.py", line 169, in isPrimeSmall for x in xrange(3,limit,2): OverflowError: long int too large to convert to int I got this by temporarily modifying isPrime(n) to def isPrime(n): #if n < 4611600000000000000: if n < 4700000000000000000: return isPrimeSmall(n) else: return isPrimeBig(n) and entering min max as 4611700000000000000 4611700000000000050. The change to 4700000000000000000 in isPrime() forced the use of isPrimeSmall(n) (and xrange()), thereby producing the OverflowError. As for why 4.6117 quintillion, see this thread in the Tutor archive: , especially . Dick >Dick Moores wrote: > >>I'd greatly appreciate some tutors taking a look at my >>factorIntegers.py at >>. I've worked >>hard to make it as efficient as possible, but suspect there is more >>that could be done. Or maybe I'm completely on the wrong track as far >>as speed is concerned. >>I've made use of the program to compute prime factors for integers in >>the 5 quintillion range. Please see >> >>for some results from the latest revision of factorIntegers.py. >>You'll note that in almost all cases the primes take the longest time >>to compute (29 minutes and change). But note also the anomalies listed >>at the top of the script. Is there something I've missed that would >>eliminate these? Or are these to be expected, given the nature of the >>prime factors of these integers? >>I also did some computing in the 400 trillion range, and found a bunch >>of these anomalies. The worst I could find was 42 seconds (primes took >>11 seconds): >>400,000,000,040,471 = 19502713*20509967 >>42 seconds >>400,000,000,040,507 = 400000000040507 is PRIME >>11 seconds >> >>Also, of course, I'd appreciate criticism (or even deserved praise) of >>anything that catches your wise and experienced eyes. >>BTW the line drawn in isPrime(n) at 4,611,600,000,000,000,000 is for my >>computer and operating system. Yours may require a different line. See >>the "large number question" Tutor thread of 9/25 and 9/26. >>Thanks, tutors. >>Dick Moores >>rdm@rcblue.com >>Python 2.3.4, Win XP >> >>"Few persons have sufficient wisdom to prefer censure, which is useful, >>to praise which deceives them." >>- Francois De La Rochefoucauld __ From cyresse at gmail.com Wed Oct 13 10:36:13 2004 From: cyresse at gmail.com (Riumu Kuraku) Date: Wed Oct 13 10:36:18 2004 Subject: [Tutor] Getchr() in Msvcrt module In-Reply-To: <1097571576.4266.134.camel@linux.site> References: <1097571576.4266.134.camel@linux.site> Message-ID: Thank you Johan, I just learnt a lot about ASCII codes, and tables, and the ord() function. Thanks, Liam Clarke On Tue, 12 Oct 2004 11:29:09 +0200, Johan Geldenhuys wrote: > Enter (CR) and new line (LF) ( carridge return and line feed) are '\x0D' > and '\x0A'. > > If you google for ASCII convertion tables you will get tables that supplies > you with the ASCII, Hex and Decimal values for printable characters. > Non-pritable characters are still unknown to me. > > Hope this helps. > > -- Johan > -- > Message has been scanned > Enjoy your day > > ---------- Forwarded message ---------- > From: Riumu Kuraku > To: tutor@python.org > Date: Tue, 12 Oct 2004 20:05:09 +1300 > Subject: [Tutor] Getchr() in Msvcrt module > Hello all, > > I'm playing around with getchar(), and I'm following Alan Gauld's tutorial. > > He states that characters read by getchar that are prefixed with > '\x00' or '\xe0' are non-ASCII such as the function keys. > > Is Enter one of these keys? Space is obviously " ", but is Enter "\n" > or something else? > > Is there somewhere in Python's documentation a list of how the keys > such as Esc etc. are defined in ASCII/non-ASCII > > Apologies for the multiple questions. > > Thanks, > > Liam > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > -- > Message has been scanned. > Enjoy Your Day. > > > From cajuntechie at gmail.com Wed Oct 13 10:38:11 2004 From: cajuntechie at gmail.com (Anthony P.) Date: Wed Oct 13 10:38:14 2004 Subject: [Tutor] Python and RFID Message-ID: Good Morning Everyone, I'm considering a business project that will implement RFID technology and I'd like to do it all (or mostly) in Python on Linux. Does anyone know of any RFID API's for Python that could give me a head start on the project? Basically, all I need to do is read tags. But the catch is that I need to be able to between multiple tags going through the system at the same time. Any help with this would be very greatly appreciated. Thanks, Anthony From w.richert at gmx.net Wed Oct 13 11:01:59 2004 From: w.richert at gmx.net (Willi Richert) Date: Wed Oct 13 11:02:08 2004 Subject: [Tutor] Infos on Python's self-modification capabilities Message-ID: <200410131101.59990.w.richert@gmx.net> Hi, I've spent some time googling on the subject of Python's self modification capabilities (f(), g(), f=g, eval, exec, execute, ...). I need some kind of tutorial for people familiar with all sorts of languages (C++, Java, Lisp, ML, etc.), but with only basic knowledge in Python. Thanks for any help, wr From kent_johnson at skillsoft.com Wed Oct 13 11:45:19 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Wed Oct 13 11:45:25 2004 Subject: [Tutor] Can I speed this up? In-Reply-To: <6.1.2.0.2.20041011012649.05653430@rcblue.com> References: <6.1.2.0.2.20041011012649.05653430@rcblue.com> Message-ID: <6.1.0.6.0.20041013053801.028d3470@mail4.skillsoft.com> Dick, There are a few places in your script where you are doing a lot of extra work. I think one of them is responsible for the "anomalies" and another could yield a 2x speedup. First, look at something like 5,000,000,000,000,005,171 = 800104651*6249182521 At the beginning of factorsOfInteger() you call isPrime(n). This will check to see if 5,000,000,000,000,005,171 is prime, which means dividing it by every odd number up to 800104651. When you find that n is not prime, you start the division all over from 2! If you could have isPrime return the first divisor found, you could factor it out right away and avoid a lot of work. Then when you find a factor you check to see if the quotient is prime. You say this speeds up some cases but I don't understand the explanation, it looks like extra work to me. Especially in the case of two large prime factors where you already know you have no divisors smaller than the factor you just found. Finally, the loop in factorsOfInteger() could increment x by 2 after handling the special case of x = 2. Since you are finding prime factors you don't have to check the even numbers; you have already factored out all the 2's. Kent At 01:27 AM 10/12/2004 -0700, Dick Moores wrote: >I'd greatly appreciate some tutors taking a look at my factorIntegers.py >at . I've worked >hard to make it as efficient as possible, but suspect there is more that >could be done. Or maybe I'm completely on the wrong track as far as speed >is concerned. > >I've made use of the program to compute prime factors for integers in the >5 quintillion range. Please see > >for some results from the latest revision of factorIntegers.py. > >You'll note that in almost all cases the primes take the longest time to >compute (29 minutes and change). But note also the anomalies listed at the >top of the script. Is there something I've missed that would eliminate >these? Or are these to be expected, given the nature of the prime factors >of these integers? > >I also did some computing in the 400 trillion range, and found a bunch of >these anomalies. The worst I could find was 42 seconds (primes took 11 >seconds): > >400,000,000,040,471 = 19502713*20509967 >42 seconds > >400,000,000,040,507 = 400000000040507 is PRIME >11 seconds > > >Also, of course, I'd appreciate criticism (or even deserved praise) of >anything that catches your wise and experienced eyes. > >BTW the line drawn in isPrime(n) at 4,611,600,000,000,000,000 is for my >computer and operating system. Yours may require a different line. See the >"large number question" Tutor thread of 9/25 and 9/26. > >Thanks, tutors. > >Dick Moores >rdm@rcblue.com > >Python 2.3.4, Win XP > > >"Few persons have sufficient wisdom to prefer censure, which is useful, to >praise which deceives them." > >- Francois De La Rochefoucauld > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From rdm at rcblue.com Wed Oct 13 13:19:18 2004 From: rdm at rcblue.com (Dick Moores) Date: Wed Oct 13 13:19:22 2004 Subject: [Tutor] Can I speed this up? In-Reply-To: <6.1.0.6.0.20041013053801.028d3470@mail4.skillsoft.com> References: <6.1.2.0.2.20041011012649.05653430@rcblue.com> <6.1.0.6.0.20041013053801.028d3470@mail4.skillsoft.com> Message-ID: <6.1.2.0.2.20041013040218.0389a900@rcblue.com> Kent, It's late on the Left Coast, and I've only got time to try the "incrementing x by 2" idea, the easiest one to implement. Great! On the worst of my "anomalies" in the 400 trillion range, 400000000021199 = 19814533*20187203, doing that cut the time from 45 seconds to 27! Don't know why I didn't see that before. I replaced x += 1 with if x > 2: x += 2 else: x = 3 Thanks! Dick Kent Johnson wrote at 02:45 10/13/2004: >Dick, > >There are a few places in your script where you are doing a lot of extra >work. I think one of them is responsible for the "anomalies" and another >could yield a 2x speedup. > >First, look at something like >5,000,000,000,000,005,171 = 800104651*6249182521 > >At the beginning of factorsOfInteger() you call isPrime(n). This will >check to see if 5,000,000,000,000,005,171 is prime, which means >dividing it by every odd number up to 800104651. When you find that n is >not prime, you start the division all over from 2! If you could have >isPrime return the first divisor found, you could factor it out right >away and avoid a lot of work. > >Then when you find a factor you check to see if the quotient is prime. >You say this speeds up some cases but I don't understand the >explanation, it looks like extra work to me. Especially in the case of >two large prime factors where you already know you have no divisors >smaller than the factor you just found. > >Finally, the loop in factorsOfInteger() could increment x by 2 after >handling the special case of x = 2. Since you are finding prime factors >you don't have to check the even numbers; you have already factored out >all the 2's. > >Kent > >At 01:27 AM 10/12/2004 -0700, Dick Moores wrote: >>I'd greatly appreciate some tutors taking a look at my >>factorIntegers.py at >>. I've worked >>hard to make it as efficient as possible, but suspect there is more >>that could be done. Or maybe I'm completely on the wrong track as far >>as speed is concerned. >> >>I've made use of the program to compute prime factors for integers in >>the 5 quintillion range. Please see >> >>for some results from the latest revision of factorIntegers.py. >> >>You'll note that in almost all cases the primes take the longest time >>to compute (29 minutes and change). But note also the anomalies listed >>at the top of the script. Is there something I've missed that would >>eliminate these? Or are these to be expected, given the nature of the >>prime factors of these integers? >> >>I also did some computing in the 400 trillion range, and found a bunch >>of these anomalies. The worst I could find was 42 seconds (primes took >>11 seconds): >> >>400,000,000,040,471 = 19502713*20509967 >>42 seconds >> >>400,000,000,040,507 = 400000000040507 is PRIME >>11 seconds >> >> >>Also, of course, I'd appreciate criticism (or even deserved praise) of >>anything that catches your wise and experienced eyes. >> >>BTW the line drawn in isPrime(n) at 4,611,600,000,000,000,000 is for my >>computer and operating system. Yours may require a different line. See >>the "large number question" Tutor thread of 9/25 and 9/26. >> >>Thanks, tutors. >> >>Dick Moores >>rdm@rcblue.com >> >>Python 2.3.4, Win XP >> >> >>"Few persons have sufficient wisdom to prefer censure, which is useful, >>to praise which deceives them." >> >>- Francois De La Rochefoucauld >> >>_______________________________________________ >>Tutor maillist - Tutor@python.org >>http://mail.python.org/mailman/listinfo/tutor > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From revanna at mn.rr.com Wed Oct 13 15:35:14 2004 From: revanna at mn.rr.com (Anna Ravenscroft) Date: Wed Oct 13 15:35:27 2004 Subject: [Tutor] New List Member/Introduction In-Reply-To: References: Message-ID: <416D2F12.9030601@mn.rr.com> Anthony P. wrote: > Hello Everyone, > > Just joined the list and wanted to take a bit of time to introduce > myself. Hope this email finds everyone happy, wealthy, and well! > > I'm Anthony from Oklahoma. I'm a 30 year old professional software > developer and owner of a development house that focuses on providing > (or developing) open source solutions to government and non-profits. > > Up until now, I've been using PHP for web development, and C++, Java, > and Perl/Tk for desktop development. A few weeks ago, I discovered > Python and decided to give it a try. I am absolutely amazed at the > simplicity and power of this language. It allows me to create desktop > applications (using wxWindows) as simply as scripting web solutions! > > I'm about to attempt my first major project in Python (some kiosk > software) and joined this list in the hopes of getting some of my > questions answered (I'm sure I'll have some). I also hope to > contribute by answering a few questions too. > > Anyway, that's long enough of an intro for now. I look forward to > meeting everyone and participating in this group soon. > > Anthony Welcome to the Python side of the force! Anna From dan at aktivix.org Wed Oct 13 15:42:41 2004 From: dan at aktivix.org (Dan) Date: Wed Oct 13 15:42:49 2004 Subject: [Tutor] Here's hoping... Message-ID: <416D30D1.8050703@aktivix.org> Oh, I know this is going to sound really bad, but I'm going to try anyway... I'm NOT a professional programmer: in fact, the last time I did any programming was on an Atari ST, with STOS (a BASIC game-writing language...) I *AM* wanting to get back into it, and python seems like a good place to begin again - but I'm totally at a loss as to where to start. I've got me IDLE installed, and done some basic hello worlding... but are there any sources on the net / can anyone help me with first steps on how I would write a web app? I particularly want to have a go at writing a server-side bookmark prog that would allow cross-referencing a la Amazon - 'people who go to these websites are also going to these websites'. Can anyone help a total beginner? Or am I on the wrong list / should I go elsewhere? Here's hoping... Dan -- 07968 997861 0114 2412723 The true meaning of life is to plant trees, under whose shade you do not expect to sit. From dan at aktivix.org Wed Oct 13 15:53:40 2004 From: dan at aktivix.org (Dan) Date: Wed Oct 13 15:53:53 2004 Subject: [Tutor] Ah... Message-ID: <416D3364.9000403@aktivix.org> Allo again - I just an automated response with loads of good starting points in! If anyone does have a comment on the server-side bookmark idea, though, such as "I've written that! Here it is...", let me know. Dan -- 07968 997861 0114 2412723 The true meaning of life is to plant trees, under whose shade you do not expect to sit. From s.venter at ntlworld.com Wed Oct 13 15:56:16 2004 From: s.venter at ntlworld.com (Gerhard Venter) Date: Wed Oct 13 15:56:21 2004 Subject: [Tutor] Here's hoping... In-Reply-To: <416D30D1.8050703@aktivix.org> References: <416D30D1.8050703@aktivix.org> Message-ID: <416D3400.7040104@ntlworld.com> Hi I've tried several of the many ways to do web-programming with Python. The easiest and best documented one I've used so far is Spyce (spyce.sf.net) Take a look at his "30-seconds sales pitch", and his Examples page - a great way of introducing your software on the Web. Gerhard Dan wrote: > Oh, I know this is going to sound really bad, but I'm going to try > anyway... > > I'm NOT a professional programmer: in fact, the last time I did any > programming was on an Atari ST, with STOS (a BASIC game-writing > language...) > > I *AM* wanting to get back into it, and python seems like a good place > to begin again - but I'm totally at a loss as to where to start. I've > got me IDLE installed, and done some basic hello worlding... > > but are there any sources on the net / can anyone help me with first > steps on how I would write a web app? > I particularly want to have a go at writing a server-side bookmark > prog that would allow cross-referencing a la Amazon - 'people who go > to these websites are also going to these websites'. > > Can anyone help a total beginner? Or am I on the wrong list / should > I go elsewhere? > > Here's hoping... > > Dan > From revanna at mn.rr.com Wed Oct 13 16:06:24 2004 From: revanna at mn.rr.com (Anna Ravenscroft) Date: Wed Oct 13 16:06:30 2004 Subject: [Tutor] Here's hoping... In-Reply-To: <416D30D1.8050703@aktivix.org> References: <416D30D1.8050703@aktivix.org> Message-ID: <416D3660.40309@mn.rr.com> Dan wrote: > Oh, I know this is going to sound really bad, but I'm going to try > anyway... > > I'm NOT a professional programmer: in fact, the last time I did any > programming was on an Atari ST, with STOS (a BASIC game-writing > language...) > > I *AM* wanting to get back into it, and python seems like a good place > to begin again - but I'm totally at a loss as to where to start. I've > got me IDLE installed, and done some basic hello worlding... > Great! Python is a great way to begin again. If you haven't already, take a look at a couple of the tutorials available on the web: Alan Gauld's: Learning to Program Josh Cogliati's: A Non-Programmer's Tutorial for Python are both good starting points. > but are there any sources on the net / can anyone help me with first > steps on how I would write a web app? You may need to take a few steps before you end up where you want. I'm not sure what's available on the web, but there's a great *book* out there on this by Steve Holden, Python Web Progamming. > I particularly want to have a go at writing a server-side bookmark prog > that would allow cross-referencing a la Amazon - 'people who go to these > websites are also going to these websites'. > > Can anyone help a total beginner? Or am I on the wrong list / should I > go elsewhere? Folks aren't going to walk you through it, you need to take the lead - start trying to do stuff. Think about a small piece of your final program that you want to try out - and try writing a program to do that. Come back here when you get stuck, when the program doesn't work, or some piece of it is baffling you, or whatever. Ask specific questions, and give us background including info on what you've tried, what platform you're on, what you'd like it to do... If you've gotten error messages, post the error message and the code that generated it. You'll find the group very helpful. That's one of the best parts of Python - their attitude toward newbies. HTH Anna From mw5858 at sbc.com Wed Oct 13 17:10:40 2004 From: mw5858 at sbc.com (WEISS, MARK (NB)) Date: Wed Oct 13 17:10:54 2004 Subject: [Tutor] Ftplib error using dir() Message-ID: <4BF710B1993F1244B41763531F098D7905A6BF@cafrfd1msgusr21.itservices.sbc.com> Lloyd, Thanks for the suggestion. As I understand the docs...ftplib defaults to passive mode since 2.1, so I will need to check with the owner of the remote machine, and verify that it will allow passive connections. Does anyone have a suggestion for how I can handle this better from the client side? Also, here is the error msg I am getting: Error code(10061), Error Message: Connection refused Cheers- mark -----Original Message----- From: Lloyd Kvam [mailto:pythonTutor@venix.com] Sent: Sunday, October 10, 2004 10:24 AM To: Chad Crabtree Cc: WEISS, MARK; Tutor Python Subject: Re: [Tutor] Ftplib error using dir() On Sat, 2004-10-09 at 15:15, Chad Crabtree wrote: > WEISS, MARK (NB) wrote: > > >Hello Group, > > > >I am trying to build a FTP client and I am getting a 'connection > >refused' error when I call the code listed below. I can login fine > (in > >my script), and I connect through a command prompt using the ftp > command > >(Win2K) I can list the files in the remote directory. Also, to > further > >confuse the matter I can run this code against a local ftp server > and > >return the list of files. > > > > > > > How about an error message? This might be a firewall issue. Putting the FTP server into passive mode may do the trick. Originally FTP servers connected back to the client to send data. Passive mode has the server wait for the client to make the data connection. Typically a client's firewall will allow the client to connect to the ftp server but block connections originating from the ftp server. > > > _______________________________ > Do you Yahoo!? > Declare Yourself - Register online to vote today! > http://vote.yahoo.com > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp From alan.gauld at freenet.co.uk Wed Oct 13 19:26:42 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed Oct 13 19:26:44 2004 Subject: [Tutor] New List Member/Introduction References: Message-ID: <004f01c4b149$cedd6000$c7b28651@xp> Hi Anthony, > Up until now, I've been using PHP for web development, and C++, Java, > and Perl/Tk for desktop development. A few weeks ago, I discovered > Python and decided to give it a try. With a background like that you should be tutoring rather than being tutored within a month! :-) And continuing the generally friendly mood, I'd like to say hello again folks. After 6 weeks of moving house and no worthwhile net access I'm back online again - hooray! :-) Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld/tutor2/ From Mark.Kels at gmail.com Wed Oct 13 20:44:40 2004 From: Mark.Kels at gmail.com (Mark Kels) Date: Wed Oct 13 20:44:43 2004 Subject: [Tutor] How to save password ? Message-ID: Hi all, I want to make an application that is protected by a password ( in the first time the user enters a password, and after the first use he must enter that password every time the application starts ). For this kind of project I need to save the password so no one would be able to access it. does anyone have any suggestion ? From jmillr at umich.edu Wed Oct 13 21:15:11 2004 From: jmillr at umich.edu (John Miller) Date: Wed Oct 13 21:15:22 2004 Subject: [Tutor] Python and RFID In-Reply-To: <20041013100054.AB0431E4020@bag.python.org> References: <20041013100054.AB0431E4020@bag.python.org> Message-ID: <3402CE38-1D4C-11D9-9056-000A95B5BA08@umich.edu> Going to the latest issue of PyZine: http://www.pyzine.com/Issue006/index.html there's supposed to be an article called "RFID Product Development With Python" by Jeff Gray, however, there's no link and there hasn't been for several months. You might try to ping the PyZine folk or try to contact the author directly to get some info. John Miller On Oct 13, 2004, Anthony P. wrote: > I'm considering a business project that will implement RFID technology > and I'd like to do it all (or mostly) in Python on Linux. Does anyone > know of any RFID API's for Python that could give me a head start on > the project? > > Basically, all I need to do is read tags. But the catch is that I need > to be able to between multiple tags going through the system at the > same time. Any help with this would be very greatly appreciated. > > Thanks, > Anthony From Lbrannma at yahoo.com Wed Oct 13 21:36:40 2004 From: Lbrannma at yahoo.com (L&L) Date: Wed Oct 13 21:37:06 2004 Subject: [Tutor] moving focus away from a raw_input dialog box Message-ID: <6.1.2.0.1.20041013213245.01998140@pop.mail.yahoo.com> Hi All, My script uses raw_input to let a user choose from a list. The user can enter 0 to exit Python (i.e. it's a while loop with 0 as the exit condition). The problem is that the list presented to the user is quite long and he/she is not able to move focus away from the dialog box that results from raw_input (I am running Windows XP). Is there a solution to this? I would like to let the user scroll through the selection list. Thanks, Lance From carroll at tjc.com Wed Oct 13 21:50:04 2004 From: carroll at tjc.com (Terry Carroll) Date: Wed Oct 13 21:50:10 2004 Subject: [Tutor] Monitoring an Internet connection in Python Message-ID: My DSL connection is pretty fragile, and tends to drop a lot, and for extended periods. I'd like to write a Python program to periodicaly (say, every 5 minutes or so) check the status of the Internet connection, and log any change in status (detecting when it becomes unavailable and when it becomes available again), so I can document the failures to SBC. What's the best way to check whether my system has a working Internet connection using Python? My thinking is to select a few IP addresses known to be reliable, and to define "connection available" as being when at least one of those sites responds to a ping. Is there a better way? From Lbrannma at yahoo.com Wed Oct 13 22:15:16 2004 From: Lbrannma at yahoo.com (L&L) Date: Wed Oct 13 22:15:40 2004 Subject: [Tutor] moving focus away from a raw_input dialog box In-Reply-To: <6.1.2.0.1.20041013213245.01998140@pop.mail.yahoo.com> References: <6.1.2.0.1.20041013213245.01998140@pop.mail.yahoo.com> Message-ID: <6.1.2.0.1.20041013221434.019afe70@pop.mail.yahoo.com> re this problem... I am running ActiveState's Python 2.3 for Windows and Windows XP At 09:36 PM 10/13/2004, L&L wrote: >Hi All, > >My script uses raw_input to let a user choose from a list. The user can >enter 0 to exit Python (i.e. it's a while loop with 0 as the exit >condition). The problem is that the list presented to the user is quite >long and he/she is not able to move focus away from the dialog box that >results from raw_input (I am running Windows XP). Is there a solution to >this? I would like to let the user scroll through the selection list. > >Thanks, >Lance > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From kent_johnson at skillsoft.com Wed Oct 13 23:17:29 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Wed Oct 13 23:17:34 2004 Subject: [Tutor] Monitoring an Internet connection in Python In-Reply-To: References: Message-ID: <6.1.0.6.0.20041013171443.028bcf68@mail4.skillsoft.com> I have a DSL router with a built-in web server. One of the web pages shows the connection status. It would be pretty simple to write a Python script to poll the router web page and extract the status. Kent At 12:50 PM 10/13/2004 -0700, Terry Carroll wrote: >My DSL connection is pretty fragile, and tends to drop a lot, and for >extended periods. I'd like to write a Python program to periodicaly (say, >every 5 minutes or so) check the status of the Internet connection, and >log any change in status (detecting when it becomes unavailable and when >it becomes available again), so I can document the failures to SBC. > >What's the best way to check whether my system has a working Internet >connection using Python? My thinking is to select a few IP addresses >known to be reliable, and to define "connection available" as being when >at least one of those sites responds to a ping. Is there a better way? > > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From thomi at imail.net.nz Wed Oct 13 23:39:36 2004 From: thomi at imail.net.nz (Thomas Clive Richards) Date: Wed Oct 13 23:39:42 2004 Subject: [Tutor] Monitoring an Internet connection in Python In-Reply-To: <6.1.0.6.0.20041013171443.028bcf68@mail4.skillsoft.com> References: <6.1.0.6.0.20041013171443.028bcf68@mail4.skillsoft.com> Message-ID: <200410141039.36504.thomi@imail.net.nz> Hi, Most external DSL routers make sue of SNMP - if you know what you're looking for, it's trivial to write a python script that polls the router every 10 minutes or so. I had to do this to write my own dynamic DNS client. Unfortunately (AFAIK) every router model differs in the exact SNMP implementation, but I'm by no means a networking guru, so take this with a pinch of salt ;) HTH! -- Thomi Richards, thomi@once.net.nz From chandrakirti at gmail.com Wed Oct 13 23:44:27 2004 From: chandrakirti at gmail.com (Lloyd Hugh Allen) Date: Wed Oct 13 23:44:30 2004 Subject: [Tutor] Monitoring an Internet connection in Python In-Reply-To: <6.1.0.6.0.20041013171443.028bcf68@mail4.skillsoft.com> References: <6.1.0.6.0.20041013171443.028bcf68@mail4.skillsoft.com> Message-ID: <24d253d90410131444626c8689@mail.gmail.com> I did this for a linksys befw11sf4 802.11b router. In particular, I wanted it to email me when my IP address changed. It works pretty well for a week or two, and then the computer pretty much grinds to a halt. I didn't know whether the fault was with my script, with Python, or with Windows 98 (under which my desktop computer runs). I had used urllib2 to load the "Status" page from the router, and then watched for changes to the IP address. A second problem was that it would occasionally try to mail me when the address had changed to 0.0.0.0, which ran into problems... I also had used smtplib to send the message to myself. This kind of thing demonstrates the "batteries included"ness of Python. I didn't really feel like writing a mail or telnet client, nor web browser, and so was happy that all of these things were built in. On Wed, 13 Oct 2004 17:17:29 -0400, Kent Johnson wrote: > I have a DSL router with a built-in web server. One of the web pages shows > the connection status. It would be pretty simple to write a Python script > to poll the router web page and extract the status. > > Kent > > > > At 12:50 PM 10/13/2004 -0700, Terry Carroll wrote: > >My DSL connection is pretty fragile, and tends to drop a lot, and for > >extended periods. I'd like to write a Python program to periodicaly (say, > >every 5 minutes or so) check the status of the Internet connection, and > >log any change in status (detecting when it becomes unavailable and when > >it becomes available again), so I can document the failures to SBC. > > > >What's the best way to check whether my system has a working Internet > >connection using Python? My thinking is to select a few IP addresses > >known to be reliable, and to define "connection available" as being when > >at least one of those sites responds to a ping. Is there a better way? > > > > > > > >_______________________________________________ > >Tutor maillist - Tutor@python.org > >http://mail.python.org/mailman/listinfo/tutor > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From carroll at tjc.com Thu Oct 14 00:19:45 2004 From: carroll at tjc.com (Terry Carroll) Date: Thu Oct 14 00:19:48 2004 Subject: [Tutor] Monitoring an Internet connection in Python In-Reply-To: <6.1.0.6.0.20041013171443.028bcf68@mail4.skillsoft.com> Message-ID: On Wed, 13 Oct 2004, Kent Johnson wrote: > I have a DSL router with a built-in web server. One of the web pages shows > the connection status. It would be pretty simple to write a Python script > to poll the router web page and extract the status. I hadn't thought of that. I do use a router; it requires a logon (even with a user and password that each consist of empty strings), but I can probably finesse that. Thanks for the idea. From carroll at tjc.com Thu Oct 14 00:27:30 2004 From: carroll at tjc.com (Terry Carroll) Date: Thu Oct 14 00:27:33 2004 Subject: [Tutor] Monitoring an Internet connection in Python In-Reply-To: <200410141039.36504.thomi@imail.net.nz> Message-ID: On Thu, 14 Oct 2004, Thomas Clive Richards wrote: > Most external DSL routers make sue of SNMP - if you know what you're looking > for, it's trivial to write a python script that polls the router every 10 > minutes or so. I don't think my router (an SMC Barricade, SMC7004ABR) supports SNMP, but that's an interesting idea. Plus it might be a little bit fun to learn SNMP. From dyoo at hkn.eecs.berkeley.edu Thu Oct 14 00:43:24 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Oct 14 00:44:49 2004 Subject: [Tutor] Detecting EOF In-Reply-To: <009001c4ac84$0cdb84b0$6501a8c0@mickeybobxp> Message-ID: On Thu, 7 Oct 2004, Robert Hines wrote: > How do you detect the end of a file? Suppose I have a pickle file with a > variable number of objects. How do I unpickle the objects without > generating an EOF exception? Hi Robert, Has anyone addressed your question yet? Checking for EOF in Python is not idiomatic: you can explicitely detect the condition by using a try/except block, but you may want to rework the code so that it doesn't need to worry about EOF under normal circumstances. In a pinch, you could probably do something like: ### objects = [] try: while True: objects.append(pickle.load(srcfile)) except EOFError: pass ### But one way to avoid checking explicitely for EOF to modify the way you're pickling your objects. Instead of keeping a variable number of objects, it might be easier to pickle a single list that contains those objects. Alternatively, you can first pickle an integer that tells us how many pickled objects you'll be dumping. That way, you'd know how many times you'd have to load() during the unpickling. Would that work for you? I hope this helps! From flaxeater at yahoo.com Thu Oct 14 05:41:55 2004 From: flaxeater at yahoo.com (Chad Crabtree) Date: Thu Oct 14 05:41:58 2004 Subject: [Tutor] How to save password ? Message-ID: <20041014034155.10448.qmail@web52605.mail.yahoo.com> Mark Kels wrote: >Hi all, > >I want to make an application that is protected by a password ( in the >first time the user enters a password, and after the first use he must >enter that password every time the application starts ). >For this kind of project I need to save the password so no one would >be able to access it. >does anyone have any suggestion ? >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > > I would do a one way hash to check it this is how Linux does it's passwords. A python module that does this http://www.python.org/doc/current/lib/module-md5.html some articles on what this is. http://www.15seconds.com/issue/000217.htm http://www.webopedia.com/TERM/O/one-way_hash_function.htm _______________________________ Do you Yahoo!? Declare Yourself - Register online to vote today! http://vote.yahoo.com From s4046441 at student.uq.edu.au Thu Oct 14 06:34:43 2004 From: s4046441 at student.uq.edu.au (Ms Soo Chong) Date: Thu Oct 14 06:34:50 2004 Subject: [Tutor] Uploading an image file Message-ID: <855d7b85099c.85099c855d7b@uq.edu.au> Hi all, I have a form where users can use it to upload images into a file and save it into a directory. I have installed PIL and Image module and do a fair bit of reading on these module. But I don't know how can I use python to get the uploaded image file from the form. Can I use something like that: ###################################################### im_file = form["userfile"] ###################################################### im = Image.open(im_file) im.show() #################################################### Can someone help? Many thanks.... Shufen From cgjung at comcast.net Thu Oct 14 06:59:18 2004 From: cgjung at comcast.net (Comcast Mail) Date: Thu Oct 14 06:59:20 2004 Subject: [Tutor] Function Problem 3.6 Message-ID: <000001c4b1aa$93194500$f6aeda18@usertz7f6j789v> Skipped content of type multipart/alternative-------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: image/jpeg Size: 2743 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20041014/4a5b1114/attachment-0001.jpe From bill.mill at gmail.com Thu Oct 14 08:21:46 2004 From: bill.mill at gmail.com (Bill Mill) Date: Thu Oct 14 08:21:51 2004 Subject: [Tutor] Function Problem 3.6 In-Reply-To: <000001c4b1aa$93194500$f6aeda18@usertz7f6j789v> References: <000001c4b1aa$93194500$f6aeda18@usertz7f6j789v> Message-ID: <797fe3d40410132321526d546a@mail.gmail.com> Mike, any statement which is in a Python block needs to be indented. Blocks include such things as functions and loops; here you are trying to enter a function. So, here's the code we're shooting for: def newLine(): print To enter this into the interpreter, enther the first line and press enter. When the ellipses appear, press tab, then enter print and hit enter. The IndentationError you were getting was caused by the print statement not being indented. At this point, you have *defined* a function, but now you can try calling it. To do so, you do this: >>>newLine() And hit enter; a blank line will be printed. Hope this helped. Peace Bill Mill bill.mill at gmail.com On Thu, 14 Oct 2004 00:59:18 -0400, Comcast Mail wrote: > > > > The exercise below refers to section 3.6 in "How to think like a computer > scientist: Learning with Python." I have version 2.3.4 of Python. I've > copied part of it between the brackets below. > > [STATEMENTS > > You can make up any names you want for the functions you create, except that > you can't use a name that is a Python keyword. The list of parameters > specifies what information, if any, you have to provide in order to use the > new function. There can be any number of statements inside the function, > but they have to be indented from the left margin. In the examples in this > book, we will use an indentation of two spaces. > > The first couple of functions we are going to write have no parameters, so > the syntax looks like this: > > def newLine(): > > print > > This function is named newLine. The empty parentheses indicate that it has > no parameters. It contains only a single statement, which outputs a newline > character. (That's what happens when you use a print command without any > arguments.) ] > > My problem is that when I attempt the exercise above, I get the following: > > > > >>>def newLine(): I then hit "enter" key, and I get > > ? > > > > I get three ellipses, no "print" output. If I then enter > > >>>print "First Line." > > > > Instead of getting the output "newLine()" as the book states > > > > I get an "indentationerror." > > > > Obviously the >>>print "Second Line." Doesn't work either. > > > > > > > > I hope I've explained this well enough. What the heck is going on? I had > no problems with earlier exercises. Any help would be greatly appreciated. > Please respond both on the board and to me at this email address if > possible. > > > > > > > > > > > > > > > > > > > > > > > > Michael > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > > From cyresse at gmail.com Thu Oct 14 10:42:59 2004 From: cyresse at gmail.com (Riumu Kuraku) Date: Thu Oct 14 10:43:02 2004 Subject: [Tutor] email & imaplib for beginners like me Message-ID: Hi all, (This started off as a plea for help.) Just tryng to understand the email package, and the docs are a little... sparse? Maybe it's more I'm having trouble with OOP. Anyway, here's a sequence I've learnt from frustrating trial and error, I'm trying to log on to a mail server, and download a message, and make it readable. I thought I'd send it through in case anyone else gets stuck like me. I'm doing it manually so I can understand how it works before I script it. I'm having trouble with some stuff like - a=test.fetch(1, 'RFC822' )... The first argument of fetch is fine. It's the second that's got me. It's a name of a Internet standard. And I used it on three different emails, and it got two headers, and one header and full text. So I am quite confused as to how exactly to get specific things, like headers/text/attachments only, so any light that can be shed in that regard would be fantastic. >>>import imaplib # IMAP protocol library >>>import email.Parser # email parser library >>>host="mail... ...com" # IMAP server name >>>use="" # Your login >>>pas="" # Your (plain text) password >>>test=imaplib.IMAP4(host) # Create instance of imap protocol connection >>>test.login(use, pas) # Send login and password to server ('OK', ['LOGIN Welcome']) # Server likes it >>>test.select() # Selects INBOX by default. Good enough for me... ('OK', ['3']) # I have 3 email messages >>>x=test.fetch(3,'RFC822') #Try and get message 3... >>> print x ('OK', [('3 (FLAGS (\\Seen hasnoatt) RFC822 {1200}', 'Return-Path: \r\nReceived: from .... ......\r\nReply-To: cyresse@gmail.com, cynos@safe-mail.net\r\nTo: protocol_test@allmail.net\r\nSubject: Boo\r\nMime-Version: 1.0\r\nContent-Type: text/plain; charset=US-ASCII\r\nContent-Transfer-Encoding: 7bit\r\n\r\nWhios\r\n'), ')']) ..Looks vaguely emailish to me (bit chopped out for brevity) >>>j=Parser #I want to parse what I downloaded using Parser >>>print j.parse(x) TypeError: unbound method parse() must be called with Parser instance as first argument (got tuple instance instead) #What does that mean? .....45 minutes later... oh.... >>>j=Parser() # REALLY IMPORTANT to include the (), I was running around in circles # for a looooong time trying to figure that out. >>>print j.parse(x) AttributeError: 'tuple' object has no attribute 'readline' #OK, so x is a tuple, and it has no attr, readline...hmmm... #Run off to docs, and open parser.py to have a look and: >>>print j.parsestr(x) #Turns out, Parser.parse() is for file objects... Parser.parsestr() # is for string objects, as I am about to learn. TypeError: expected read buffer, tuple found #Still not liking tuple. Hmmm... >>>i=str(x) >>>print j.parsestr(i) >From nobody Thu Oct 14 21:10:42 2004 ('OK', [('3 (FLAGS (\\Seen hasnoatt) RFC822 {1200}', 'Return-Path: \r\nReceived: from .... . .....Reply-To: cyresse@gmail.com, cynos@safe-mail.net\r\nTo: protocol_test@allmail.net\r\nSubject: Boo\r\nMime-Version: 1.0\r\nContent-Type: text/plain; charset=US-ASCII\r\nContent-Trarnsfer-Encoding: 7bit\r\n\r\nWhios\r\n'), ')']) Huzzah! A header, that is easy to read! (Once again, snipped for brevity.) Now, to reliably be able to get a whole email... I could write my own client : ) From FrankBloeink at nerdshack.com Thu Oct 14 11:05:39 2004 From: FrankBloeink at nerdshack.com (FrankBloeink@nerdshack.com) Date: Thu Oct 14 11:09:25 2004 Subject: [Tutor] Function Problem 3.6 In-Reply-To: <000001c4b1aa$93194500$f6aeda18@usertz7f6j789v> References: <000001c4b1aa$93194500$f6aeda18@usertz7f6j789v> Message-ID: <20041014110539.4fb08dca@speedking.dyndns.org> Hello Michael Here's what I got when I read and tried the example you gave from the book: #defining the function (take care of indentation!) >>> def newLine(): ... print ... #executing the function gives the ecpected output(a newline # character, ie the cursor is jumping to the next line) >>> newLine() >>> The problem with executing print "First Line" newLine() print "Second Line" in the python-shell is that every statement in the shell is directly followed by the input, meaning you get a mixture of programm code and output: >>> print "First Line" First Line >>> nl() >>> print "Second Line" Second Line >>> If you would run this Program as a python script outside the interpreter, you shoul get the expected result: ---start the script---- First Line Second Line ---end of the output--- hth Frank P.S: This is my first post to the list, although I've read on the list for about 2 months. Thanks to all the members on the list for the informative posts, I hope I can contibute myself from time to time, at least at the more basic stuff for I'm only a Python-beginner, too. On Thu, 14 Oct 2004 00:59:18 -0400 "Comcast Mail" wrote: > The exercise below refers to section 3.6 in "How to think like a > computer scientist: Learning with Python." > def newLine(): > > print > > This function is named newLine. The empty parentheses indicate that it > has no parameters. It contains only a single statement, which outputs > a newline character. (That's what happens when you use a print command > without any arguments.) ] > > My problem is that when I attempt the exercise above, I get the > following: > > > > >>>def newLine(): I then hit "enter" key, and I get > > . > > > > I get three ellipses, no "print" output. If I then enter > > >>>print "First Line." > > > > Instead of getting the output "newLine()" as the book states > > > > I get an "indentationerror." > > > > Obviously the >>>print "Second Line." Doesn't work either. > > Michael > > > > -- "(8) It is more complicated than you think." RFC 1925: The Twelve Networking Truths -- "(8) It is more complicated than you think." RFC 1925: The Twelve Networking Truths From melnyk at gmail.com Thu Oct 14 13:12:16 2004 From: melnyk at gmail.com (Scott Melnyk) Date: Thu Oct 14 13:12:21 2004 Subject: [Tutor] finding non unique data in lists Message-ID: Hello! I have a collection of lists of different lengths (containing exons from genetic data) that I would like to compare and only keep the those that are found within each of the lists. Any exon not present in all the lists is not important to me. I am new to python and was told that sets could be used easily to find the unique data but I am unsure the most efficient way how to pull out the non-unique data. All suggestions are very much appreciated and welcome. -- Scott From kent_johnson at skillsoft.com Thu Oct 14 13:44:55 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Thu Oct 14 13:44:59 2004 Subject: [Tutor] finding non unique data in lists In-Reply-To: References: Message-ID: <6.1.0.6.0.20041014073643.028c64a8@mail4.skillsoft.com> Scott, You can make a Set from each list, then find the intersection of all the sets. That will contain just the elements in all the lists. >>> from sets import Set First some raw data: >>> l1 = [1,2,3,4,5,6,7] >>> l2 = [2,3,4,7] >>> l3 = [1,2,3,5,6,7] Sets can be constructed from lists: >>> s1 = Set(l1) >>> s1 Set([1, 2, 3, 4, 5, 6, 7]) >>> s2 = Set(l2) >>> s3 = Set(l3) Sets overload the & operator to mean set intersection: >>> all = s1 & s2 & s3 >>> all Set([2, 3, 7]) Sets allow iteration to process their elements one-by-one: >>> for i in all: ... print i ... 2 3 7 For more information about sets see the library reference page at http://docs.python.org/lib/module-sets.html Kent At 01:12 PM 10/14/2004 +0200, Scott Melnyk wrote: >Hello! > >I have a collection of lists of different lengths (containing exons >from genetic data) that I would like to compare and only keep the >those that are found within each of the lists. Any exon not present >in all the lists is not important to me. > >I am new to python and was told that sets could be used easily to find >the unique data but I am unsure the most efficient way how to pull out >the non-unique data. > >All suggestions are very much appreciated and welcome. > > >-- >Scott >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From Mark.Kels at gmail.com Thu Oct 14 15:36:06 2004 From: Mark.Kels at gmail.com (Mark Kels) Date: Thu Oct 14 15:36:10 2004 Subject: [Tutor] How to save password ? In-Reply-To: <20041014034155.10448.qmail@web52605.mail.yahoo.com> References: <20041014034155.10448.qmail@web52605.mail.yahoo.com> Message-ID: but how do I change back the hash to the password ( to confirm it ) ? From pythonTutor at venix.com Thu Oct 14 15:49:51 2004 From: pythonTutor at venix.com (Lloyd Kvam) Date: Thu Oct 14 15:50:00 2004 Subject: [Tutor] How to save password ? In-Reply-To: References: <20041014034155.10448.qmail@web52605.mail.yahoo.com> Message-ID: <1097761791.6684.3.camel@laptop.venix.com> On Thu, 2004-10-14 at 09:36, Mark Kels wrote: > but how do I change back the hash to the password ( to confirm it ) ? You don't. You hash the password you receive and see if it matches the hash you saved. In general, you do not want your application to "know" the user passwords. > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp From rdm at rcblue.com Thu Oct 14 16:38:31 2004 From: rdm at rcblue.com (Dick Moores) Date: Thu Oct 14 16:38:34 2004 Subject: [Tutor] Can I speed this up? In-Reply-To: <6.1.0.6.0.20041012082330.028ba110@mail4.skillsoft.com> References: <6.1.2.0.2.20041011012649.05653430@rcblue.com> <6.1.0.6.0.20041012082330.028ba110@mail4.skillsoft.com> Message-ID: <6.1.2.0.2.20041014073123.062a6040@rcblue.com> Kent Johnson wrote at 05:32 10/12/2004: >Using psyco gives a small speedup - in my limited testing, about 15%. > >Install psyco from http://psyco.sourceforge.net, then put these two >lines after the definition of factorsOfInteger: >import psyco >psyco.bind(factorsOfInteger) Sorry to be so dumb about these things, but I can't figure out how to install Psyco. I now have psyco-1.2-win-2.3.zip in my C:\Python23 folder (Win XP). I've poked around in the file but I don't see any instructions as to what to next to install Psyco. Also, doesn't help this dummy. Help, please. Dick Moores rdm@rcblue.com From mhansen at cso.atmel.com Thu Oct 14 16:51:27 2004 From: mhansen at cso.atmel.com (Mike Hansen) Date: Thu Oct 14 16:52:01 2004 Subject: [Tutor] pyPgSQL and Slackware 9.1 Message-ID: <416E926F.700@cso.atmel.com> I'm having trouble getting _any_ postgre interface module to install on one of our Slackware 9.1 servers. I can get around in Linux, but pretty green on knowing where things are in Linux. Postgre 7.4.1 is up and running on this server.(Many Perl web apps connect to it no problem.) Python 2.3.1 is running on this server. Here's what happens when I try to run the setup for pyPgSQL module as root: # python setup.py build /usr/lib/python2.3/distutils/dist.py:213: UserWarning: 'licence' distribution o tion is deprecated; use 'license' warnings.warn(msg) running build running build_py running build_ext building 'pyPgSQL.libpq.libpqmodule' extension gcc -pthread -shared build/temp.linux-i686-2.3/libpqmodule.o build/temp.linux-i 86-2.3/pgboolean.o build/temp.linux-i686-2.3/pgint2object.o build/temp.linux-i6 6-2.3/pgint8object.o build/temp.linux-i686-2.3/pgversion.o build/temp.linux-i68 -2.3/pglargeobject.o build/temp.linux-i686-2.3/pgnotify.o build/temp.linux-i686 2.3/pgconnection.o build/temp.linux-i686-2.3/pgresult.o build/temp.linux-i686-2 3/pymemstrdup.o build/temp.linux-i686-2.3/port/strtoll.o build/temp.linux-i686- .3/port/strtoull.o build/temp.linux-i686-2.3/port/strtok.o -L/usr/lib -lpq -o b ild/lib.linux-i686-2.3/pyPgSQL/libpq/libpqmodule.so /usr/lib/gcc-lib/i486-slackware-linux/3.2.3/../../../../i486-slackware-linux/bi /ld: cannot find -lpq collect2: ld returned 1 exit status error: command 'gcc' failed with exit status 1 Can someone tell what's causing the error? Do I need to tweak the setup.py to change where it looks for the files it needs? I started with pyPgSQL since I had used it before from Windows. Although as long as I get a DB-API 2.0 compliant module working on this server, I don't really care about which postgre interface module I use. While I'm asking questions, can anyone recommend a linux book that discusses the typical directory structure, where to find things, and why they are were they are?(If that makes any sense.) Thanks, Mike From flaxeater at yahoo.com Thu Oct 14 16:58:01 2004 From: flaxeater at yahoo.com (Chad Crabtree) Date: Thu Oct 14 17:01:31 2004 Subject: [Tutor] Can I speed this up? Message-ID: <20041014145801.8213.qmail@web52609.mail.yahoo.com> Dick Moores wrote: > > Sorry to be so dumb about these things, but I can't figure out how to > install Psyco. I now have psyco-1.2-win-2.3.zip in my C:\Python23 > folder (Win XP). I've poked around in the file but I don't see any > instructions as to what to next to install Psyco. Also, > doesn't help this > dummy. > When I used it in the past there was a windows installer. Make sure you've downloaded the binary package. _______________________________ Do you Yahoo!? Declare Yourself - Register online to vote today! http://vote.yahoo.com From kent_johnson at skillsoft.com Thu Oct 14 17:15:42 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Thu Oct 14 17:15:54 2004 Subject: [Tutor] Can I speed this up? In-Reply-To: <6.1.2.0.2.20041014073123.062a6040@rcblue.com> References: <6.1.2.0.2.20041011012649.05653430@rcblue.com> <6.1.0.6.0.20041012082330.028ba110@mail4.skillsoft.com> <6.1.2.0.2.20041014073123.062a6040@rcblue.com> Message-ID: <6.1.0.6.0.20041014111411.02869a00@mail4.skillsoft.com> Unzip the zip file. Copy the folder psyco-1.2/psyco into Python23/Lib/site-packages. (Create site-packages if you don't already have it.) Should be good to go then. Kent At 07:38 AM 10/14/2004 -0700, Dick Moores wrote: >Kent Johnson wrote at 05:32 10/12/2004: >>Using psyco gives a small speedup - in my limited testing, about 15%. >> >>Install psyco from http://psyco.sourceforge.net, then put these two lines >>after the definition of factorsOfInteger: >>import psyco >>psyco.bind(factorsOfInteger) > >Sorry to be so dumb about these things, but I can't figure out how to >install Psyco. I now have psyco-1.2-win-2.3.zip in my C:\Python23 folder >(Win XP). I've poked around in the file but I don't see any instructions >as to what to next to install Psyco. Also, > doesn't help this dummy. > >Help, please. > >Dick Moores >rdm@rcblue.com > > From my.mailing.lists at noos.fr Thu Oct 14 17:19:05 2004 From: my.mailing.lists at noos.fr (nik) Date: Thu Oct 14 17:19:15 2004 Subject: [Tutor] pyPgSQL and Slackware 9.1 In-Reply-To: <416E926F.700@cso.atmel.com> References: <416E926F.700@cso.atmel.com> Message-ID: <416E98E9.7070404@noos.fr> I can't help much with your build problem, other than try using; locate libpq to see if the library is on your system (may have to do an updatedb first), and possibly put a symbolic link into /usr/lib (isn't the library normally in /usr/local/pgsql/lib ?) but otherwise man hier will give a good description of what goes where in linux... nik Mike Hansen wrote: > I'm having trouble getting _any_ postgre interface module to install > on one of our Slackware 9.1 servers. I can get around in Linux, but > pretty green on knowing where things are in Linux. Postgre 7.4.1 is up > and running on this server.(Many Perl web apps connect to it no > problem.) Python 2.3.1 is running on this server. Here's what happens > when I try to run the setup for pyPgSQL module as root: > > # python setup.py build > /usr/lib/python2.3/distutils/dist.py:213: UserWarning: 'licence' > distribution o > tion is deprecated; use 'license' > warnings.warn(msg) > running build > running build_py > running build_ext > building 'pyPgSQL.libpq.libpqmodule' extension > gcc -pthread -shared build/temp.linux-i686-2.3/libpqmodule.o > build/temp.linux-i > 86-2.3/pgboolean.o build/temp.linux-i686-2.3/pgint2object.o > build/temp.linux-i6 > 6-2.3/pgint8object.o build/temp.linux-i686-2.3/pgversion.o > build/temp.linux-i68 > -2.3/pglargeobject.o build/temp.linux-i686-2.3/pgnotify.o > build/temp.linux-i686 > 2.3/pgconnection.o build/temp.linux-i686-2.3/pgresult.o > build/temp.linux-i686-2 > 3/pymemstrdup.o build/temp.linux-i686-2.3/port/strtoll.o > build/temp.linux-i686- > .3/port/strtoull.o build/temp.linux-i686-2.3/port/strtok.o -L/usr/lib > -lpq -o b > ild/lib.linux-i686-2.3/pyPgSQL/libpq/libpqmodule.so > /usr/lib/gcc-lib/i486-slackware-linux/3.2.3/../../../../i486-slackware-linux/bi > > /ld: cannot find -lpq > collect2: ld returned 1 exit status > error: command 'gcc' failed with exit status 1 > > Can someone tell what's causing the error? Do I need to tweak the > setup.py to change where it looks for the files it needs? I started > with pyPgSQL since I had used it before from Windows. Although as long > as I get a DB-API 2.0 compliant module working on this server, I don't > really care about which postgre interface module I use. > > While I'm asking questions, can anyone recommend a linux book that > discusses the typical directory structure, where to find things, and > why they are were they are?(If that makes any sense.) > > Thanks, > > Mike > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From Mark.Kels at gmail.com Thu Oct 14 17:43:42 2004 From: Mark.Kels at gmail.com (Mark Kels) Date: Thu Oct 14 17:43:50 2004 Subject: [Tutor] checking if file exists Message-ID: Hi, How can I check if file exists in a folder ? I tryed to do it with an if statment, but I cant use the error as a boolean expression... Any suggestions ? Thanks, From wilson at visi.com Thu Oct 14 17:51:34 2004 From: wilson at visi.com (Tim Wilson) Date: Thu Oct 14 17:51:40 2004 Subject: [Tutor] checking if file exists In-Reply-To: Message-ID: On 10/14/04 10:43 AM, "Mark Kels" wrote: > How can I check if file exists in a folder ? > I tryed to do it with an if statment, but I cant use the error as a > boolean expression... > Any suggestions ? I'm sure someone will suggest something most specific, but this is where the try-except combination comes in. It would look something like this: try: f = open(filename) etc etc etc except IOError: print "There's no %s file there." % filename etc etc etc -Tim -- Tim Wilson Twin Cities, Minnesota, USA Educational technology guy, Linux and OS X fan, Grad. student, Daddy mailto: wilson@visi.com aim: tis270 public key: 0x8C0F8813 From bwinton at latte.ca Thu Oct 14 17:52:16 2004 From: bwinton at latte.ca (Blake Winton) Date: Thu Oct 14 17:52:19 2004 Subject: [Tutor] checking if file exists In-Reply-To: References: Message-ID: <416EA0B0.9080703@latte.ca> Mark Kels wrote: > How can I check if file exists in a folder ? > I tryed to do it with an if statment, but I cant use the error as a > boolean expression... > Any suggestions ? >>> import os.path >>> os.path.exists( r'c:\program files\python\python.exe' ) True >>> os.path.exists( r'c:\program files\python\pythin.exe' ) False (I don't normally just give people the answers, but in this case I don't think there's anything significant to be learned. Maybe "check the standard library", but that's a bit of a stretch to turn into a lesson.) Later, Blake. From N.Marabe at spitech.com Thu Oct 14 18:08:42 2004 From: N.Marabe at spitech.com (Marabe, Nelsie) Date: Thu Oct 14 18:04:43 2004 Subject: [Tutor] checking if file exists Message-ID: <048A40781D05D143842A596D7C78F40F03F9E6F3@SPI-MAIL2003.SPITECH.COM> Another solution is to use the os module. import os if os.path.exists(file): print "file exists" else: print "file not exists" -----Original Message----- From: Tim Wilson [mailto:wilson@visi.com] Sent: Thursday, October 14, 2004 11:52 PM To: Mark Kels; tutor@python.org Subject: Re: [Tutor] checking if file exists On 10/14/04 10:43 AM, "Mark Kels" wrote: > How can I check if file exists in a folder ? > I tryed to do it with an if statment, but I cant use the error as a > boolean expression... Any suggestions ? I'm sure someone will suggest something most specific, but this is where the try-except combination comes in. It would look something like this: try: f = open(filename) etc etc etc except IOError: print "There's no %s file there." % filename etc etc etc -Tim -- Tim Wilson Twin Cities, Minnesota, USA Educational technology guy, Linux and OS X fan, Grad. student, Daddy mailto: wilson@visi.com aim: tis270 public key: 0x8C0F8813 From abra9823 at mail.usyd.edu.au Thu Oct 14 18:51:49 2004 From: abra9823 at mail.usyd.edu.au (Ajay) Date: Thu Oct 14 18:51:56 2004 Subject: [Tutor] checking if file exists In-Reply-To: <416EA0B0.9080703@latte.ca> References: <416EA0B0.9080703@latte.ca> Message-ID: <1097772709.416eaea5eb376@www-mail.usyd.edu.au> Quoting Blake Winton : > Mark Kels wrote: > > How can I check if file exists in a folder ? > > I tryed to do it with an if statment, but I cant use the error as a > > boolean expression... > > Any suggestions ? > > >>> import os.path > >>> os.path.exists( r'c:\program files\python\python.exe' ) > True > >>> os.path.exists( r'c:\program files\python\pythin.exe' ) > False > > (I don't normally just give people the answers, but in this case I don't > think there's anything significant to be learned. Maybe "check the > standard library", but that's a bit of a stretch to turn into a lesson.) > > Later, > Blake. and there is also the os.path.isfile(path) function call. > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > ---------------------------------------------------------------- This message was sent using IMP, the Internet Messaging Program. From Mark.Kels at gmail.com Thu Oct 14 20:05:23 2004 From: Mark.Kels at gmail.com (Mark Kels) Date: Thu Oct 14 20:05:29 2004 Subject: [Tutor] How to save password ? In-Reply-To: <2b46c7150410140639316859d0@mail.gmail.com> References: <20041014034155.10448.qmail@web52605.mail.yahoo.com> <2b46c7150410140639316859d0@mail.gmail.com> Message-ID: On Thu, 14 Oct 2004 10:39:44 -0300, Marcos Mendon?a wrote: > Hi > > You don't need to change back and md5 is a one way enconding technique. > Just read the password the user enters, hash it and them compare it to > the stored hashed value. If the hashes are the same the password is > valid. > > Hope i have helped > > Marcos Mendon?a > See Ya! > > On Thu, 14 Oct 2004 15:36:06 +0200, Mark Kels wrote: > > but how do I change back the hash to the password ( to confirm it ) ? > > > > > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > Oh, ok, thanks. But how can I save the hash so no one could change it but the app will be able to access it and compare it to the password the user enters ? Thanks again. From rdm at rcblue.com Thu Oct 14 20:34:33 2004 From: rdm at rcblue.com (Dick Moores) Date: Thu Oct 14 20:34:37 2004 Subject: [Tutor] Can I speed this up? In-Reply-To: <6.1.0.6.0.20041014111411.02869a00@mail4.skillsoft.com> References: <6.1.2.0.2.20041011012649.05653430@rcblue.com> <6.1.0.6.0.20041012082330.028ba110@mail4.skillsoft.com> <6.1.2.0.2.20041014073123.062a6040@rcblue.com> <6.1.0.6.0.20041014111411.02869a00@mail4.skillsoft.com> Message-ID: <6.1.2.0.2.20041014085008.032f21a0@rcblue.com> Kent, Thanks very much. Got psyco working, and it makes a significant difference. The worst "anomalie" I'd found in the 400 trillion range was 400,000,000,092,821 = 19624679*20382499. After implementing a couple of your previous suggestions the time for this went from 41 to 18 seconds. And now with psyco, to 13 seconds! Version I first asked about is still at I'm still trying to re-rethink isPrime(), isPrimeSmall(), isPrimeBig() and factorsOfInteger(). BTW I'm wondering why you said to put import psyco psyco.bind(factorsOfInteger) after the definition of factorsOfInteger(). I have "import time" at the top, above all the functions. Is this wrong (it works there) or non-standard? Dick Kent Johnson wrote at 08:15 10/14/2004: >Unzip the zip file. Copy the folder psyco-1.2/psyco into >Python23/Lib/site-packages. (Create site-packages if you don't already >have it.) Should be good to go then. > >Kent > >At 07:38 AM 10/14/2004 -0700, Dick Moores wrote: >>Kent Johnson wrote at 05:32 10/12/2004: >>>Using psyco gives a small speedup - in my limited testing, about 15%. >>> >>>Install psyco from http://psyco.sourceforge.net, then put these two >>>lines after the definition of factorsOfInteger: >>>import psyco >>>psyco.bind(factorsOfInteger) >> >>Sorry to be so dumb about these things, but I can't figure out how to >>install Psyco. I now have psyco-1.2-win-2.3.zip in my C:\Python23 >>folder (Win XP). I've poked around in the file but I don't see any >>instructions as to what to next to install Psyco. Also, >> doesn't help this dummy. >> >>Help, please. >> >>Dick Moores >>rdm@rcblue.com >> > From kent_johnson at skillsoft.com Thu Oct 14 20:44:12 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Thu Oct 14 20:44:18 2004 Subject: [Tutor] Can I speed this up? In-Reply-To: <6.1.2.0.2.20041014085008.032f21a0@rcblue.com> References: <6.1.2.0.2.20041011012649.05653430@rcblue.com> <6.1.0.6.0.20041012082330.028ba110@mail4.skillsoft.com> <6.1.2.0.2.20041014073123.062a6040@rcblue.com> <6.1.0.6.0.20041014111411.02869a00@mail4.skillsoft.com> <6.1.2.0.2.20041014085008.032f21a0@rcblue.com> Message-ID: <6.1.0.6.0.20041014144049.02982490@mail4.skillsoft.com> The import psyco can be anywhere. The psyco.bind(factorsOfInteger) has to come after the definition of factorsOfInteger or you will get a NameError. I've been monkeying around with a version of this, I'll post it when I get time to write it up...the key for me was instead of isPrime() I have find findFactor() Kent At 11:34 AM 10/14/2004 -0700, Dick Moores wrote: >Kent, > >Thanks very much. Got psyco working, and it makes a significant >difference. The worst "anomalie" I'd found in the 400 trillion range was >400,000,000,092,821 = 19624679*20382499. >After implementing a couple of your previous suggestions the time for this >went >from 41 to 18 seconds. And now with psyco, to 13 seconds! > > >Version I first asked about is still at > > >I'm still trying to re-rethink isPrime(), isPrimeSmall(), isPrimeBig() >and factorsOfInteger(). > >BTW I'm wondering why you said to put > >import psyco >psyco.bind(factorsOfInteger) > >after the definition of factorsOfInteger(). I have "import time" at the >top, above all the functions. Is this wrong (it works there) or non-standard? > >Dick > > >Kent Johnson wrote at 08:15 10/14/2004: >>Unzip the zip file. Copy the folder psyco-1.2/psyco into >>Python23/Lib/site-packages. (Create site-packages if you don't already >>have it.) Should be good to go then. >> >>Kent >> >>At 07:38 AM 10/14/2004 -0700, Dick Moores wrote: >>>Kent Johnson wrote at 05:32 10/12/2004: >>>>Using psyco gives a small speedup - in my limited testing, about 15%. >>>> >>>>Install psyco from http://psyco.sourceforge.net, then put these two >>>>lines after the definition of factorsOfInteger: >>>>import psyco >>>>psyco.bind(factorsOfInteger) >>> >>>Sorry to be so dumb about these things, but I can't figure out how to >>>install Psyco. I now have psyco-1.2-win-2.3.zip in my C:\Python23 folder >>>(Win XP). I've poked around in the file but I don't see any instructions >>>as to what to next to install Psyco. Also, >>> doesn't help this dummy. >>> >>>Help, please. >>> >>>Dick Moores >>>rdm@rcblue.com > From mhansen at cso.atmel.com Thu Oct 14 21:11:25 2004 From: mhansen at cso.atmel.com (Mike Hansen) Date: Thu Oct 14 21:11:27 2004 Subject: [Tutor] pyPgSQL and Slackware 9.1 In-Reply-To: <416E98E9.7070404@noos.fr> References: <416E926F.700@cso.atmel.com> <416E98E9.7070404@noos.fr> Message-ID: <416ECF5D.5010409@cso.atmel.com> Thanks Nik. Changing the lib in the setup to /usr/local/pgsql/lib got the build to work. The install behaved as well. However, when I run the test cases, I get the failures below. I made a script that connects to a database and prints some records and it seems to work. I am concerned about these failures. $ python test/PgSQLTestCases.py ........................................F.F....................... ====================================================================== FAIL: CheckDoMoreResultObjectChecks (__main__.PgSQLTestCases) ---------------------------------------------------------------------- Traceback (most recent call last): File "test/PgSQLTestCases.py", line 817, in CheckDoMoreResultObjectChecks self.fail(msg) File "/usr/lib/python2.3/unittest.py", line 270, in fail raise self.failureException, msg AssertionError: '7.4' ====================================================================== FAIL: Test execute() with a singleton string as the parameter. ---------------------------------------------------------------------- Traceback (most recent call last): File "test/PgSQLTestCases.py", line 639, in CheckExecuteWithSingleton "Length of cur.description is %d, it should be %d." % File "/usr/lib/python2.3/unittest.py", line 302, in failUnlessEqual raise self.failureException, \ AssertionError: Length of cur.description is 11, it should be 4. ---------------------------------------------------------------------- Ran 66 tests in 0.854s FAILED (failures=2) nik wrote: > I can't help much with your build problem, other than try using; > locate libpq > to see if the library is on your system (may have to do an updatedb > first), and possibly put a symbolic link into /usr/lib (isn't the > library normally in /usr/local/pgsql/lib ?) > > but otherwise > man hier > will give a good description of what goes where in linux... > > nik > > Mike Hansen wrote: > >> I'm having trouble getting _any_ postgre interface module to install >> on one of our Slackware 9.1 servers. I can get around in Linux, but >> pretty green on knowing where things are in Linux. Postgre 7.4.1 is >> up and running on this server.(Many Perl web apps connect to it no >> problem.) Python 2.3.1 is running on this server. Here's what happens >> when I try to run the setup for pyPgSQL module as root: >> >> # python setup.py build >> /usr/lib/python2.3/distutils/dist.py:213: UserWarning: 'licence' >> distribution o >> tion is deprecated; use 'license' >> warnings.warn(msg) >> running build >> running build_py >> running build_ext >> building 'pyPgSQL.libpq.libpqmodule' extension >> gcc -pthread -shared build/temp.linux-i686-2.3/libpqmodule.o >> build/temp.linux-i >> 86-2.3/pgboolean.o build/temp.linux-i686-2.3/pgint2object.o >> build/temp.linux-i6 >> 6-2.3/pgint8object.o build/temp.linux-i686-2.3/pgversion.o >> build/temp.linux-i68 >> -2.3/pglargeobject.o build/temp.linux-i686-2.3/pgnotify.o >> build/temp.linux-i686 >> 2.3/pgconnection.o build/temp.linux-i686-2.3/pgresult.o >> build/temp.linux-i686-2 >> 3/pymemstrdup.o build/temp.linux-i686-2.3/port/strtoll.o >> build/temp.linux-i686- >> .3/port/strtoull.o build/temp.linux-i686-2.3/port/strtok.o -L/usr/lib >> -lpq -o b >> ild/lib.linux-i686-2.3/pyPgSQL/libpq/libpqmodule.so >> /usr/lib/gcc-lib/i486-slackware-linux/3.2.3/../../../../i486-slackware-linux/bi >> >> /ld: cannot find -lpq >> collect2: ld returned 1 exit status >> error: command 'gcc' failed with exit status 1 >> >> Can someone tell what's causing the error? Do I need to tweak the >> setup.py to change where it looks for the files it needs? I started >> with pyPgSQL since I had used it before from Windows. Although as >> long as I get a DB-API 2.0 compliant module working on this server, I >> don't really care about which postgre interface module I use. >> >> While I'm asking questions, can anyone recommend a linux book that >> discusses the typical directory structure, where to find things, and >> why they are were they are?(If that makes any sense.) >> >> Thanks, >> >> Mike >> _______________________________________________ >> Tutor maillist - Tutor@python.org >> http://mail.python.org/mailman/listinfo/tutor >> >> > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From dyoo at hkn.eecs.berkeley.edu Thu Oct 14 21:29:08 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Oct 14 21:29:15 2004 Subject: [Tutor] Problem with mxODBC insert statement In-Reply-To: <416C4BF3.8010709@noos.fr> Message-ID: > Khawaja-Shahzad Butt wrote: > > > I don't know how to use SQL which way for mxODBC and python. I used > > this statement and got this error. > > > >q= "INSERT INTO > >rss_feed_items(item_date,item_title,item_author,item_permalink, > > item_description) > > VALUES(%s)"%(item_dmodified); Hello, What's the value of item_dmodified here? The SQL query that you're generating will probably need correction, as there needs to be as many values as there are columns in the SQL insertion statement. I expected to see something like: ### q = """INSERT INTO rss_feed_items( item_date, item_title, item_author, item_permalink, item_description) VALUES( ?, ?, ?, ?, ?)""" ### > >or can i use the ? instead of %s can you give me example since there is > >none in egenix manual for mxODBC. What am i doing wrong. Also should > >always use auto_commit while using mxODBC Let me check the mxODBC manual... ok, here's what they say about parameters: """ execute(operation[,parameters]) Prepare and execute a database operation (query or command). Parameters must be provided as sequence and will be bound to variables in the operation. Variables are specified using the ODBC variable placeholder '?', e.g. 'SELECT name,id FROM table WHERE amount > ? AND amount < ?' (also see the module attribute paramstyle) and get bound in the order they appear in the SQL statement from left to right. A reference to the operation will be retained by the cursor. If the same operation object is passed in again, then the cursor will optimize its behavior by reusing the previously prepared statement. This is most effective for algorithms where the same operation is used, but different parameters are bound to it (many times). """ (http://www.egenix.com/files/python/mxODBC.html) So yes, you can use "?" parameter syntax. For example: ### query = "select * from person where age = ? or grade > ?" cursor = conn.cursor() cursor.execute(query, 25, 60) ### And in fact, you should always use parameter "prepared statements" in SQL unless you have an overwhelming reason not too. There are a lot of potential problems that you can run into if you try to do the string interpolation yourself, so I'd recommend letting the mxODBC driver handle interpolation for you. Good luck! From flaxeater at yahoo.com Thu Oct 14 22:03:57 2004 From: flaxeater at yahoo.com (Chad Crabtree) Date: Thu Oct 14 22:04:41 2004 Subject: [Tutor] How to save password ? Message-ID: <20041014200357.45923.qmail@web52601.mail.yahoo.com> Mark Kels wrote: >Oh, ok, thanks. >But how can I save the hash so no one could change it but the app will >be able to access it and compare it to the password the user enters ? > > I don't think you can do this, you can just try to hide it or perhaps you can encrypt the password file, but if someone is determined enough then it will be broken in addition they can just open up the script and modify out the password authentication. http://docs.python.org/lib/module-rotor.html __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From my.mailing.lists at noos.fr Thu Oct 14 22:50:35 2004 From: my.mailing.lists at noos.fr (nik) Date: Thu Oct 14 22:50:40 2004 Subject: [Tutor] pyPgSQL and Slackware 9.1 In-Reply-To: <416ECF5D.5010409@cso.atmel.com> References: <416E926F.700@cso.atmel.com> <416E98E9.7070404@noos.fr> <416ECF5D.5010409@cso.atmel.com> Message-ID: <416EE69B.3060408@noos.fr> I'm afraid I'm not that familiar with the postgreSQL stuff myself, I'm using the firebird database with kinterbasdb. I think there's a pypgsql-users forum that might be a better place for an answer (http://lists.sourceforge.net/lists/listinfo/pypgsql-users ) Mike Hansen wrote: > Thanks Nik. Changing the lib in the setup to /usr/local/pgsql/lib got > the build to work. The install behaved as well. However, when I run > the test cases, I get the failures below. I made a script that > connects to a database and prints some records and it seems to work. I > am concerned about these failures. > > $ python test/PgSQLTestCases.py > ........................................F.F....................... > ====================================================================== > FAIL: CheckDoMoreResultObjectChecks (__main__.PgSQLTestCases) > ---------------------------------------------------------------------- > Traceback (most recent call last): > File "test/PgSQLTestCases.py", line 817, in > CheckDoMoreResultObjectChecks > self.fail(msg) > File "/usr/lib/python2.3/unittest.py", line 270, in fail > raise self.failureException, msg > AssertionError: '7.4' > > ====================================================================== > FAIL: Test execute() with a singleton string as the parameter. > ---------------------------------------------------------------------- > Traceback (most recent call last): > File "test/PgSQLTestCases.py", line 639, in CheckExecuteWithSingleton > "Length of cur.description is %d, it should be %d." % > File "/usr/lib/python2.3/unittest.py", line 302, in failUnlessEqual > raise self.failureException, \ > AssertionError: Length of cur.description is 11, it should be 4. > > ---------------------------------------------------------------------- > Ran 66 tests in 0.854s > > FAILED (failures=2) > > > nik wrote: > >> I can't help much with your build problem, other than try using; >> locate libpq >> to see if the library is on your system (may have to do an updatedb >> first), and possibly put a symbolic link into /usr/lib (isn't the >> library normally in /usr/local/pgsql/lib ?) >> >> but otherwise >> man hier >> will give a good description of what goes where in linux... >> >> nik >> >> Mike Hansen wrote: >> >>> I'm having trouble getting _any_ postgre interface module to install >>> on one of our Slackware 9.1 servers. I can get around in Linux, but >>> pretty green on knowing where things are in Linux. Postgre 7.4.1 is >>> up and running on this server.(Many Perl web apps connect to it no >>> problem.) Python 2.3.1 is running on this server. Here's what >>> happens when I try to run the setup for pyPgSQL module as root: >>> >>> # python setup.py build >>> /usr/lib/python2.3/distutils/dist.py:213: UserWarning: 'licence' >>> distribution o >>> tion is deprecated; use 'license' >>> warnings.warn(msg) >>> running build >>> running build_py >>> running build_ext >>> building 'pyPgSQL.libpq.libpqmodule' extension >>> gcc -pthread -shared build/temp.linux-i686-2.3/libpqmodule.o >>> build/temp.linux-i >>> 86-2.3/pgboolean.o build/temp.linux-i686-2.3/pgint2object.o >>> build/temp.linux-i6 >>> 6-2.3/pgint8object.o build/temp.linux-i686-2.3/pgversion.o >>> build/temp.linux-i68 >>> -2.3/pglargeobject.o build/temp.linux-i686-2.3/pgnotify.o >>> build/temp.linux-i686 >>> 2.3/pgconnection.o build/temp.linux-i686-2.3/pgresult.o >>> build/temp.linux-i686-2 >>> 3/pymemstrdup.o build/temp.linux-i686-2.3/port/strtoll.o >>> build/temp.linux-i686- >>> .3/port/strtoull.o build/temp.linux-i686-2.3/port/strtok.o >>> -L/usr/lib -lpq -o b >>> ild/lib.linux-i686-2.3/pyPgSQL/libpq/libpqmodule.so >>> /usr/lib/gcc-lib/i486-slackware-linux/3.2.3/../../../../i486-slackware-linux/bi >>> >>> /ld: cannot find -lpq >>> collect2: ld returned 1 exit status >>> error: command 'gcc' failed with exit status 1 >>> >>> Can someone tell what's causing the error? Do I need to tweak the >>> setup.py to change where it looks for the files it needs? I started >>> with pyPgSQL since I had used it before from Windows. Although as >>> long as I get a DB-API 2.0 compliant module working on this server, >>> I don't really care about which postgre interface module I use. >>> >>> While I'm asking questions, can anyone recommend a linux book that >>> discusses the typical directory structure, where to find things, and >>> why they are were they are?(If that makes any sense.) >>> >>> Thanks, >>> >>> Mike >>> _______________________________________________ >>> Tutor maillist - Tutor@python.org >>> http://mail.python.org/mailman/listinfo/tutor >>> >>> >> >> _______________________________________________ >> Tutor maillist - Tutor@python.org >> http://mail.python.org/mailman/listinfo/tutor > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From mhansen at cso.atmel.com Thu Oct 14 23:06:31 2004 From: mhansen at cso.atmel.com (Mike Hansen) Date: Thu Oct 14 23:06:33 2004 Subject: [Tutor] pyPgSQL and Slackware 9.1 In-Reply-To: <416EE69B.3060408@noos.fr> References: <416E926F.700@cso.atmel.com> <416E98E9.7070404@noos.fr> <416ECF5D.5010409@cso.atmel.com> <416EE69B.3060408@noos.fr> Message-ID: <416EEA57.7040409@cso.atmel.com> I did poke through that list earlier. I'll look a little deeper in the list and see. I appreciate the help. Thanks again. Mike nik wrote: > I'm afraid I'm not that familiar with the postgreSQL stuff myself, I'm > using the firebird database with kinterbasdb. I think there's a > pypgsql-users forum that might be a better place for an answer > (http://lists.sourceforge.net/lists/listinfo/pypgsql-users ) > > Mike Hansen wrote: > >> Thanks Nik. Changing the lib in the setup to /usr/local/pgsql/lib got >> the build to work. The install behaved as well. However, when I run >> the test cases, I get the failures below. I made a script that >> connects to a database and prints some records and it seems to work. >> I am concerned about these failures. >> >> $ python test/PgSQLTestCases.py >> ........................................F.F....................... >> ====================================================================== >> FAIL: CheckDoMoreResultObjectChecks (__main__.PgSQLTestCases) >> ---------------------------------------------------------------------- >> Traceback (most recent call last): >> File "test/PgSQLTestCases.py", line 817, in >> CheckDoMoreResultObjectChecks >> self.fail(msg) >> File "/usr/lib/python2.3/unittest.py", line 270, in fail >> raise self.failureException, msg >> AssertionError: '7.4' >> >> ====================================================================== >> FAIL: Test execute() with a singleton string as the parameter. >> ---------------------------------------------------------------------- >> Traceback (most recent call last): >> File "test/PgSQLTestCases.py", line 639, in CheckExecuteWithSingleton >> "Length of cur.description is %d, it should be %d." % >> File "/usr/lib/python2.3/unittest.py", line 302, in failUnlessEqual >> raise self.failureException, \ >> AssertionError: Length of cur.description is 11, it should be 4. >> >> ---------------------------------------------------------------------- >> Ran 66 tests in 0.854s >> >> FAILED (failures=2) > > From kent_johnson at skillsoft.com Fri Oct 15 00:56:01 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Fri Oct 15 00:56:10 2004 Subject: [Tutor] Can I speed this up? In-Reply-To: <6.1.0.6.0.20041014144049.02982490@mail4.skillsoft.com> References: <6.1.2.0.2.20041011012649.05653430@rcblue.com> <6.1.0.6.0.20041012082330.028ba110@mail4.skillsoft.com> <6.1.2.0.2.20041014073123.062a6040@rcblue.com> <6.1.0.6.0.20041014111411.02869a00@mail4.skillsoft.com> <6.1.2.0.2.20041014085008.032f21a0@rcblue.com> <6.1.0.6.0.20041014144049.02982490@mail4.skillsoft.com> Message-ID: <6.1.0.6.0.20041014181025.02a49570@mail4.skillsoft.com> Most likely the best way to speed this up would be to use a better algorithm. But anyway it's fun to play with optimizations, and I find it interesting to learn where the bottlenecks are and what can be done about them. Here is my version of factorsOfInteger(). I'll show the code first, then talk about what I have learned... def findFactor(n, startingAt): """ For n >= 4610000000000000000 """ limit = int(sqrt(n)) + 1 x = startingAt while x < limit: if not n % x: return x x += 2 return 0 def factorsOfInteger(n): factors = [] # Get the factors of two out of the way to simplify findFactor while n % 2 == 0: factors.append(2) n = n / 2 lastFactor = 3 r = n while True: factor = findFactor(r, lastFactor) if not factor: # r is prime factors.append(r) break factors.append(factor) lastFactor = factor r = r / factor if n in factors: return [] return factors The first thing I did was to rewrite factorsOfInteger() to use a factor-finding subroutine instead of isPrime. This way the program becames basically - look for a factor - divide out the factor - repeat until there are no more factors (what is left is prime) This rewrite gets rid of the problem the original program had of finding the first factor of n twice - once in isPrime and once in the main loop. My first rewrite was a little simpler than what I have here. At first I didn't keep track of lastFactor, I just started over from 2 every time. Surprisingly, it doesn't make it much faster to keep track with lastFactor. I think that is because with the sizes of numbers we are using, once the first large factor has been found, the second findFactor() is relatively quick even starting from 2. I put the handling for factors of 2 into the main function because findFactor with the starting increment and the special case for 2 was too ugly. One thing I found out is that it doesn't make much difference to use xrange() or an explicit loop. I tried it with timeit and it looks like the while loop might actually be faster: C:\Python23\Lib>python timeit.py -s "x = 3" "while x < 3000000: x += 2" 10 loops, best of 3: 2.71e+004 usec per loop C:\Python23\Lib>python timeit.py "for i in xrange(3, 3000000, 2): pass" 10 loops, best of 3: 1.03e+005 usec per loop So I took out the xrange() version and just used the while loop. One interesting thing is that the test if not n % x: is faster than if n % x == 0: I found this out by looking at the disassembled byte codes of the findFactor function. Here is how: >>> import Primes >>> import dis >>> dis.dis(Primes.findFactor) 62 0 LOAD_GLOBAL 0 (int) 3 LOAD_GLOBAL 1 (sqrt) 6 LOAD_FAST 0 (n) 9 CALL_FUNCTION 1 12 CALL_FUNCTION 1 15 LOAD_CONST 1 (1) 18 BINARY_ADD 19 STORE_FAST 2 (limit) 63 22 LOAD_FAST 1 (startingAt) 25 STORE_FAST 3 (x) 64 28 SETUP_LOOP 48 (to 79) >> 31 LOAD_FAST 3 (x) 34 LOAD_FAST 2 (limit) 37 COMPARE_OP 0 (<) 40 JUMP_IF_FALSE 34 (to 77) 43 POP_TOP 65 44 LOAD_FAST 0 (n) 47 LOAD_FAST 3 (x) 50 BINARY_MODULO 51 UNARY_NOT 52 JUMP_IF_FALSE 8 (to 63) 55 POP_TOP 66 56 LOAD_FAST 3 (x) 59 RETURN_VALUE 60 JUMP_FORWARD 1 (to 64) >> 63 POP_TOP 67 >> 64 LOAD_FAST 3 (x) 67 LOAD_CONST 2 (2) 70 INPLACE_ADD 71 STORE_FAST 3 (x) 74 JUMP_ABSOLUTE 31 >> 77 POP_TOP 78 POP_BLOCK 69 >> 79 LOAD_CONST 3 (0) 82 RETURN_VALUE 83 LOAD_CONST 4 (None) 86 RETURN_VALUE The numbers on the far left ar line numbers. Line 65 is the if statement; it takes two opcodes to load x and n, one for the modulo operation, one for the not, then a test and jump. If the test is n %x = 0, the UNARY_NOT is replaced by a load and a compare: 65 44 LOAD_FAST 0 (n) 47 LOAD_FAST 3 (x) 50 BINARY_MODULO 51 LOAD_CONST 2 (2) 54 COMPARE_OP 2 (==) 57 JUMP_IF_FALSE 8 (to 68) 60 POP_TOP So using not n % x saves an opcode and makes a slight improvement in the execution time. I tried using Raymond Hettinger's Bind Constants recipe (http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/277940) but it didn't help, the only constants are int and sqrt, and they are only called once each. So, short of learning Pyrex and compiling this to C, or rewriting it directly in byte codes (there are an annoying number of loads and stores of x in the main loop) I think this is as fast as I'm going to get with this algorithm. Kent At 02:44 PM 10/14/2004 -0400, Kent Johnson wrote: >The import psyco can be anywhere. The psyco.bind(factorsOfInteger) has to >come after the definition of factorsOfInteger or you will get a NameError. > >I've been monkeying around with a version of this, I'll post it when I get >time to write it up...the key for me was instead of isPrime() I have find >findFactor() > >Kent > >At 11:34 AM 10/14/2004 -0700, Dick Moores wrote: >>Kent, >> >>Thanks very much. Got psyco working, and it makes a significant >>difference. The worst "anomalie" I'd found in the 400 trillion range was >>400,000,000,092,821 = 19624679*20382499. >>After implementing a couple of your previous suggestions the time for >>this went >>from 41 to 18 seconds. And now with psyco, to 13 seconds! >> >> >>Version I first asked about is still at >> >> >>I'm still trying to re-rethink isPrime(), isPrimeSmall(), isPrimeBig() >>and factorsOfInteger(). >> >>BTW I'm wondering why you said to put >> >>import psyco >>psyco.bind(factorsOfInteger) >> >>after the definition of factorsOfInteger(). I have "import time" at the >>top, above all the functions. Is this wrong (it works there) or non-standard? >> >>Dick >> >> >>Kent Johnson wrote at 08:15 10/14/2004: >>>Unzip the zip file. Copy the folder psyco-1.2/psyco into >>>Python23/Lib/site-packages. (Create site-packages if you don't already >>>have it.) Should be good to go then. >>> >>>Kent >>> >>>At 07:38 AM 10/14/2004 -0700, Dick Moores wrote: >>>>Kent Johnson wrote at 05:32 10/12/2004: >>>>>Using psyco gives a small speedup - in my limited testing, about 15%. >>>>> >>>>>Install psyco from http://psyco.sourceforge.net, then put these two >>>>>lines after the definition of factorsOfInteger: >>>>>import psyco >>>>>psyco.bind(factorsOfInteger) >>>> >>>>Sorry to be so dumb about these things, but I can't figure out how to >>>>install Psyco. I now have psyco-1.2-win-2.3.zip in my C:\Python23 >>>>folder (Win XP). I've poked around in the file but I don't see any >>>>instructions as to what to next to install Psyco. Also, >>>> doesn't help this dummy. >>>> >>>>Help, please. >>>> >>>>Dick Moores >>>>rdm@rcblue.com > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From tmclaughlin at csu.edu.au Fri Oct 15 01:03:16 2004 From: tmclaughlin at csu.edu.au (McLaughlin, Toby) Date: Fri Oct 15 01:03:30 2004 Subject: [Tutor] How to save password ? Message-ID: <211F78EFD1D870409CC3E4158F4881DA09602AFF@xcww01.riv.csu.edu.au> Or again, you could take inspiration from the Unix authentication mechanism. Perhaps something like: Make your program setguid "myprog"; Make the password file owned by group "myprog"; Make the password file writable by group "myprog" but not by ordinary users. That way, only the program (or root) can write to the password file. For more info, try googling for "shadow passwords" which is the Unix mechanism to which I'm referring. This is assuming that you are developing for a Unix like system of course. Also: This is first post. Hello everyone! > -----Original Message----- > From: tutor-bounces@python.org > [mailto:tutor-bounces@python.org] On Behalf Of Chad Crabtree > Sent: Friday, 15 October 2004 6:04 AM > To: Mark Kels > Cc: tutor@python.org > Subject: Re: [Tutor] How to save password ? > > > Mark Kels wrote: > > >Oh, ok, thanks. > >But how can I save the hash so no one could change it but the app > will > >be able to access it and compare it to the password the user enters > ? > > > > > I don't think you can do this, you can just try to hide it or perhaps > > you can encrypt the password file, but if someone is determined > enough > then it will be broken in addition they can just open up the script > and > modify out the password authentication. > http://docs.python.org/lib/module-rotor.html __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From ps_python at yahoo.com Fri Oct 15 01:16:13 2004 From: ps_python at yahoo.com (kumar s) Date: Fri Oct 15 01:16:17 2004 Subject: [Tutor] Index out of range Message-ID: <20041014231613.58349.qmail@web53704.mail.yahoo.com> Dear Group, My brother helped me to write a program for writing a file contents into SQL statements. I have a file with 71 columns in tab delimited text. table-name A B D E F G A71 1 2 3 4 5 6... 71 2 3 4 5 6 3 45 5 6 7 3 7 7 34 . . . number of rows - 10,000. I wanted to write a python script that writes these values like this: INSERT INTO table-name values('1','2','3','4','5','6',.....'71'); I have the following script from string import *; f = open("sql.txt","r"); text = f.read(); f.close f = open("insert.txt", "w"); list = split(text,"\n"); tname = list[0]; for i in range(len(list)): if(i!=0): col = split(list[i], "\t"); f.write("insert into table "+tname+" values( "+col[1]+" "+col[2]+" "+col[3]+" "+col[4]+""+col[5]+""+col[6]+""+col[7]+""+col[8]+""+col[9]+""+col[10]+""+col[11]+""+col[12]+""+col[13]+""+col[14]+""+col[15]+""+col[16]+""+col[17]+""+col[18]+""+col[19]+""+col[20]+""+col[21]+""+col[22]+""+col[23]+""+col[24]+""+col[25]+""+col[26]+""+col[27]+""+col[28]+""+col[29]+""+col[30]+""+col[31]+""+col[32]+""+col[33]+""+col[34]+" "+col[35]+""+col[36]+""+col[37]+""+col[38]+""+col[39]+" "+col[40]+" "+col[41]+" "+col[42]+""+col[43]+""+col[44]+""+col[45]+""+col[46]+""+col[47]+""+col[48]+""+col[49]+""+col[50]+""+col[51]+""+col[52]+""+col[53]+""+col[54]+""+col[55]+""+col[56]+""+col[57]+""+col[58]+""+col[59]+""+col[60]+""+col[61]+""+col[62]+""+col[63]+""+col[64]+""+col[65]+""+col[66]+""+col[67]+""+col[68]+""+col[69]+""+col[70]+")"+" "+col[71]+"\n"); When I execute this: Traceback (most recent call last): File "insert.py", line 11, in ? f.write("insert into table "+tname+" values( "+col[1]+" "+col[2]+" "+col[3]+" "+col[4]+""+col[5]+""+col[6]+""+col[7]+""+col[8]+""+col[9]+""+col[10]+""+col[11]+""+col[12]+""+col[13]+""+col[14]+""+col[15]+""+col[16]+""+col[17]+""+col[18]+""+col[19]+""+col[20]+""+col[21]+""+col[22]+""+col[23]+""+col[24]+""+col[25]+""+col[26]+""+col[27]+""+col[28]+""+col[29]+""+col[30]+""+col[31]+""+col[32]+""+col[33]+""+col[34]+" "+col[35]+""+col[36]+""+col[37]+""+col[38]+""+col[39]+" "+col[40]+" "+col[41]+" "+col[42]+""+col[43]+""+col[44]+""+col[45]+""+col[46]+""+col[47]+""+col[48]+""+col[49]+""+col[50]+""+col[51]+""+col[52]+""+col[53]+""+col[54]+""+col[55]+""+col[56]+""+col[57]+""+col[58]+""+col[59]+""+col[60]+""+col[61]+""+col[62]+""+col[63]+""+col[64]+""+col[65]+""+col[66]+""+col[67]+""+col[68]+""+col[69]+""+col[70]+")"+" "+col[71]+"\n"); IndexError: list index out of range I get index out of range. I checked the number of columns matched the col[] values here. Even then there is some problem. Is there some easy method to get this done. Please help. Thank you. Kumar. __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From kent_johnson at skillsoft.com Fri Oct 15 01:51:32 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Fri Oct 15 01:51:40 2004 Subject: [Tutor] Index out of range In-Reply-To: <20041014231613.58349.qmail@web53704.mail.yahoo.com> References: <20041014231613.58349.qmail@web53704.mail.yahoo.com> Message-ID: <6.1.0.6.0.20041014194008.028b6d90@mail4.skillsoft.com> Kumar, IndexError means a list subscript is out of range. My guess is that one of the rows is missing a data item or is badly-formed in some other way, so when you split it you get the wrong number of fields. You could rewrite your program to check the length of 'col'. If the length is not 71 then print the line number and the line itself. Or you could catch the IndexError and print i and list[i] in the exception handler. BTW you might like to use join() to make your insert statement - you could write it like this: "insert into table "+tname+" values('" + "', '".join(col) + "')" Kent At 04:16 PM 10/14/2004 -0700, kumar s wrote: >Dear Group, > > My brother helped me to write a program for writing >a file contents into SQL statements. > >I have a file with 71 columns in tab delimited text. > >table-name >A B D E F G A71 >1 2 3 4 5 6... 71 >2 3 4 5 6 3 45 >5 6 7 3 7 7 34 >. >. >. >number of rows - 10,000. > >I wanted to write a python script that writes these >values like this: > >INSERT INTO table-name >values('1','2','3','4','5','6',.....'71'); > > >I have the following script >from string import *; >f = open("sql.txt","r"); >text = f.read(); >f.close >f = open("insert.txt", "w"); >list = split(text,"\n"); >tname = list[0]; >for i in range(len(list)): > if(i!=0): > col = split(list[i], "\t"); > f.write("insert into table "+tname+" values( >"+col[1]+" "+col[2]+" "+col[3]+" >"+col[4]+""+col[5]+""+col[6]+""+col[7]+""+col[8]+""+col[9]+""+col[10]+""+col[11]+""+col[12]+""+col[13]+""+col[14]+""+col[15]+""+col[16]+""+col[17]+""+col[18]+""+col[19]+""+col[20]+""+col[21]+""+col[22]+""+col[23]+""+col[24]+""+col[25]+""+col[26]+""+col[27]+""+col[28]+""+col[29]+""+col[30]+""+col[31]+""+col[32]+""+col[33]+""+col[34]+" > >"+col[35]+""+col[36]+""+col[37]+""+col[38]+""+col[39]+" >"+col[40]+" "+col[41]+" >"+col[42]+""+col[43]+""+col[44]+""+col[45]+""+col[46]+""+col[47]+""+col[48]+""+col[49]+""+col[50]+""+col[51]+""+col[52]+""+col[53]+""+col[54]+""+col[55]+""+col[56]+""+col[57]+""+col[58]+""+col[59]+""+col[60]+""+col[61]+""+col[62]+""+col[63]+""+col[64]+""+col[65]+""+col[66]+""+col[67]+""+col[68]+""+col[69]+""+col[70]+")"+" >"+col[71]+"\n"); > > >When I execute this: >Traceback (most recent call last): > File "insert.py", line 11, in ? > f.write("insert into table "+tname+" values( >"+col[1]+" "+col[2]+" "+col[3]+" >"+col[4]+""+col[5]+""+col[6]+""+col[7]+""+col[8]+""+col[9]+""+col[10]+""+col[11]+""+col[12]+""+col[13]+""+col[14]+""+col[15]+""+col[16]+""+col[17]+""+col[18]+""+col[19]+""+col[20]+""+col[21]+""+col[22]+""+col[23]+""+col[24]+""+col[25]+""+col[26]+""+col[27]+""+col[28]+""+col[29]+""+col[30]+""+col[31]+""+col[32]+""+col[33]+""+col[34]+" > >"+col[35]+""+col[36]+""+col[37]+""+col[38]+""+col[39]+" >"+col[40]+" "+col[41]+" >"+col[42]+""+col[43]+""+col[44]+""+col[45]+""+col[46]+""+col[47]+""+col[48]+""+col[49]+""+col[50]+""+col[51]+""+col[52]+""+col[53]+""+col[54]+""+col[55]+""+col[56]+""+col[57]+""+col[58]+""+col[59]+""+col[60]+""+col[61]+""+col[62]+""+col[63]+""+col[64]+""+col[65]+""+col[66]+""+col[67]+""+col[68]+""+col[69]+""+col[70]+")"+" >"+col[71]+"\n"); >IndexError: list index out of range > > >I get index out of range. I checked the number of >columns matched the col[] values here. Even then there >is some problem. Is there some easy method to get this >done. > >Please help. > >Thank you. > >Kumar. > > > >__________________________________________________ >Do You Yahoo!? >Tired of spam? Yahoo! Mail has the best spam protection around >http://mail.yahoo.com >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From rdm at rcblue.com Fri Oct 15 03:07:36 2004 From: rdm at rcblue.com (Dick Moores) Date: Fri Oct 15 03:07:40 2004 Subject: [Tutor] Can I speed this up? In-Reply-To: <6.1.0.6.0.20041014181025.02a49570@mail4.skillsoft.com> References: <6.1.2.0.2.20041011012649.05653430@rcblue.com> <6.1.0.6.0.20041012082330.028ba110@mail4.skillsoft.com> <6.1.2.0.2.20041014073123.062a6040@rcblue.com> <6.1.0.6.0.20041014111411.02869a00@mail4.skillsoft.com> <6.1.2.0.2.20041014085008.032f21a0@rcblue.com> <6.1.0.6.0.20041014144049.02982490@mail4.skillsoft.com> <6.1.0.6.0.20041014181025.02a49570@mail4.skillsoft.com> Message-ID: <6.1.2.0.2.20041014174146.02272bd0@rcblue.com> Kent, Fascinating stuff. Not sure I understand it all--in fact I'm sure I don't. Of course the first thing I did was to compare times of yours with my pre-psyco version, Both did 5,000,000,000,000,003,954 = 5000000000000003954 = 2*17*37*3974562798092213 in 34 seconds. Both did 400,000,000,139,227 = 400000000139227 = 14492981*27599567 in 8 secs. Both did 400,000,000,139,141 = 400000000139141 (PRIME) in 11 secs. Of course your code is much nicer, and I'll learn from it. I'd tried the lastFactor idea earlier today, but couldn't get it to work. It's interesting that you found it didn't really help, though I was sure it would. And thanks again for psyco!! BTW Working on this has gotten me interested in primes and their distribution. You'd never guess it, but I majored in math (without any interest in number theory) a long time ago. So maybe I'll try to program some of those other prime number algorithms you pointed me towards. Or not. Probably I should move on to another area in Python. Still so much to learn. Dick Kent Johnson wrote at 15:56 10/14/2004: >Most likely the best way to speed this up would be to use a better >algorithm. But anyway it's fun to play with optimizations, and I find it >interesting to learn where the bottlenecks are and what can be done >about them. Here is my version of factorsOfInteger(). I'll show the code >first, then talk about what I have learned... > >def findFactor(n, startingAt): > """ > For n >= 4610000000000000000 > """ > limit = int(sqrt(n)) + 1 > x = startingAt > while x < limit: > if not n % x: > return x > x += 2 > > return 0 > > >def factorsOfInteger(n): > factors = [] > > # Get the factors of two out of the way to simplify findFactor > while n % 2 == 0: > factors.append(2) > n = n / 2 > > lastFactor = 3 > r = n > while True: > factor = findFactor(r, lastFactor) > if not factor: > # r is prime > factors.append(r) > break > > factors.append(factor) > lastFactor = factor > r = r / factor > > if n in factors: > return [] > return factors > > >The first thing I did was to rewrite factorsOfInteger() to use a >factor-finding subroutine instead of isPrime. This way the program >becames basically >- look for a factor >- divide out the factor >- repeat until there are no more factors (what is left is prime) > >This rewrite gets rid of the problem the original program had of finding >the first factor of n twice - once in isPrime and once in the main loop. > >My first rewrite was a little simpler than what I have here. At first I >didn't keep track of lastFactor, I just started over from 2 every time. >Surprisingly, it doesn't make it much faster to keep track with >lastFactor. I think that is because with the sizes of numbers we are >using, once the first large factor has been found, the second >findFactor() is relatively quick even starting from 2. > >I put the handling for factors of 2 into the main function because >findFactor with the starting increment and the special case for 2 was >too ugly. > >One thing I found out is that it doesn't make much difference to use >xrange() or an explicit loop. I tried it with timeit and it looks like >the while loop might actually be faster: >C:\Python23\Lib>python timeit.py -s "x = 3" "while x < 3000000: x += 2" >10 loops, best of 3: 2.71e+004 usec per loop > >C:\Python23\Lib>python timeit.py "for i in xrange(3, 3000000, 2): pass" >10 loops, best of 3: 1.03e+005 usec per loop > >So I took out the xrange() version and just used the while loop. > >One interesting thing is that the test > if not n % x: >is faster than > if n % x == 0: > >I found this out by looking at the disassembled byte codes of the >findFactor function. Here is how: > >>> import Primes > >>> import dis > >>> dis.dis(Primes.findFactor) > 62 0 LOAD_GLOBAL 0 (int) > 3 LOAD_GLOBAL 1 (sqrt) > 6 LOAD_FAST 0 (n) > 9 CALL_FUNCTION 1 > 12 CALL_FUNCTION 1 > 15 LOAD_CONST 1 (1) > 18 BINARY_ADD > 19 STORE_FAST 2 (limit) > > 63 22 LOAD_FAST 1 (startingAt) > 25 STORE_FAST 3 (x) > > 64 28 SETUP_LOOP 48 (to 79) > >> 31 LOAD_FAST 3 (x) > 34 LOAD_FAST 2 (limit) > 37 COMPARE_OP 0 (<) > 40 JUMP_IF_FALSE 34 (to 77) > 43 POP_TOP > > 65 44 LOAD_FAST 0 (n) > 47 LOAD_FAST 3 (x) > 50 BINARY_MODULO > 51 UNARY_NOT > 52 JUMP_IF_FALSE 8 (to 63) > 55 POP_TOP > > 66 56 LOAD_FAST 3 (x) > 59 RETURN_VALUE > 60 JUMP_FORWARD 1 (to 64) > >> 63 POP_TOP > > 67 >> 64 LOAD_FAST 3 (x) > 67 LOAD_CONST 2 (2) > 70 INPLACE_ADD > 71 STORE_FAST 3 (x) > 74 JUMP_ABSOLUTE 31 > >> 77 POP_TOP > 78 POP_BLOCK > > 69 >> 79 LOAD_CONST 3 (0) > 82 RETURN_VALUE > 83 LOAD_CONST 4 (None) > 86 RETURN_VALUE > >The numbers on the far left ar line numbers. Line 65 is the if >statement; it takes two opcodes to load x and n, one for the modulo >operation, one for the not, then a test and jump. If the test is n %x = >0, the UNARY_NOT is replaced by a load and a compare: > >65 44 LOAD_FAST 0 (n) > 47 LOAD_FAST 3 (x) > 50 BINARY_MODULO > 51 LOAD_CONST 2 (2) > 54 COMPARE_OP 2 (==) > 57 JUMP_IF_FALSE 8 (to 68) > 60 POP_TOP > >So using not n % x saves an opcode and makes a slight improvement in the >execution time. > >I tried using Raymond Hettinger's Bind Constants recipe >(http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/277940) but it >didn't help, the only constants are int and sqrt, and they are only >called once each. > >So, short of learning Pyrex and compiling this to C, or rewriting it >directly in byte codes (there are an annoying number of loads and stores >of x in the main loop) I think this is as fast as I'm going to get with >this algorithm. > >Kent > >At 02:44 PM 10/14/2004 -0400, Kent Johnson wrote: >>The import psyco can be anywhere. The psyco.bind(factorsOfInteger) has >>to come after the definition of factorsOfInteger or you will get a NameError. >> >>I've been monkeying around with a version of this, I'll post it when I >>get time to write it up...the key for me was instead of isPrime() I >>have find findFactor() >> >>Kent >> >>At 11:34 AM 10/14/2004 -0700, Dick Moores wrote: >>>Kent, >>> >>>Thanks very much. Got psyco working, and it makes a significant >>>difference. The worst "anomalie" I'd found in the 400 trillion range was >>>400,000,000,092,821 = 19624679*20382499. >>>After implementing a couple of your previous suggestions the time for >>>this went >>>from 41 to 18 seconds. And now with psyco, to 13 seconds! >>> >>> >>>Version I first asked about is still at >>> >>> >>>I'm still trying to re-rethink isPrime(), >>>isPrimeSmall(), isPrimeBig() and factorsOfInteger(). >>> >>>BTW I'm wondering why you said to put >>> >>>import psyco >>>psyco.bind(factorsOfInteger) >>> >>>after the definition of factorsOfInteger(). I have "import time" at >>>the top, above all the functions. Is this wrong (it works there) or >>>non-standard? >>> >>>Dick >>> >>> >>>Kent Johnson wrote at 08:15 10/14/2004: >>>>Unzip the zip file. Copy the folder psyco-1.2/psyco into >>>>Python23/Lib/site-packages. (Create site-packages if you don't >>>>already have it.) Should be good to go then. >>>> >>>>Kent >>>> >>>>At 07:38 AM 10/14/2004 -0700, Dick Moores wrote: >>>>>Kent Johnson wrote at 05:32 10/12/2004: >>>>>>Using psyco gives a small speedup - in my limited testing, about 15%. >>>>>> >>>>>>Install psyco from http://psyco.sourceforge.net, then put these two >>>>>>lines after the definition of factorsOfInteger: >>>>>>import psyco >>>>>>psyco.bind(factorsOfInteger) >>>>> >>>>>Sorry to be so dumb about these things, but I can't figure out how >>>>>to install Psyco. I now have psyco-1.2-win-2.3.zip in my C:\Python23 >>>>>folder (Win XP). I've poked around in the file but I don't see any >>>>>instructions as to what to next to install Psyco. Also, >>>>> doesn't help this dummy. >>>>> >>>>>Help, please. >>>>> >>>>>Dick Moores >>>>>rdm@rcblue.com >> >>__ From carroll at tjc.com Fri Oct 15 03:45:00 2004 From: carroll at tjc.com (Terry Carroll) Date: Fri Oct 15 03:45:03 2004 Subject: [Tutor] visual development environs? In-Reply-To: <200409162230.43711.thomi@imail.net.nz> Message-ID: On Thu, 16 Sep 2004, Thomas Clive Richards wrote: > I'm looking for a visual development environment (I'm not sure this si the > right term) similar to blackadder > (http://www.thekompany.com/products/blackadder/). (and then, later...) > I forgot to mention that it has to run under Linux > (thus the MS visual studio plugins are out of the picture).... I've been idly wondering about running Eclipse (which is an IDE intended for Java development, and that runs under the Java VM, so should be okay under Linux) along with Pydev for Eclipse for the Python support. I haven't tried this, so I don't put this out as a recommendation, but you might want to look at it. (And then let us know how it went!) URLs: http://www.eclipse.org/ http://sourceforge.net/projects/pydev/ Note there are other Eclipse-based Python projects listed at , but pydev seems to be the leader. From kent_johnson at skillsoft.com Fri Oct 15 03:49:52 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Fri Oct 15 03:49:58 2004 Subject: [Tutor] Can I speed this up? In-Reply-To: <6.1.2.0.2.20041014174146.02272bd0@rcblue.com> References: <6.1.2.0.2.20041011012649.05653430@rcblue.com> <6.1.0.6.0.20041012082330.028ba110@mail4.skillsoft.com> <6.1.2.0.2.20041014073123.062a6040@rcblue.com> <6.1.0.6.0.20041014111411.02869a00@mail4.skillsoft.com> <6.1.2.0.2.20041014085008.032f21a0@rcblue.com> <6.1.0.6.0.20041014144049.02982490@mail4.skillsoft.com> <6.1.0.6.0.20041014181025.02a49570@mail4.skillsoft.com> <6.1.2.0.2.20041014174146.02272bd0@rcblue.com> Message-ID: <6.1.0.6.0.20041014213209.028b7688@mail4.skillsoft.com> Well sure, if you just try the easy ones! How about this? 5,000,000,000,000,001,028 = 2*2*854908727*1462144391 10 minutes, 10 seconds 5,000,000,000,000,005,171 = 800104651*6249182521 11 minutes, 12 seconds And my machine is a little slower than yours, I think... BTW I majored in math a long time ago too :-) Programming is much more fun. Kent At 06:07 PM 10/14/2004 -0700, Dick Moores wrote: >Kent, > >Fascinating stuff. Not sure I understand it all--in fact I'm sure I don't. > >Of course the first thing I did was to compare times of yours with my >pre-psyco version, > > >Both did >5,000,000,000,000,003,954 = 5000000000000003954 = 2*17*37*3974562798092213 >in 34 seconds. >Both did >400,000,000,139,227 = 400000000139227 = 14492981*27599567 in 8 secs. >Both did >400,000,000,139,141 = 400000000139141 (PRIME) in 11 secs. > >Of course your code is much nicer, and I'll learn from it. > >I'd tried the lastFactor idea earlier today, but couldn't get it to work. >It's interesting that you found it didn't really help, though I was sure >it would. > >And thanks again for psyco!! > >BTW Working on this has gotten me interested in primes and their >distribution. You'd never guess it, but I majored in math (without any >interest in number theory) a long time ago. > >So maybe I'll try to program some of those other prime number algorithms >you pointed me towards. Or not. Probably I should move on to another area >in Python. Still so much to learn. > >Dick > >Kent Johnson wrote at 15:56 10/14/2004: >>Most likely the best way to speed this up would be to use a better >>algorithm. But anyway it's fun to play with optimizations, and I find it >>interesting to learn where the bottlenecks are and what can be done about >>them. Here is my version of factorsOfInteger(). I'll show the code first, >>then talk about what I have learned... >> >>def findFactor(n, startingAt): >> """ >> For n >= 4610000000000000000 >> """ >> limit = int(sqrt(n)) + 1 >> x = startingAt >> while x < limit: >> if not n % x: >> return x >> x += 2 >> >> return 0 >> >> >>def factorsOfInteger(n): >> factors = [] >> >> # Get the factors of two out of the way to simplify findFactor >> while n % 2 == 0: >> factors.append(2) >> n = n / 2 >> >> lastFactor = 3 >> r = n >> while True: >> factor = findFactor(r, lastFactor) >> if not factor: >> # r is prime >> factors.append(r) >> break >> >> factors.append(factor) >> lastFactor = factor >> r = r / factor >> >> if n in factors: >> return [] >> return factors >> >> >>The first thing I did was to rewrite factorsOfInteger() to use a >>factor-finding subroutine instead of isPrime. This way the program >>becames basically >>- look for a factor >>- divide out the factor >>- repeat until there are no more factors (what is left is prime) >> >>This rewrite gets rid of the problem the original program had of finding >>the first factor of n twice - once in isPrime and once in the main loop. >> >>My first rewrite was a little simpler than what I have here. At first I >>didn't keep track of lastFactor, I just started over from 2 every time. >>Surprisingly, it doesn't make it much faster to keep track with >>lastFactor. I think that is because with the sizes of numbers we are >>using, once the first large factor has been found, the second >>findFactor() is relatively quick even starting from 2. >> >>I put the handling for factors of 2 into the main function because >>findFactor with the starting increment and the special case for 2 was too ugly. >> >>One thing I found out is that it doesn't make much difference to use >>xrange() or an explicit loop. I tried it with timeit and it looks like >>the while loop might actually be faster: >>C:\Python23\Lib>python timeit.py -s "x = 3" "while x < 3000000: x += 2" >>10 loops, best of 3: 2.71e+004 usec per loop >> >>C:\Python23\Lib>python timeit.py "for i in xrange(3, 3000000, 2): pass" >>10 loops, best of 3: 1.03e+005 usec per loop >> >>So I took out the xrange() version and just used the while loop. >> >>One interesting thing is that the test >> if not n % x: >>is faster than >> if n % x == 0: >> >>I found this out by looking at the disassembled byte codes of the >>findFactor function. Here is how: >> >>> import Primes >> >>> import dis >> >>> dis.dis(Primes.findFactor) >> 62 0 LOAD_GLOBAL 0 (int) >> 3 LOAD_GLOBAL 1 (sqrt) >> 6 LOAD_FAST 0 (n) >> 9 CALL_FUNCTION 1 >> 12 CALL_FUNCTION 1 >> 15 LOAD_CONST 1 (1) >> 18 BINARY_ADD >> 19 STORE_FAST 2 (limit) >> >> 63 22 LOAD_FAST 1 (startingAt) >> 25 STORE_FAST 3 (x) >> >> 64 28 SETUP_LOOP 48 (to 79) >> >> 31 LOAD_FAST 3 (x) >> 34 LOAD_FAST 2 (limit) >> 37 COMPARE_OP 0 (<) >> 40 JUMP_IF_FALSE 34 (to 77) >> 43 POP_TOP >> >> 65 44 LOAD_FAST 0 (n) >> 47 LOAD_FAST 3 (x) >> 50 BINARY_MODULO >> 51 UNARY_NOT >> 52 JUMP_IF_FALSE 8 (to 63) >> 55 POP_TOP >> >> 66 56 LOAD_FAST 3 (x) >> 59 RETURN_VALUE >> 60 JUMP_FORWARD 1 (to 64) >> >> 63 POP_TOP >> >> 67 >> 64 LOAD_FAST 3 (x) >> 67 LOAD_CONST 2 (2) >> 70 INPLACE_ADD >> 71 STORE_FAST 3 (x) >> 74 JUMP_ABSOLUTE 31 >> >> 77 POP_TOP >> 78 POP_BLOCK >> >> 69 >> 79 LOAD_CONST 3 (0) >> 82 RETURN_VALUE >> 83 LOAD_CONST 4 (None) >> 86 RETURN_VALUE >> >>The numbers on the far left ar line numbers. Line 65 is the if statement; >>it takes two opcodes to load x and n, one for the modulo operation, one >>for the not, then a test and jump. If the test is n %x = 0, the UNARY_NOT >>is replaced by a load and a compare: >> >>65 44 LOAD_FAST 0 (n) >> 47 LOAD_FAST 3 (x) >> 50 BINARY_MODULO >> 51 LOAD_CONST 2 (2) >> 54 COMPARE_OP 2 (==) >> 57 JUMP_IF_FALSE 8 (to 68) >> 60 POP_TOP >> >>So using not n % x saves an opcode and makes a slight improvement in the >>execution time. >> >>I tried using Raymond Hettinger's Bind Constants recipe >>(http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/277940) but it >>didn't help, the only constants are int and sqrt, and they are only >>called once each. >> >>So, short of learning Pyrex and compiling this to C, or rewriting it >>directly in byte codes (there are an annoying number of loads and stores >>of x in the main loop) I think this is as fast as I'm going to get with >>this algorithm. >> >>Kent >> >>At 02:44 PM 10/14/2004 -0400, Kent Johnson wrote: >>>The import psyco can be anywhere. The psyco.bind(factorsOfInteger) has >>>to come after the definition of factorsOfInteger or you will get a NameError. >>> >>>I've been monkeying around with a version of this, I'll post it when I >>>get time to write it up...the key for me was instead of isPrime() I have >>>find findFactor() >>> >>>Kent >>> >>>At 11:34 AM 10/14/2004 -0700, Dick Moores wrote: >>>>Kent, >>>> >>>>Thanks very much. Got psyco working, and it makes a significant >>>>difference. The worst "anomalie" I'd found in the 400 trillion range was >>>>400,000,000,092,821 = 19624679*20382499. >>>>After implementing a couple of your previous suggestions the time for >>>>this went >>>>from 41 to 18 seconds. And now with psyco, to 13 seconds! >>>> >>>> >>>>Version I first asked about is still at >>>> >>>> >>>>I'm still trying to re-rethink isPrime(), isPrimeSmall(), isPrimeBig() >>>>and factorsOfInteger(). >>>> >>>>BTW I'm wondering why you said to put >>>> >>>>import psyco >>>>psyco.bind(factorsOfInteger) >>>> >>>>after the definition of factorsOfInteger(). I have "import time" at the >>>>top, above all the functions. Is this wrong (it works there) or non-standard? >>>> >>>>Dick >>>> >>>> >>>>Kent Johnson wrote at 08:15 10/14/2004: >>>>>Unzip the zip file. Copy the folder psyco-1.2/psyco into >>>>>Python23/Lib/site-packages. (Create site-packages if you don't already >>>>>have it.) Should be good to go then. >>>>> >>>>>Kent >>>>> >>>>>At 07:38 AM 10/14/2004 -0700, Dick Moores wrote: >>>>>>Kent Johnson wrote at 05:32 10/12/2004: >>>>>>>Using psyco gives a small speedup - in my limited testing, about 15%. >>>>>>> >>>>>>>Install psyco from http://psyco.sourceforge.net, then put these two >>>>>>>lines after the definition of factorsOfInteger: >>>>>>>import psyco >>>>>>>psyco.bind(factorsOfInteger) >>>>>> >>>>>>Sorry to be so dumb about these things, but I can't figure out how to >>>>>>install Psyco. I now have psyco-1.2-win-2.3.zip in my C:\Python23 >>>>>>folder (Win XP). I've poked around in the file but I don't see any >>>>>>instructions as to what to next to install Psyco. Also, >>>>>> doesn't help this dummy. >>>>>> >>>>>>Help, please. >>>>>> >>>>>>Dick Moores >>>>>>rdm@rcblue.com >>> >>>__ > > From leomandy at hotmail.com Fri Oct 15 05:54:57 2004 From: leomandy at hotmail.com (mandy b) Date: Fri Oct 15 05:55:08 2004 Subject: [Tutor] could someone check this? Message-ID: I am trying to send email from within a program - I have an odd feeling maybe Email() should be in a different place than where I have it... if someone could check it and tell me if I have it in the wrong place or will it work the way it is? (I do not have an actual "localhost" so it will not run for me without errors...) please see link for code: http://rafb.net/paste/results/H1aAFM73.html Thanks! _________________________________________________________________ Express yourself instantly with MSN Messenger! Download today - it's FREE! http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ From rdm at rcblue.com Fri Oct 15 06:03:35 2004 From: rdm at rcblue.com (Dick Moores) Date: Fri Oct 15 06:03:37 2004 Subject: [Tutor] Can I speed this up? Message-ID: <6.1.2.0.2.20041014210310.02fc08a0@rcblue.com> Kent, OoKaay, I see. 5,000,000,000,000,001,028 = 2*2*854908727*1462144391 Yours: 8 minutes, 35 seconds Mine: 21 minutes, 46 seconds 5,000,000,000,000,005,171 = 800104651*6249182521 Yours:9 minutes, 24 seconds Mine: 10 minutes, 33 seconds Dick Kent Johnson wrote at 18:49 10/14/2004: >Well sure, if you just try the easy ones! > >How about this? >5,000,000,000,000,001,028 = 2*2*854908727*1462144391 10 minutes, 10 seconds >5,000,000,000,000,005,171 = 800104651*6249182521 11 minutes, 12 seconds > >And my machine is a little slower than yours, I think... > >BTW I majored in math a long time ago too :-) >Programming is much more fun. > >Kent > >At 06:07 PM 10/14/2004 -0700, Dick Moores wrote: >>Kent, >> >>Fascinating stuff. Not sure I understand it all--in fact I'm sure I don't. >> >>Of course the first thing I did was to compare times of yours with my >>pre-psyco version, >> >> >>Both did >>5,000,000,000,000,003,954 = 5000000000000003954 = >>2*17*37*3974562798092213 in 34 seconds. >>Both did >>400,000,000,139,227 = 400000000139227 = 14492981*27599567 in 8 secs. >>Both did >>400,000,000,139,141 = 400000000139141 (PRIME) in 11 secs. >> >>Of course your code is much nicer, and I'll learn from it. >> >>I'd tried the lastFactor idea earlier today, but couldn't get it to >>work. It's interesting that you found it didn't really help, though I >>was sure it would. >> >>And thanks again for psyco!! >> >>BTW Working on this has gotten me interested in primes and their >>distribution. You'd never guess it, but I majored in math (without any >>interest in number theory) a long time ago. >> >>So maybe I'll try to program some of those other prime number >>algorithms you pointed me towards. Or not. Probably I should move on to >>another area in Python. Still so much to learn. >> >>Dick >> >>Kent Johnson wrote at 15:56 10/14/2004: >>>Most likely the best way to speed this up would be to use a better >>>algorithm. But anyway it's fun to play with optimizations, and I find >>>it interesting to learn where the bottlenecks are and what can be done >>>about them. Here is my version of factorsOfInteger(). I'll show the >>>code first, then talk about what I have learned... >>> >>>def findFactor(n, startingAt): >>> """ >>> For n >= 4610000000000000000 >>> """ >>> limit = int(sqrt(n)) + 1 >>> x = startingAt >>> while x < limit: >>> if not n % x: >>> return x >>> x += 2 >>> >>> return 0 >>> >>> >>>def factorsOfInteger(n): >>> factors = [] >>> >>> # Get the factors of two out of the way to simplify findFactor >>> while n % 2 == 0: >>> factors.append(2) >>> n = n / 2 >>> >>> lastFactor = 3 >>> r = n >>> while True: >>> factor = findFactor(r, lastFactor) >>> if not factor: >>> # r is prime >>> factors.append(r) >>> break >>> >>> factors.append(factor) >>> lastFactor = factor >>> r = r / factor >>> >>> if n in factors: >>> return [] >>> return factors >>> >>> >>>The first thing I did was to rewrite factorsOfInteger() to use a >>>factor-finding subroutine instead of isPrime. This way the program >>>becames basically >>>- look for a factor >>>- divide out the factor >>>- repeat until there are no more factors (what is left is prime) >>> >>>This rewrite gets rid of the problem the original program had of >>>finding the first factor of n twice - once in isPrime and once in the >>>main loop. >>> >>>My first rewrite was a little simpler than what I have here. At first >>>I didn't keep track of lastFactor, I just started over from 2 every >>>time. Surprisingly, it doesn't make it much faster to keep track with >>>lastFactor. I think that is because with the sizes of numbers we are >>>using, once the first large factor has been found, the second >>>findFactor() is relatively quick even starting from 2. >>> >>>I put the handling for factors of 2 into the main function because >>>findFactor with the starting increment and the special case for 2 was >>>too ugly. >>> >>>One thing I found out is that it doesn't make much difference to use >>>xrange() or an explicit loop. I tried it with timeit and it looks like >>>the while loop might actually be faster: >>>C:\Python23\Lib>python timeit.py -s "x = 3" "while x < 3000000: x += 2" >>>10 loops, best of 3: 2.71e+004 usec per loop >>> >>>C:\Python23\Lib>python timeit.py "for i in xrange(3, 3000000, 2): pass" >>>10 loops, best of 3: 1.03e+005 usec per loop >>> >>>So I took out the xrange() version and just used the while loop. >>> >>>One interesting thing is that the test >>> if not n % x: >>>is faster than >>> if n % x == 0: >>> >>>I found this out by looking at the disassembled byte codes of the >>>findFactor function. Here is how: >>> >>> import Primes >>> >>> import dis >>> >>> dis.dis(Primes.findFactor) >>> 62 0 LOAD_GLOBAL 0 (int) >>> 3 LOAD_GLOBAL 1 (sqrt) >>> 6 LOAD_FAST 0 (n) >>> 9 CALL_FUNCTION 1 >>> 12 CALL_FUNCTION 1 >>> 15 LOAD_CONST 1 (1) >>> 18 BINARY_ADD >>> 19 STORE_FAST 2 (limit) >>> >>> 63 22 LOAD_FAST 1 (startingAt) >>> 25 STORE_FAST 3 (x) >>> >>> 64 28 SETUP_LOOP 48 (to 79) >>> >> 31 LOAD_FAST 3 (x) >>> 34 LOAD_FAST 2 (limit) >>> 37 COMPARE_OP 0 (<) >>> 40 JUMP_IF_FALSE 34 (to 77) >>> 43 POP_TOP >>> >>> 65 44 LOAD_FAST 0 (n) >>> 47 LOAD_FAST 3 (x) >>> 50 BINARY_MODULO >>> 51 UNARY_NOT >>> 52 JUMP_IF_FALSE 8 (to 63) >>> 55 POP_TOP >>> >>> 66 56 LOAD_FAST 3 (x) >>> 59 RETURN_VALUE >>> 60 JUMP_FORWARD 1 (to 64) >>> >> 63 POP_TOP >>> >>> 67 >> 64 LOAD_FAST 3 (x) >>> 67 LOAD_CONST 2 (2) >>> 70 INPLACE_ADD >>> 71 STORE_FAST 3 (x) >>> 74 JUMP_ABSOLUTE 31 >>> >> 77 POP_TOP >>> 78 POP_BLOCK >>> >>> 69 >> 79 LOAD_CONST 3 (0) >>> 82 RETURN_VALUE >>> 83 LOAD_CONST 4 (None) >>> 86 RETURN_VALUE >>> >>>The numbers on the far left ar line numbers. Line 65 is the if >>>statement; it takes two opcodes to load x and n, one for the modulo >>>operation, one for the not, then a test and jump. If the test is n %x >>>= 0, the UNARY_NOT is replaced by a load and a compare: >>> >>>65 44 LOAD_FAST 0 (n) >>> 47 LOAD_FAST 3 (x) >>> 50 BINARY_MODULO >>> 51 LOAD_CONST 2 (2) >>> 54 COMPARE_OP 2 (==) >>> 57 JUMP_IF_FALSE 8 (to 68) >>> 60 POP_TOP >>> >>>So using not n % x saves an opcode and makes a slight improvement in >>>the execution time. >>> >>>I tried using Raymond Hettinger's Bind Constants recipe >>>(http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/277940) but >>>it didn't help, the only constants are int and sqrt, and they are only >>>called once each. >>> >>>So, short of learning Pyrex and compiling this to C, or rewriting it >>>directly in byte codes (there are an annoying number of loads and >>>stores of x in the main loop) I think this is as fast as I'm going to >>>get with this algorithm. >>> >>>Kent >>> >>>At 02:44 PM 10/14/2004 -0400, Kent Johnson wrote: >>>>The import psyco can be anywhere. The psyco.bind(factorsOfInteger) >>>>has to come after the definition of factorsOfInteger or you will get >>>>a NameError. >>>> >>>>I've been monkeying around with a version of this, I'll post it when >>>>I get time to write it up...the key for me was instead of isPrime() I >>>>have find findFactor() >>>> >>>>Kent >>>> >>>>At 11:34 AM 10/14/2004 -0700, Dick Moores wrote: >>>>>Kent, >>>>> >>>>>Thanks very much. Got psyco working, and it makes a significant >>>>>difference. The worst "anomalie" I'd found in the 400 trillion range was >>>>>400,000,000,092,821 = 19624679*20382499. >>>>>After implementing a couple of your previous suggestions the time >>>>>for this went >>>>>from 41 to 18 seconds. And now with psyco, to 13 seconds! >>>>> >>>>> >>>>>Version I first asked about is still at >>>>> >>>>> >>>>>I'm still trying to re-rethink isPrime(), >>>>>isPrimeSmall(), isPrimeBig() and factorsOfInteger(). >>>>> >>>>>BTW I'm wondering why you said to put >>>>> >>>>>import psyco >>>>>psyco.bind(factorsOfInteger) >>>>> >>>>>after the definition of factorsOfInteger(). I have "import time" at >>>>>the top, above all the functions. Is this wrong (it works there) or >>>>>non-standard? >>>>> >>>>>Dick >>>>> >>>>> >>>>>Kent Johnson wrote at 08:15 10/14/2004: >>>>>>Unzip the zip file. Copy the folder psyco-1.2/psyco into >>>>>>Python23/Lib/site-packages. (Create site-packages if you don't >>>>>>already have it.) Should be good to go then. >>>>>> >>>>>>Kent >>>>>> >>>>>>At 07:38 AM 10/14/2004 -0700, Dick Moores wrote: >>>>>>>Kent Johnson wrote at 05:32 10/12/2004: >>>>>>>>Using psyco gives a small speedup - in my limited testing, about 15%. >>>>>>>> >>>>>>>>Install psyco from http://psyco.sourceforge.net, then put these >>>>>>>>two lines after the definition of factorsOfInteger: >>>>>>>>import psyco >>>>>>>>psyco.bind(factorsOfInteger) >>>>>>> >>>>>>>Sorry to be so dumb about these things, but I can't figure out how >>>>>>>to install Psyco. I now have psyco-1.2-win-2.3.zip in my >>>>>>>C:\Python23 folder (Win XP). I've poked around in the file but I >>>>>>>don't see any instructions as to what to next to install >>>>>>>Psyco. Also, >>>>>>>doesn't help this dummy. >>>>>>> >>>>>>>Help, please. >>>>>>> >>>>>>>Dick Moores >>>>>>>rdm@rcblue.com From nitt at iprimus.com.au Fri Oct 15 08:09:01 2004 From: nitt at iprimus.com.au (nitt) Date: Fri Oct 15 08:09:28 2004 Subject: [Tutor] declare-define Message-ID: <000c01c4b27d$78437740$49108aca@jason> Hi All' Trying to get the following, and yes,tried most everything. input("p(1)=") input("p(1)=") input("p(3)=") a=p(1)*(p(1)*p(2)-1)*(p(3)+1)/(p(1)+1) print int(a) rjust(45) Keep getting name error,p() not defined and rjust doesn't exist. using 234 Appreciate any help given King regards nitt@iprimus.com.au -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20041015/ffaec460/attachment.html From kraus at hagen-partner.de Fri Oct 15 08:42:08 2004 From: kraus at hagen-partner.de (Wolfram Kraus) Date: Fri Oct 15 08:42:11 2004 Subject: [Tutor] Re: Index out of range In-Reply-To: <20041014231613.58349.qmail@web53704.mail.yahoo.com> References: <20041014231613.58349.qmail@web53704.mail.yahoo.com> Message-ID: kumar s wrote: > Dear Group, > > My brother helped me to write a program for writing > a file contents into SQL statements. > > I have a file with 71 columns in tab delimited text. > > table-name > A B D E F G A71 > 1 2 3 4 5 6... 71 > 2 3 4 5 6 3 45 > 5 6 7 3 7 7 34 > . > . > . > number of rows - 10,000. > > I wanted to write a python script that writes these > values like this: > > INSERT INTO table-name > values('1','2','3','4','5','6',.....'71'); > > > I have the following script > from string import *; > f = open("sql.txt","r"); > text = f.read(); > f.close > f = open("insert.txt", "w"); > list = split(text,"\n"); > tname = list[0]; > for i in range(len(list)): > if(i!=0): > col = split(list[i], "\t"); > f.write("insert into table "+tname+" values( > "+col[1]+" "+col[2]+" "+col[3]+" > "+col[4]+""+col[5]+""+col[6]+""+col[7]+""+col[8]+""+col[9]+""+col[10]+""+col[11]+""+col[12]+""+col[13]+""+col[14]+""+col[15]+""+col[16]+""+col[17]+""+col[18]+""+col[19]+""+col[20]+""+col[21]+""+col[22]+""+col[23]+""+col[24]+""+col[25]+""+col[26]+""+col[27]+""+col[28]+""+col[29]+""+col[30]+""+col[31]+""+col[32]+""+col[33]+""+col[34]+" > > "+col[35]+""+col[36]+""+col[37]+""+col[38]+""+col[39]+" > "+col[40]+" "+col[41]+" > "+col[42]+""+col[43]+""+col[44]+""+col[45]+""+col[46]+""+col[47]+""+col[48]+""+col[49]+""+col[50]+""+col[51]+""+col[52]+""+col[53]+""+col[54]+""+col[55]+""+col[56]+""+col[57]+""+col[58]+""+col[59]+""+col[60]+""+col[61]+""+col[62]+""+col[63]+""+col[64]+""+col[65]+""+col[66]+""+col[67]+""+col[68]+""+col[69]+""+col[70]+")"+" > "+col[71]+"\n"); > > > When I execute this: > Traceback (most recent call last): > File "insert.py", line 11, in ? > f.write("insert into table "+tname+" values( > "+col[1]+" "+col[2]+" "+col[3]+" > "+col[4]+""+col[5]+""+col[6]+""+col[7]+""+col[8]+""+col[9]+""+col[10]+""+col[11]+""+col[12]+""+col[13]+""+col[14]+""+col[15]+""+col[16]+""+col[17]+""+col[18]+""+col[19]+""+col[20]+""+col[21]+""+col[22]+""+col[23]+""+col[24]+""+col[25]+""+col[26]+""+col[27]+""+col[28]+""+col[29]+""+col[30]+""+col[31]+""+col[32]+""+col[33]+""+col[34]+" > > "+col[35]+""+col[36]+""+col[37]+""+col[38]+""+col[39]+" > "+col[40]+" "+col[41]+" > "+col[42]+""+col[43]+""+col[44]+""+col[45]+""+col[46]+""+col[47]+""+col[48]+""+col[49]+""+col[50]+""+col[51]+""+col[52]+""+col[53]+""+col[54]+""+col[55]+""+col[56]+""+col[57]+""+col[58]+""+col[59]+""+col[60]+""+col[61]+""+col[62]+""+col[63]+""+col[64]+""+col[65]+""+col[66]+""+col[67]+""+col[68]+""+col[69]+""+col[70]+")"+" > "+col[71]+"\n"); > IndexError: list index out of range > The first index of the list is col[0] and not col[1], and the last index is n-1 if the length of the list is n. So here you have to go from col[0] to col[70]. BTW you can write the construction of the statement in a very short form when you use string concatenation (or as a faster solution a list of strings and then join() the list, do a search on the net) to construct the insert-statement before you use f.write(). I leave this as an exercise. Oh, and your inset statement needs commas "," ;-) > I get index out of range. I checked the number of > columns matched the col[] values here. Even then there > is some problem. Is there some easy method to get this > done. > > Please help. > > Thank you. > > Kumar. > > HTH, Wolfram From eric at digitalert.net Fri Oct 15 09:20:26 2004 From: eric at digitalert.net (Eric) Date: Fri Oct 15 09:19:57 2004 Subject: [Tutor] How to watch a changing list, and wait for a certain value to leave? In-Reply-To: <000c01c4b27d$78437740$49108aca@jason> References: <000c01c4b27d$78437740$49108aca@jason> Message-ID: <416F7A3A.7050906@digitalert.net> I got some help here before with this program I have started to write, and I am hung up on something again. Anyway I'm trying to write a simple program that will watch for a connection to be made by a certain host, sound the system bell when the connection is made, and then when the connection is closed have the system bell sound again. Then loop back to the beginning and start watching again. Here is the only working part I have so far... import os import time connected = False while not connected: o=os.popen("netstat -an") for l in o: try: if l.split()[1].endswith("192.168.0.250:21"): print "\a\a\a\a\aMatch!" connected = True else: print "Nothing" except IndexError: print "Index Exception" time.sleep(1) That works just like I want it to however now I need to figure out a way to know when the host disconnects. I have tried to use count() function in conjunction with the less than operator to wait till "192.168.0.250:21" is <1 , but can't seem to get it right. Can anyone give me a hint, but not write the entire thing for me, or maybe give me some insite on a better way to do this? Thanks From frankbloeink at nerdshack.com Fri Oct 15 10:21:22 2004 From: frankbloeink at nerdshack.com (Frank Bloeink) Date: Fri Oct 15 10:21:30 2004 Subject: [Tutor] Function Problem 3.6 In-Reply-To: <002e01c4b236$cc6c1530$f6aeda18@usertz7f6j789v> References: <20041014104439.0e8167ce@speedking.dyndns.org> <002e01c4b236$cc6c1530$f6aeda18@usertz7f6j789v> Message-ID: <20041015102122.1a4a28b3@speedking.dyndns.org> Hey Mike there's absolutely nothing wrong with running the code in the python-shell, it works like expected, so there is no necessity to run it as a script. But if you want to run it as a python script in Linux you could hava a look at the python tutor (see section 2.2.2 for executable python script) -> http://docs.python.org/tut/node4.html But since your mail-header suggests that you're using Windows, I must admit that I haven't uses Windows for a long time and therefore don't know how to run python scripts there. But my guess would be you just copy the programm code into a textfile named scriptname.py and execute it with "python scriptname.py" Please correct me if I'm wrong! bye Frank On Thu, 14 Oct 2004 17:43:03 -0400 "Comcast Mail" wrote: > Hi Frank, > > Thanks for your suggestion! Considering that this is a beginner's > book, it would have been nice if they clued the reader into the > necessity to run as a script - there appears to be no such clue in the > book. Quickly, do you know the script procedure? If not, I'll find > out soon enough. > > Thanks Again! > Mike > > -----Original Message----- > From: Frank Bloeink [mailto:F.Bloeink@gmx.net] > Sent: Thursday, October 14, 2004 4:45 AM > To: tutor@python.org; Comcast Mail > Subject: Re: [Tutor] Function Problem 3.6 > > Hello Michael > > ... > > The problem with executing > > print "First Line" > newLine() > print "Second Line" > > in the python-shell is that every statement in the shell is directly > followed by the input, meaning you get a mixture of programm code and > output: > >>> print "First Line" > First Line > >>> nl() > > >>> print "Second Line" > Second Line > >>> > > If you would run this Program as a python script outside the > interpreter, you shoul get the expected result: > > ---start the script---- > First Line > > Second Line > ---end of the output--- > > hth Frank > > > P.S: This is my first post to the list, although I've read on the list > for about 2 months. Thanks to all the members on the list for the > informative posts, I hope I can contibute myself from time to time, at > least at the more basic stuff for I'm only a Python-beginner, too. > > > > On Thu, 14 Oct 2004 00:59:18 -0400 > "Comcast Mail" wrote: > > > > The exercise below refers to section 3.6 in "How to think like a > > computer scientist: Learning with Python." > > > def newLine(): > > > > print > > > > This function is named newLine. The empty parentheses indicate that > > it has no parameters. It contains only a single statement, which > > outputs a newline character. (That's what happens when you use a > > print command without any arguments.) ] > > > > My problem is that when I attempt the exercise above, I get the > > following: > > > > > > > > >>>def newLine(): I then hit "enter" key, and I get > > > > . > > > > > > > > I get three ellipses, no "print" output. If I then enter > > > > >>>print "First Line." > > > > > > > > Instead of getting the output "newLine()" as the book states > > > > > > > > I get an "indentationerror." > > > > > > > > Obviously the >>>print "Second Line." Doesn't work either. > > > > > Michael > > > > > > > > > > > -- > > "(8) It is more complicated than you think." > RFC 1925: The Twelve Networking Truths > > -- "(8) It is more complicated than you think." RFC 1925: The Twelve Networking Truths From gil at tuckers.de Fri Oct 15 11:30:21 2004 From: gil at tuckers.de (gil@tuckers.de) Date: Fri Oct 15 11:26:42 2004 Subject: [Tutor] python 2.3.4 GUI Message-ID: <000701c4b299$aeef5f40$6500a8c0@p933> Hi greetings, I am running Win 2000. When I download Python 2.2 and higher and I call the GUI it doesn`t come. The command line is okay the IDLE refuse to respond. Some tip or tips could be welcome. cheers gil From cyresse at gmail.com Fri Oct 15 12:48:58 2004 From: cyresse at gmail.com (Riumu Kuraku) Date: Fri Oct 15 12:49:01 2004 Subject: [Tutor] Re: email & imaplib for beginners like me In-Reply-To: References: Message-ID: ...edit.... Use RFC 2822 for formatting of headers in particular... RFC 2060 for particular semantics of IMAP4 protocol. On Thu, 14 Oct 2004 21:42:59 +1300, Riumu Kuraku wrote: > Hi all, > > (This started off as a plea for help.) > > Just tryng to understand the email package, and the docs are a > little... sparse? Maybe it's more I'm having trouble with OOP. > > Anyway, here's a sequence I've learnt from frustrating trial and > error, I'm trying to log on to a mail server, and download a message, > and make it readable. > > I thought I'd send it through in case anyone else gets stuck like me. > I'm doing it manually so I can understand how it works before I script it. > > I'm having trouble with some stuff like - > > a=test.fetch(1, 'RFC822' )... The first argument of fetch is fine. > It's the second that's got me. It's a name of a Internet standard. And > I used it on three different emails, and it got two headers, and one > header and full text. So I am quite confused as to how exactly to get > specific things, like headers/text/attachments only, so any light that > can be shed in that regard would be fantastic. > > >>>import imaplib # IMAP protocol library > >>>import email.Parser # email parser library > > >>>host="mail... ...com" # IMAP server name > >>>use="" # Your login > >>>pas="" # Your (plain text) password > > >>>test=imaplib.IMAP4(host) # Create instance of imap protocol connection > > >>>test.login(use, pas) # Send login and password to server > ('OK', ['LOGIN Welcome']) # Server likes it > > >>>test.select() # Selects INBOX by > default. Good enough for me... > ('OK', ['3']) # I have 3 email messages > > >>>x=test.fetch(3,'RFC822') #Try and get message 3... > > >>> print x > ('OK', [('3 (FLAGS (\\Seen hasnoatt) RFC822 {1200}', 'Return-Path: > \r\nReceived: from .... > ......\r\nReply-To: cyresse@gmail.com, > cynos@safe-mail.net\r\nTo: protocol_test@allmail.net\r\nSubject: > Boo\r\nMime-Version: 1.0\r\nContent-Type: text/plain; > charset=US-ASCII\r\nContent-Transfer-Encoding: > 7bit\r\n\r\nWhios\r\n'), ')']) > > ..Looks vaguely emailish to me (bit chopped out for brevity) > > >>>j=Parser #I want to parse what I downloaded using Parser > >>>print j.parse(x) > > TypeError: unbound method parse() must be called with Parser instance > as first argument (got tuple instance instead) > > #What does that mean? > > .....45 minutes later... oh.... > > >>>j=Parser() # REALLY IMPORTANT to include the (), I was running > around in circles > # for a looooong time trying to figure that out. > > >>>print j.parse(x) > AttributeError: 'tuple' object has no attribute 'readline' > > #OK, so x is a tuple, and it has no attr, readline...hmmm... > #Run off to docs, and open parser.py to have a look and: > > >>>print j.parsestr(x) #Turns out, Parser.parse() is for file > objects... Parser.parsestr() > # is for string objects, as I am > about to learn. > > TypeError: expected read buffer, tuple found > > #Still not liking tuple. Hmmm... > > >>>i=str(x) > >>>print j.parsestr(i) > > From nobody Thu Oct 14 21:10:42 2004 > ('OK', [('3 (FLAGS (\\Seen hasnoatt) RFC822 {1200}', 'Return-Path: > \r\nReceived: from .... > . > .....Reply-To: cyresse@gmail.com, > cynos@safe-mail.net\r\nTo: > protocol_test@allmail.net\r\nSubject: Boo\r\nMime-Version: > 1.0\r\nContent-Type: text/plain; > charset=US-ASCII\r\nContent-Trarnsfer-Encoding: 7bit\r\n\r\nWhios\r\n'), > ')']) > > Huzzah! A header, that is easy to read! (Once again, snipped for brevity.) > > Now, to reliably be able to get a whole email... I could write my own client : ) > From nick at javacat.f2s.com Fri Oct 15 13:00:18 2004 From: nick at javacat.f2s.com (nick@javacat.f2s.com) Date: Fri Oct 15 13:00:21 2004 Subject: [Tutor] Find out if a number is even or not Message-ID: <1097838018.416fadc261290@webmail.freedom2surf.net> Hi group, Im sure this is simple to do, but Ive just been looking through the python docs and the archive of this mailing list and cant find what Im after. I just want to know if a number is even or not. I've had a look at the math package but that doesnt seem to have anything this simple in it. I thought something like >>> if 10 div 2 == 0 : print 'even' >>> else : print 'odd' but obviously that doesnt work. Sorry for such a basic question, but I really cant find out how to do this. Kind regards Nick. ------------------------------------------------- Everyone should have http://www.freedom2surf.net/ From kraus at hagen-partner.de Fri Oct 15 13:11:47 2004 From: kraus at hagen-partner.de (Wolfram Kraus) Date: Fri Oct 15 13:11:32 2004 Subject: [Tutor] Re: Find out if a number is even or not In-Reply-To: <1097838018.416fadc261290@webmail.freedom2surf.net> References: <1097838018.416fadc261290@webmail.freedom2surf.net> Message-ID: nick@javacat.f2s.com wrote: > Hi group, > > Im sure this is simple to do, but Ive just been looking through the python docs > and the archive of this mailing list and cant find what Im after. > > I just want to know if a number is even or not. > > I've had a look at the math package but that doesnt seem to have anything this > simple in it. > > I thought something like > > >>>>if 10 div 2 == 0 : print 'even' >>>>else : print 'odd' > > > but obviously that doesnt work. > > Sorry for such a basic question, but I really cant find out how to do this. > > Kind regards > Nick. > Use the modulo-operator %: >>> x = 11 >>> if not x % 2: ... print "even" ... else: ... print "odd" ... odd >>> x = 12 >>> if not x % 2: ... print "even" ... else: ... print "odd" ... even HTH, Wolfram From cyresse at gmail.com Fri Oct 15 13:10:31 2004 From: cyresse at gmail.com (Riumu Kuraku) Date: Fri Oct 15 13:12:12 2004 Subject: [Tutor] Find out if a number is even or not In-Reply-To: <1097838018.416fadc261290@webmail.freedom2surf.net> References: <1097838018.416fadc261290@webmail.freedom2surf.net> Message-ID: >From "Python docs" The % (modulo) operator yields the remainder from the division of the first argument by the second. The numeric arguments are first converted to a common type. A zero right argument raises the ZeroDivisionError exception. The arguments may be floating point numbers, e.g., 3.14%0.7 equals 0.34 (since 3.14 equals 4*0.7 + 0.34.) The modulo operator always yields a result with the same sign as its second operand (or zero); the absolute value of the result is strictly smaller than the absolute value of the second operand5.1. if a number divides by 2, and yields no remainder, it's even. Be cool and write your own function for this... def OddorEven(x): a=0 a=x % 2 if a ==0: return "Even" else: eturn "Odd" On Fri, 15 Oct 2004 12:00:18 +0100, nick@javacat.f2s.com wrote: > Hi group, > > Im sure this is simple to do, but Ive just been looking through the python docs > and the archive of this mailing list and cant find what Im after. > > I just want to know if a number is even or not. > > I've had a look at the math package but that doesnt seem to have anything this > simple in it. > > I thought something like > > >>> if 10 div 2 == 0 : print 'even' > >>> else : print 'odd' > > but obviously that doesnt work. > > Sorry for such a basic question, but I really cant find out how to do this. > > Kind regards > Nick. > > ------------------------------------------------- > Everyone should have http://www.freedom2surf.net/ > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From my.mailing.lists at noos.fr Fri Oct 15 13:15:43 2004 From: my.mailing.lists at noos.fr (nik) Date: Fri Oct 15 13:15:51 2004 Subject: [Tutor] Find out if a number is even or not In-Reply-To: <1097838018.416fadc261290@webmail.freedom2surf.net> References: <1097838018.416fadc261290@webmail.freedom2surf.net> Message-ID: <416FB15F.8030307@noos.fr> try using the mod operator, % if 10%2 == 0 etc... this returns the remainder left over from dividing the two numbers nik nick@javacat.f2s.com wrote: >Hi group, > >Im sure this is simple to do, but Ive just been looking through the python docs >and the archive of this mailing list and cant find what Im after. > >I just want to know if a number is even or not. > >I've had a look at the math package but that doesnt seem to have anything this >simple in it. > >I thought something like > > > >>>>if 10 div 2 == 0 : print 'even' >>>>else : print 'odd' >>>> >>>> > >but obviously that doesnt work. > >Sorry for such a basic question, but I really cant find out how to do this. > >Kind regards >Nick. > > > > > >------------------------------------------------- >Everyone should have http://www.freedom2surf.net/ >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > > From kent_johnson at skillsoft.com Fri Oct 15 13:16:12 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Fri Oct 15 13:16:16 2004 Subject: [Tutor] Find out if a number is even or not In-Reply-To: <1097838018.416fadc261290@webmail.freedom2surf.net> References: <1097838018.416fadc261290@webmail.freedom2surf.net> Message-ID: <6.1.0.6.0.20041015071349.02883488@mail4.skillsoft.com> Nick, You need the % (modulus) operator. a % b gives the remainder when a is divided by b. So a % 2 == 0 tests for even: >>> for i in range(10): ... print i, i%2 ... 0 0 1 1 2 0 3 1 4 0 5 1 6 0 7 1 8 0 9 1 Kent At 12:00 PM 10/15/2004 +0100, nick@javacat.f2s.com wrote: >Hi group, > >Im sure this is simple to do, but Ive just been looking through the python >docs >and the archive of this mailing list and cant find what Im after. > >I just want to know if a number is even or not. > >I've had a look at the math package but that doesnt seem to have anything this >simple in it. > >I thought something like > > >>> if 10 div 2 == 0 : print 'even' > >>> else : print 'odd' > >but obviously that doesnt work. > >Sorry for such a basic question, but I really cant find out how to do this. > >Kind regards >Nick. > > > > > >------------------------------------------------- >Everyone should have http://www.freedom2surf.net/ >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From nick at javacat.f2s.com Fri Oct 15 13:57:12 2004 From: nick at javacat.f2s.com (nick@javacat.f2s.com) Date: Fri Oct 15 13:57:14 2004 Subject: [Tutor] Find out if a number is even or not In-Reply-To: <6.1.0.6.0.20041015071349.02883488@mail4.skillsoft.com> References: <1097838018.416fadc261290@webmail.freedom2surf.net> <6.1.0.6.0.20041015071349.02883488@mail4.skillsoft.com> Message-ID: <1097841432.416fbb1864586@webmail.freedom2surf.net> Thankyou everyone for your responses. Now you've show me the modulus (%) operator I remember seeing it used on this list several times. Thanks again, Nick. Quoting Kent Johnson : > Nick, > > You need the % (modulus) operator. a % b gives the remainder when a is > divided by b. So a % 2 == 0 tests for even: > > >>> for i in range(10): > ... print i, i%2 > ... > 0 0 > 1 1 > 2 0 > 3 1 > 4 0 > 5 1 > 6 0 > 7 1 > 8 0 > 9 1 > > Kent > > At 12:00 PM 10/15/2004 +0100, nick@javacat.f2s.com wrote: > >Hi group, > > > >Im sure this is simple to do, but Ive just been looking through the python > >docs > >and the archive of this mailing list and cant find what Im after. > > > >I just want to know if a number is even or not. > > > >I've had a look at the math package but that doesnt seem to have anything > this > >simple in it. > > > >I thought something like > > > > >>> if 10 div 2 == 0 : print 'even' > > >>> else : print 'odd' > > > >but obviously that doesnt work. > > > >Sorry for such a basic question, but I really cant find out how to do this. > > > >Kind regards > >Nick. > > > > > > > > > > > >------------------------------------------------- > >Everyone should have http://www.freedom2surf.net/ > >_______________________________________________ > >Tutor maillist - Tutor@python.org > >http://mail.python.org/mailman/listinfo/tutor > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > ------------------------------------------------- Everyone should have http://www.freedom2surf.net/ From chandrakirti at gmail.com Fri Oct 15 14:19:05 2004 From: chandrakirti at gmail.com (Lloyd Hugh Allen) Date: Fri Oct 15 14:20:54 2004 Subject: [Tutor] python 2.3.4 GUI In-Reply-To: <000701c4b299$aeef5f40$6500a8c0@p933> References: <000701c4b299$aeef5f40$6500a8c0@p933> Message-ID: <24d253d9041015051946aae209@mail.gmail.com> Do you have any other programming languages installed on your computer, particularly any that use Tk/TCL? Installing Ruby broke my Python a few years ago, because Ruby had screwed with all the Tk/TCL stuff. I submitted this as an issue to both Python and Ruby, and got responses of "it's not OUR fault" from both sides. And then the Ruby uninstaller didn't clean up after itself. Messy situation. In the absence of other programming languages, I would try cleanly uninstalling all versions of Python, and then reinstalling the most recent one. On Fri, 15 Oct 2004 11:30:21 +0200, gil@tuckers.de wrote: > > > Hi greetings, > I am running Win 2000. When I download Python 2.2 and higher > and I call the GUI it doesn`t come. The command line is okay the IDLE refuse to > respond. Some tip or tips could be welcome. > cheers gil > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From pythonTutor at venix.com Fri Oct 15 15:20:36 2004 From: pythonTutor at venix.com (Lloyd Kvam) Date: Fri Oct 15 15:20:46 2004 Subject: [Tutor] declare-define In-Reply-To: <000c01c4b27d$78437740$49108aca@jason> References: <000c01c4b27d$78437740$49108aca@jason> Message-ID: <1097846436.8095.16.camel@laptop.venix.com> On Fri, 2004-10-15 at 02:09, nitt wrote: > Hi All' > > Trying to get the following, and yes,tried most everything. > > input("p(1)=") This creates a prompt for assigning to p(1), BUT it does not actually save the input. Also, p(1) is NOT a valid python name. It calls p with an argument of 1. p would likely be a function or a class. p_1 = input("p_1=") is a simple rewrite of the line into valid python code. > input("p(1)=") This is probably a typo and should become: p_2 = input("p_2=") > input("p(3)=") You know the pattern now. > a=p(1)*(p(1)*p(2)-1)*(p(3)+1)/(p(1)+1) a = p_1 * (p_1*p_2-1)*(p_3+1)/(p_1+1) As you can see, the numbers in the variable names make this equation hard to read. Names like a,b,c would be easier to separate from the numbers. Descriptive names (e.g. area = length * width ) are best. > print int(a) rjust(45) a should already be an integer. The things to be printed should be separated by commas. print a, p_1, p_2, p_3 I do not know the intent of rjust(45). The string % operator can be used to control numeric formats. It is documented in the Library Reference Manual. If you simply wanted more space between a and 45, print a, " ", 45 > Keep getting name error,p() not defined and rjust doesn't exist. > using 234 > Appreciate any help given > > King regards > nitt@iprimus.com.au > > > ______________________________________________________________________ > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp From mw5858 at sbc.com Fri Oct 15 17:18:55 2004 From: mw5858 at sbc.com (WEISS, MARK (NB)) Date: Fri Oct 15 17:19:05 2004 Subject: [Tutor] visual development environs? Message-ID: <4BF710B1993F1244B41763531F098D7905A8F4@cafrfd1msgusr21.itservices.sbc.com> I have recently been on the search for a new IDE as well. You may want to check out Stani's Python Editor (SPE) at http://spe.pycs.net/ Another place to look is the Developer Works (IBM) site. David Mertz has posted several reviews of Python IDEs there. cheers, mark -----Original Message----- From: tutor-bounces@python.org [mailto:tutor-bounces@python.org] On Behalf Of Terry Carroll Sent: Thursday, October 14, 2004 6:45 PM To: tutor@python.org Subject: Re: [Tutor] visual development environs? On Thu, 16 Sep 2004, Thomas Clive Richards wrote: > I'm looking for a visual development environment (I'm not sure this si the > right term) similar to blackadder > (http://www.thekompany.com/products/blackadder/). (and then, later...) > I forgot to mention that it has to run under Linux > (thus the MS visual studio plugins are out of the picture).... I've been idly wondering about running Eclipse (which is an IDE intended for Java development, and that runs under the Java VM, so should be okay under Linux) along with Pydev for Eclipse for the Python support. I haven't tried this, so I don't put this out as a recommendation, but you might want to look at it. (And then let us know how it went!) URLs: http://www.eclipse.org/ http://sourceforge.net/projects/pydev/ Note there are other Eclipse-based Python projects listed at , but pydev seems to be the leader. _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From bill at celestial.net Fri Oct 15 18:56:06 2004 From: bill at celestial.net (Bill Campbell) Date: Fri Oct 15 18:56:10 2004 Subject: [Tutor] using exceptions to implement case/switch? Message-ID: <20041015165606.GA19744@alexis.mi.celestial.com> I'm looking for feedback on the pros and cons of using exceptions to implement constructions similar to the C switch or other language's case statements. I'm in the process of converting bunch of C code that makes extensive use of switch() statements. In particular I'm doing a python curses implementation where it's parsing keys as they are pressed with different case parts when special keys are hit. Rather than doing this with a set of ``if'' statements, this could be done using exceptions, perhaps as in the code below. # start import curses import curses.ascii as ascii keyf1 = 'key F1 pressed' keyf2 = 'key F2 pressed' keyf3 = 'key F3 pressed' keyf4 = 'key F4 pressed' # ... def getchar(win): '''Get printable character from curses window''' while True: c = win.getch() if ascii.isprint(c) : return c if c == curses.KEY_F1 : raise keyf1 if c == curses.KEY_F2 : raise keyf2 if c == curses.KEY_F3 : raise keyf3 if c == curses.KEY_F4 : raise keyf4 curses.beep() win = something_to_initialize_curses_window() while True: try: c = getchar(win) except keyf1: process_keyF1() except (keyf2, keyf3): process_keyf2andf3() except keyf4: process keyf4() # ... #end... Bill -- INTERNET: bill@Celestial.COM Bill Campbell; Celestial Software LLC UUCP: camco!bill PO Box 820; 6641 E. Mercer Way FAX: (206) 232-9186 Mercer Island, WA 98040-0820; (206) 236-1676 URL: http://www.celestial.com/ ``I have no reason to suppose that he, who would take away my Liberty, would not when he had me in his Power, take away everything else.'' John Locke From kent_johnson at skillsoft.com Fri Oct 15 19:22:30 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Fri Oct 15 19:22:35 2004 Subject: [Tutor] using exceptions to implement case/switch? In-Reply-To: <20041015165606.GA19744@alexis.mi.celestial.com> References: <20041015165606.GA19744@alexis.mi.celestial.com> Message-ID: <6.1.0.6.0.20041015131746.02a3d0a8@mail4.skillsoft.com> A simple way to do this is to use a dictionary as a dispatcher: dispatch = { curses.KEY_F1 : process_keyF1, # Note - no parentheses here, this is a reference to the fn, not a call curses.KEY_F2 : process_keyF2, curses.KEY_F3 : process_keyF3, curses.KEY_F4 : process_keyF4, } while True: c = win.getch() if ascii.isprint(c) : return c fn = dispatch.get(c, curses.beep) fn() Kent At 09:56 AM 10/15/2004 -0700, Bill Campbell wrote: >I'm looking for feedback on the pros and cons of using exceptions to >implement constructions similar to the C switch or other language's case >statements. > >I'm in the process of converting bunch of C code that makes extensive use >of switch() statements. In particular I'm doing a python curses >implementation where it's parsing keys as they are pressed with different >case parts when special keys are hit. Rather than doing this with a set of >``if'' statements, this could be done using exceptions, perhaps as in the >code below. > ># start >import curses >import curses.ascii as ascii > >keyf1 = 'key F1 pressed' >keyf2 = 'key F2 pressed' >keyf3 = 'key F3 pressed' >keyf4 = 'key F4 pressed' ># ... > >def getchar(win): > '''Get printable character from curses window''' > while True: > c = win.getch() > if ascii.isprint(c) : return c > if c == curses.KEY_F1 : raise keyf1 > if c == curses.KEY_F2 : raise keyf2 > if c == curses.KEY_F3 : raise keyf3 > if c == curses.KEY_F4 : raise keyf4 > curses.beep() > >win = something_to_initialize_curses_window() > >while True: > try: > c = getchar(win) > except keyf1: > process_keyF1() > except (keyf2, keyf3): > process_keyf2andf3() > except keyf4: > process keyf4() > # ... >#end... > >Bill >-- >INTERNET: bill@Celestial.COM Bill Campbell; Celestial Software LLC >UUCP: camco!bill PO Box 820; 6641 E. Mercer Way >FAX: (206) 232-9186 Mercer Island, WA 98040-0820; (206) 236-1676 >URL: http://www.celestial.com/ > >``I have no reason to suppose that he, who would take away my Liberty, would >not when he had me in his Power, take away everything else.'' John Locke >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From dyoo at hkn.eecs.berkeley.edu Fri Oct 15 20:22:13 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Oct 15 20:22:17 2004 Subject: [Tutor] declare-define In-Reply-To: <000c01c4b27d$78437740$49108aca@jason> Message-ID: On Fri, 15 Oct 2004, nitt wrote: > Hi All' > > Trying to get the following, and yes,tried most everything. > > input("p(1)=") > input("p(1)=") > input("p(3)=") Hi Nitt, Ah! The problem here is that input() actually knows nothing about the string prompt that you're giving it. What I mean is that we could have easily have written: input("The first value of the p variable:") or: input("Give me something to input:") Python will print out the input, but it basically doesn't try to understand what the prompt means. input() is not smart enough to interpret English. *grin* So you need to tell it to store the result of the input() into the target variable in an explicit way. For example: p1 = input("please enter p1") or: p1 = input("p(1)=") Does this make sense? > print int(a) rjust(45) > Keep getting name error,p() not defined and rjust doesn't exist. What is rjust()? Which tutorial or documentation are you looking at? Best of wishes to you! From zmerch at 30below.com Fri Oct 15 20:56:09 2004 From: zmerch at 30below.com (Roger Merchberger) Date: Fri Oct 15 20:56:35 2004 Subject: [Tutor] Find out if a number is even or not In-Reply-To: References: <1097838018.416fadc261290@webmail.freedom2surf.net> <1097838018.416fadc261290@webmail.freedom2surf.net> Message-ID: <5.1.0.14.2.20041015144947.059e48a0@mail.30below.com> Rumor has it that Riumu Kuraku may have mentioned these words: >[snip] >Be cool and write your own function for this... > >def OddorEven(x): >a=0 >a=x % 2 >if a ==0: > return "Even" >else: > eturn "Odd" Just to let you know: The first assignment of 0 to a seems superfluous as you're reassigning it in the very next statement; and just to show others a different way of coding this... def OddorEven(x): a=x % 2 if a: return "Odd" else: return "Even" [[ Oh, and your indentation was a schootch off... ;-) ]] HTH, Roger "Merch" Merchberger -- Roger "Merch" Merchberger | JC: "Like those people in Celeronville!" sysadmin, Iceberg Computers | Me: "Don't you mean Silicon Valley???" zmerch@30below.com | JC: "Yea, that's the place!" | JC == Jeremy Christian From kent_johnson at skillsoft.com Fri Oct 15 20:59:24 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Fri Oct 15 20:59:24 2004 Subject: [Tutor] declare-define In-Reply-To: References: <000c01c4b27d$78437740$49108aca@jason> Message-ID: <6.1.0.6.0.20041015145711.029f35f0@mail4.skillsoft.com> rjust is a string method, try print str(a).rjust(45) alternatively use formatted print: print "%45d" % a At 11:22 AM 10/15/2004 -0700, Danny Yoo wrote: > > print int(a) rjust(45) > > Keep getting name error,p() not defined and rjust doesn't exist. > > >What is rjust()? Which tutorial or documentation are you looking at? From bill at celestial.net Fri Oct 15 21:22:20 2004 From: bill at celestial.net (Bill Campbell) Date: Fri Oct 15 21:22:23 2004 Subject: [Tutor] using exceptions to implement case/switch? In-Reply-To: <6.1.0.6.0.20041015131746.02a3d0a8@mail4.skillsoft.com> References: <20041015165606.GA19744@alexis.mi.celestial.com> <6.1.0.6.0.20041015131746.02a3d0a8@mail4.skillsoft.com> Message-ID: <20041015192219.GA27629@alexis.mi.celestial.com> On Fri, Oct 15, 2004, Kent Johnson wrote: >A simple way to do this is to use a dictionary as a dispatcher: >dispatch = { > curses.KEY_F1 : process_keyF1, # Note - no parentheses here, this is a >reference to the fn, not a call > curses.KEY_F2 : process_keyF2, > curses.KEY_F3 : process_keyF3, > curses.KEY_F4 : process_keyF4, >} > > while True: > c = win.getch() > if ascii.isprint(c) : return c > fn = dispatch.get(c, curses.beep) > fn() That's a good approach when one wants to run separate processes, but doesn't handle the case where one wants to run in the current name space. In the curses example below, key codes like left-arrow or right-arrow may change the cursor position on the screen by changing y, x variables. A variation might be to have a dictionary of lambda functions that raise the appropriate exceptions (hopefully I have the syntax correct :-): dispatch = { curses.KEY_F1 : (lambda x: raise keyf1), curses.KEY_F2 : (lambda x: raise keyf2), curses.KEY_F3 : (lambda x: raise keyf3), curses.KEY_F4 : (lambda x: raise keyf4), } def getchar(win, keymap=dispatch): while True: c = win.getch() if curses.ascii.isprint(c) : return(c) fn = keymap.get(c, curses.beep) fn() Using a dictionary has the advantage that it's easier to map multiple keys to the same exception, and the addition of the optional keymap parameter to getchar allows one to change the key map depending on the situation. >Kent > >At 09:56 AM 10/15/2004 -0700, Bill Campbell wrote: >>I'm looking for feedback on the pros and cons of using exceptions to >>implement constructions similar to the C switch or other language's case >>statements. >> >>I'm in the process of converting bunch of C code that makes extensive use >>of switch() statements. In particular I'm doing a python curses >>implementation where it's parsing keys as they are pressed with different >>case parts when special keys are hit. Rather than doing this with a set of >>``if'' statements, this could be done using exceptions, perhaps as in the >>code below. >> >># start >>import curses >>import curses.ascii as ascii >> >>keyf1 = 'key F1 pressed' >>keyf2 = 'key F2 pressed' >>keyf3 = 'key F3 pressed' >>keyf4 = 'key F4 pressed' >># ... >> >>def getchar(win): >> '''Get printable character from curses window''' >> while True: >> c = win.getch() >> if ascii.isprint(c) : return c >> if c == curses.KEY_F1 : raise keyf1 >> if c == curses.KEY_F2 : raise keyf2 >> if c == curses.KEY_F3 : raise keyf3 >> if c == curses.KEY_F4 : raise keyf4 >> curses.beep() >> >>win = something_to_initialize_curses_window() >> >>while True: >> try: >> c = getchar(win) >> except keyf1: >> process_keyF1() >> except (keyf2, keyf3): >> process_keyf2andf3() >> except keyf4: >> process keyf4() >> # ... >>#end... >> >>Bill >>-- >>INTERNET: bill@Celestial.COM Bill Campbell; Celestial Software LLC >>UUCP: camco!bill PO Box 820; 6641 E. Mercer Way >>FAX: (206) 232-9186 Mercer Island, WA 98040-0820; (206) >>236-1676 >>URL: http://www.celestial.com/ >> >>``I have no reason to suppose that he, who would take away my Liberty, >>would >>not when he had me in his Power, take away everything else.'' John Locke >>_______________________________________________ >>Tutor maillist - Tutor@python.org >>http://mail.python.org/mailman/listinfo/tutor > -- Bill -- INTERNET: bill@Celestial.COM Bill Campbell; Celestial Software LLC UUCP: camco!bill PO Box 820; 6641 E. Mercer Way FAX: (206) 232-9186 Mercer Island, WA 98040-0820; (206) 236-1676 URL: http://www.celestial.com/ ``If you make yourselves sheep, the wolves will eat you'' -- Benjamin Franklin From jfabiani at yolo.com Fri Oct 15 22:05:10 2004 From: jfabiani at yolo.com (John Fabiani) Date: Fri Oct 15 22:05:30 2004 Subject: [Tutor] visual development environs? In-Reply-To: <4BF710B1993F1244B41763531F098D7905A8F4@cafrfd1msgusr21.itservices.sbc.com> References: <4BF710B1993F1244B41763531F098D7905A8F4@cafrfd1msgusr21.itservices.sbc.com> Message-ID: <200410151305.10161.jfabiani@yolo.com> On Friday 15 October 2004 08:18, WEISS, MARK (NB) wrote: > I have recently been on the search for a new IDE as well. You may want > to check out Stani's Python Editor (SPE) at http://spe.pycs.net/ Another > place to look is the Developer Works (IBM) site. David Mertz has posted > several reviews of Python IDEs there. > > cheers, > mark > You might want to check out using wing 2.0 with wxGlade. You have to buy wing 2.0 but wxGlade is free. None of the IDE's that I have found (so far) match anything of the Microsoft IDE's for VB or VFP. All of them are missing the ease of developing a form based app. Don't get me wrong because I believe improvements are happening daily but (as of today) the IDE's are far behind Microsoft offerings - at least for Python. John From bill.mill at gmail.com Fri Oct 15 22:30:06 2004 From: bill.mill at gmail.com (Bill Mill) Date: Fri Oct 15 22:30:36 2004 Subject: [Tutor] visual development environs? In-Reply-To: <200410151305.10161.jfabiani@yolo.com> References: <4BF710B1993F1244B41763531F098D7905A8F4@cafrfd1msgusr21.itservices.sbc.com> <200410151305.10161.jfabiani@yolo.com> Message-ID: <797fe3d40410151330443d9adc@mail.gmail.com> Alright Thomas, I'm gonna be "that guy", but why does he need a VB-style IDE? If he's developing on Linux, he should be at least passingly comfortable with the command line. Why not give him one terminal with pico (or teach him vim/emacs, but I doubt he needs 2 things to learn at once) and another with ipython loaded? IMHO, he could learn a lot about how things really work just by typing "python myfile.py" that he couldn't get if he started right out in an IDE. Just a thought. Peace Bill Mill bill.mill at gmail.com On Fri, 15 Oct 2004 13:05:10 -0700, John Fabiani wrote: > On Friday 15 October 2004 08:18, WEISS, MARK (NB) wrote: > > I have recently been on the search for a new IDE as well. You may want > > to check out Stani's Python Editor (SPE) at http://spe.pycs.net/ Another > > place to look is the Developer Works (IBM) site. David Mertz has posted > > several reviews of Python IDEs there. > > > > cheers, > > mark > > > You might want to check out using wing 2.0 with wxGlade. You have to buy wing > 2.0 but wxGlade is free. None of the IDE's that I have found (so far) match > anything of the Microsoft IDE's for VB or VFP. All of them are missing the > ease of developing a form based app. Don't get me wrong because I believe > improvements are happening daily but (as of today) the IDE's are far behind > Microsoft offerings - at least for Python. > > John > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From nick at javacat.f2s.com Fri Oct 15 22:39:07 2004 From: nick at javacat.f2s.com (Nick Lunt) Date: Fri Oct 15 22:34:08 2004 Subject: [Tutor] visual development environs? In-Reply-To: <200410151305.10161.jfabiani@yolo.com> Message-ID: I've only just noticed this thread, but pythoncard is a surefire winner for me. http://pythoncard.sourceforge.net/ Cheers Nick. -----Original Message----- From: tutor-bounces@python.org [mailto:tutor-bounces@python.org]On Behalf Of John Fabiani Sent: 15 October 2004 21:05 To: tutor@python.org Subject: Re: [Tutor] visual development environs? On Friday 15 October 2004 08:18, WEISS, MARK (NB) wrote: > I have recently been on the search for a new IDE as well. You may want > to check out Stani's Python Editor (SPE) at http://spe.pycs.net/ Another > place to look is the Developer Works (IBM) site. David Mertz has posted > several reviews of Python IDEs there. > > cheers, > mark > You might want to check out using wing 2.0 with wxGlade. You have to buy wing 2.0 but wxGlade is free. None of the IDE's that I have found (so far) match anything of the Microsoft IDE's for VB or VFP. All of them are missing the ease of developing a form based app. Don't get me wrong because I believe improvements are happening daily but (as of today) the IDE's are far behind Microsoft offerings - at least for Python. John _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor --- Incoming mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.775 / Virus Database: 522 - Release Date: 08/10/2004 --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.775 / Virus Database: 522 - Release Date: 08/10/2004 From bill.mill at gmail.com Fri Oct 15 22:36:42 2004 From: bill.mill at gmail.com (Bill Mill) Date: Fri Oct 15 22:36:45 2004 Subject: [Tutor] using exceptions to implement case/switch? In-Reply-To: <20041015192219.GA27629@alexis.mi.celestial.com> References: <20041015165606.GA19744@alexis.mi.celestial.com> <6.1.0.6.0.20041015131746.02a3d0a8@mail4.skillsoft.com> <20041015192219.GA27629@alexis.mi.celestial.com> Message-ID: <797fe3d4041015133648a4a1dc@mail.gmail.com> Bill, I think you've misunderstood the example; pardon me if I've misunderstood you in turn, but Kent's dispatcher will run the functions in the current namespace. No new processes or namespaces will be created, making your lambda method redundant. Peace Bill Mill bill.mill at gmail.com On Fri, 15 Oct 2004 12:22:20 -0700, Bill Campbell wrote: > On Fri, Oct 15, 2004, Kent Johnson wrote: > >A simple way to do this is to use a dictionary as a dispatcher: > >dispatch = { > > curses.KEY_F1 : process_keyF1, # Note - no parentheses here, this is a > >reference to the fn, not a call > > curses.KEY_F2 : process_keyF2, > > curses.KEY_F3 : process_keyF3, > > curses.KEY_F4 : process_keyF4, > >} > > > > while True: > > c = win.getch() > > if ascii.isprint(c) : return c > > fn = dispatch.get(c, curses.beep) > > fn() > > That's a good approach when one wants to run separate processes, but > doesn't handle the case where one wants to run in the current name space. > > In the curses example below, key codes like left-arrow or right-arrow may > change the cursor position on the screen by changing y, x variables. A > variation might be to have a dictionary of lambda functions that raise the > appropriate exceptions (hopefully I have the syntax correct :-): > > dispatch = { > curses.KEY_F1 : (lambda x: raise keyf1), > curses.KEY_F2 : (lambda x: raise keyf2), > curses.KEY_F3 : (lambda x: raise keyf3), > curses.KEY_F4 : (lambda x: raise keyf4), > } > > def getchar(win, keymap=dispatch): > while True: > c = win.getch() > if curses.ascii.isprint(c) : return(c) > fn = keymap.get(c, curses.beep) > fn() > > Using a dictionary has the advantage that it's easier to map multiple keys > to the same exception, and the addition of the optional keymap parameter to > getchar allows one to change the key map depending on the situation. > > >Kent > > > >At 09:56 AM 10/15/2004 -0700, Bill Campbell wrote: > >>I'm looking for feedback on the pros and cons of using exceptions to > >>implement constructions similar to the C switch or other language's case > >>statements. > >> > >>I'm in the process of converting bunch of C code that makes extensive use > >>of switch() statements. In particular I'm doing a python curses > >>implementation where it's parsing keys as they are pressed with different > >>case parts when special keys are hit. Rather than doing this with a set of > >>``if'' statements, this could be done using exceptions, perhaps as in the > >>code below. > >> > >># start > >>import curses > >>import curses.ascii as ascii > >> > >>keyf1 = 'key F1 pressed' > >>keyf2 = 'key F2 pressed' > >>keyf3 = 'key F3 pressed' > >>keyf4 = 'key F4 pressed' > >># ... > >> > >>def getchar(win): > >> '''Get printable character from curses window''' > >> while True: > >> c = win.getch() > >> if ascii.isprint(c) : return c > >> if c == curses.KEY_F1 : raise keyf1 > >> if c == curses.KEY_F2 : raise keyf2 > >> if c == curses.KEY_F3 : raise keyf3 > >> if c == curses.KEY_F4 : raise keyf4 > >> curses.beep() > >> > >>win = something_to_initialize_curses_window() > >> > >>while True: > >> try: > >> c = getchar(win) > >> except keyf1: > >> process_keyF1() > >> except (keyf2, keyf3): > >> process_keyf2andf3() > >> except keyf4: > >> process keyf4() > >> # ... > >>#end... > >> > >>Bill > >>-- > >>INTERNET: bill@Celestial.COM Bill Campbell; Celestial Software LLC > >>UUCP: camco!bill PO Box 820; 6641 E. Mercer Way > >>FAX: (206) 232-9186 Mercer Island, WA 98040-0820; (206) > >>236-1676 > >>URL: http://www.celestial.com/ > >> > >>``I have no reason to suppose that he, who would take away my Liberty, > >>would > >>not when he had me in his Power, take away everything else.'' John Locke > >>_______________________________________________ > >>Tutor maillist - Tutor@python.org > >>http://mail.python.org/mailman/listinfo/tutor > > > > -- > Bill > -- > INTERNET: bill@Celestial.COM Bill Campbell; Celestial Software LLC > UUCP: camco!bill PO Box 820; 6641 E. Mercer Way > FAX: (206) 232-9186 Mercer Island, WA 98040-0820; (206) 236-1676 > URL: http://www.celestial.com/ > > ``If you make yourselves sheep, the wolves will eat you'' -- Benjamin Franklin > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From maxnoel_fr at yahoo.fr Fri Oct 15 22:51:48 2004 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Fri Oct 15 22:51:54 2004 Subject: Fwd: [Tutor] using exceptions to implement case/switch? Message-ID: <087EF7AE-1EEC-11D9-994D-000393CBC88E@yahoo.fr> (sigh... Forgot to click "reply to all". It'd be more practical if that list set a reply-to header IMO...) Begin forwarded message: > From: Max Noel > Date: October 15, 2004 21:42:37 BST > To: Bill Mill > Subject: Re: [Tutor] using exceptions to implement case/switch? > > > On Oct 15, 2004, at 21:36, Bill Mill wrote: > >> Bill, >> >> I think you've misunderstood the example; pardon me if I've >> misunderstood you in turn, but Kent's dispatcher will run the >> functions in the current namespace. No new processes or namespaces >> will be created, making your lambda method redundant. >> >> Peace >> Bill Mill >> bill.mill at gmail.com > > I think he meant scope, not namespace. However IIRC lambda functions > have their own scope, like normal functions (not 100% sure of that, I > never use lambdas), thus the method is redundant either way. > > -- Wild_Cat > maxnoel_fr at yahoo dot fr -- ICQ #85274019 > "Look at you hacker... A pathetic creature of meat and bone, panting > and sweating as you run through my corridors... How can you challenge > a perfect, immortal machine?" > > -- maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From bill at celestial.net Fri Oct 15 23:32:05 2004 From: bill at celestial.net (Bill Campbell) Date: Fri Oct 15 23:32:08 2004 Subject: Fwd: [Tutor] using exceptions to implement case/switch? In-Reply-To: <087EF7AE-1EEC-11D9-994D-000393CBC88E@yahoo.fr> References: <087EF7AE-1EEC-11D9-994D-000393CBC88E@yahoo.fr> Message-ID: <20041015213205.GA35069@alexis.mi.celestial.com> On Fri, Oct 15, 2004, Max Noel wrote: >(sigh... Forgot to click "reply to all". It'd be more practical if that >list set a reply-to header IMO...) Funny, my archaic mailer works just fine replying to lists by pressing ``L''. >Begin forwarded message: > >>From: Max Noel >>Date: October 15, 2004 21:42:37 BST >>To: Bill Mill >>Subject: Re: [Tutor] using exceptions to implement case/switch? >> >> >>On Oct 15, 2004, at 21:36, Bill Mill wrote: >> >>>Bill, >>> >>>I think you've misunderstood the example; pardon me if I've >>>misunderstood you in turn, but Kent's dispatcher will run the >>>functions in the current namespace. No new processes or namespaces >>>will be created, making your lambda method redundant. >>> >>>Peace >>>Bill Mill >>>bill.mill at gmail.com >> >> I think he meant scope, not namespace. However IIRC lambda functions >>have their own scope, like normal functions (not 100% sure of that, I >>never use lambdas), thus the method is redundant either way. My main goal had little to do with lamdas or function calls, but the desire to implement a construct that closely resembles C switch or other language's case statements. How the exceptions are raised isn't important. The important thing is using multiple ``except'' sections after a ``try'' instead of using conditional tests. Bill -- INTERNET: bill@Celestial.COM Bill Campbell; Celestial Software LLC UUCP: camco!bill PO Box 820; 6641 E. Mercer Way FAX: (206) 232-9186 Mercer Island, WA 98040-0820; (206) 236-1676 URL: http://www.celestial.com/ With Congress, every time they make a joke it's a law; and every time they make a law it's a joke. -- Will Rogers From kent_johnson at skillsoft.com Fri Oct 15 23:47:03 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Fri Oct 15 23:47:09 2004 Subject: Fwd: [Tutor] using exceptions to implement case/switch? In-Reply-To: <20041015213205.GA35069@alexis.mi.celestial.com> References: <087EF7AE-1EEC-11D9-994D-000393CBC88E@yahoo.fr> <20041015213205.GA35069@alexis.mi.celestial.com> Message-ID: <6.1.0.6.0.20041015174137.028cfcd0@mail4.skillsoft.com> Bill, I'm really confused now. Are you trying to duplicate the visual appearance of a case statement? Your solution hasn't eliminated the conditionals, it just hides them in a helper function. It adds the overhead of throwing and catching an exception. If your question is, how do I do this the Python way? - the usual solution is either chained conditionals (if / elif / ... / else) or using a dict as a dispatcher. If your question is, will this work? - yes, it will work, but I sure don't understand why you would want to do it that way. Kent At 02:32 PM 10/15/2004 -0700, Bill Campbell wrote: >On Fri, Oct 15, 2004, Max Noel wrote: > >(sigh... Forgot to click "reply to all". It'd be more practical if that > >list set a reply-to header IMO...) > >Funny, my archaic mailer works just fine replying to lists by >pressing ``L''. > > >Begin forwarded message: > > > >>From: Max Noel > >>Date: October 15, 2004 21:42:37 BST > >>To: Bill Mill > >>Subject: Re: [Tutor] using exceptions to implement case/switch? > >> > >> > >>On Oct 15, 2004, at 21:36, Bill Mill wrote: > >> > >>>Bill, > >>> > >>>I think you've misunderstood the example; pardon me if I've > >>>misunderstood you in turn, but Kent's dispatcher will run the > >>>functions in the current namespace. No new processes or namespaces > >>>will be created, making your lambda method redundant. > >>> > >>>Peace > >>>Bill Mill > >>>bill.mill at gmail.com > >> > >> I think he meant scope, not namespace. However IIRC lambda functions > >>have their own scope, like normal functions (not 100% sure of that, I > >>never use lambdas), thus the method is redundant either way. > >My main goal had little to do with lamdas or function calls, but the desire >to implement a construct that closely resembles C switch or other >language's case statements. How the exceptions are raised isn't important. >The important thing is using multiple ``except'' sections after a ``try'' >instead of using conditional tests. > >Bill >-- >INTERNET: bill@Celestial.COM Bill Campbell; Celestial Software LLC >UUCP: camco!bill PO Box 820; 6641 E. Mercer Way >FAX: (206) 232-9186 Mercer Island, WA 98040-0820; (206) 236-1676 >URL: http://www.celestial.com/ > >With Congress, every time they make a joke it's a law; and every time >they make a law it's a joke. > -- Will Rogers >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From cyresse at gmail.com Sat Oct 16 00:31:20 2004 From: cyresse at gmail.com (Riumu Kuraku) Date: Sat Oct 16 00:31:23 2004 Subject: [Tutor] email & imaplib for beginners like me In-Reply-To: References: <1ff2dfbf041015093875845d86@mail.gmail.com> Message-ID: On Sat, 16 Oct 2004 11:28:41 +1300, Riumu Kuraku wrote: > With... > x=session.fetch(1, "(RFC822)") > > >>>print x[0] > OK > >>>print x[1] > (All of x except for the 'OK') > > >>>print x[1][0] is the same output as above > > but, >>>print x[1][0][1] gives the full email, relatively laid out.... > print x[1][0][0] gives > 1 (RFC822 {12273} > > >>> print x[1][1] gives me this: > ) > >>> print x[2] give list index out of range. > > So, to clarify my understanding, when I fetch, > I get a tuple of 2 values, x[0], and x[1]. x[0] is the server return > code (Ok, BAD etc.) > and x[1] is the data I fetched, plus an additional code. > > x[1][0]is the full data I feteched + that additional code , x[1][1] is > a closed bracket? Is this normal? > > Then, x[1][0] is divided into two bits,x[1][0][0] which is the code > which is 1 (RFC822){12273}, which is (guessing here) UID, what I > requested and... ? then, > x[1][0][1] is the data without server return codes, or that additional code. > > How am I doing? > > So, for error catching, I check x[0], not sure what I'd use x[1][0][0] > for, if it is the UID, it would be good for keeping track of which > email is where, and x[1][0][1] is what I was trying to fetch. > > Thanks, Michael, and please correct me if my conclusions are erroneous. > /me runs off to re-examine tuples in tutorial. > > (Oh, and those links you posted don't point to live sites, but google > has caches -) > http://www.google.co.nz/search?q=cache:YWgEVsgYXgAJ:aspn.activestate.com/ASPN/Mail/Message/python-Tutor/1619598+&hl=en > http://www.google.co.nz/search?q=cache:4Fr-5SCPsTgJ:aspn.activestate.com/ASPN/Mail/Message/python-Tutor/1619609+&hl=en > > Regards, > > Liam Clarke > > > On Fri, 15 Oct 2004 18:38:36 +0200, Michael Janssen > wrote: > > On Thu, 14 Oct 2004 21:42:59 +1300, Riumu Kuraku wrote: > > > > > Just tryng to understand the email package, and the docs are a > > > little... sparse? > > > > Would be nice to have some more examples in the example section. > > Someone needs to write them ... > > > > > a=test.fetch(1, 'RFC822' )... The first argument of fetch is fine. > > > It's the second that's got me. It's a name of a Internet standard. And > > > I used it on three different emails, and it got two headers, and one > > > header and full text. So I am quite confused as to how exactly to get > > > specific things, like headers/text/attachments only, so any light that > > > can be shed in that regard would be fantastic. > > > > some time past, but googles knows it: > > http://aspn.activestate.com/ASPN/Mail/Message/python-Tutor/1619598 > > > > and: > > http://aspn.activestate.com/ASPN/Mail/Message/python-Tutor/1619609 > > > > To quote myself: > > "rfc3501 section 6.4.4 lists all possibilities" > > > > --> section 6.4.5 lists all possibilities of the fetch command. > > > > That's the point the the imaplib docs: you *need* to read the rfc's to > > get them (imaplib docs should state this ...). > > > > > >>>print j.parse(x) > > > AttributeError: 'tuple' object has no attribute 'readline' > > > > > > #OK, so x is a tuple, and it has no attr, readline...hmmm... > > > > it's a tuple of the server returncode ("OK") and a list of messages > > (which are tuples in turn). > > > > x[1] # list of messages > > x[1][0] # first one > > x[1][0][1] # content of first one. That's bad, eh? > > > > > #Run off to docs, and open parser.py to have a look and: > > > > > > >>>print j.parsestr(x) #Turns out, Parser.parse() is for file > > > objects... Parser.parsestr() > > > # is for string objects, as I am about to learn. > > > > > > TypeError: expected read buffer, tuple found > > > > > > #Still not liking tuple. Hmmm... > > > > > >>>i=str(x) > > > >>>print j.parsestr(i) > > > > converting the whole tuple into a string, poor parser is confused by > > all those brackets and 'OK' messages. So it will "parse" message > > without extracting much information from it. > > > > try something like: > > > > msg = x[1][0][1] > > print msg > > > > or: > > print j.parsestr(msg) > > > > regards > > Michael > > > From cyresse at gmail.com Sat Oct 16 00:34:27 2004 From: cyresse at gmail.com (Riumu Kuraku) Date: Sat Oct 16 00:34:31 2004 Subject: [Tutor] Find out if a number is even or not In-Reply-To: <5.1.0.14.2.20041015144947.059e48a0@mail.30below.com> References: <1097838018.416fadc261290@webmail.freedom2surf.net> <5.1.0.14.2.20041015144947.059e48a0@mail.30below.com> Message-ID: Hehe, yeah, it was a roughy, I've only been doing this for one week myself. the first assignment of 0 is just me being paranoid about non-assigned variables, and I've still got to comprehend 'if not' statements. Regards, Liam Clarke On Fri, 15 Oct 2004 14:56:09 -0400, Roger Merchberger wrote: > Rumor has it that Riumu Kuraku may have mentioned these words: > >[snip] > >Be cool and write your own function for this... > > > >def OddorEven(x): > >a=0 > >a=x % 2 > >if a ==0: > > return "Even" > >else: > > eturn "Odd" > > Just to let you know: > > The first assignment of 0 to a seems superfluous as you're reassigning it > in the very next statement; and just to show others a different way of > coding this... > > def OddorEven(x): > a=x % 2 > if a: > return "Odd" > else: > return "Even" > > [[ Oh, and your indentation was a schootch off... ;-) ]] > > HTH, > Roger "Merch" Merchberger > > -- > Roger "Merch" Merchberger | JC: "Like those people in Celeronville!" > sysadmin, Iceberg Computers | Me: "Don't you mean Silicon Valley???" > zmerch@30below.com | JC: "Yea, that's the place!" > | JC == Jeremy Christian > > _______________________________________________ > > > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld at freenet.co.uk Sat Oct 16 00:51:37 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat Oct 16 00:51:35 2004 Subject: [Tutor] Find out if a number is even or not References: <1097838018.416fadc261290@webmail.freedom2surf.net><1097838018.416fadc261290@webmail.freedom2surf.net> <5.1.0.14.2.20041015144947.059e48a0@mail.30below.com> Message-ID: <006b01c4b309$873ff610$d79b8851@xp> > >def OddorEven(x): > >a=0 > >a=x % 2 > >if a ==0: > > return "Even" > >else: > > return "Odd" I may have missed this one earlier but an obvious shortner here is: def OddorEven(x): return x % 2 and 'Even' or 'Odd' But IMHO better still is to turn it into a true predicate: def isOdd(x): return x%2 So we get a boolean result and can display a suitable message outside the function. Keeping presentation away from logic is nearly always the right thing... Alan G. From alan.gauld at freenet.co.uk Sat Oct 16 00:58:15 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat Oct 16 00:58:19 2004 Subject: [Tutor] using exceptions to implement case/switch? References: <20041015165606.GA19744@alexis.mi.celestial.com> Message-ID: <007001c4b30a$74d77a60$d79b8851@xp> > case parts when special keys are hit. Rather than doing this with a set of > ``if'' statements, this could be done using exceptions, perhaps as in the > code below. But you are using if statement anyway - the worst of both worlds. The normal way would be a chain of elif statement. > if ascii.isprint(c) : return c > if c == curses.KEY_F1 : raise keyf1 if c == curses.KEY_F1: process_keyF1() elif c == curses.KEY_F2: process_keyF2() Or more efficiently still, put the key/functon pairs in a dictionary: keys = { curses.KEY_F1: process_keyF1, curses.KEY_F2: process_keyF2, ... } # code as before until: if ascii.isprint(c) : return c try: keys[c]() except KeyError: print 'No such key' HTH, Alan G. From dyoo at hkn.eecs.berkeley.edu Sat Oct 16 01:39:07 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat Oct 16 01:39:11 2004 Subject: [Tutor] META: Tutor is set not to munge reply-to In-Reply-To: <087EF7AE-1EEC-11D9-994D-000393CBC88E@yahoo.fr> Message-ID: On Fri, 15 Oct 2004, Max Noel wrote: > (sigh... Forgot to click "reply to all". It'd be more practical if that > list set a reply-to header IMO...) Hi Max, Yes, but there are good reasons for not munging the reply-to headers: http://www.unicom.com/pw/reply-to-harmful.html So I hope that makes sense why we keep the mailing list on the default non-munging settings. Good luck to you! From eric at digitalert.net Sat Oct 16 02:17:56 2004 From: eric at digitalert.net (Eric) Date: Sat Oct 16 02:17:32 2004 Subject: [Tutor] How to watch a changing list, and wait for a certain value to leave? In-Reply-To: <416F7A3A.7050906@digitalert.net> References: <000c01c4b27d$78437740$49108aca@jason> <416F7A3A.7050906@digitalert.net> Message-ID: <417068B4.80803@digitalert.net> Eric wrote: > I got some help here before with this program I have started to write, > and I am hung up on something again. Anyway I'm trying to write a > simple program that will watch for a connection to be made by a > certain host, sound the system bell when the connection is made, and > then when the connection is closed have the system bell sound again. > Then loop back to the beginning and start watching again. Here is the > only working part I have so far... > > > import os > import time > > connected = False > > while not connected: > o=os.popen("netstat -an") > for l in o: > try: > if l.split()[1].endswith("192.168.0.250:21"): > print "\a\a\a\a\aMatch!" > connected = True > else: > print "Nothing" except IndexError: > print "Index Exception" > time.sleep(1) > > > That works just like I want it to however now I need to figure out a > way to know when the host disconnects. I have tried to use count() > function in conjunction with the less than operator to wait till > "192.168.0.250:21" is <1 , but can't seem to get it right. Can anyone > give me a hint, but not write the entire thing for me, or maybe give > me some insite on a better way to do this? > > Thanks > I got it working.. import os import time connected = False while not connected: o=os.popen("netstat -an") for l in o: try: if l.split()[1].endswith("192.168.0.250:21"): print "\a\a\a\a\aMatch!" connected = True else: print "Nothing" except IndexError: print "Index Exception" time.sleep(1) amount=0 while connected: o=os.popen("netstat -an") for l in o: try: if l.split()[1].endswith("192.168.0.250:21"): print "Still There" connected = True amount +=1 print amount else: print "Nothing" except IndexError: print "Index Exception" time.sleep(1) if amount == 1: amount -=1 else: print "It's Gone" connected = False print "\a\a" raw_input("Press Enter to close") From carroll at tjc.com Sat Oct 16 02:40:06 2004 From: carroll at tjc.com (Terry Carroll) Date: Sat Oct 16 02:40:09 2004 Subject: [Tutor] META: Tutor is set not to munge reply-to In-Reply-To: Message-ID: On Fri, 15 Oct 2004, Danny Yoo wrote: > Yes, but there are good reasons for not munging the reply-to headers: I like the munging, so I do it myself in procmail. From maxnoel_fr at yahoo.fr Sat Oct 16 02:41:43 2004 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Sat Oct 16 02:41:49 2004 Subject: [Tutor] Re: META: Tutor is set not to munge reply-to In-Reply-To: References: Message-ID: <26CE0636-1F0C-11D9-98C9-000393CBC88E@yahoo.fr> On Oct 16, 2004, at 00:39, Danny Yoo wrote: > Hi Max, > > Yes, but there are good reasons for not munging the reply-to headers: > > http://www.unicom.com/pw/reply-to-harmful.html > > So I hope that makes sense why we keep the mailing list on the default > non-munging settings. Yeah, that article makes some good points. It's just a matter of habit, I guess... All the other mailing lists I'm on use the Reply-to header, so I guess I was expecting all the lists in the world to work in that fashion, not because that's the optimal way (it isn't) but because that's what I'm used to. Lemming syndrome. And to think I spend my days bashing others because of that. :p -- Wild_Cat maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From kent_johnson at skillsoft.com Sat Oct 16 04:25:18 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Sat Oct 16 04:25:24 2004 Subject: [Tutor] How to watch a changing list, and wait for a certain value to leave? In-Reply-To: <417068B4.80803@digitalert.net> References: <000c01c4b27d$78437740$49108aca@jason> <416F7A3A.7050906@digitalert.net> <417068B4.80803@digitalert.net> Message-ID: <6.1.0.6.0.20041015221015.0289a8d8@mail4.skillsoft.com> Eric, You have a lot of duplicated code between the two loops. One way to avoid this is by making a function: def isConnected(): connected = False o=os.popen("netstat -an") for l in o: try: if l.split()[1].endswith("192.168.0.250:21"): connected = True except IndexError: then your main program will look something like this: connected = isConnected() while not connected: print 'Not connected' sleep(1) connected = isConnected() while connected: print 'Still there' sleep(1) connected = isConnected() print "It's gone" Kent At 08:17 PM 10/15/2004 -0400, Eric wrote: >Eric wrote: > >>I got some help here before with this program I have started to write, >>and I am hung up on something again. Anyway I'm trying to write a simple >>program that will watch for a connection to be made by a certain host, >>sound the system bell when the connection is made, and then when the >>connection is closed have the system bell sound again. Then loop back to >>the beginning and start watching again. Here is the only working part I >>have so far... >> >> >>import os >>import time >> >>connected = False >> >>while not connected: >> o=os.popen("netstat -an") >> for l in o: >> try: >> if l.split()[1].endswith("192.168.0.250:21"): >> print "\a\a\a\a\aMatch!" >> connected = True >> else: >> print "Nothing" except IndexError: >> print "Index Exception" >> time.sleep(1) >> >> >>That works just like I want it to however now I need to figure out a way >>to know when the host disconnects. I have tried to use count() function >>in conjunction with the less than operator to wait till >>"192.168.0.250:21" is <1 , but can't seem to get it right. Can anyone >>give me a hint, but not write the entire thing for me, or maybe give me >>some insite on a better way to do this? >> >>Thanks > > >I got it working.. > > >import os >import time > >connected = False > >while not connected: > o=os.popen("netstat -an") > for l in o: > try: > if l.split()[1].endswith("192.168.0.250:21"): > print "\a\a\a\a\aMatch!" > connected = True > else: > print "Nothing" > except IndexError: > print "Index Exception" > time.sleep(1) > > >amount=0 >while connected: > o=os.popen("netstat -an") > for l in o: > try: > if l.split()[1].endswith("192.168.0.250:21"): > print "Still There" > connected = True > amount +=1 > print amount > else: > print "Nothing" > except IndexError: > print "Index Exception" > time.sleep(1) > if amount == 1: > amount -=1 > else: > print "It's Gone" > connected = False > > > >print "\a\a" >raw_input("Press Enter to close") >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From chandrakirti at gmail.com Sat Oct 16 05:09:45 2004 From: chandrakirti at gmail.com (Lloyd Hugh Allen) Date: Sat Oct 16 05:09:48 2004 Subject: [Tutor] Find out if a number is even or not In-Reply-To: <1097838018.416fadc261290@webmail.freedom2surf.net> References: <1097838018.416fadc261290@webmail.freedom2surf.net> Message-ID: <24d253d904101520094f73a206@mail.gmail.com> There's also the bitwise & operation def isEvenQ(num): return not (num & 1) don't know if it's actually faster though. On Fri, 15 Oct 2004 12:00:18 +0100, nick@javacat.f2s.com wrote: > Hi group, > > Im sure this is simple to do, but Ive just been looking through the python docs > and the archive of this mailing list and cant find what Im after. > > I just want to know if a number is even or not. > > I've had a look at the math package but that doesnt seem to have anything this > simple in it. > > I thought something like > > >>> if 10 div 2 == 0 : print 'even' > >>> else : print 'odd' > > but obviously that doesnt work. > > Sorry for such a basic question, but I really cant find out how to do this. > > Kind regards > Nick. > > ------------------------------------------------- > Everyone should have http://www.freedom2surf.net/ > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From cyresse at gmail.com Sat Oct 16 05:12:33 2004 From: cyresse at gmail.com (Riumu Kuraku) Date: Sat Oct 16 05:12:36 2004 Subject: [Tutor] Find out if a number is even or not In-Reply-To: <006b01c4b309$873ff610$d79b8851@xp> References: <1097838018.416fadc261290@webmail.freedom2surf.net> <5.1.0.14.2.20041015144947.059e48a0@mail.30below.com> <006b01c4b309$873ff610$d79b8851@xp> Message-ID: I don't quite understand the syntax of return x % 2 and 'Even' or 'Odd'... so if x > 0 it should return x and 'Odd', but if x is 0 then it returns 0 and 'Even'? How does that work? I can see how your isOdd function works, if x divides by 2 with no remainder, then isOdd(x) is False. I'm having trouble understanding conditionals, like... if x: So if x is... what exactly? Is it checking for a non-null or non-zero value? Or if not x:.... Can anyone recommend a link that goes into details on if & while statements, and the various checks? Regards, Liam Clarke On Fri, 15 Oct 2004 23:51:37 +0100, Alan Gauld wrote: > > >def OddorEven(x): > > >a=0 > > >a=x % 2 > > >if a ==0: > > > return "Even" > > >else: > > > return "Odd" > > I may have missed this one earlier but an obvious shortner > here is: > > def OddorEven(x): > return x % 2 and 'Even' or 'Odd' > > But IMHO better still is to turn it into a true predicate: > > def isOdd(x): > return x%2 > > So we get a boolean result and can display a suitable message > outside the function. Keeping presentation away from logic is > nearly always the right thing... > > Alan G. > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From cyresse at gmail.com Sat Oct 16 05:16:51 2004 From: cyresse at gmail.com (Riumu Kuraku) Date: Sat Oct 16 05:16:54 2004 Subject: [Tutor] python 2.3.4 GUI In-Reply-To: <24d253d9041015051946aae209@mail.gmail.com> References: <000701c4b299$aeef5f40$6500a8c0@p933> <24d253d9041015051946aae209@mail.gmail.com> Message-ID: I think if you're trying to call a Tkinter GUI from IDLE it messes up, because IDLE is a Tk GUI itself, so the mainloop()'s collide. Well, that's my understanding, try calling the GUI from the dox box python, and it'll work fine. IDLE it won't. On Fri, 15 Oct 2004 08:19:05 -0400, Lloyd Hugh Allen wrote: > Do you have any other programming languages installed on your > computer, particularly any that use Tk/TCL? Installing Ruby broke my > Python a few years ago, because Ruby had screwed with all the Tk/TCL > stuff. I submitted this as an issue to both Python and Ruby, and got > responses of "it's not OUR fault" from both sides. > > And then the Ruby uninstaller didn't clean up after itself. Messy situation. > > In the absence of other programming languages, I would try cleanly > uninstalling all versions of Python, and then reinstalling the most > recent one. > > > > On Fri, 15 Oct 2004 11:30:21 +0200, gil@tuckers.de wrote: > > > > > > Hi greetings, > > I am running Win 2000. When I download Python 2.2 and higher > > and I call the GUI it doesn`t come. The command line is okay the IDLE refuse to > > respond. Some tip or tips could be welcome. > > cheers gil > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld at freenet.co.uk Sat Oct 16 09:47:12 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat Oct 16 09:47:10 2004 Subject: [Tutor] Find out if a number is even or not References: <1097838018.416fadc261290@webmail.freedom2surf.net><5.1.0.14.2.20041015144947.059e48a0@mail.30below.com><006b01c4b309$873ff610$d79b8851@xp> Message-ID: <00a601c4b354$5979b630$d79b8851@xp> > I don't quite understand the syntax of > > return x % 2 and 'Even' or 'Odd'... This is fully exlained in my tutorial on the Functional Programming topic, but the short answer is: x % 2 and 'Even' or 'Odd'... Can be written: ((x%2) and 'Even') or 'Odd') This is a boolean expression. Python works out the first term, x%2 and of it is true looks at the second term in the AND expression, 'Even'. Since 'Even' is true (only empty strings are considered false) the whole AND expression is True and because it is True Python doesn't need to evaluate the second part of the OR expression so it returns the True part of the AND expression. And here is the trick. Python doesn't return an actual boolean value (True or False), instead it returns the actual value it last tested, in this case the string 'Even'. If x%2 is 0 and thus False in boolean terms the whole AND expression must be false. So Python now evaluates the second part of the OR expression, 'Odd'. Again this string is True boolean-wise, so Python returns the last True value, namely the string 'Odd'. So the actual return value from the overall expression is 'Even' if x%2 is true and 'Odd' if x%2 is False. This is not intuitively obvious but the tutorial page gives several more examples to illustrate how it works. In this case I thing the functional form works quite well because it kind of makes sense (to me anyway!) to say the function returns 'Even' or 'Odd' > I'm having trouble understanding conditionals, like... if x: So if x > is... what exactly? Is it checking for a non-null or non-zero value? > Or if not x:.... if x: is siply shorthand for saying if x == True: And the logical equivalent to True depends on the data type. Normally it is whatever comes closest in meaning to not being 'empty'. Thus for numbers it means not being zero, for sequences it really is not being empty, for files it means the file is open and readable - ie we aren't at the end. There is a page in the Python documentation that decribes for each type the boolean equivalents. I think its in the reference manual. HTH, Alan G. From cyresse at gmail.com Sat Oct 16 10:47:49 2004 From: cyresse at gmail.com (Liam Clarke) Date: Sat Oct 16 10:47:52 2004 Subject: [Tutor] Find out if a number is even or not In-Reply-To: <00a601c4b354$5979b630$d79b8851@xp> References: <1097838018.416fadc261290@webmail.freedom2surf.net> <5.1.0.14.2.20041015144947.059e48a0@mail.30below.com> <006b01c4b309$873ff610$d79b8851@xp> <00a601c4b354$5979b630$d79b8851@xp> Message-ID: Ah sorry, I haven't got to the functional programming bit yet. So, that would mean 'if not x' is shorthand for 'if x is False' or 'if x == 0' so, any expression, say, if a - 10: if a - 10 doesn't equal zero, then it's true. and the x % 2 and 'Even' or 'Odd' thing is nifty.. That shines a ray of light on it for me, Thanks. On Sat, 16 Oct 2004 08:47:12 +0100, Alan Gauld wrote: > > > I don't quite understand the syntax of > > > > return x % 2 and 'Even' or 'Odd'... > > This is fully exlained in my tutorial on the Functional Programming > topic, but the short answer is: > > x % 2 and 'Even' or 'Odd'... > > Can be written: > > ((x%2) and 'Even') or 'Odd') > > This is a boolean expression. > > Python works out the first term, x%2 and of it is true looks at > the second term in the AND expression, 'Even'. Since 'Even' is true > (only empty strings are considered false) the whole AND expression > is True and because it is True Python doesn't need to evaluate the > second part of the OR expression so it returns the True part of the > AND expression. > > And here is the trick. Python doesn't return an actual boolean value > (True or False), instead it returns the actual value it last tested, > in this case the string 'Even'. > > If x%2 is 0 and thus False in boolean terms the whole AND expression > must be false. So Python now evaluates the second part of the OR > expression, 'Odd'. Again this string is True boolean-wise, so Python > returns the last True value, namely the string 'Odd'. > > So the actual return value from the overall expression is 'Even' > if x%2 is true and 'Odd' if x%2 is False. > > This is not intuitively obvious but the tutorial page gives several > more examples to illustrate how it works. In this case I thing the > functional form works quite well because it kind of makes sense > (to me anyway!) to say the function returns 'Even' or 'Odd' > > > I'm having trouble understanding conditionals, like... if x: So if > x > > is... what exactly? Is it checking for a non-null or non-zero value? > > Or if not x:.... > > if x: > > is siply shorthand for saying > > if x == True: > > And the logical equivalent to True depends on the data type. > Normally it is whatever comes closest in meaning to not > being 'empty'. Thus for numbers it means not being zero, > for sequences it really is not being empty, for files it > means the file is open and readable - ie we aren't at the end. > > There is a page in the Python documentation that decribes > for each type the boolean equivalents. I think its in the > reference manual. > > HTH, > > Alan G. > > From cyresse at gmail.com Sat Oct 16 13:38:48 2004 From: cyresse at gmail.com (Liam Clarke) Date: Sat Oct 16 13:38:53 2004 Subject: [Tutor] email & imaplib for beginners like me In-Reply-To: References: <1ff2dfbf041015093875845d86@mail.gmail.com> Message-ID: Hello again, One last niggle. I've managed to download a MIME multi-part, and successfully decode an attachment, so thanks for all your help. I'm just having trouble trying to get a specific header field : - I can't find any examples, but this is what I'm trying - (a, b)=session.fetch(5, '(BODY[HEADER.FIELDS[FROM]])'' ) and variants thereof (of all 4 bracket sets), all involving FROM being in brackets after HEADER.FIELDS, as I get this error : ['Missing required open parenthesis in Fetch BODY[HEADER.FIELDS'] Normal error is this FETCH command error: BAD ['Invalid body section'] So yeah, getting mildly frustrated with precise syntaxes (syntaxii?), RFC 2822 and 3501 aren't hugely helpful on precise locations of brackets. >From RFC 3501: in BODY HEADER.FIELDS and HEADER.FIELDS.NOT are followed by a list of field-name (as defined in [RFC-2822]) names, and return a subset of the header. ... Thanks in advance for your time. Liam Clarke On Sat, 16 Oct 2004 11:31:20 +1300, Riumu Kuraku wrote: > On Sat, 16 Oct 2004 11:28:41 +1300, Riumu Kuraku wrote: > > > > With... > > x=session.fetch(1, "(RFC822)") > > > > >>>print x[0] > > OK > > >>>print x[1] > > (All of x except for the 'OK') > > > > >>>print x[1][0] is the same output as above > > > > but, >>>print x[1][0][1] gives the full email, relatively laid out.... > > print x[1][0][0] gives > > 1 (RFC822 {12273} > > > > >>> print x[1][1] gives me this: > > ) > > >>> print x[2] give list index out of range. > > > > So, to clarify my understanding, when I fetch, > > I get a tuple of 2 values, x[0], and x[1]. x[0] is the server return > > code (Ok, BAD etc.) > > and x[1] is the data I fetched, plus an additional code. > > > > x[1][0]is the full data I feteched + that additional code , x[1][1] is > > a closed bracket? Is this normal? > > > > Then, x[1][0] is divided into two bits,x[1][0][0] which is the code > > which is 1 (RFC822){12273}, which is (guessing here) UID, what I > > requested and... ? then, > > x[1][0][1] is the data without server return codes, or that additional code. > > > > How am I doing? > > > > So, for error catching, I check x[0], not sure what I'd use x[1][0][0] > > for, if it is the UID, it would be good for keeping track of which > > email is where, and x[1][0][1] is what I was trying to fetch. > > > > Thanks, Michael, and please correct me if my conclusions are erroneous. > > /me runs off to re-examine tuples in tutorial. > > > > (Oh, and those links you posted don't point to live sites, but google > > has caches -) > > http://www.google.co.nz/search?q=cache:YWgEVsgYXgAJ:aspn.activestate.com/ASPN/Mail/Message/python-Tutor/1619598+&hl=en > > http://www.google.co.nz/search?q=cache:4Fr-5SCPsTgJ:aspn.activestate.com/ASPN/Mail/Message/python-Tutor/1619609+&hl=en > > > > Regards, > > > > Liam Clarke > > > > > > On Fri, 15 Oct 2004 18:38:36 +0200, Michael Janssen > > wrote: > > > On Thu, 14 Oct 2004 21:42:59 +1300, Riumu Kuraku wrote: > > > > > > > Just tryng to understand the email package, and the docs are a > > > > little... sparse? > > > > > > Would be nice to have some more examples in the example section. > > > Someone needs to write them ... > > > > > > > a=test.fetch(1, 'RFC822' )... The first argument of fetch is fine. > > > > It's the second that's got me. It's a name of a Internet standard. And > > > > I used it on three different emails, and it got two headers, and one > > > > header and full text. So I am quite confused as to how exactly to get > > > > specific things, like headers/text/attachments only, so any light that > > > > can be shed in that regard would be fantastic. > > > > > > some time past, but googles knows it: > > > http://aspn.activestate.com/ASPN/Mail/Message/python-Tutor/1619598 > > > > > > and: > > > http://aspn.activestate.com/ASPN/Mail/Message/python-Tutor/1619609 > > > > > > To quote myself: > > > "rfc3501 section 6.4.4 lists all possibilities" > > > > > > --> section 6.4.5 lists all possibilities of the fetch command. > > > > > > That's the point the the imaplib docs: you *need* to read the rfc's to > > > get them (imaplib docs should state this ...). > > > > > > > >>>print j.parse(x) > > > > AttributeError: 'tuple' object has no attribute 'readline' > > > > > > > > #OK, so x is a tuple, and it has no attr, readline...hmmm... > > > > > > it's a tuple of the server returncode ("OK") and a list of messages > > > (which are tuples in turn). > > > > > > x[1] # list of messages > > > x[1][0] # first one > > > x[1][0][1] # content of first one. That's bad, eh? > > > > > > > #Run off to docs, and open parser.py to have a look and: > > > > > > > > >>>print j.parsestr(x) #Turns out, Parser.parse() is for file > > > > objects... Parser.parsestr() > > > > # is for string objects, as I am about to learn. > > > > > > > > TypeError: expected read buffer, tuple found > > > > > > > > #Still not liking tuple. Hmmm... > > > > > > > >>>i=str(x) > > > > >>>print j.parsestr(i) > > > > > > converting the whole tuple into a string, poor parser is confused by > > > all those brackets and 'OK' messages. So it will "parse" message > > > without extracting much information from it. > > > > > > try something like: > > > > > > msg = x[1][0][1] > > > print msg > > > > > > or: > > > print j.parsestr(msg) > > > > > > regards > > > Michael > > > > > > From bill.mill at gmail.com Sat Oct 16 15:06:55 2004 From: bill.mill at gmail.com (Bill Mill) Date: Sat Oct 16 15:06:58 2004 Subject: [Tutor] Find out if a number is even or not In-Reply-To: <00a601c4b354$5979b630$d79b8851@xp> References: <1097838018.416fadc261290@webmail.freedom2surf.net> <5.1.0.14.2.20041015144947.059e48a0@mail.30below.com> <006b01c4b309$873ff610$d79b8851@xp> <00a601c4b354$5979b630$d79b8851@xp> Message-ID: <797fe3d404101606063896301f@mail.gmail.com> So, shouldn't that piece of code be: return x%2 and 'Odd' or 'Even' to make it semantically correct? As it is, it returns 'Odd' for even numbers, and vice versa. Peace Bill Mill On Sat, 16 Oct 2004 08:47:12 +0100, Alan Gauld wrote: > > > I don't quite understand the syntax of > > > > return x % 2 and 'Even' or 'Odd'... > > This is fully exlained in my tutorial on the Functional Programming > topic, but the short answer is: > > x % 2 and 'Even' or 'Odd'... > > Can be written: > > ((x%2) and 'Even') or 'Odd') > > This is a boolean expression. > > Python works out the first term, x%2 and of it is true looks at > the second term in the AND expression, 'Even'. Since 'Even' is true > (only empty strings are considered false) the whole AND expression > is True and because it is True Python doesn't need to evaluate the > second part of the OR expression so it returns the True part of the > AND expression. > > And here is the trick. Python doesn't return an actual boolean value > (True or False), instead it returns the actual value it last tested, > in this case the string 'Even'. > > If x%2 is 0 and thus False in boolean terms the whole AND expression > must be false. So Python now evaluates the second part of the OR > expression, 'Odd'. Again this string is True boolean-wise, so Python > returns the last True value, namely the string 'Odd'. > > So the actual return value from the overall expression is 'Even' > if x%2 is true and 'Odd' if x%2 is False. > > This is not intuitively obvious but the tutorial page gives several > more examples to illustrate how it works. In this case I thing the > functional form works quite well because it kind of makes sense > (to me anyway!) to say the function returns 'Even' or 'Odd' > > > I'm having trouble understanding conditionals, like... if x: So if > x > > is... what exactly? Is it checking for a non-null or non-zero value? > > Or if not x:.... > > if x: > > is siply shorthand for saying > > if x == True: > > And the logical equivalent to True depends on the data type. > Normally it is whatever comes closest in meaning to not > being 'empty'. Thus for numbers it means not being zero, > for sequences it really is not being empty, for files it > means the file is open and readable - ie we aren't at the end. > > There is a page in the Python documentation that decribes > for each type the boolean equivalents. I think its in the > reference manual. > > HTH, > > > > Alan G. > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From kent_johnson at skillsoft.com Sat Oct 16 17:32:33 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Sat Oct 16 17:32:40 2004 Subject: [Tutor] python 2.3.4 GUI In-Reply-To: References: <000701c4b299$aeef5f40$6500a8c0@p933> <24d253d9041015051946aae209@mail.gmail.com> Message-ID: <6.1.0.6.0.20041016113005.028e30b0@mail4.skillsoft.com> This problem was fixed in python 2.3 (when idle-fork was folded in to the main distribution) Kent At 04:16 PM 10/16/2004 +1300, Riumu Kuraku wrote: >I think if you're trying to call a Tkinter GUI from IDLE it messes up, >because IDLE is a Tk GUI itself, so the mainloop()'s collide. > >Well, that's my understanding, try calling the GUI from the dox box >python, and it'll work fine. IDLE it won't. > > >On Fri, 15 Oct 2004 08:19:05 -0400, Lloyd Hugh Allen > wrote: > > Do you have any other programming languages installed on your > > computer, particularly any that use Tk/TCL? Installing Ruby broke my > > Python a few years ago, because Ruby had screwed with all the Tk/TCL > > stuff. I submitted this as an issue to both Python and Ruby, and got > > responses of "it's not OUR fault" from both sides. > > > > And then the Ruby uninstaller didn't clean up after itself. Messy > situation. > > > > In the absence of other programming languages, I would try cleanly > > uninstalling all versions of Python, and then reinstalling the most > > recent one. > > > > > > > > On Fri, 15 Oct 2004 11:30:21 +0200, gil@tuckers.de wrote: > > > > > > > > > Hi greetings, > > > I am running Win 2000. When I download > Python 2.2 and higher > > > and I call the GUI it doesn`t come. The command line is okay the > IDLE refuse to > > > respond. Some tip or tips could be welcome. > > > cheers gil > > > > > > _______________________________________________ > > > Tutor maillist - Tutor@python.org > > > http://mail.python.org/mailman/listinfo/tutor > > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From davholla2002 at yahoo.co.uk Sat Oct 16 17:32:44 2004 From: davholla2002 at yahoo.co.uk (David Holland) Date: Sat Oct 16 17:32:46 2004 Subject: [Tutor] Problems with GUI calling a class In-Reply-To: <20041016100031.0E45E1E403D@bag.python.org> Message-ID: <20041016153244.17494.qmail@web25404.mail.ukl.yahoo.com> I wrote a program to calculate the likely result of a one day cricket match and then decided to make it into a class and have another class for a GUI. It all works well but I can not call the function from the first class from the GUI class, insteading of returning a result it just gives this error 'Exception in Tkinter callback Traceback (most recent call last): File "/usr/lib/python2.3/lib-tk/Tkinter.py", line 1345, in __call__ return self.func(*args) File "/home/david/Documents/pyprogramming/cricketv6.py", line 194, in cricket_getinfo self.results_txt.insert(0.0,results) UnboundLocalError: local variable 'results' referenced before assignment ' This is the code which create the GUI and if it worked would call the calculations. def cricket_getinfo(self): """Get values from the GUI and submit for calculation""" print "test" runs = self.runs_ent.get() wickets = self.wickets_ent.get() overs = self.overs_ent.get() if self.yes_no.get(): used_before = 'Y' else: used_before = 'N' Cricketobj = Cricket() #create code to call the calculations z = 50 win = 10 if self.yes_no == 'N': win = 10 originalscore = 0 wold = 0 yold = 0 results = Cricketobj.runfuns(wickets,overs,runs,z, win, originalscore, orignovoers, wold, yold) print results elif self.yes_no == 'Y': #get the data from last time xold, yold, wold = openlasttime() #now we are calculating using the more up to date run rate orignovoers = y runs = int(runs) xold = int(xold) x = x - xold overs = int(overs) - int(yold) wickets = int(wickets) - int(wold) wold = int(wold) win = 10 z = 50 results = Cricketobj.runfuns(wickets,overs,runs,z, win, originalscore, orignovoers, wold, yold)#(w,y,x,z,win, xold, orignovoers, wold, yold) #the line below is causing it crash #results = 1 self.results_txt.insert(0.0,results) Cricketobj.savecurrentstate(runs,overs,wickets) Can anyone see why I am not calling the class's function properly ? Thanks in advance. David ___________________________________________________________ALL-NEW Yahoo! Messenger - all new features - even more fun! http://uk.messenger.yahoo.com From davholla2002 at yahoo.co.uk Sat Oct 16 17:37:32 2004 From: davholla2002 at yahoo.co.uk (David Holland) Date: Sat Oct 16 17:37:35 2004 Subject: [Tutor] Cricket predictor In-Reply-To: <20041016100031.0E45E1E403D@bag.python.org> Message-ID: <20041016153732.97376.qmail@web25407.mail.ukl.yahoo.com> Here is the code for the whole programme #predicts the result of a limited over cricket match based on current score #aim to modify it so that everytime it is run it looks at the last time and #takes in account the changes from Tkinter import * class Cricket: def numberofballs(y): """Convert overs to number of balls so far""" y = float(y) b = int(y) numberofballsinthisover = (y-b)*10 numberofballsbefore = b*6 totalnumberofballs = numberofballsinthisover + numberofballsbefore return totalnumberofballs def scoreperball(x,y): """Runs per ball""" #x is the score x = float(x) y = float(x) runsperball = x/y return runsperball def ifnotout(y,z): #y score per ball #z number of overs in game z = z * 6 a = y * z a = int(a) return a def ifallout(x,w): #predicts score if they will not last z overs #x is the score per ball #w is number of balls to get them out b = x * w b = int(b) return b def willsurvive(w,y,z, wold, yold): #will they survive to z overs #w number of wickets so far #y how many balls so far w = float(w) y = float(y) #how many balls to get a wicket wlost = y/w #numberofballs to get them allout if this the first time we look at all 10 wickets #the second just the number of wickets that were running that time allout = ((10 - wold) * wlost) + yold numballsingame = z * 6 if allout < numballsingame: alloutearly = allout else: alloutearly = 0 return alloutearly #create a function to run all functions def runfuns(self, w,y,x,z, win, originalscore, orignoovers, wold, yold): """This is to get all functions to run""" numberofovers = orignoovers y = numberofballs(y) runsperball = scoreperball(x,y) #see if they will survive z overs alloutearly = willsurvive(w,y,z, wold, yold) if alloutearly == 0: a = ifnotout(runsperball,z) resulttext = "Predicted score is", a + originalscore else: b = ifallout(runsperball,alloutearly) resulttext = "Predicted score is all out for ", b + originalscore #create a number of number of wickets now + 5 numberofoversnexttime = numberofovers +5 resulttext = resulttext + "Please wait until", numberofoversnexttime, "overs have been played before using this again" return resulttext print "Line 85" def savecurrentstate(x,y,w): listcurrentstate = [x,y,w] #save x score, y number of overs, w number of wickets pickle_file = open("cricket1.dat","w") cPickle.dump(listcurrentstate, pickle_file) pickle_file.close() def openlasttime(): """Get the state of play last time""" try: pickle_file = open("cricket1.dat", "r") #print "line 86 okay" laststateofplay = cPickle.load(pickle_file) #print "line 88 okay" except: print "I am sorry but I could not open this file so not using the old values" laststateofplay = [0,0,0] xold = laststateofplay[0] #print "line 90 okay " yold = laststateofplay[1] #print "line 92 okay" wold = laststateofplay[2] #print "line 94 okay" return xold, yold, wold class CricketGUI(Frame): """GUI to enter the info for the cricket class""" def __init__(self, master): """Initiliaze Frame.""" Frame.__init__(self, master) self.grid() self.create_widgets() def create_widgets(self): #create runs label self.runs_lbl = Label(self, text = "Enter the number of runs") self.runs_lbl.grid(row = 0, column = 0, columnspan = 2, sticky = W) #create overs label self.overs_lbl = Label(self, text = "Enter the number of overs") self.overs_lbl.grid(row = 1, column = 0, columnspan = 2, sticky = W) #create wickets label self.wickets_lbl = Label(self, text = "Enter the number of wickets") self.wickets_lbl.grid(row = 2, column = 0, columnspan = 2, sticky = W) #create results label self.result_lbl = Label(self, text = "The result is") self.result_lbl.grid(row = 5, column = 0, columnspan = 2, sticky = W) #create entry to put in number of runs self.runs_ent = Entry(self) self.runs_ent.grid(row=0, column = 1, columnspan = 2, sticky = W) #create entry to put in number of overs self.overs_ent = Entry(self) self.overs_ent.grid(row=1, column = 1, columnspan = 2, sticky = W) #create entry to put in number of wickets self.wickets_ent = Entry(self) self.wickets_ent.grid(row=2, column = 1, columnspan = 2, sticky = W) #create checkbutton to see if he they have done it before for this game self.yes_no = BooleanVar() Checkbutton(self, text ="Have you used this before for this game, click if yes otherwise leave blank", variable = self.yes_no).grid(row = 3, column = 0, sticky = W) #need to create a submit button Button(self, text = "Click for result", command = self.cricket_getinfo).grid(row = 4, column = 0, columnspan = 4) #show results self.results_txt = Text(self, width = 50, height = 10, wrap = WORD) self.results_txt.grid(row = 5, column = 0, columnspan = 4) def cricket_getinfo(self): """Get values from the GUI and submit for calculation""" print "test" runs = self.runs_ent.get() wickets = self.wickets_ent.get() overs = self.overs_ent.get() if self.yes_no.get(): used_before = 'Y' else: used_before = 'N' Cricketobj = Cricket() #create code to call the calculations z = 50 win = 10 if self.yes_no == 'N': win = 10 originalscore = 0 wold = 0 yold = 0 results = Cricketobj.runfuns(wickets,overs,runs,z, win, originalscore, orignovoers, wold, yold) print results elif self.yes_no == 'Y': #get the data from last time xold, yold, wold = openlasttime() #now we are calculating using the more up to date run rate orignovoers = y runs = int(runs) xold = int(xold) x = x - xold overs = int(overs) - int(yold) wickets = int(wickets) - int(wold) wold = int(wold) win = 10 z = 50 results = Cricketobj.runfuns(wickets,overs,runs,z, win, originalscore, orignovoers, wold, yold)#(w,y,x,z,win, xold, orignovoers, wold, yold) #the line below is causing it crash #results = 1 self.results_txt.insert(0.0,results) Cricketobj.savecurrentstate(runs,overs,wickets) #main import cPickle, shelve from Tkinter import * root = Tk() root.title("Cricket Results") app = CricketGUI(root) root.mainloop() --- tutor-request@python.org wrote: > Send Tutor mailing list submissions to > tutor@python.org > > To subscribe or unsubscribe via the World Wide Web, > visit > http://mail.python.org/mailman/listinfo/tutor > or, via email, send a message with subject or body > 'help' to > tutor-request@python.org > > You can reach the person managing the list at > tutor-owner@python.org > > When replying, please edit your Subject line so it > is more specific > than "Re: Contents of Tutor digest..." > > > Today's Topics: > > 1. Re: Find out if a number is even or not (Alan > Gauld) > 2. Re: Find out if a number is even or not (Liam > Clarke) > > > ---------------------------------------------------------------------- > > Message: 1 > Date: Sat, 16 Oct 2004 08:47:12 +0100 > From: "Alan Gauld" > Subject: Re: [Tutor] Find out if a number is even or > not > To: , , > > Message-ID: <00a601c4b354$5979b630$d79b8851@xp> > Content-Type: text/plain; charset="iso-8859-1" > > > > I don't quite understand the syntax of > > > > return x % 2 and 'Even' or 'Odd'... > > This is fully exlained in my tutorial on the > Functional Programming > topic, but the short answer is: > > x % 2 and 'Even' or 'Odd'... > > Can be written: > > ((x%2) and 'Even') or 'Odd') > > This is a boolean expression. > > Python works out the first term, x%2 and of it is > true looks at > the second term in the AND expression, 'Even'. Since > 'Even' is true > (only empty strings are considered false) the whole > AND expression > is True and because it is True Python doesn't need > to evaluate the > second part of the OR expression so it returns the > True part of the > AND expression. > > And here is the trick. Python doesn't return an > actual boolean value > (True or False), instead it returns the actual value > it last tested, > in this case the string 'Even'. > > If x%2 is 0 and thus False in boolean terms the > whole AND expression > must be false. So Python now evaluates the second > part of the OR > expression, 'Odd'. Again this string is True > boolean-wise, so Python > returns the last True value, namely the string > 'Odd'. > > So the actual return value from the overall > expression is 'Even' > if x%2 is true and 'Odd' if x%2 is False. > > This is not intuitively obvious but the tutorial > page gives several > more examples to illustrate how it works. In this > case I thing the > functional form works quite well because it kind of > makes sense > (to me anyway!) to say the function returns 'Even' > or 'Odd' > > > I'm having trouble understanding conditionals, > like... if x: So if > x > > is... what exactly? Is it checking for a non-null > or non-zero value? > > Or if not x:.... > > if x: > > is siply shorthand for saying > > if x == True: > > And the logical equivalent to True depends on the > data type. > Normally it is whatever comes closest in meaning to > not > being 'empty'. Thus for numbers it means not being > zero, > for sequences it really is not being empty, for > files it > means the file is open and readable - ie we aren't > at the end. > > There is a page in the Python documentation that > decribes > for each type the boolean equivalents. I think its > in the > reference manual. > > HTH, > > Alan G. > > > > ------------------------------ > > Message: 2 > Date: Sat, 16 Oct 2004 21:47:49 +1300 > From: Liam Clarke > Subject: Re: [Tutor] Find out if a number is even or > not > To: Alan Gauld > Cc: tutor@python.org, cynos@safe-mail.net > Message-ID: > > Content-Type: text/plain; charset=US-ASCII > > Ah sorry, I haven't got to the functional > programming bit yet. > > So, that would mean 'if not x' is shorthand for 'if > x is False' or 'if x == 0' > > so, any expression, say, if a - 10: if a - 10 > doesn't equal zero, > then it's true. > > and the x % 2 and 'Even' or 'Odd' thing is nifty.. > > That shines a ray of light on it for me, > > Thanks. > > > On Sat, 16 Oct 2004 08:47:12 +0100, Alan Gauld > wrote: > > > > > I don't quite understand the syntax of > > > > > > return x % 2 and 'Even' or 'Odd'... > > > > This is fully exlained in my tutorial on the > Functional Programming > > topic, but the short answer is: > > > > x % 2 and 'Even' or 'Odd'... > > > > Can be written: > > > > ((x%2) and 'Even') or 'Odd') > > > > This is a boolean expression. > > > > Python works out the first term, x%2 and of it is > true looks at > > the second term in the AND expression, 'Even'. > Since 'Even' is true > > (only empty strings are considered false) the > whole AND expression > > is True and because it is True Python doesn't need > to evaluate the > > second part of the OR expression so it returns the > True part of the > > AND expression. > > > > And here is the trick. Python doesn't return an > actual boolean value > > (True or False), instead it returns the actual > value it last tested, > > in this case the string 'Even'. > > > > If x%2 is 0 and thus False in boolean terms the > whole AND expression > > must be false. So Python now evaluates the second > part === message truncated === ___________________________________________________________ALL-NEW Yahoo! Messenger - all new features - even more fun! http://uk.messenger.yahoo.com From kent_johnson at skillsoft.com Sat Oct 16 17:45:01 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Sat Oct 16 17:45:14 2004 Subject: [Tutor] Problems with GUI calling a class In-Reply-To: <20041016153244.17494.qmail@web25404.mail.ukl.yahoo.com> References: <20041016100031.0E45E1E403D@bag.python.org> <20041016153244.17494.qmail@web25404.mail.ukl.yahoo.com> Message-ID: <6.1.0.6.0.20041016113958.028e2cd8@mail4.skillsoft.com> David, It looks like neither branch of your conditional is being executed. You have, in outline, if self.yes_no == 'N': results = ... elif self.yes_no == 'Y': results = ... self.results_txt.insert(0.0,results) If self.yes_no is neither 'N' or 'Y' then results will not be initialized and you will get the error you are seeing. Looking a little above this section in your code, you have if self.yes_no.get(): so I am guessing that self.yes_no is a reference to something in the gui? and not a string. Maybe the conditional that is failing also should be using self.yes_no.get()? Kent At 04:32 PM 10/16/2004 +0100, David Holland wrote: > I wrote a program to calculate the likely result of a >one day cricket match and then decided to make it into >a class and have another class for a GUI. >It all works well but I can not call the function from >the first class from the GUI class, insteading of >returning a result it just gives this error 'Exception >in Tkinter callback >Traceback (most recent call last): > File "/usr/lib/python2.3/lib-tk/Tkinter.py", line >1345, in __call__ > return self.func(*args) > File >"/home/david/Documents/pyprogramming/cricketv6.py", >line 194, in cricket_getinfo > self.results_txt.insert(0.0,results) >UnboundLocalError: local variable 'results' referenced >before assignment >' >This is the code which create the GUI and if it worked >would call the calculations. > def cricket_getinfo(self): > """Get values from the GUI and submit for >calculation""" > print "test" > runs = self.runs_ent.get() > wickets = self.wickets_ent.get() > overs = self.overs_ent.get() > if self.yes_no.get(): > used_before = 'Y' > else: > used_before = 'N' > Cricketobj = Cricket() > #create code to call the calculations > z = 50 > win = 10 > if self.yes_no == 'N': > win = 10 > originalscore = 0 > wold = 0 > yold = 0 > results = >Cricketobj.runfuns(wickets,overs,runs,z, win, >originalscore, orignovoers, wold, yold) > print results > elif self.yes_no == 'Y': > #get the data from last time > xold, yold, wold = openlasttime() > #now we are calculating using the more up to >date run rate > orignovoers = y > runs = int(runs) > xold = int(xold) > x = x - xold > overs = int(overs) - int(yold) > wickets = int(wickets) - int(wold) > wold = int(wold) > win = 10 > z = 50 > results = >Cricketobj.runfuns(wickets,overs,runs,z, win, >originalscore, orignovoers, wold, yold)#(w,y,x,z,win, >xold, orignovoers, wold, yold) > #the line below is causing it crash > #results = 1 > self.results_txt.insert(0.0,results) > >Cricketobj.savecurrentstate(runs,overs,wickets) > > >Can anyone see why I am not calling the class's >function properly ? > >Thanks in advance. >David > > > > > >___________________________________________________________ALL-NEW Yahoo! >Messenger - all new features - even more fun! http://uk.messenger.yahoo.com >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From davholla2002 at yahoo.co.uk Sat Oct 16 17:59:04 2004 From: davholla2002 at yahoo.co.uk (David Holland) Date: Sat Oct 16 17:59:07 2004 Subject: [Tutor] Problems with GUI calling a class In-Reply-To: <6.1.0.6.0.20041016113958.028e2cd8@mail4.skillsoft.com> Message-ID: <20041016155904.55730.qmail@web25408.mail.ukl.yahoo.com> Kent, Thanks that it is the problem. It still has a few problems but none that I can not solve now. --- Kent Johnson wrote: > David, > > It looks like neither branch of your conditional is > being executed. You > have, in outline, > if self.yes_no == 'N': > results = ... > elif self.yes_no == 'Y': > results = ... > self.results_txt.insert(0.0,results) > > If self.yes_no is neither 'N' or 'Y' then results > will not be initialized > and you will get the error you are seeing. > > Looking a little above this section in your code, > you have > if self.yes_no.get(): > so I am guessing that self.yes_no is a reference to > something in the gui? > and not a string. Maybe the conditional that is > failing also should be > using self.yes_no.get()? > > Kent > > At 04:32 PM 10/16/2004 +0100, David Holland wrote: > > I wrote a program to calculate the likely result > of a > >one day cricket match and then decided to make it > into > >a class and have another class for a GUI. > >It all works well but I can not call the function > from > >the first class from the GUI class, insteading of > >returning a result it just gives this error > 'Exception > >in Tkinter callback > >Traceback (most recent call last): > > File "/usr/lib/python2.3/lib-tk/Tkinter.py", > line > >1345, in __call__ > > return self.func(*args) > > File > >"/home/david/Documents/pyprogramming/cricketv6.py", > >line 194, in cricket_getinfo > > self.results_txt.insert(0.0,results) > >UnboundLocalError: local variable 'results' > referenced > >before assignment > >' > >This is the code which create the GUI and if it > worked > >would call the calculations. > > def cricket_getinfo(self): > > """Get values from the GUI and submit for > >calculation""" > > print "test" > > runs = self.runs_ent.get() > > wickets = self.wickets_ent.get() > > overs = self.overs_ent.get() > > if self.yes_no.get(): > > used_before = 'Y' > > else: > > used_before = 'N' > > Cricketobj = Cricket() > > #create code to call the calculations > > z = 50 > > win = 10 > > if self.yes_no == 'N': > > win = 10 > > originalscore = 0 > > wold = 0 > > yold = 0 > > results = > >Cricketobj.runfuns(wickets,overs,runs,z, win, > >originalscore, orignovoers, wold, yold) > > print results > > elif self.yes_no == 'Y': > > #get the data from last time > > xold, yold, wold = openlasttime() > > #now we are calculating using the more up > to > >date run rate > > orignovoers = y > > runs = int(runs) > > xold = int(xold) > > x = x - xold > > overs = int(overs) - int(yold) > > wickets = int(wickets) - int(wold) > > wold = int(wold) > > win = 10 > > z = 50 > > results = > >Cricketobj.runfuns(wickets,overs,runs,z, win, > >originalscore, orignovoers, wold, > yold)#(w,y,x,z,win, > >xold, orignovoers, wold, yold) > > #the line below is causing it crash > > #results = 1 > > self.results_txt.insert(0.0,results) > > > >Cricketobj.savecurrentstate(runs,overs,wickets) > > > > > >Can anyone see why I am not calling the class's > >function properly ? > > > >Thanks in advance. > >David > > > > > > > > > > > >___________________________________________________________ALL-NEW > Yahoo! > >Messenger - all new features - even more fun! > http://uk.messenger.yahoo.com > >_______________________________________________ > >Tutor maillist - Tutor@python.org > >http://mail.python.org/mailman/listinfo/tutor > > ___________________________________________________________ALL-NEW Yahoo! Messenger - all new features - even more fun! http://uk.messenger.yahoo.com From john at 8ftarch.org Sat Oct 16 19:22:53 2004 From: john at 8ftarch.org (John Matthews) Date: Sat Oct 16 19:22:43 2004 Subject: [Tutor] python 2.3.4 GUI In-Reply-To: <6.1.0.6.0.20041016113005.028e30b0@mail4.skillsoft.com> References: <000701c4b299$aeef5f40$6500a8c0@p933> <24d253d9041015051946aae209@mail.gmail.com> <6.1.0.6.0.20041016113005.028e30b0@mail4.skillsoft.com> Message-ID: <417158ED.4090702@8ftarch.org> My experience is exactly opposite. IDLE became broken with Python 2.3 and it has nothing to do with other programming languages being installed because I don't have any others. Sometimes deleting the .cfg files in \.idlerc\ makes it work, but sometimes not. It has always been a problem for me so I still run 2.2.2 which works fine. -- John Matthews | http://8ftarch.org I'll be mowing my lawn on Thursday evenings http://factcheck.com get your facts straight!(recommended by Dick Cheney) REGIME CHANGE 2004 Kent Johnson wrote: > This problem was fixed in python 2.3 (when idle-fork was folded in to > the main distribution) > > Kent > > At 04:16 PM 10/16/2004 +1300, Riumu Kuraku wrote: > >> I think if you're trying to call a Tkinter GUI from IDLE it messes up, >> because IDLE is a Tk GUI itself, so the mainloop()'s collide. >> >> Well, that's my understanding, try calling the GUI from the dox box >> python, and it'll work fine. IDLE it won't. >> >> >> On Fri, 15 Oct 2004 08:19:05 -0400, Lloyd Hugh Allen >> wrote: >> > Do you have any other programming languages installed on your >> > computer, particularly any that use Tk/TCL? Installing Ruby broke my >> > Python a few years ago, because Ruby had screwed with all the Tk/TCL >> > stuff. I submitted this as an issue to both Python and Ruby, and got >> > responses of "it's not OUR fault" from both sides. >> > >> > And then the Ruby uninstaller didn't clean up after itself. Messy >> situation. >> > >> > In the absence of other programming languages, I would try cleanly >> > uninstalling all versions of Python, and then reinstalling the most >> > recent one. >> > >> > >> > >> > On Fri, 15 Oct 2004 11:30:21 +0200, gil@tuckers.de >> wrote: >> > > >> > > >> > > Hi greetings, >> > > I am running Win 2000. When I >> download Python 2.2 and higher >> > > and I call the GUI it doesn`t come. The command line is okay the >> IDLE refuse to >> > > respond. Some tip or tips could be welcome. >> > > cheers gil >> > > >> > > _______________________________________________ >> > > Tutor maillist - Tutor@python.org >> > > http://mail.python.org/mailman/listinfo/tutor >> > > >> > _______________________________________________ >> > Tutor maillist - Tutor@python.org >> > http://mail.python.org/mailman/listinfo/tutor >> > >> _______________________________________________ >> Tutor maillist - Tutor@python.org >> http://mail.python.org/mailman/listinfo/tutor > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld at freenet.co.uk Sat Oct 16 19:24:40 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat Oct 16 19:24:26 2004 Subject: [Tutor] Find out if a number is even or not References: <1097838018.416fadc261290@webmail.freedom2surf.net> <5.1.0.14.2.20041015144947.059e48a0@mail.30below.com> <006b01c4b309$873ff610$d79b8851@xp> <00a601c4b354$5979b630$d79b8851@xp> <797fe3d404101606063896301f@mail.gmail.com> Message-ID: <00bb01c4b3a5$0524f3a0$d79b8851@xp> > So, shouldn't that piece of code be: > > return x%2 and 'Odd' or 'Even' > > to make it semantically correct? As it is, it returns 'Odd' for even > numbers, and vice versa. Woops! Never post untested code! You are quite correct. Alan G. From alan.gauld at freenet.co.uk Sat Oct 16 19:35:57 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat Oct 16 19:35:41 2004 Subject: [Tutor] Problems with GUI calling a class References: <20041016153244.17494.qmail@web25404.mail.ukl.yahoo.com> Message-ID: <00cd01c4b3a6$98ed2d40$d79b8851@xp> > line 194, in cricket_getinfo > self.results_txt.insert(0.0,results) > UnboundLocalError: local variable 'results' referenced > before assignment THis says results doesn't exist yet. > if self.yes_no == 'N': > win = 10 > originalscore = 0 > wold = 0 > yold = 0 > results = WE create results inside the if block. Is there any chance that yes_no could be other than 'N' before it gets to this stage? > Can anyone see why I am not calling the class's > function properly ? Thats not what the error message is telling you, it says the results variable doesn't exist. Alan G. From andre.roberge at ns.sympatico.ca Sat Oct 16 19:37:44 2004 From: andre.roberge at ns.sympatico.ca (=?ISO-8859-1?Q?Andr=E9_Roberge?=) Date: Sat Oct 16 19:37:46 2004 Subject: [Tutor] "Visually following" Python program execution Message-ID: <41715C68.5090100@ns.sympatico.ca> Note: I posted this on comp.lang.python last night from a friend's house. Let's see if the tutor folks can beat the newsgroup readers who, so far, have shown little interest in my problem. Andr? === I want to "import and execute" a python program (input_test.py below) within another program (execute_test.py below) and "watch it" being executed. By watching it, I mean to display the file input_test.py in a window (GUI) and highlighting the line being executed. I am *simulating* this here by printing the line being executed with the corresponding line number and it works as expected for "simple" programs. The problem arises when I want to do a loop (or other similar blocks). If I write a loop as for i in range(2): print i exec() gives an EOF error, as it processes the "for" line. I have tried to put the loop on a single physical line, something like for i in range(2):\n print i but this didn't work either. I really would like to be able to follow within the loops too... Any pointer would be greatly appreciated. Andre Roberge Btw, input_test.py is already processed to tag on the ";NUM = ...". It is not the file as I would want it to appear on a window being traced. ===== File Constants.py ==== NUM = 1 ===== File input_test.py === from Constants import * ; NUM = 2 print "Starting within input_test"; NUM = 3 print "Within input_test, NUM =", NUM; NUM = 4 print "Done!" ===== File execute_test.py === import time from Constants import * inp = open("input_test.py", "r") for line in inp.readlines(): print "NUM =", NUM, ":", exec(line) time.sleep(1) inp.close() ======= Output from the program ===== NUM = 1 : NUM = 2 : Starting within input_test NUM = 3 : Within input_test, NUM = 3 NUM = 4 : Done! From chandrakirti at gmail.com Sat Oct 16 19:45:11 2004 From: chandrakirti at gmail.com (Lloyd Hugh Allen) Date: Sat Oct 16 19:45:14 2004 Subject: [Tutor] Find out if a number is even or not In-Reply-To: <24d253d904101520094f73a206@mail.gmail.com> References: <1097838018.416fadc261290@webmail.freedom2surf.net> <24d253d904101520094f73a206@mail.gmail.com> Message-ID: <24d253d904101610453b801a62@mail.gmail.com> I'm going to say more about mine. We know that computers like binary better, because it is easier to tell the difference between "on" and "off" than for a circuit to try to measure an analog level of voltage on a circuit. So to the computer, 6 looks like 110, which is (going from right to left) 0*(2**0) + 1*(2**1) + 1*(2**2) == 0 + 2 + 4. Counting in binary would look like 1 1 2 10 3 11 4 100 5 101 6 110 7 111 8 1000 we notice that the odd numbers have a "one's" digit, in binary, of one. The bitwise and operator, &, compares the binary digits of its two arguments. For instance, 4&5 notes that the only digit that is on in both binary expansions is the one in the fours place. Therefore, 4&5 == 4. Similarly, 1 & odd == 1 and 1 & even == 0. Python 2.3 has booleans. I like them, and the original question was phrased as, "I want to know when a number is even." So num & 1 will give a nonzero result for odds and a result of zero for evens; since not zero is True and not (nonzero) is False, taking not (num & 1) gives the "even-ness" of an integer. As a happy sidenote, bitwise and gets angry when a float is thrown at it. I don't want to guess as to whether a float is even or odd; my function throws an exception. On Fri, 15 Oct 2004 23:09:45 -0400, Lloyd Hugh Allen wrote: > There's also the bitwise & operation > > def isEvenQ(num): > return not (num & 1) > > don't know if it's actually faster though. > > > > On Fri, 15 Oct 2004 12:00:18 +0100, nick@javacat.f2s.com > wrote: > > Hi group, > > > > Im sure this is simple to do, but Ive just been looking through the python docs > > and the archive of this mailing list and cant find what Im after. > > > > I just want to know if a number is even or not. > > > > I've had a look at the math package but that doesnt seem to have anything this > > simple in it. > > > > I thought something like > > > > >>> if 10 div 2 == 0 : print 'even' > > >>> else : print 'odd' > > > > but obviously that doesnt work. > > > > Sorry for such a basic question, but I really cant find out how to do this. > > > > Kind regards > > Nick. > > > > ------------------------------------------------- > > Everyone should have http://www.freedom2surf.net/ > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > From alipolatel at yahoo.com Sat Oct 16 19:46:45 2004 From: alipolatel at yahoo.com (Ali Polatel) Date: Sat Oct 16 19:46:48 2004 Subject: [Tutor] Simple Question... Message-ID: <20041016174645.31391.qmail@web61009.mail.yahoo.com> Hi dear tutors... I want to write a programme that will get certain information from a file.: open('c:\\example.txt','a') # file opened... Now I want it to choose a random line and read it... but just one line and not the first one but a random one... how to do that? Regards, Ali Polatel __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20041016/9338874f/attachment-0001.htm From maxnoel_fr at yahoo.fr Sat Oct 16 20:09:27 2004 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Sat Oct 16 20:09:31 2004 Subject: [Tutor] Simple Question... In-Reply-To: <20041016174645.31391.qmail@web61009.mail.yahoo.com> References: <20041016174645.31391.qmail@web61009.mail.yahoo.com> Message-ID: <8464C062-1F9E-11D9-8BDA-000393CBC88E@yahoo.fr> On Oct 16, 2004, at 18:46, Ali Polatel wrote: > Hi dear tutors... > I want to write a programme that will get certain information from a > file.: > open('c:\\example.txt','a')? # file opened... > Now I want it to choose a random line and read it... but just one line > and not the first one but a random one... > how to do that? > Regards, > Ali Polatel There's probably a way to do it exactly how you described it. However, it'd be too complicated and not a lot faster than what I'm going to propose. Anyway. The fast and easy way to do that is to load the entire file in an array using readlines(), then rand a line and access it. import random def randomLineFromFile(fileName): source = open(fileName, 'r') lines = source.readlines() # an array of all the file's lines source.close() return lines[random.randint(1, len(lines))] This will work perfectly if your file is small enough to fit in your computer's memory. If you want a function that does this on large files, you'll have to use something in those lines: import random def randomLineFromBigFile(fileName, numLines): whatLine = random.randint(1, numLines) # choose a random line number source = open(fileName, 'r') i = 0 for line in source: i += 1 if i == whatLine: return line return None This function uses very little (and a constant amount of) memory. The downside is that you have to know the total number of lines in the file (that's the numLines argument) before calling it. It's not a very hard thing to do. (Oh, by the way, it's a bad practice to use backslashes in file paths. If you use them, your program will only work on Windows, and it requires typing an additional character each time -- use slashes, they work everywhere and will make the transition easier when you eventually see the light :p ) -- Wild_Cat maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From kent_johnson at skillsoft.com Sat Oct 16 21:24:30 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Sat Oct 16 21:24:39 2004 Subject: [Tutor] "Visually following" Python program execution In-Reply-To: <41715C68.5090100@ns.sympatico.ca> References: <41715C68.5090100@ns.sympatico.ca> Message-ID: <6.1.0.6.0.20041016151133.028dcbc0@mail4.skillsoft.com> This is pretty much what a debugger does. In fact the IDLE debugger is not far from this at all, can you just use it or modify it to do what you want? I suggest you look at how pdb and the IDLE debugger work. A few starting points would be the pdb module docs at http://docs.python.org/lib/module-pdb.html especially the "How it works" section. Both pdb and IDLE use the bdb module as a base, you should probably do the same. This is a challenging project, good luck! Kent At 02:37 PM 10/16/2004 -0300, Andr? Roberge wrote: >Note: I posted this on comp.lang.python last night from a friend's house. >Let's see if the tutor folks can beat the newsgroup readers who, so far, >have shown little interest in my problem. >Andr? > >=== >I want to "import and execute" a python program (input_test.py below) >within another program (execute_test.py below) and "watch it" being >executed. >By watching it, I mean to display the file input_test.py in a window >(GUI) and >highlighting the line being executed. >I am *simulating* this here by printing the line being executed with >the corresponding line number and it works as expected for "simple" >programs. > >The problem arises when I want to do a loop (or other similar blocks). >If I write a loop as > >for i in range(2): > print i > >exec() gives an EOF error, as it processes the "for" line. >I have tried to put the loop on a single physical line, something like >for i in range(2):\n print i > >but this didn't work either. I really would like to be able to >follow within the loops too... >Any pointer would be greatly appreciated. > >Andre Roberge > >Btw, input_test.py is already processed to tag on the ";NUM = ...". It is >not the file as I would want it to appear on a window being >traced. > >===== File Constants.py ==== >NUM = 1 > >===== File input_test.py === >from Constants import * ; NUM = 2 >print "Starting within input_test"; NUM = 3 >print "Within input_test, NUM =", NUM; NUM = 4 >print "Done!" > >===== File execute_test.py === >import time >from Constants import * >inp = open("input_test.py", "r") > >for line in inp.readlines(): > print "NUM =", NUM, ":", > exec(line) > time.sleep(1) > >inp.close() > >======= Output from the program ===== >NUM = 1 : NUM = 2 : Starting within input_test >NUM = 3 : Within input_test, NUM = 3 >NUM = 4 : Done! > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From bill.mill at gmail.com Sat Oct 16 22:26:47 2004 From: bill.mill at gmail.com (Bill Mill) Date: Sat Oct 16 22:26:51 2004 Subject: [Tutor] Find out if a number is even or not In-Reply-To: <24d253d904101610453b801a62@mail.gmail.com> References: <1097838018.416fadc261290@webmail.freedom2surf.net> <24d253d904101520094f73a206@mail.gmail.com> <24d253d904101610453b801a62@mail.gmail.com> Message-ID: <797fe3d4041016132643f0e2f9@mail.gmail.com> Just for fun, I wrote each of the suggestions into a file and timed how long it took them to test each number from 0 to 100 for evenness. If you don't want to read the code and results, I'll just tell you that the bitwise method is the fastest, and the 'Odd' or 'Even' method is the slowest. This makes sense as the bitwise operator has a simple hardware operation, while the latter method has to create a string and possibly do an extra boolean operation. For 100,000 runs from 0 to 100, the difference is about 1.6 seconds. If you're interested, the code and results follow: import timeit def isEven1(n): return not n&1 def isEven2(n): return n % 2 == 0 def isEven3(n): return n % 2 and 'Odd' or 'Even' def testfunc(predicate): for i in range(100): predicate(i) def testtimes(): for function in ('isEven1', 'isEven2', 'isEven3'): t = timeit.Timer('testfunc(%s)' % (function), \ 'from __main__ import %s, testfunc' % function) print "%s: %f" % (function, t.timeit(100000)) if __name__ == "__main__": testtimes() ############## # Results in: isEven1: 8.174000 isEven2: 8.839000 isEven3: 9.899000 Peace Bill Mill bill.mill@gmail.com On Sat, 16 Oct 2004 13:45:11 -0400, Lloyd Hugh Allen wrote: > I'm going to say more about mine. > > We know that computers like binary better, because it is easier to > tell the difference between "on" and "off" than for a circuit to try > to measure an analog level of voltage on a circuit. > > So to the computer, 6 looks like 110, which is (going from right to > left) 0*(2**0) + 1*(2**1) + 1*(2**2) == 0 + 2 + 4. Counting in binary > would look like > > 1 1 > 2 10 > 3 11 > 4 100 > 5 101 > 6 110 > 7 111 > 8 1000 > > we notice that the odd numbers have a "one's" digit, in binary, of one. > > The bitwise and operator, &, compares the binary digits of its two > arguments. For instance, 4&5 notes that the only digit that is on in > both binary expansions is the one in the fours place. Therefore, 4&5 > == 4. Similarly, 1 & odd == 1 and 1 & even == 0. > > Python 2.3 has booleans. I like them, and the original question was > phrased as, "I want to know when a number is even." > > So num & 1 will give a nonzero result for odds and a result of zero > for evens; since not zero is True and not (nonzero) is False, taking > not (num & 1) gives the "even-ness" of an integer. > > As a happy sidenote, bitwise and gets angry when a float is thrown at > it. I don't want to guess as to whether a float is even or odd; my > function throws an exception. > > On Fri, 15 Oct 2004 23:09:45 -0400, Lloyd Hugh Allen > > > wrote: > > There's also the bitwise & operation > > > > def isEvenQ(num): > > return not (num & 1) > > > > don't know if it's actually faster though. > > > > > > > > On Fri, 15 Oct 2004 12:00:18 +0100, nick@javacat.f2s.com > > wrote: > > > Hi group, > > > > > > Im sure this is simple to do, but Ive just been looking through the python docs > > > and the archive of this mailing list and cant find what Im after. > > > > > > I just want to know if a number is even or not. > > > > > > I've had a look at the math package but that doesnt seem to have anything this > > > simple in it. > > > > > > I thought something like > > > > > > >>> if 10 div 2 == 0 : print 'even' > > > >>> else : print 'odd' > > > > > > but obviously that doesnt work. > > > > > > Sorry for such a basic question, but I really cant find out how to do this. > > > > > > Kind regards > > > Nick. > > > > > > ------------------------------------------------- > > > Everyone should have http://www.freedom2surf.net/ > > > _______________________________________________ > > > Tutor maillist - Tutor@python.org > > > http://mail.python.org/mailman/listinfo/tutor > > > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From amonroe at columbus.rr.com Sat Oct 16 22:52:16 2004 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Sat Oct 16 22:52:27 2004 Subject: [Tutor] Simple Question... In-Reply-To: <8464C062-1F9E-11D9-8BDA-000393CBC88E@yahoo.fr> References: <20041016174645.31391.qmail@web61009.mail.yahoo.com> <8464C062-1F9E-11D9-8BDA-000393CBC88E@yahoo.fr> Message-ID: <47856308316.20041016165216@columbus.rr.com> > This will work perfectly if your file is small enough to fit in your > computer's memory. If you want a function that does this on large > files, you'll have to use something in those lines: > import random > def randomLineFromBigFile(fileName, numLines): > whatLine = random.randint(1, numLines) # choose a random line number > source = open(fileName, 'r') > i = 0 > for line in source: > i += 1 > if i == whatLine: return line > return None > This function uses very little (and a constant amount of) memory. The > downside is that you have to know the total number of lines in the file > (that's the numLines argument) before calling it. It's not a very hard > thing to do. Wouldn't it be much quicker to do something like this? import os.path import random size = os.path.getsize('test.txt') print size randline = random.randint(1, size) print randline testfile = open('test.txt', 'r') testfile.seek(randline) print testfile.readline() #read what is likely half a line print testfile.readline() #read the next whole line testfile.close() You'd just need to add some exception handling in the event you tried to read off the end of the file. Alan From bill.mill at gmail.com Sat Oct 16 23:30:54 2004 From: bill.mill at gmail.com (Bill Mill) Date: Sat Oct 16 23:30:58 2004 Subject: [Tutor] Simple Question... In-Reply-To: <47856308316.20041016165216@columbus.rr.com> References: <20041016174645.31391.qmail@web61009.mail.yahoo.com> <8464C062-1F9E-11D9-8BDA-000393CBC88E@yahoo.fr> <47856308316.20041016165216@columbus.rr.com> Message-ID: <797fe3d4041016143034feddd3@mail.gmail.com> To do this without loading the file into memory, and without relying on wc (which ought to be very fast even with large files, if you need that), you could do: import random def linecount(f): """count the number of lines in the file then rewind it""" l = ' ' c = 0 while l: l = f.readline() if l[-1:] == '\n': c +=1 #I don't think the 'if' is necessary, #but for safety's sake we'll leave it f.seek(0) return c def getrandline(f): """get a random line from f (assumes file pointer is at beginning)""" lines = linecount(f) r = random.randint(0,int(lines)) for i in range(1, r): f.readline() return f.readline() anybody have a faster implementation? Peace Bill Mill bill.mill at gmail.com On Sat, 16 Oct 2004 16:52:16 -0400, R. Alan Monroe wrote: > > This will work perfectly if your file is small enough to fit in your > > computer's memory. If you want a function that does this on large > > files, you'll have to use something in those lines: > > > import random > > > def randomLineFromBigFile(fileName, numLines): > > whatLine = random.randint(1, numLines) # choose a random line number > > source = open(fileName, 'r') > > i = 0 > > for line in source: > > i += 1 > > if i == whatLine: return line > > return None > > > This function uses very little (and a constant amount of) memory. The > > downside is that you have to know the total number of lines in the file > > (that's the numLines argument) before calling it. It's not a very hard > > thing to do. > > Wouldn't it be much quicker to do something like this? > > import os.path > import random > > size = os.path.getsize('test.txt') > print size > > randline = random.randint(1, size) > print randline > > testfile = open('test.txt', 'r') > testfile.seek(randline) > print testfile.readline() #read what is likely half a line > print testfile.readline() #read the next whole line > testfile.close() > > You'd just need to add some exception handling in the event you tried > to read off the end of the file. > > Alan > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From hugonz-lists at h-lab.net Fri Oct 15 17:10:04 2004 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Sun Oct 17 00:13:10 2004 Subject: [Tutor] Running script under Windows In-Reply-To: <20041014110539.4fb08dca@speedking.dyndns.org> References: <000001c4b1aa$93194500$f6aeda18@usertz7f6j789v> <20041014110539.4fb08dca@speedking.dyndns.org> Message-ID: <416FE84C.70802@h-lab.net> Probably the best way you have to do it is edit the scrip using IDLE (this editor should be in Start-> Python2.3) Select "new file" from the menu, save it wherever you want with a ".py" extension. Upon double click, explorer will open the interpreter and run the script. However, I normally do F5 in the IDLE editor, which will fire the script on the integrated prompt for me.... Hope it helps, Hugo From keridee at jayco.net Fri Oct 15 03:29:16 2004 From: keridee at jayco.net (Jacob S.) Date: Sun Oct 17 02:08:37 2004 Subject: [Tutor] Late Introduction Message-ID: <000001c4b3dd$8e7149f0$dc5328cf@JSLAPTOP> Hi, I'm sorry guys. It never occurred to me to introduce myself to you before. Then on the mailing list someone else writes an introductory email and I thought "duh stupid". I don't want to get on your bad side everyone. My name is Jacob Schmidt. I am a freshman in high school and I dabble in Python and Javascript, writing miniscule things such as a program that graphs functions using VPython or one that draws tangent lines to a function to create what my dad describes as "string art on the computer." If you're ever bored and want to look through a whole bunch of seemingly insignificant and childish looking code, then write me an email, because I have several programs I can send you! I wanted to know how to print to a file because I was writing a (barely) functioning raw_input sort of barcoding interpreter for the CueCat scanners. I don't quite have as much functionality as a WalMart checkout desk, but it would do for what I want. The reason I want to print a file -- or I guess I should say a string, it would be more convenient -- is the fact that I wish to print receipts. I could most possibly latch on to a receipt printer on ebay. Blah, blah, blah. I carry on, don't I? I'm sorry I didn't introduce myself before. When I read the other guy's email, I realized that I kinda started asking questions and giving answers before anyone knew me. Hope this eases the tides a little. Talk to you soon everyone! Jacob Schmidt From amonroe at columbus.rr.com Sun Oct 17 03:31:47 2004 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Sun Oct 17 03:32:00 2004 Subject: [Tutor] Simple Question... In-Reply-To: <797fe3d4041016143034feddd3@mail.gmail.com> References: <20041016174645.31391.qmail@web61009.mail.yahoo.com> <8464C062-1F9E-11D9-8BDA-000393CBC88E@yahoo.fr> <47856308316.20041016165216@columbus.rr.com> <797fe3d4041016143034feddd3@mail.gmail.com> Message-ID: <135873078670.20041016213147@columbus.rr.com> > To do this without loading the file into memory, and without relying > on wc (which ought to be very fast even with large files, if you need > that), you could do: > [snip] > for i in range(1, r): f.readline() This seems like it would be awfully slow on a multimegabyte file, force reading every line up to where you want to be. > anybody have a faster implementation? Does someone have a link to a neutral text file we can all use to test with? I'm betting a blind seek right to the middle of the file is going to blow the above away, but I want to try it. I'm on windows and don't have a typical fortune file on hand. >> testfile.seek(randline) >> print testfile.readline() #read what is likely half a line >> print testfile.readline() #read the next whole line Alan From andre.roberge at ns.sympatico.ca Sun Oct 17 03:59:52 2004 From: andre.roberge at ns.sympatico.ca (=?ISO-8859-1?Q?Andr=E9_Roberge?=) Date: Sun Oct 17 03:59:53 2004 Subject: [Tutor] "Visually following" Python program execution In-Reply-To: <6.1.0.6.0.20041016151133.028dcbc0@mail4.skillsoft.com> References: <41715C68.5090100@ns.sympatico.ca> <6.1.0.6.0.20041016151133.028dcbc0@mail4.skillsoft.com> Message-ID: <4171D218.4060204@ns.sympatico.ca> Kent: Thanks for the suggestion; I tried this approach ... but it proved too "powerful" for what I had in mind, as it goes into program parts that I wanted to hide from the user. However, I did find a solution to my problem. I'll outline it here, in case someone has a better idea. But first, I probably need to give the context. What I want to do (and I am very much at the preliminary stage) is to write my own Python version of "Karel the Robot" (or "Guido van Robot" as a Python adaptation is now known) so that it can have additional features. [For those that don't know this GREAT project have a look at http://gvr.sourceforge.net/]. One of the "new" features I want, is for the user to be able to highlight the instruction (move, or putbeeper, etc.) in the program at the same time it is performed on the "world" GUI. Rather than build my own parser (or stepper as it is known in GvR), I will put a "time.sleep()" instruction in the basic robot moves, and use the full power of Python interpretor. This will allow to go beyond the five basic instructions, using variables and, possibly, sub-classes. So, suppose the user defines a simple program (basic.py) as follows: === basic.py=== def turnright(): turnleft() turnleft() turnleft() move() turnright() ===== Then, my "new and improved solution" is to generate a second program (processed_basic.py) from the first which would read as follows: ==== processed_basic.py=== from Constants import * from Instructions import * NUM = 1 def turnright(): NUM = 2 turnleft() NUM = 3 turnleft() NUM = 4 turnleft() NUM = 5 NUM = 7 move() NUM = 8 turnright() ============== and use execfile("processed_basic.py") in my main program as I display "basic.py" in a separate window and use the information from the variable NUM to know which line to highlight. Right now, all I have are little bits and pieces but it looks promising. However, I am more than open to suggestions for potential improvement! Sorry for the amount of bandwidth! Andr? Kent Johnson wrote: > This is pretty much what a debugger does. In fact the IDLE debugger is > not far from this at all, can you just use it or modify it to do what > you want? > > I suggest you look at how pdb and the IDLE debugger work. A few starting > points would be the pdb module docs at > http://docs.python.org/lib/module-pdb.html especially the "How it works" > section. Both pdb and IDLE use the bdb module as a base, you should > probably do the same. > > This is a challenging project, good luck! > Kent > > At 02:37 PM 10/16/2004 -0300, Andr? Roberge wrote: > >> Note: I posted this on comp.lang.python last night from a friend's house. >> Let's see if the tutor folks can beat the newsgroup readers who, so far, >> have shown little interest in my problem. >> Andr? >> >> === >> I want to "import and execute" a python program (input_test.py below) >> within another program (execute_test.py below) and "watch it" being >> executed. >> By watching it, I mean to display the file input_test.py in a window >> (GUI) and >> highlighting the line being executed. >> I am *simulating* this here by printing the line being executed with >> the corresponding line number and it works as expected for "simple" >> programs. >> >> The problem arises when I want to do a loop (or other similar blocks). >> If I write a loop as >> >> for i in range(2): >> print i >> >> exec() gives an EOF error, as it processes the "for" line. >> I have tried to put the loop on a single physical line, something like >> for i in range(2):\n print i >> >> but this didn't work either. I really would like to be able to >> follow within the loops too... >> Any pointer would be greatly appreciated. >> >> Andre Roberge >> >> Btw, input_test.py is already processed to tag on the ";NUM = ...". It >> is not the file as I would want it to appear on a window being >> traced. >> >> ===== File Constants.py ==== >> NUM = 1 >> >> ===== File input_test.py === >> from Constants import * ; NUM = 2 >> print "Starting within input_test"; NUM = 3 >> print "Within input_test, NUM =", NUM; NUM = 4 >> print "Done!" >> >> ===== File execute_test.py === >> import time >> from Constants import * >> inp = open("input_test.py", "r") >> >> for line in inp.readlines(): >> print "NUM =", NUM, ":", >> exec(line) >> time.sleep(1) >> >> inp.close() >> >> ======= Output from the program ===== >> NUM = 1 : NUM = 2 : Starting within input_test >> NUM = 3 : Within input_test, NUM = 3 >> NUM = 4 : Done! >> >> _______________________________________________ >> Tutor maillist - Tutor@python.org >> http://mail.python.org/mailman/listinfo/tutor > > > From cyresse at gmail.com Sun Oct 17 04:11:33 2004 From: cyresse at gmail.com (Liam Clarke) Date: Sun Oct 17 04:11:36 2004 Subject: [Tutor] Working with dates Message-ID: Kia ora all, I am trying to write a function that will get today's date when run, and set a string to the date of a day in the previous week. i.e. it's Saturday the 16th of October, and I want to find the date of Friday last week. I want to generate a date string that is valid for the IMAP4 protocol, so it must be in format 16-Oct-2004. It will be run once a week, usually on a Monday, usually looking for the last Friday. I want it to be able to handle Friday being in a different month or year and still give a precise date. This is what I've done so far, but I'm sure there's a more efficient way to do it, so feedback is gratefully received. A little note on day_offset - gmtime() returns a integer representing the day of the week, Monday to Sunday is 0 to 6. So, I set up a wee index spanning two weeks like so: - M T W T F S S M T W T F S S -7 -6 -5 -4 -3 -2 -1 ( 0 1 2 3 4 5 6) The numbers in brackets are returned by calendar.weekday, the negative ones are my constructs. import time import datetime day_offset=-3 #Friday of previous week, will be changable by user in config gm_data=time.gmtime() #Get today's date/time (year, month, day, weekday)=gm_data[0], gm_data[1], gm_data[2], gm_data[6] #Only need first 3 values and 7th, which is weekday. date_offset = -(day_offset-weekday) # This is to work with datetime.timedelta,which works with positive days. # so it works out to date_offset = - ( -3 - 5) = 8 last_friday=datetime.date(year, month, day) - datetime.timedelta(days=date_offset) #Create date object for today's date, to use Python's built handling of date arithmetic. #timedelta is difference, so last_friday = today's date - 8 days retrieve_date_string=str(last_friday) #last_friday is an object, I need a string so that I can reformat the date (last_friday outputs as 2004-10-08) split_date=retrieve_date_string.split('-') email_sent_date=time.strftime("%d-%b-%Y", (int(split_date[0]), int(split_date[1]), int(split_date[2]), 0, 0, 0, 0, 0, 0)) (time.strftime looks for a tuple of (year, month, day, hour, minute, second, weekday, day of year, and something called tm_isdst) I can't pass it my last_friday object, so I have to generate a tuple for last Friday. gmtime() generates the 9 value tuple normally.) And email_sent_date = "8-Oct-2004" Am I using redundant code anywhere? I just found a redundancy in that I was using gmtime() to get my year month and day, but was using calendar.weekday to get my week day value, when gmtime() generates it anyway. I can see a problem here, if this is run on the Saturday or Sunday, it won't get the Friday just been, but the Friday previously. So, I may just add a catcher for if weekday >= 5 Thank-you for your time Liam Clarke From bill.mill at gmail.com Sun Oct 17 04:30:54 2004 From: bill.mill at gmail.com (Bill Mill) Date: Sun Oct 17 04:31:00 2004 Subject: [Tutor] Simple Question... In-Reply-To: <135873078670.20041016213147@columbus.rr.com> References: <20041016174645.31391.qmail@web61009.mail.yahoo.com> <8464C062-1F9E-11D9-8BDA-000393CBC88E@yahoo.fr> <47856308316.20041016165216@columbus.rr.com> <797fe3d4041016143034feddd3@mail.gmail.com> <135873078670.20041016213147@columbus.rr.com> Message-ID: <797fe3d404101619306051e62a@mail.gmail.com> OK, I posted a fortune file to my webserver. It's at http://llimllib.f2o.org/files/osfortune . I see 2 competitions: 1) fastest function to find a random line from the file; the catch is that this function must be able to pick a random line from anywhere in the file. It must be capable of returning the first line, the last line, and anything in between. 2) fastest function to count the lines in the file. Let's see some creativity! Peace Bill Mill bill.mill at gmail.com On Sat, 16 Oct 2004 21:31:47 -0400, R. Alan Monroe wrote: > > To do this without loading the file into memory, and without relying > > on wc (which ought to be very fast even with large files, if you need > > that), you could do: > > [snip] > > > for i in range(1, r): f.readline() > > This seems like it would be awfully slow on a multimegabyte file, > force reading every line up to where you want to be. > > > anybody have a faster implementation? > > Does someone have a link to a neutral text file we can all use to test > with? I'm betting a blind seek right to the middle of the file is > going to blow the above away, but I want to try it. I'm on windows and > don't have a typical fortune file on hand. > > >> testfile.seek(randline) > >> print testfile.readline() #read what is likely half a line > >> print testfile.readline() #read the next whole line > > Alan > > From cyresse at gmail.com Sun Oct 17 05:07:49 2004 From: cyresse at gmail.com (Liam Clarke) Date: Sun Oct 17 05:07:51 2004 Subject: [Tutor] email & imaplib for beginners like me In-Reply-To: References: <1ff2dfbf041015093875845d86@mail.gmail.com> Message-ID: Arrrggh, finally. For anyone's further info later on. (a,b)=ses.fetch(6, '(BODY[HEADER.FIELDS(FROM)])') doesn't work, neither does - (a,b)=ses.fetch(6, '(BODY[HEADER.FIELDS (FROM) ])') what does work is (a,b)=ses.fetch(6, '(BODY[HEADER.FIELDS (FROM)])') so... requests for specific fields are '(BODY[HEADER.FIELDS (field name)])' Note the space between HEADER.FIELDS and (field name). Note also that there is no space after (field name) - this is really, really, important. Field names are as specified by RFC's 822 and 2822/ On Sun, 17 Oct 2004 00:38:48 +1300, Liam Clarke wrote: > Hello again, > > One last niggle. I've managed to download a MIME multi-part, and > successfully decode an attachment, so thanks for all your help. > > I'm just having trouble trying to get a specific header field : - > > I can't find any examples, but this is what I'm trying - > > (a, b)=session.fetch(5, '(BODY[HEADER.FIELDS[FROM]])'' ) > > and variants thereof (of all 4 bracket sets), all involving FROM being > in brackets after HEADER.FIELDS, as I get this error : > ['Missing required open parenthesis in Fetch BODY[HEADER.FIELDS'] > > Normal error is this > FETCH command error: BAD ['Invalid body section'] > > So yeah, getting mildly frustrated with precise syntaxes (syntaxii?), > RFC 2822 and 3501 aren't hugely helpful on precise locations of > brackets. > > From RFC 3501: > > in BODY > HEADER.FIELDS and HEADER.FIELDS.NOT are followed by a list of > field-name (as defined in [RFC-2822]) names, and return a subset of > the header. ... > > Thanks in advance for your time. > > Liam Clarke > > > > > On Sat, 16 Oct 2004 11:31:20 +1300, Riumu Kuraku wrote: > > On Sat, 16 Oct 2004 11:28:41 +1300, Riumu Kuraku wrote: > > > > > > > With... > > > x=session.fetch(1, "(RFC822)") > > > > > > >>>print x[0] > > > OK > > > >>>print x[1] > > > (All of x except for the 'OK') > > > > > > >>>print x[1][0] is the same output as above > > > > > > but, >>>print x[1][0][1] gives the full email, relatively laid out.... > > > print x[1][0][0] gives > > > 1 (RFC822 {12273} > > > > > > >>> print x[1][1] gives me this: > > > ) > > > >>> print x[2] give list index out of range. > > > > > > So, to clarify my understanding, when I fetch, > > > I get a tuple of 2 values, x[0], and x[1]. x[0] is the server return > > > code (Ok, BAD etc.) > > > and x[1] is the data I fetched, plus an additional code. > > > > > > x[1][0]is the full data I feteched + that additional code , x[1][1] is > > > a closed bracket? Is this normal? > > > > > > Then, x[1][0] is divided into two bits,x[1][0][0] which is the code > > > which is 1 (RFC822){12273}, which is (guessing here) UID, what I > > > requested and... ? then, > > > x[1][0][1] is the data without server return codes, or that additional code. > > > > > > How am I doing? > > > > > > So, for error catching, I check x[0], not sure what I'd use x[1][0][0] > > > for, if it is the UID, it would be good for keeping track of which > > > email is where, and x[1][0][1] is what I was trying to fetch. > > > > > > Thanks, Michael, and please correct me if my conclusions are erroneous. > > > /me runs off to re-examine tuples in tutorial. > > > > > > (Oh, and those links you posted don't point to live sites, but google > > > has caches -) > > > http://www.google.co.nz/search?q=cache:YWgEVsgYXgAJ:aspn.activestate.com/ASPN/Mail/Message/python-Tutor/1619598+&hl=en > > > http://www.google.co.nz/search?q=cache:4Fr-5SCPsTgJ:aspn.activestate.com/ASPN/Mail/Message/python-Tutor/1619609+&hl=en > > > > > > Regards, > > > > > > Liam Clarke > > > > > > > > > On Fri, 15 Oct 2004 18:38:36 +0200, Michael Janssen > > > wrote: > > > > On Thu, 14 Oct 2004 21:42:59 +1300, Riumu Kuraku wrote: > > > > > > > > > Just tryng to understand the email package, and the docs are a > > > > > little... sparse? > > > > > > > > Would be nice to have some more examples in the example section. > > > > Someone needs to write them ... > > > > > > > > > a=test.fetch(1, 'RFC822' )... The first argument of fetch is fine. > > > > > It's the second that's got me. It's a name of a Internet standard. And > > > > > I used it on three different emails, and it got two headers, and one > > > > > header and full text. So I am quite confused as to how exactly to get > > > > > specific things, like headers/text/attachments only, so any light that > > > > > can be shed in that regard would be fantastic. > > > > > > > > some time past, but googles knows it: > > > > http://aspn.activestate.com/ASPN/Mail/Message/python-Tutor/1619598 > > > > > > > > and: > > > > http://aspn.activestate.com/ASPN/Mail/Message/python-Tutor/1619609 > > > > > > > > To quote myself: > > > > "rfc3501 section 6.4.4 lists all possibilities" > > > > > > > > --> section 6.4.5 lists all possibilities of the fetch command. > > > > > > > > That's the point the the imaplib docs: you *need* to read the rfc's to > > > > get them (imaplib docs should state this ...). > > > > > > > > > >>>print j.parse(x) > > > > > AttributeError: 'tuple' object has no attribute 'readline' > > > > > > > > > > #OK, so x is a tuple, and it has no attr, readline...hmmm... > > > > > > > > it's a tuple of the server returncode ("OK") and a list of messages > > > > (which are tuples in turn). > > > > > > > > x[1] # list of messages > > > > x[1][0] # first one > > > > x[1][0][1] # content of first one. That's bad, eh? > > > > > > > > > #Run off to docs, and open parser.py to have a look and: > > > > > > > > > > >>>print j.parsestr(x) #Turns out, Parser.parse() is for file > > > > > objects... Parser.parsestr() > > > > > # is for string objects, as I am about to learn. > > > > > > > > > > TypeError: expected read buffer, tuple found > > > > > > > > > > #Still not liking tuple. Hmmm... > > > > > > > > > >>>i=str(x) > > > > > >>>print j.parsestr(i) > > > > > > > > converting the whole tuple into a string, poor parser is confused by > > > > all those brackets and 'OK' messages. So it will "parse" message > > > > without extracting much information from it. > > > > > > > > try something like: > > > > > > > > msg = x[1][0][1] > > > > print msg > > > > > > > > or: > > > > print j.parsestr(msg) > > > > > > > > regards > > > > Michael > > > > > > > > > > From bill.mill at gmail.com Sun Oct 17 05:13:06 2004 From: bill.mill at gmail.com (Bill Mill) Date: Sun Oct 17 05:13:08 2004 Subject: [Tutor] Working with dates In-Reply-To: References: Message-ID: <797fe3d4041016201368e316c1@mail.gmail.com> Liam, check out the mx.DateTime library at http://www.egenix.com/files/python/mxDateTime.html . In specific, look at the RelativeDate class; if you don't want to include this as a requirement in your software, look at how they code it. Peace Bill Mill bill.mill at gmail.com On Sun, 17 Oct 2004 15:11:33 +1300, Liam Clarke wrote: > Kia ora all, > > I am trying to write a function that will get today's date when run, > and set a string to the date of a day in the previous week. > > i.e. it's Saturday the 16th of October, and I want to find the date of > Friday last week. > I want to generate a date string that is valid for the IMAP4 protocol, > so it must be in format > 16-Oct-2004. > > It will be run once a week, usually on a Monday, usually looking for > the last Friday. I want it to be able to handle Friday being in a > different month or year and still give a precise date. > > This is what I've done so far, but I'm sure there's a more efficient > way to do it, so feedback is gratefully received. > > A little note on day_offset - > > gmtime() returns a integer representing the day of the week, Monday to > Sunday is 0 to 6. > > So, I set up a wee index spanning two weeks like so: - > > M T W T F S S M T W T F S S > -7 -6 -5 -4 -3 -2 -1 ( 0 1 2 3 4 5 6) > > The numbers in brackets are returned by calendar.weekday, the negative > ones are my constructs. > > import time > import datetime > > day_offset=-3 #Friday of previous week, will be changable by user in config > > gm_data=time.gmtime() #Get today's date/time > > (year, month, day, weekday)=gm_data[0], gm_data[1], gm_data[2], > gm_data[6] #Only need first 3 values and 7th, which is weekday. > > date_offset = -(day_offset-weekday) > > # This is to work with datetime.timedelta,which works with positive days. > # so it works out to date_offset = - ( -3 - 5) = 8 > > last_friday=datetime.date(year, month, day) - > datetime.timedelta(days=date_offset) > > #Create date object for today's date, to use Python's built handling > of date arithmetic. > #timedelta is difference, so last_friday = today's date - 8 days > > retrieve_date_string=str(last_friday) > #last_friday is an object, I need a string so that I can reformat the date > (last_friday outputs as 2004-10-08) > > split_date=retrieve_date_string.split('-') > > email_sent_date=time.strftime("%d-%b-%Y", (int(split_date[0]), > int(split_date[1]), int(split_date[2]), 0, 0, 0, 0, 0, 0)) > > (time.strftime looks for a tuple of (year, month, day, hour, minute, > second, weekday, day of year, and something called tm_isdst) I can't > pass it my last_friday object, so I have to generate a tuple for last > Friday. gmtime() generates the 9 value tuple normally.) > > And email_sent_date = "8-Oct-2004" > > Am I using redundant code anywhere? I just found a redundancy in that > I was using gmtime() to get my year month and day, but was using > calendar.weekday to get my week day value, when gmtime() generates it > anyway. > > I can see a problem here, if this is run on the Saturday or Sunday, it > won't get the Friday just been, but the Friday previously. So, I may > just add a catcher for if weekday >= 5 > > Thank-you for your time > > Liam Clarke > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From amonroe at columbus.rr.com Sun Oct 17 05:57:22 2004 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Sun Oct 17 05:57:34 2004 Subject: [Tutor] Simple Question... In-Reply-To: <797fe3d404101619306051e62a@mail.gmail.com> References: <20041016174645.31391.qmail@web61009.mail.yahoo.com> <8464C062-1F9E-11D9-8BDA-000393CBC88E@yahoo.fr> <47856308316.20041016165216@columbus.rr.com> <797fe3d4041016143034feddd3@mail.gmail.com> <135873078670.20041016213147@columbus.rr.com> <797fe3d404101619306051e62a@mail.gmail.com> Message-ID: <26881814011.20041016235722@columbus.rr.com> > the file. It must be capable of returning the first line, the last > line, and anything in between. Your fortune file was a bit hard to debug with since many lines were blank. I'll attach the test file I ended up using. Repeatedly opening/closing the file in question is murder, in a tight loop. Doing an os.path.getsize() is pretty slow too. If you do both of those on the outside of the tight loop, it really speeds up. C:\coding\python>python randomline.py 4.13174830879 (open/close the file each time) 2.369336885 (open the file outside the loop) 0.68840117948 (open and get size outside the loop) Times given are for 20000 iterations on a 2.4ghz laptop. Alan -------------- next part -------------- 1ldkfg 2aasd 3srgn 4der 5zd 6xf 7dt 8rs 9yi 10dfg 11xr 12m 13dth 14js 15gth 16dxfgn 17drn 18hs 19g 20nd 21thm 22dth 23nxd 24g 25hr 26dhj 27dsr 28gk 29dfty 30ur 31dftm 32d 33gx 34fn 35d 36thm 37dr 38hfm 39r 40hs 41etjdtrhdj 42d 43thm 44dm 45thd,dthkmd 46dhn 47dthmsdrt 48ncvbn c -------------- next part -------------- import os.path import random import time def getrandomline1(filename): size = os.path.getsize(filename) testfile = open(filename, 'r') firstline = testfile.readline() secondline = testfile.readline() retval="" while len(retval) < 1: randpos = random.randint(1, size) if randpos <= len(firstline): retval = firstline else: testfile.seek(randpos) if randpos <= len(firstline) + len(secondline): testfile.seek(1-len(secondline), 1) testfile.readline() retval = testfile.readline() testfile.close() return (randpos, retval.strip()) def getrandomline2(filename, testfile): size = os.path.getsize(filename) testfile.seek(0) firstline = testfile.readline() secondline = testfile.readline() retval="" while len(retval) < 1: randpos = random.randint(1, size) if randpos <= len(firstline): retval = firstline else: testfile.seek(randpos) if randpos <= len(firstline) + len(secondline): testfile.seek(1-len(secondline), 1) testfile.readline() retval = testfile.readline() return (randpos, retval.strip()) def getrandomline3(filename, testfile, size): testfile.seek(0) firstline = testfile.readline() secondline = testfile.readline() retval="" while len(retval) < 1: randpos = random.randint(1, size) if randpos <= len(firstline): retval = firstline else: testfile.seek(randpos) if randpos <= len(firstline) + len(secondline): testfile.seek(1-len(secondline), 1) testfile.readline() retval = testfile.readline() return (randpos, retval.strip()) starttime=time.clock() for x in range(20000): randline=getrandomline1('test.txt') endtime=time.clock() print endtime-starttime filehandle = open('test.txt', 'r') starttime=time.clock() for x in range(20000): randline=getrandomline2('test.txt', filehandle) endtime=time.clock() filehandle.close() print endtime-starttime filehandle = open('test.txt', 'r') filesize = os.path.getsize('test.txt') starttime=time.clock() for x in range(20000): randline=getrandomline3('test.txt', filehandle, filesize) endtime=time.clock() filehandle.close() print endtime-starttime From kent_johnson at skillsoft.com Sun Oct 17 06:44:21 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Sun Oct 17 06:44:59 2004 Subject: [Tutor] Working with dates In-Reply-To: References: Message-ID: <6.1.0.6.0.20041017004150.0289f9c8@mail4.skillsoft.com> That's pretty complicated. What about this? import datetime lastFriday = datetime.date.today() oneday = datetime.timedelta(days=1) while lastFriday.weekday() != 4: lastFriday -= oneday print lastFriday.strftime('%d-%b-%Y') Kent At 03:11 PM 10/17/2004 +1300, Liam Clarke wrote: >Kia ora all, > >I am trying to write a function that will get today's date when run, >and set a string to the date of a day in the previous week. > >i.e. it's Saturday the 16th of October, and I want to find the date of >Friday last week. >I want to generate a date string that is valid for the IMAP4 protocol, >so it must be in format >16-Oct-2004. > >It will be run once a week, usually on a Monday, usually looking for >the last Friday. I want it to be able to handle Friday being in a >different month or year and still give a precise date. > >This is what I've done so far, but I'm sure there's a more efficient >way to do it, so feedback is gratefully received. > >A little note on day_offset - > >gmtime() returns a integer representing the day of the week, Monday to >Sunday is 0 to 6. > >So, I set up a wee index spanning two weeks like so: - > > M T W T F S S M T W T F S S >-7 -6 -5 -4 -3 -2 -1 ( 0 1 2 3 4 5 6) > >The numbers in brackets are returned by calendar.weekday, the negative >ones are my constructs. > >import time >import datetime > >day_offset=-3 #Friday of previous week, will be changable by user in config > >gm_data=time.gmtime() #Get today's date/time > >(year, month, day, weekday)=gm_data[0], gm_data[1], gm_data[2], >gm_data[6] #Only need first 3 values and 7th, which is weekday. > >date_offset = -(day_offset-weekday) > ># This is to work with datetime.timedelta,which works with positive days. ># so it works out to date_offset = - ( -3 - 5) = 8 > >last_friday=datetime.date(year, month, day) - >datetime.timedelta(days=date_offset) > >#Create date object for today's date, to use Python's built handling >of date arithmetic. >#timedelta is difference, so last_friday = today's date - 8 days > >retrieve_date_string=str(last_friday) >#last_friday is an object, I need a string so that I can reformat the date >(last_friday outputs as 2004-10-08) > >split_date=retrieve_date_string.split('-') > >email_sent_date=time.strftime("%d-%b-%Y", (int(split_date[0]), >int(split_date[1]), int(split_date[2]), 0, 0, 0, 0, 0, 0)) > >(time.strftime looks for a tuple of (year, month, day, hour, minute, >second, weekday, day of year, and something called tm_isdst) I can't >pass it my last_friday object, so I have to generate a tuple for last >Friday. gmtime() generates the 9 value tuple normally.) > >And email_sent_date = "8-Oct-2004" > >Am I using redundant code anywhere? I just found a redundancy in that >I was using gmtime() to get my year month and day, but was using >calendar.weekday to get my week day value, when gmtime() generates it >anyway. > >I can see a problem here, if this is run on the Saturday or Sunday, it >won't get the Friday just been, but the Friday previously. So, I may >just add a catcher for if weekday >= 5 > >Thank-you for your time > >Liam Clarke >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From CryptoLevel9 at aol.com Sun Oct 17 07:25:12 2004 From: CryptoLevel9 at aol.com (CryptoLevel9@aol.com) Date: Sun Oct 17 07:25:19 2004 Subject: [Tutor] Values in matrices Message-ID: <1ee.2c607e05.2ea35c38@aol.com> Lets say you have a N x M matrix initially filled with zeros and you need to place a value, lets say V, in some row X and column Y where V, X, and Y are all values determined by user input and X and Y are less than or equal to N and M respectively. If this is possible, could this be done many times for different values of V and different values of X and Y without assigning the values V, X, and Y new variable names for each new value, possibly using some form of programming loop? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20041017/9c771ec3/attachment.html From dyoo at hkn.eecs.berkeley.edu Sun Oct 17 08:15:51 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun Oct 17 08:15:55 2004 Subject: [Tutor] Late Introduction In-Reply-To: <000001c4b3dd$8e7149f0$dc5328cf@JSLAPTOP> Message-ID: On Thu, 14 Oct 2004, Jacob S. wrote: > I'm sorry guys. It never occurred to me to introduce myself to you > before. Hi Jacob, No problem, don't worry about it. Welcome aboard! > I wanted to know how to print to a file because I was writing a (barely) > functioning raw_input sort of barcoding interpreter for the CueCat > scanners. [some text cut] > The reason I want to print a file -- or I guess I should say a string, > it would be more convenient -- is the fact that I wish to print > receipts. I could most possibly latch on to a receipt printer on ebay. You can print to a file by first opening up the file in 'write' mode. For example: ### myfile = open("reciept.txt", "w") ### Be careful, though: when we open a file in this "write" mode, it ends up clearing the file, so if there was stuff in there previously, it'll get erased after that open() call above. Once we have an opened file, we can use the print statement. There's a special way to use print on a file: ### print >>myfile, "this is a test. Hello world!" ### Is this what you're looking for? Please feel free to ask more questions on the Tutor list. Good luck! From dyoo at hkn.eecs.berkeley.edu Sun Oct 17 08:23:29 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun Oct 17 08:23:32 2004 Subject: [Tutor] Working with dates In-Reply-To: <797fe3d4041016201368e316c1@mail.gmail.com> Message-ID: > > I am trying to write a function that will get today's date when run, > > and set a string to the date of a day in the previous week. > check out the mx.DateTime library at > http://www.egenix.com/files/python/mxDateTime.html . In specific, look > at the RelativeDate class; if you don't want to include this as a > requirement in your software, look at how they code it. Alternatively, we can use the DateTime class in the Standard Library: http://www.python.org/doc/lib/module-datetime.html The classes there allow us to represent dates and time-difference "deltas", and they should be perfect for this problem. For example, here is a function for figuring out when the next 8:00am will be: ### def getTargetTime(hour=8, minute=00, second=0): """Returns the next upcoming datetime with the given hour, minute, or second. The target datetime can be either today or tomorrow.""" DAYDELTA = datetime.date.resolution currentTime = datetime.datetime.today() targetTime = currentTime.replace(hour=hour, minute=minute, second=second) if targetTime > currentTime: return targetTime else: return targetTime + DAYDELTA ### It's part of a small "alarm clock" program that I wrote for myself... *grin* It should be useful for what Liam is trying to do. Good luck! From alan.gauld at freenet.co.uk Sun Oct 17 09:03:57 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun Oct 17 09:03:33 2004 Subject: [Tutor] Find out if a number is even or not References: <1097838018.416fadc261290@webmail.freedom2surf.net><24d253d904101520094f73a206@mail.gmail.com><24d253d904101610453b801a62@mail.gmail.com> <797fe3d4041016132643f0e2f9@mail.gmail.com> Message-ID: <010201c4b417$792b60f0$d79b8851@xp> > def isEven1(n): return not n&1 > def isEven2(n): return n % 2 == 0 > def isEven3(n): return n % 2 and 'Odd' or 'Even' Since the last is doing something quite different could you try: def isEven4(n): return n%2 and False or True Which makes it closer to the others. I'd still expect it to be slower but I wonder whether it closes the gap in any way? Alan g From cyresse at gmail.com Sun Oct 17 11:06:24 2004 From: cyresse at gmail.com (Liam Clarke) Date: Sun Oct 17 11:06:26 2004 Subject: [Tutor] Working with dates In-Reply-To: References: <797fe3d4041016201368e316c1@mail.gmail.com> Message-ID: Thanks all for your responses, I think one of my weaknesses in this is a poor understanding of how to properly utilise classes. gm_data=time.gmtime()... ....((split_date[2]), 0, 0, 0, 0, 0, 0)) I have 2 datetime.date instances there, and I'm not using them to their full capability, looking at Kent's example 'lastFriday=datetime.date.today()' I gather this creates a date instance called lastFriday and gives it today's date/time values? 'while lastFriday.weekday() != 4:' and I'm guessing that the method weekday in class date generates an integer value for day of the week, and that it generates that based on the stored date in lastFriday. 'lastFriday -= oneday' I don't quite understand what -= does. It's not a boolean/arithmetic operator? Is it peculiar to the datetime module? I'm guessing it increments the date stored in lastFriday back by period oneday? what is different between - and -= ? 'print lastFriday.strftime('%d-%b-%Y')' and of course, you can generate a string direct from lastFriday using the strftime method... ( because datetime supercedes the date and time modules?) It's all very clear to me now, hindsight is great that way. (Just spent ten minutes rereading manual on date class, and it now makes more sense, this OOP thing.) I read the tutorials on OOP, but it kind of went over my head. So an instance of the class date, can hold variables such as year etc. and then run a contained function (like strftime) on that variable.... the light dawns.... Danny, I don't quite understand what datetime.date.resolution does exactly. Your function generates the targetTime, and checks that it hasn't already happened, but if it does it adds DAYDELTA? Thank you for your knowledge and help. I'm learning heaps. And Kent, your code does exactly what I need, and so elegantly too. From kent_johnson at skillsoft.com Sun Oct 17 14:44:35 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Sun Oct 17 14:44:41 2004 Subject: [Tutor] Working with dates In-Reply-To: References: <797fe3d4041016201368e316c1@mail.gmail.com> Message-ID: <6.1.0.6.0.20041017064935.028cfc08@mail4.skillsoft.com> At 10:06 PM 10/17/2004 +1300, Liam Clarke wrote: >Thanks all for your responses, > >I think one of my weaknesses in this is a poor understanding of how to >properly utilise classes. Or more specifically a lack of understanding of the classes in the standard library :-) There are many, many very useful classes included with Python. Most of them are documented in the Library Reference at http://docs.python.org/lib/lib.html. Browsing this reference is a good way to learnabout what Python can do. >'lastFriday=datetime.date.today()' I gather this creates a date >instance called lastFriday and gives it today's date/time values? > >'while lastFriday.weekday() != 4:' and I'm guessing that the method >weekday in class date generates an integer value for day of the week, >and that it generates that based on the stored date in lastFriday. Take a look at the docs for the datetime module. The easiest way to look up a specific module is from the Global Module Index (http://docs.python.org/modindex.html). This takes us to the datetime module and the page for datetime.date. There you will find the entries today( ) Return the current local date. This is equivalent to date.fromtimestamp(time.time()). and weekday( ) Return the day of the week as an integer, where Monday is 0 and Sunday is 6. For example, date(2002, 12, 4).weekday() == 2, a Wednesday. So your guesses are correct. >'lastFriday -= oneday' I don't quite understand what -= does. >It's not a boolean/arithmetic operator? Is it peculiar to the datetime >module? I'm guessing it increments the date stored in lastFriday back >by period oneday? > >what is different between - and -= ? In general for any binary operator , x = y is the same as x = x y So lastFriday -= oneday is the same as lastFriday = lastFriday - oneday >'print lastFriday.strftime('%d-%b-%Y')' and of course, you can >generate a string direct from lastFriday using the strftime method... >( because datetime supercedes the date and time modules?) It doesn't supercede them, but it does duplicate some functionality. I think the intent when datetime was added was to make it easier to work with dates and times. >It's all very clear to me now, hindsight is great that way. > >(Just spent ten minutes rereading manual on date class, and it now >makes more sense, this OOP thing.) > >I read the tutorials on OOP, but it kind of went over my head. > >So an instance of the class date, can hold variables such as year etc. >and then run a contained function (like strftime) on that variable.... Exactly >the light dawns.... > >Danny, I don't quite understand what datetime.date.resolution does >exactly. Your function generates the targetTime, and checks that it >hasn't already happened, but if it does it adds DAYDELTA? datetime.date.resolution is the same as my oneday variable, it is the time interval of a day. Danny's code makes a date object that represents 8am today; if that time is in the past then it changes it to 8am tomorrow by adding datetime.date.resolution. Kent >Thank you for your knowledge and help. I'm learning heaps. >And Kent, your code does exactly what I need, and so elegantly too. >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From alan.gauld at freenet.co.uk Sun Oct 17 16:58:09 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun Oct 17 16:57:40 2004 Subject: [Tutor] Values in matrices References: <1ee.2c607e05.2ea35c38@aol.com> Message-ID: <014101c4b459$b7d93150$d79b8851@xp> > Lets say you have a N x M matrix initially filled with zeros and you need to > place a value, lets say V, in some row X and column Y where V, X, and Y are > all values determined by user input and X and Y are less than or equal to N > and M respectively. You can write a function (or create a class!): def insertValueInMatrixAt(v, m, x, y): m[x][y] = v > If this is possible, could this be done many times for > different values of V and different values of X and Y # assume matrix created elsewhere... while True: value = raw_input('Value (Hit enter to stop): ') if not value: break value = int(value) row = int(raw_input('Row: ')) col = int(raw_input('Column: ')) if row < N and col < M: insertValueInMatrixAt(value, matrix, row, col) Should do something like what you want? You could just use the assignment directly of course but I'd actually be tempted to move the data validation inside the function too... Alan G. From alan.gauld at freenet.co.uk Sun Oct 17 17:02:04 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun Oct 17 17:02:38 2004 Subject: [Tutor] Working with dates References: <797fe3d4041016201368e316c1@mail.gmail.com> Message-ID: <014c01c4b45a$43ec9150$d79b8851@xp> > what is different between - and -= ? - just subtracts -= also assigns the result x-y calculates a value x -= y gives x the value of x-y thus it is equivalent to: x = x-y There are similar += and *= operators. HTH, Alan G From Dragonfirebane at aol.com Mon Oct 18 01:02:37 2004 From: Dragonfirebane at aol.com (Dragonfirebane@aol.com) Date: Mon Oct 18 01:03:21 2004 Subject: [Tutor] Late Introduction Message-ID: <1c4.1f79d43a.2ea4540d@aol.com> Or you could just do myfile = open("reciept.txt", "a") to append to the end of the file. Email: dragonfirebane@aol.com AIM: singingxduck Programming Python for the fun of it. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20041017/4938826a/attachment.htm From rmkrauter at yahoo.com Mon Oct 18 02:23:00 2004 From: rmkrauter at yahoo.com (Rich Krauter) Date: Mon Oct 18 02:22:58 2004 Subject: [Tutor] Simple Question... In-Reply-To: <797fe3d404101619306051e62a@mail.gmail.com> References: <20041016174645.31391.qmail@web61009.mail.yahoo.com> <8464C062-1F9E-11D9-8BDA-000393CBC88E@yahoo.fr> <47856308316.20041016165216@columbus.rr.com> <797fe3d4041016143034feddd3@mail.gmail.com> <135873078670.20041016213147@columbus.rr.com> <797fe3d404101619306051e62a@mail.gmail.com> Message-ID: <41730CE4.9050907@yahoo.com> Bill Mill wrote: > OK, I posted a fortune file to my webserver. It's at > http://llimllib.f2o.org/files/osfortune . I see 2 competitions: > > 1) fastest function to find a random line from the file; the catch is > that this function must be able to pick a random line from anywhere in > the file. It must be capable of returning the first line, the last > line, and anything in between. > > 2) fastest function to count the lines in the file. > I doubt the following is the fastest on either point - just figured I'd post it since it uses built-in module linecache, which I haven't seen mentioned in this thread yet. Just like some of the posted solutions, linecache reads the entire file into a list; that module's code may be of interest to those proposing that type of solution. import random import linecache def getrandomline(fname,nlines): n = random.randint(0,nlines) return n,linecache.getline(fname,n) def wcl(fname): # make sure file has been cached; to do so, # run linecache.getline() and discard result if not linecache.cache[fname]: linecache.getline(fname,1) # return number of lines in file return len(linecache.cache[fname][2]) if __name__ == '__main__': print getrandomline('junk.txt',wcl(fname)) The linecache module doesn't have a function to return the number of lines in a file; but it very easily could provide one since the cached file's lines are available in a list. I used that fact to count the number of lines, in wcl() above, rather than opening the file again to count its lines. Rich From carroll at tjc.com Mon Oct 18 03:00:50 2004 From: carroll at tjc.com (Terry Carroll) Date: Mon Oct 18 03:01:07 2004 Subject: [Tutor] Why doesn't this filter FutureWarning? Message-ID: Here's what I get in the interactive session: >>> num=0x1234 >>> import warnings >>> num=num & 0xffffffff :1: FutureWarning: hex/oct constants > sys.maxint will return positive va lues in Python 2.4 and up >>> warnings.filterwarnings('ignore', "hex/oct constants", FutureWarning) >>> num=num & 0xffffffff That's just what I'd expect. I get the FutureWarning on the first try, but after invoking filterwarnings, I no longer get it. But when I do the same code from inside a file: C:\test>cat fw.py num=0x1234 import warnings num=num & 0xffffffff warnings.filterwarnings('ignore', "hex/oct constants", FutureWarning) num=num & 0xffffffff C:\test>python fw.py fw.py:3: FutureWarning: hex/oct constants > sys.maxint will return positive valu es in Python 2.4 and up num=num & 0xffffffff fw.py:5: FutureWarning: hex/oct constants > sys.maxint will return positive valu es in Python 2.4 and up num=num & 0xffffffff What gives? Why would this work in an interactive session, but not from a file? From keridee at jayco.net Mon Oct 18 04:05:55 2004 From: keridee at jayco.net (Jacob S.) Date: Mon Oct 18 04:05:10 2004 Subject: [Tutor] Late Introduction References: <000001c4b3dd$8e7149f0$dc5328cf@JSLAPTOP> Message-ID: <004801c4b4b7$037cc560$e95428cf@JSLAPTOP> Hello again! What I actually meant was to send a text file to a printer connected to a parallel or usb port. I happen to know that I could dynamically write a batch file that would print the particular file and use os.startfile() to run it. However, recently I noticed that one of the modules has functions for executing one line command line commands. So I could probably skip the batch command. (It would look something like this "myfile.txt > lpt1". Anyway, I was looking for something that would skip the use of command line commands and just use a python function instead. Thanks for the interesting new way to write to a file though. I have been using just things like, >>> a = open("myfile.txt","w") >>> stri = "Hello world, how are you today? " # I use stri as the variable because string and str are potentially reserved words. >>> a.write(stri) >>> a.close() >>> I thank you again for the print >>myfile,"This is a test. Hello world. " Jacob Schmidt From cowboycody016 at verizon.net Mon Oct 18 04:07:16 2004 From: cowboycody016 at verizon.net (Cody) Date: Mon Oct 18 04:07:20 2004 Subject: [Tutor] help. Message-ID: <000801c3951a$a2f3a270$6400a8c0@cody368747> ok i want a program to put a audio file and a video file together on a track. i have a program but i want one for other ppl that need it. i do animation, witch saves it to .avi and audio to .wav i need to combine them to .wmv on a track. and i want it to have like an interface i can make them in photoshop and save as .jpeg for the program or whatever format it needs. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20041018/70282a45/attachment.html From cowboycody016 at verizon.net Mon Oct 18 04:07:52 2004 From: cowboycody016 at verizon.net (Cody) Date: Mon Oct 18 04:07:53 2004 Subject: [Tutor] help!!! Message-ID: <001801c3951b$2b7cca40$6400a8c0@cody368747> how can i decompile a .exe file. thanks,cody -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20041018/fb7cda2e/attachment.htm From keridee at jayco.net Mon Oct 18 04:18:25 2004 From: keridee at jayco.net (Jacob S.) Date: Mon Oct 18 04:17:42 2004 Subject: [Tutor] Index out of range References: <20041014231613.58349.qmail@web53704.mail.yahoo.com> Message-ID: <005301c4b4b8$c34f41f0$e95428cf@JSLAPTOP> I know your what your problem is! You started you col referencing with 1. Python starts indexing at 0. For example. >>> a = [1,2,3,4,1,5] >>> a[0] 1 >>> a[5] 5 >>> a[6] Traceback (most recent call last): File "", line 1, in ? IndexError: list index out of range >>> Your script goes from col[1] to col[71]. col[71] is not recognized because it actually references item 72, which doesn't exist. I agree with Kent Johnson, it would be a lot easier to use the join function than to write out all of those list references. > >"insert into table "+tname+" values('" + "', '".join(col) + "')" > HTH, Jacob Schmidt From cmeesters at ucdavis.edu Mon Oct 18 05:16:08 2004 From: cmeesters at ucdavis.edu (Christian Meesters) Date: Mon Oct 18 05:16:15 2004 Subject: [Tutor] Values in matrices Message-ID: <0E3FB31D-20B4-11D9-AF03-000393D8EC3A@ucdavis.edu> Hi, Sorry, my reply might come a little late ... Of course you can use a function like the one presented by Alan. But for the case you have other demands on matrices as well, you might want to check out additional modules: http://www.stsci.edu/resources/software_hardware/numarray or: http://www.pfdubois.com/numpy/ Working with the numarray module might make your task(s?) a little easier ... Cheers Christian From dyoo at hkn.eecs.berkeley.edu Mon Oct 18 05:51:11 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Oct 18 05:51:15 2004 Subject: [Tutor] help!!! In-Reply-To: <001801c3951b$2b7cca40$6400a8c0@cody368747> Message-ID: On Fri, 17 Oct 2003, Cody wrote: > how can i decompile a .exe file. This is difficult to do in general. .EXE "executable" files are intended for machines. .EXE files are produced by compilers, and these compilers will often strip off information that a human would need to understand a program. As a concrete example, we can take a Python function, and ask the system what the "bytecodes" --- the primitive instructions --- will look like: ### >>> def square(x): ... return x * x ... >>> import dis >>> dis.dis(square) 2 0 LOAD_FAST 0 (x) 3 LOAD_FAST 0 (x) 6 BINARY_MULTIPLY 7 RETURN_VALUE 8 LOAD_CONST 0 (None) 11 RETURN_VALUE ### What you are asking is something equivalent to going the other way around: that is, to take the binary instructions and try to infer the original source code. Python doesn't do heavy postprocessing on bytecode, so there are decompilers for Python bytecode: http://www.crazy-compilers.com/decompyle/ But for the general case, given an .EXE, I don't think there's a good way to get back comprehensible source code. Hope this helps! From alan.gauld at freenet.co.uk Mon Oct 18 06:04:43 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon Oct 18 06:04:12 2004 Subject: [Tutor] help!!! References: <001801c3951b$2b7cca40$6400a8c0@cody368747> Message-ID: <017201c4b4c7$99a426e0$d79b8851@xp> > how can i decompile a .exe file. You can use the DOS DEBUG command to disassemble an EXE back into assembler. True decompiling is extremely difficult because you don't know what language it was written in, and even if you do there aren't many decompilers around. And the few that exist are very expensive. But even if you did decompile/disassemble an exe it would be hard to read since the layout would be gone and there would be no comments... Any reason why you need to do this or is it just curiosity? (THere may be another way to achieve your goal...) Alan G. From cyresse at gmail.com Mon Oct 18 11:22:22 2004 From: cyresse at gmail.com (Liam Clarke) Date: Mon Oct 18 11:22:25 2004 Subject: [Tutor] Would an OOP approach be simpler? Message-ID: Hi all, This module (code below), is comprised of functions, which are run by a main function, which just passes bits of data around. http://rafb.net/paste/results/mpCxox91.html Still trying to 'reconfigure my brain' (as several OOP tutorials put it), to understand the 'OOP paradigm' as nearly every OOP site puts it. At the very least, repartition my brain and install an OOP OS in a separate section. : ) My module is pretty much going to do one thing (get emails, and dump their attachments in a directory for another module to extract info, which will pass the info to another module which will generate a csv of the extracted data, and email it again, all feeding back at appropriate times to a small GUI), and all the bits of data being flung from function to function (in quite a linear sequence), will be self-contained within that module. I can see two functions which may be used by other modules, but the values they use won't change, they'll just hand them to different functions to play with (i.e the load cfg module will load the config file, and pass the information to a function which allows the user to change the config, and the second function will then save the config) I really need a situation that screams 'objects are the only way' to work on to comprehend why OOP = good I think. The OOP tutorials I've found tend to be OOP for the sake of OOP... Thoughts appreciated. (And there are several errors in the posted code, like my except clause when trying to login, but that's because I haven't gotten around to that yet. And some are typos. : ) ) From melnyk at gmail.com Mon Oct 18 13:31:34 2004 From: melnyk at gmail.com (Scott Melnyk) Date: Mon Oct 18 13:31:38 2004 Subject: [Tutor] nested lists of data Message-ID: Hello! I am looking at data in the form of Type, subgroup, data it is genetic data so I will try to make this a generic question but includ ethe real data so someone can help explain what I have done wrong or a better way to go about this. Type 1 may have 1 or more subgroups, each subgroub must have at least one piece of data format is : (although it looks here like the exons on on separate lines, in the data file the new line occurs only after NEW GENE, NEW TRANSCRIPT and the last exon in a transcript (and thewhite space line is just newlline) type subgroup data ENSG is gene id ENST is transcript id ENSE the exons NEW GENE ENSG00000187908.1 ENST00000339871.1 ENSE00001383339.1 ENSE00001387275.1 ENSE00001378578.1 ENSE00001379544.1 ENSE00001368222.1 ENSE00001372264.1 ENSE00001365999.1 NEW TRANSCRIPT ENSG00000187908.1 ENST00000344399.1 ENSE00001384814.1 ENSE00001374811.1 ENSE00001391015.1 ENSE00001370692.1 ENSE00001372884.1 ENSE00001386551.1 ENSE00001386137.1 NEW TRANSCRIPT ENSG00000187908.1 ENST00000338354.1 ENSE00001364942.1 ENSE00001379878.1 ENSE00001376065.1 ENSE00001379576.1 NEW GENE ENSG00000129899.5 ENST00000306922.4 ENSE00001350558.2 ENSE00001316817.3 ENSE00001149607.1 ENSE00001149600.1 ENSE00001149591.1 ENSE00001149579.1 ENSE00001383071.1 ENSE00001149558.2 ENSE00001149547.1 ENSE00001302825.1 ENSE00001149539.1 ENSE00001149529.1 ENSE00001186785.1 ENSE00001350475.1 ENSE00001350469.2 ENSE00001350465.2 ENSE00001350461.2 ENSE00001350458.2 ENSE00001309288.1 ENSE00001149467.2 ENSE00001250660.4 NEW TRANSCRIPT ENSG00000129899.5 ENST00000306944.5 ENSE00001350584.2 ENSE00001316817.3 ENSE00001149607.1 ENSE00001149600.1 ENSE00001149591.1 ENSE00001149579.1 ENSE00001383071.1 ENSE00001149558.2 ENSE00001149547.1 ENSE00001302825.1 ENSE00001149539.1 ENSE00001149529.1 ENSE00001186785.1 I would like to use sets to generate a txt file of any data in the transcripts that is repeated between each transcript. So for a given gene each if each transcript has exons x and y then I want to know that. In another way, within a group (GENE) if all subgroups(transcripts) contain exon(s) x(y,z, or more) then write to a file that contain gene id then all exons that are in all transcripts for gene x ENSG00000129899.5 ENSE00001149539.1 ENSE00001149579.1 the output file is equivilent to group x data 3 data4 group x data 7 data 9 data 10 etc. here is what i am trying-the print statements are for checking the program as I go along they will be removed info=re.compile('^(ENSG\d+\.\d).+(ENST\d+\.\d).+(ENSE\d+\.\d)+') #above is match gene, transcript, then one or more exons exonArray=[] geneflag=0 transArray=[] AllTrans=[] for line in TFILE: Matched2= info.match(line) if line.startswith('NEW GENE'): geneflag=geneflag+1 transloop=0 if Matched2: if line.startswith('ENS'): geneid,transid,exons=line.split(None,2) exonArray=exons.split() print "this is the gene "+geneid print "this is the transcript "+transid print "these are the exons: \n" for exon in exonArray: print exon ," ", print "\n" print transloop #up to here seems to be working fine by the output #problems here transArray[transloop]=exonArray #transArray[0]=exonArray tried this same error transloop=transloop+1 AllTrans[geneflag]=transArray[transloop] if not line.startswith('ENS'): break when run I get: Z:\datasets>C:\scomel\python2.3.4\python.exe Z:\scripts\MondayExonRemoval.py Mo dayTest.txt MonOct18spam.txt this is the gene ENSG00000187908.1 this is the transcript ENST00000339871.1 these are the exons: ENSE00001383339.1 ENSE00001387275.1 ENSE00001378578.1 ENSE00001379544.1 ENSE00001368222.1 ENSE00001372264.1 ENSE00001365999.1 ENSE00001377564.1 ENSE00001382923.1 ENSE00001366872.1 ENSE00001372652.1 ENSE00001374822.1 ENSE00001390913.1 ENSE00001386215.1 ENSE00001378373.1 ENSE00001389805.1 ENSE00001367196.1 ENSE00001377652.1 ENSE00001375990.1 ENSE00001386225.1 0 Traceback (most recent call last): File "Z:\scripts\MondayExonRemoval.py", line 58, in ? transArray[transloop]=exonArray IndexError: list assignment index out of range I was thinking it would be an set of nested lists AlllTrans [0] would be the first gene group which is set to the geneflag number and the group is transArray (list of transcripts) each of which has the list of exons these nested lists are making me a bit dizzy but I am not seeing a clearer way to go on. I was going to convert each list into a set and use the sets to pull out what was the same within each. Any suggestions and help appreciated -- Scott Melnyk melnyk@gmail.com From hall at nhn.ou.edu Mon Oct 18 16:40:57 2004 From: hall at nhn.ou.edu (Isaac Hall) Date: Mon Oct 18 16:41:02 2004 Subject: [Tutor] python and network connections (ssh) Message-ID: Hi pythoneers! OK, say I want to have a python program/script ssh to another machine on an intranet, prompt for a password, after getting a successful password, it would then go and retrieve one file and then close the connection. can this be done by just making the program run shell commands, or is there a smarter/sleeker way to do this? Thanks, Ike -- From mhansen at cso.atmel.com Mon Oct 18 19:42:22 2004 From: mhansen at cso.atmel.com (Mike Hansen) Date: Mon Oct 18 19:42:22 2004 Subject: [Tutor] Over optimizing Message-ID: <4174007E.9040900@cso.atmel.com> [steps up on soapbox] Lately there's been a lot of talk about getting various code snippets to run faster. It's good to exercise your brain coming up with better ways to optimize code and get exposed to different methods of writing code. I would like to offer a little bit of caution for those new to programming. Many programs run into problems when the the programmer is overly concerned with optimizing. Sometimes inadvertently sacrificing stability and readability in the name of optimization. Sometimes the clever optimization becomes difficult to read and possibly difficult to modify. In general, you should worry about optimizing code only when it appears to be running too slow. Don't try to second guess the program's performance. Machines are pretty fast these days, and are getting faster. In short, get it working, make sure it's readable, and optimize only if it's performing too slow. Just an opinion based on some books I've read and some experience. Thanks [steps off soapbox] Mike From Mark.Kels at gmail.com Mon Oct 18 19:50:57 2004 From: Mark.Kels at gmail.com (Mark Kels) Date: Mon Oct 18 19:51:00 2004 Subject: [Tutor] How does bittorrent works ??? Message-ID: Hi all, I guess you all know bittorrent (If not, check this site - http://bittorrent.com/ ). The program is writen in python and it uses wxWindows for GUI... But how does it work on a computer that dont have python ?! Thanks ! From dyoo at hkn.eecs.berkeley.edu Mon Oct 18 20:00:00 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Oct 18 20:00:05 2004 Subject: [Tutor] How does bittorrent works ??? In-Reply-To: Message-ID: On Mon, 18 Oct 2004, Mark Kels wrote: > I guess you all know bittorrent (If not, check this site - > http://bittorrent.com/ ). > The program is writen in python and it uses wxWindows for GUI... > But how does it work on a computer that dont have python ?! Hi Mark, I suspect that the Bittorrent program has been "frozen" by using a utility that bundles a Python runtime and a Python program into a single .EXE. One of the more popular of these freezers is py2exe: http://starship.python.net/crew/theller/py2exe/ Let me check something... Ok, confirmed. Bram Cohen does use py2exe, according to the 'BUILD.windows' instructions that he's written: http://cvs.sourceforge.net/viewcvs.py/bittorrent/BitTorrent/BUILD.windows.txt?view=markup So it's a combination of using py2exe to build a standalone, and the 'nullsoft installer' to make it easy to install for Windows. Hope this helps! From dyoo at hkn.eecs.berkeley.edu Mon Oct 18 20:05:53 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Oct 18 20:05:59 2004 Subject: [Tutor] python and network connections (ssh) In-Reply-To: Message-ID: On Mon, 18 Oct 2004, Isaac Hall wrote: > OK, say I want to have a python program/script ssh to another machine on > an intranet, prompt for a password, after getting a successful password, > it would then go and retrieve one file and then close the connection. > > can this be done by just making the program run shell commands, or is > there a smarter/sleeker way to do this? Hi Issac, Yes, it should be able to work through os.system() or os.popen(). There is a way of making such a program less intrusive: you may want to see if you can use something like 'ssh-agent' or Keychain to avoid having to manually enter a password from the script. http://www.gentoo.org/proj/en/keychain/index.xml Good luck! From kent_johnson at skillsoft.com Mon Oct 18 20:35:39 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Mon Oct 18 20:35:43 2004 Subject: [Tutor] Over optimizing In-Reply-To: <4174007E.9040900@cso.atmel.com> References: <4174007E.9040900@cso.atmel.com> Message-ID: <6.1.0.6.0.20041018142615.02a8d258@67.132.9.32> Yes. As a confirmed optimization junkie, I will second that! CAR Hoare famously said "Premature optimization is the root of all evil." For most of the programs mentioned on this list, optimization is not needed at all. Once the program is working correctly any performance problems can be addressed. If you do need to improve performance, use a profiler to find the hot spots. You will often be surprised at where the time is going! This page http://c2.com/cgi/wiki?RulesOfOptimization has three rules of optimization (and links to other useful info): 1. Don't 2. Don't yet 3. Profile before optimizing. Kent At 11:42 AM 10/18/2004 -0600, Mike Hansen wrote: >[steps up on soapbox] > >Lately there's been a lot of talk about getting various code snippets to >run faster. It's good to exercise your brain coming up with better ways to >optimize code and get exposed to different methods of writing code. I >would like to offer a little bit of caution for those new to programming. >Many programs run into problems when the the programmer is overly >concerned with optimizing. Sometimes inadvertently sacrificing stability >and readability in the name of optimization. Sometimes the clever >optimization becomes difficult to read and possibly difficult to modify. >In general, you should worry about optimizing code only when it appears to >be running too slow. Don't try to second guess the program's performance. >Machines are pretty fast these days, and are getting faster. In short, get >it working, make sure it's readable, and optimize only if it's performing >too slow. > >Just an opinion based on some books I've read and some experience. > >Thanks > >[steps off soapbox] > >Mike >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From mw5858 at sbc.com Mon Oct 18 21:17:00 2004 From: mw5858 at sbc.com (WEISS, MARK (NB)) Date: Mon Oct 18 21:17:10 2004 Subject: [Tutor] Ado data type conversions Message-ID: <4BF710B1993F1244B41763531F098D7905A6C4@cafrfd1msgusr21.itservices.sbc.com> Good morning everyone! I am trying to dynamically create an UPDATE sql statement based on an ADO recordset queried from a staging database. Is there an easy way to handle the adDate and NULL data types? I think I should be able to cast them to the specific type (as with strings and int's), but I'm having a hard time finding the solution. I would appreciate any suggestions or hints. Thank you! Mark My function uses this loop to parse through a recordset, and return a list of values: (Python 2.3.3 running on Windows 2000) for i in updateflds: try: if str(rs.Fields(i).type) == '202': # we have an ADO adVarWChar type (= 202) value = str(rs.Fields(i).value).strip() elif str(rs.Fields(i).type) == '3': # we have an ADO adInteger type (= 3) value = eval(str(rs.Fields(i).value)) elif str(rs.Fields(i).type) == '7': # we have an ADO adDate type (= 7) # value should be cast to an adDate type or just object(?) value = rs.Fields(i).value else: # we have an unhandled ADO type (= i) value = 'UNHANDLED_TYPE_' + i + "_" + str(rs.Fields(i).type) # print i + " - " + str(rs.Fields(i).type) + " - " + str(rs.Fields(i).value) if value is None: # value should be cast to an object that adds NULL to the list... can't be 'NULL' value = value updatevalues.append(value) except Exception: updatevalues.append('err_UNHANDLED_TYPE_' + i + "_" + str(rs.Fields(i).type)) pass The result of the loop above is used like this: qString = "UPDATE " + tname + " SET "+ str(tuple(updateflds)) + " = " + str(tuple(updatevalues)) whereString = " WHERE KEY = '" + str(rs_key) + "'" writeToFile(ATTRIBUTE_MOD_SQL, qString + whereString) From bill.mill at gmail.com Mon Oct 18 21:58:22 2004 From: bill.mill at gmail.com (Bill Mill) Date: Mon Oct 18 21:58:25 2004 Subject: [Tutor] Simple Question... In-Reply-To: <41730CE4.9050907@yahoo.com> References: <20041016174645.31391.qmail@web61009.mail.yahoo.com> <8464C062-1F9E-11D9-8BDA-000393CBC88E@yahoo.fr> <47856308316.20041016165216@columbus.rr.com> <797fe3d4041016143034feddd3@mail.gmail.com> <135873078670.20041016213147@columbus.rr.com> <797fe3d404101619306051e62a@mail.gmail.com> <41730CE4.9050907@yahoo.com> Message-ID: <797fe3d4041018125855d54b3c@mail.gmail.com> The fastest linecounting function that I could find, without loading the entire file into memory, was this function: def wc(f): c = 0 for line in f: c+=1 This function is about 3 times faster than this one (the next fastest I could think of): def wcslow(f): line = ' ' c = 0 while line: line = f.read(1024) c += line.count('\n') Which leads me to question, why is iterator-based file access so much faster than read? Also, regarding the random line function, I realized that if you want to have equal probability of selecting any line, you *must* know how many lines are in the file beforehand. If you're ok with favoring longer lines over shorter ones, then you can just pick a random spot in the file. Peace Bill Mill bill.mill at gmail.com On Sun, 17 Oct 2004 20:23:00 -0400, Rich Krauter wrote: > Bill Mill wrote: > > OK, I posted a fortune file to my webserver. It's at > > http://llimllib.f2o.org/files/osfortune . I see 2 competitions: > > > > 1) fastest function to find a random line from the file; the catch is > > that this function must be able to pick a random line from anywhere in > > the file. It must be capable of returning the first line, the last > > line, and anything in between. > > > > 2) fastest function to count the lines in the file. > > > > I doubt the following is the fastest on either point - just figured I'd > post it since it uses built-in module linecache, which I haven't seen > mentioned in this thread yet. > > Just like some of the posted solutions, linecache reads the entire file > into a list; that module's code may be of interest to those proposing > that type of solution. > > import random > import linecache > > def getrandomline(fname,nlines): > n = random.randint(0,nlines) > return n,linecache.getline(fname,n) > > def wcl(fname): > # make sure file has been cached; to do so, > # run linecache.getline() and discard result > if not linecache.cache[fname]: > linecache.getline(fname,1) > # return number of lines in file > return len(linecache.cache[fname][2]) > > if __name__ == '__main__': > print getrandomline('junk.txt',wcl(fname)) > > The linecache module doesn't have a function to return the number of > lines in a file; but it very easily could provide one since the cached > file's lines are available in a list. I used that fact to count the > number of lines, in wcl() above, rather than opening the file again to > count its lines. > > Rich > _______________________________________________ > > > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From bill.mill at gmail.com Mon Oct 18 22:05:07 2004 From: bill.mill at gmail.com (Bill Mill) Date: Mon Oct 18 22:05:14 2004 Subject: [Tutor] Find out if a number is even or not In-Reply-To: <010201c4b417$792b60f0$d79b8851@xp> References: <1097838018.416fadc261290@webmail.freedom2surf.net> <24d253d904101520094f73a206@mail.gmail.com> <24d253d904101610453b801a62@mail.gmail.com> <797fe3d4041016132643f0e2f9@mail.gmail.com> <010201c4b417$792b60f0$d79b8851@xp> Message-ID: <797fe3d40410181305724305b1@mail.gmail.com> Alan, this approach (return n%2 and False or True, labelled isEven4) appears to be the slowest: isEven1: 7.345000 isEven2: 7.811000 isEven3: 8.685000 isEven4: 9.129000 Why these times are, on average, faster than they were before, I'm not sure. Still, the boolean type approach is the slowest. Perhaps there is some overhead in the creation of booleans? Peace Bill Mill bill.mill at gmail.com On Sun, 17 Oct 2004 08:03:57 +0100, Alan Gauld wrote: > > def isEven1(n): return not n&1 > > def isEven2(n): return n % 2 == 0 > > def isEven3(n): return n % 2 and 'Odd' or 'Even' > > Since the last is doing something quite different > could you try: > > def isEven4(n): return n%2 and False or True > > Which makes it closer to the others. I'd still expect it to > be slower but I wonder whether it closes the gap in any way? > > Alan g > From bill.mill at gmail.com Mon Oct 18 22:09:33 2004 From: bill.mill at gmail.com (Bill Mill) Date: Mon Oct 18 22:09:36 2004 Subject: [Tutor] Over optimizing In-Reply-To: <6.1.0.6.0.20041018142615.02a8d258@67.132.9.32> References: <4174007E.9040900@cso.atmel.com> <6.1.0.6.0.20041018142615.02a8d258@67.132.9.32> Message-ID: <797fe3d404101813094e5dfb0@mail.gmail.com> Hello, as probably the guy you're talking at, I just want to say that I agree 100%. The topic just kind of came up in one thread, but I introduced it into another. I find that sometimes optimization is fun for its own sake, and to learn a little bit more about the environment in which you're programming or operating. However, as you say, these are treacherous waters. When I write actual programs, I don't even think about optimization until after the program's operational, and I can find the bottlenecks in it. Most likely, the tutor mailing list is not the place for these discussions. I will try to refrain from them in the future. Peace Bill Mill bill.mill at gmail.com On Mon, 18 Oct 2004 14:35:39 -0400, Kent Johnson wrote: > Yes. As a confirmed optimization junkie, I will second that! CAR Hoare > famously said "Premature optimization is the root of all evil." > > For most of the programs mentioned on this list, optimization is not needed > at all. Once the program is working correctly any performance problems can > be addressed. > > If you do need to improve performance, use a profiler to find the hot > spots. You will often be surprised at where the time is going! > > This page http://c2.com/cgi/wiki?RulesOfOptimization has three rules of > optimization (and links to other useful info): > 1. Don't > 2. Don't yet > 3. Profile before optimizing. > > Kent > > > > At 11:42 AM 10/18/2004 -0600, Mike Hansen wrote: > >[steps up on soapbox] > > > >Lately there's been a lot of talk about getting various code snippets to > >run faster. It's good to exercise your brain coming up with better ways to > >optimize code and get exposed to different methods of writing code. I > >would like to offer a little bit of caution for those new to programming. > >Many programs run into problems when the the programmer is overly > >concerned with optimizing. Sometimes inadvertently sacrificing stability > >and readability in the name of optimization. Sometimes the clever > >optimization becomes difficult to read and possibly difficult to modify. > >In general, you should worry about optimizing code only when it appears to > >be running too slow. Don't try to second guess the program's performance. > >Machines are pretty fast these days, and are getting faster. In short, get > >it working, make sure it's readable, and optimize only if it's performing > >too slow. > > > >Just an opinion based on some books I've read and some experience. > > > >Thanks > > > >[steps off soapbox] > > > >Mike > >_______________________________________________ > >Tutor maillist - Tutor@python.org > >http://mail.python.org/mailman/listinfo/tutor > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From mhansen at cso.atmel.com Mon Oct 18 23:50:57 2004 From: mhansen at cso.atmel.com (Mike Hansen) Date: Mon Oct 18 23:50:55 2004 Subject: [Tutor] Over optimizing In-Reply-To: <797fe3d404101813094e5dfb0@mail.gmail.com> References: <4174007E.9040900@cso.atmel.com> <6.1.0.6.0.20041018142615.02a8d258@67.132.9.32> <797fe3d404101813094e5dfb0@mail.gmail.com> Message-ID: <41743AC1.3070104@cso.atmel.com> My post wasn't directed at anyone. It also wasn't intended to stop the discussions on optimizing. There's much to be learned from viewing different and better ways of coding. I just wanted to put optimizing in the overall picture of programming. Bill Mill wrote: >Hello, > >as probably the guy you're talking at, I just want to say that I agree >100%. The topic just kind of came up in one thread, but I introduced >it into another. I find that sometimes optimization is fun for its own >sake, and to learn a little bit more about the environment in which >you're programming or operating. > >However, as you say, these are treacherous waters. When I write actual >programs, I don't even think about optimization until after the >program's operational, and I can find the bottlenecks in it. > >Most likely, the tutor mailing list is not the place for these >discussions. I will try to refrain from them in the future. > >Peace >Bill Mill >bill.mill at gmail.com > > >On Mon, 18 Oct 2004 14:35:39 -0400, Kent Johnson > wrote: > > >>Yes. As a confirmed optimization junkie, I will second that! CAR Hoare >>famously said "Premature optimization is the root of all evil." >> >>For most of the programs mentioned on this list, optimization is not needed >>at all. Once the program is working correctly any performance problems can >>be addressed. >> >>If you do need to improve performance, use a profiler to find the hot >>spots. You will often be surprised at where the time is going! >> >>This page http://c2.com/cgi/wiki?RulesOfOptimization has three rules of >>optimization (and links to other useful info): >>1. Don't >>2. Don't yet >>3. Profile before optimizing. >> >>Kent >> >> >> >>At 11:42 AM 10/18/2004 -0600, Mike Hansen wrote: >> >> >>>[steps up on soapbox] >>> >>>Lately there's been a lot of talk about getting various code snippets to >>>run faster. It's good to exercise your brain coming up with better ways to >>>optimize code and get exposed to different methods of writing code. I >>>would like to offer a little bit of caution for those new to programming. >>>Many programs run into problems when the the programmer is overly >>>concerned with optimizing. Sometimes inadvertently sacrificing stability >>>and readability in the name of optimization. Sometimes the clever >>>optimization becomes difficult to read and possibly difficult to modify. >>>In general, you should worry about optimizing code only when it appears to >>>be running too slow. Don't try to second guess the program's performance. >>>Machines are pretty fast these days, and are getting faster. In short, get >>>it working, make sure it's readable, and optimize only if it's performing >>>too slow. >>> >>>Just an opinion based on some books I've read and some experience. >>> >>>Thanks >>> >>>[steps off soapbox] >>> >>>Mike >>>_______________________________________________ >>>Tutor maillist - Tutor@python.org >>>http://mail.python.org/mailman/listinfo/tutor >>> >>> >>_______________________________________________ >>Tutor maillist - Tutor@python.org >>http://mail.python.org/mailman/listinfo/tutor >> >> >> From dyoo at hkn.eecs.berkeley.edu Tue Oct 19 01:54:14 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Oct 19 01:54:17 2004 Subject: [Tutor] Values in matrices In-Reply-To: <1ee.2c607e05.2ea35c38@aol.com> Message-ID: On Sun, 17 Oct 2004 CryptoLevel9@aol.com wrote: > Lets say you have a N x M matrix initially filled with zeros and you > need to place a value, lets say V, in some row X and column Y where V, > X, and Y are all values determined by user input and X and Y are less > than or equal to N and M respectively. If this is possible, could this > be done many times for different values of V and different values of X > and Y without assigning the values V, X, and Y new variable names for > each new value, possibly using some form of programming loop? Hello, Yes, this is possible to do with a for loop. You can use reassignment to reuse the same variable names over and over. Something like: for r in rows: for c in cols: array[r][c] = some_function_that_depends_on(r, c) However, if you plan to do more sophisticated matrixy stuff, you may want to look at the 'numarray' package: http://www.stsci.edu/resources/software_hardware/numarray It is not a part of the Standard Library, but is an invaluable module if you plan to do a lot of matrix manipulation. For example, ### >>> import numarray >>> m = numarray.zeros((5,5)) >>> m array([[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]) ### 'numarray' makes it ridiculously easy to set a whole row or column to a particular value: ### >>> m[3] = 17 >>> m array([[ 0, 0, 0, 0, 0], [ 0, 0, 0, 0, 0], [ 0, 0, 0, 0, 0], [17, 17, 17, 17, 17], [ 0, 0, 0, 0, 0]]) >>> >>> >>> m[:, 2] = 42 >>> m array([[ 0, 0, 42, 0, 0], [ 0, 0, 42, 0, 0], [ 0, 0, 42, 0, 0], [17, 17, 42, 17, 17], [ 0, 0, 42, 0, 0]]) ### So numarray allows us to do a lot, even allowing us to do operations on whole rows and columns. And we can also create arrays whose row/col values depend on their row and column: ### >>> def dist(x, y): ... return ((x-5)**2 + (y-5)**2) ** 0.5 ... >>> numarray.fromfunction(dist, (3, 5)) array([[ 7.07106781, 6.40312424, 5.83095189, 5.38516481, 5.09901951], [ 6.40312424, 5.65685425, 5. , 4.47213595, 4.12310563], [ 5.83095189, 5. , 4.24264069, 3.60555128, 3.16227766]]) ### Hope this helps! From cepl at surfbest.net Tue Oct 19 01:57:45 2004 From: cepl at surfbest.net (Matej Cepl) Date: Tue Oct 19 01:58:00 2004 Subject: [Tutor] BeautifulSoup: cut first n tags? Message-ID: <200410181957.45655.cepl@surfbest.net> Hi, I am quite amazed by the beauty of your BeautifulSoup (it is truly beautiful), but still I have one problem which I would like to resolve: I have a not so bad webpage (Boston Globe story, version for print) on http://www.ceplovi.cz/matej/tmp/globe.html and I would to get some very clean stuff from it. It is not problem to get some interesting information from the

element, but I haven't figure out how to get the story. Let's see what I have: from BeautifulSoup import BeautifulSoup def get_content(soup,element,cls): return string.strip(str(ent.first(element,{'class':cls}).contents[0])) html = open("globe.html","r").read() soup = BeautifulSoup() soup.feed(html) story = soup.first("div",{'class':'story'}) headline = get_content(story,'h1','mainHead') subhead = get_content(story,'h2','subHead') author = get_content(story,'p','byline') date = string.strip(str(story.first('span',\ {'style':'white-space: nowrap;'}) So far, surprisingly easy. But how can I get "all remaining tags (not only

s) in story after (and without)

element which is class 'byline' and no, I don't need any elements, thanks!"? Is there any way how to work with the ALL elements as a simple list? I know, that I can do something like body = story.fetch('p')[1:] but what if some unfortunate author unexepctedly decides that he doesn't want to make such ugly soup after all and uses some other tag than

(

,
, or even
    comes to mind)? Thanks a lot, Matej -- Matej Cepl, http://www.ceplovi.cz/matej GPG Finger: 89EF 4BC6 288A BF43 1BAB 25C3 E09F EF25 D964 84AC 138 Highland Ave. #10, Somerville, Ma 02143, (617) 623-1488 The function of the expert is not to be more right than other people, but to be wrong for more sophisticated reasons. -- Dr. David Butler, British psephologist From guillermo.fernandez.castellanos at gmail.com Tue Oct 19 03:46:59 2004 From: guillermo.fernandez.castellanos at gmail.com (Guillermo Fernandez Castellanos) Date: Tue Oct 19 03:47:02 2004 Subject: [Tutor] python and network connections (ssh) In-Reply-To: References: Message-ID: <7d7029e70410181846683bf14c@mail.gmail.com> Hi, Maybe you want to have a look to this library: http://pyssh.sourceforge.net/ Thus it can be done through running shell comands, I guess a library would make the job easier and more portable (the library seems to work for POSIX and Windows systems), I haven't tried personally though. Enjoy! Guille On Mon, 18 Oct 2004 09:40:57 -0500 (CDT), Isaac Hall wrote: > Hi pythoneers! > > OK, say I want to have a python program/script ssh to another machine on > an intranet, prompt for a password, after getting a successful password, > it would then go and retrieve one file and then close the connection. > > can this be done by just making the program run shell commands, or is > there a smarter/sleeker way to do this? > > Thanks, > Ike > > -- > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From rmkrauter at yahoo.com Tue Oct 19 04:52:23 2004 From: rmkrauter at yahoo.com (Rich Krauter) Date: Tue Oct 19 04:52:27 2004 Subject: [Tutor] nested lists of data In-Reply-To: References: Message-ID: <41748167.2060403@yahoo.com> Scott Melnyk wrote: > Hello! > > I am looking at data in the form of Type, subgroup, data > it is genetic data so I will try to make this a generic question but > includ ethe real data so someone can help explain what I have done > wrong or a better way to go about this. > > Type 1 may have 1 or more subgroups, each subgroub must have at least > one piece of data > > format is : > (although it looks here like the exons on on separate lines, in the > data file the new line occurs only after NEW GENE, NEW TRANSCRIPT and > the last exon in a transcript (and thewhite space line is just > newlline) > type subgroup data > ENSG is gene id ENST is transcript id ENSE the exons > > NEW GENE > ENSG00000187908.1 ENST00000339871.1 ENSE00001383339.1 > ENSE00001387275.1 ENSE00001378578.1 ENSE00001379544.1 > ENSE00001368222.1 ENSE00001372264.1 ENSE00001365999.1 > > NEW TRANSCRIPT > ENSG00000187908.1 ENST00000344399.1 ENSE00001384814.1 > ENSE00001374811.1 ENSE00001391015.1 ENSE00001370692.1 > ENSE00001372884.1 ENSE00001386551.1 ENSE00001386137.1 > > NEW TRANSCRIPT > ENSG00000187908.1 ENST00000338354.1 ENSE00001364942.1 > ENSE00001379878.1 ENSE00001376065.1 ENSE00001379576.1 > > NEW GENE > ENSG00000129899.5 ENST00000306922.4 ENSE00001350558.2 > ENSE00001316817.3 ENSE00001149607.1 ENSE00001149600.1 > ENSE00001149591.1 ENSE00001149579.1 ENSE00001383071.1 > ENSE00001149558.2 ENSE00001149547.1 ENSE00001302825.1 > ENSE00001149539.1 ENSE00001149529.1 ENSE00001186785.1 > ENSE00001350475.1 ENSE00001350469.2 ENSE00001350465.2 > ENSE00001350461.2 ENSE00001350458.2 ENSE00001309288.1 > ENSE00001149467.2 ENSE00001250660.4 > > NEW TRANSCRIPT > ENSG00000129899.5 ENST00000306944.5 ENSE00001350584.2 > ENSE00001316817.3 ENSE00001149607.1 ENSE00001149600.1 > ENSE00001149591.1 ENSE00001149579.1 ENSE00001383071.1 > ENSE00001149558.2 ENSE00001149547.1 ENSE00001302825.1 > ENSE00001149539.1 ENSE00001149529.1 ENSE00001186785.1 > > I would like to use sets to generate a txt file of any data in the > transcripts that is repeated between each transcript. So for a given > gene each if each transcript has exons x and y then I want to know > that. > In another way, within a group (GENE) if all subgroups(transcripts) > contain exon(s) x(y,z, or more) then write to a file that contain > gene id then all exons that are in all transcripts for gene x > ENSG00000129899.5 ENSE00001149539.1 ENSE00001149579.1 > > the output file is equivilent to > group x data 3 data4 > group x data 7 data 9 data 10 > etc. > > > info=re.compile('^(ENSG\d+\.\d).+(ENST\d+\.\d).+(ENSE\d+\.\d)+') > #above is match gene, transcript, then one or more exons > > exonArray=[] > geneflag=0 > transArray=[] > AllTrans=[] > > for line in TFILE: > Matched2= info.match(line) > if line.startswith('NEW GENE'): > geneflag=geneflag+1 > transloop=0 > if Matched2: > if line.startswith('ENS'): > geneid,transid,exons=line.split(None,2) > exonArray=exons.split() > print "this is the gene "+geneid > print "this is the transcript "+transid > print "these are the exons: \n" > for exon in exonArray: > print exon ," ", > print "\n" > print transloop > #up to here seems to be working fine by the output > > #problems here > transArray[transloop]=exonArray > #transArray[0]=exonArray tried this same error > transloop=transloop+1 > AllTrans[geneflag]=transArray[transloop] > if not line.startswith('ENS'): > break > > > I was going to convert each list into a set and use the sets to pull > out what was the same within each. > You need to change transArray[transloop]=exonArray to transArray.append(exonArray), or pre-allocate your array, to fix that error. Same goes for AllTrans[geneflag]=transArray[transloop]. Below is the code I tried. I got rid the the regex and the flags; all the exons for a given gene-transript pair are on one line, so I didn't see any benefit in checking for the 'NEW' markers. Based on what I understood from your post, for a given gene, I found exon intersections among that gene's transcripts. I didn't find intersections between genes. import sets def getintersection(setdict,keys): keys = keys[:] # work with copy matches = [] resultSet = sets.Set() current = keys.pop() for k in keys: # only get intersections for different #transcripts of the same gene if k[0] == current[0]: resultSet = setdict[current].intersection(setdict[k]) if len(resultSet) > 0: matches.append((current,k,resultSet)) return matches def parse_file(fname='D:/rk/exons.txt'): exonSets = {} f = open(fname) for line in f: if line.startswith('ENS'): parts = line.split() gene = parts[0] transcript = parts[1] exons = parts[2:] exonSets.setdefault((gene,transcript), sets.Set()).union_update(exons) return exonSets if __name__ == '__main__': exonSets = parse_file('D:/rk/exons.txt') keys = exonSets.keys() while keys: result = getintersection(exonSets,keys) for r in result: print '%s and %s both contain:'%(r[0],r[1]) for item in r[2]: print item keys.pop() Hope that helps. Rich From alan.gauld at freenet.co.uk Tue Oct 19 05:48:20 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue Oct 19 05:47:25 2004 Subject: [Tutor] Find out if a number is even or not References: <1097838018.416fadc261290@webmail.freedom2surf.net> <24d253d904101520094f73a206@mail.gmail.com> <24d253d904101610453b801a62@mail.gmail.com> <797fe3d4041016132643f0e2f9@mail.gmail.com> <010201c4b417$792b60f0$d79b8851@xp> <797fe3d40410181305724305b1@mail.gmail.com> Message-ID: <019101c4b58e$7a293180$d79b8851@xp> > Why these times are, on average, faster than they were before, I'm not > sure. The actual times are never reliable in these tests its the comparison that is important. The time can be influenced by other background activity on the PC, how much RAM is free at any given moment etc... > Still, the boolean type approach is the slowest. Perhaps there > is some overhead in the creation of booleans? It would seem so Bill. Very odd, I expected Python to have cached True ad alse as it does with Numbers and so be quite fast. Thanks for doing that bit of research, it all adds to the collective pot :-) Alan G. From alan.gauld at freenet.co.uk Tue Oct 19 05:56:31 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue Oct 19 05:55:42 2004 Subject: [Tutor] Over optimizing References: <4174007E.9040900@cso.atmel.com><6.1.0.6.0.20041018142615.02a8d258@67.132.9.32> <797fe3d404101813094e5dfb0@mail.gmail.com> Message-ID: <01b401c4b58f$9f996ec0$d79b8851@xp> > it into another. I find that sometimes optimization is fun for its own > sake, and to learn a little bit more about the environment in which > you're programming or operating. I think the latter point is most important. Fine tuning code for speed is instructive but rarely cost effective. Only do it once you know there is a problem. On really big performance problems the fault is often not in the code at all but in the use of network or file resources, or database access. These factors can cause order of magnitude slow downs whereas code issues typically only cause factors of 2 or 3 slow downs. But when learning how to program it is useful to know what can cause blockages so I don't think the discussions are inappropriate here, but at the same time reminders not to get too obsessive about it are good too! :-) Alan G. From hugonz-lists at h-lab.net Tue Oct 19 07:51:51 2004 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Tue Oct 19 07:51:57 2004 Subject: [Tutor] modified readline()??? Message-ID: <4174AB77.4030302@h-lab.net> Hi all, I'm invoking cdrecord from my python program, and I want to parse its progress so as to paint a progress bar. Now, I'd be doing: filep = popen ("/mypath/cdrecord yabba yabba yabba") then read from filep in a loop If cdrecord sent the percentages in canonical form (ie, with \n between the lines) I could just do while True: can_line = filep.readline() #here I'd look for the XX% string in the output, regexp or something if percentage == "100%": break But the program just puts some kind of terminal control between status lines. Can I redefine the "CR" in readline() as to read up to that character??? I cannot simply use read() and block with some buffer size since that does not guarante I'm getting the whole "50%" string so that I can parse it.... I could be getting just 5 in one pass, and then 0% in the next.... Thanks all for your kind insight.... =) Hugo From H.FANGOHR at soton.ac.uk Tue Oct 19 11:32:02 2004 From: H.FANGOHR at soton.ac.uk (Hans Fangohr) Date: Tue Oct 19 11:32:33 2004 Subject: [Tutor] how to play arrays as audio signal Message-ID: Greetings, I would like to 'acoustically play' values in an array (or list, tupel, ...) as if the position of the speaker membrane at different times was given by the value in that array. Is there a module (in the best case a standard module) that would do this for me? (I will need this on Windows.) Here is an example: import numarray freq=110 #frequency in Hertz samplerate = 1000 #Hertz x=numarray.arange(0,1,1.0/samplerate) y=numarray.sin(x*2*numarray.pi*freq) What is missing, is something along the following lines: import sound? sound?.playvector( y, samplerate ) Looking forward to hearing any suggestions, Hans From mi.janssen at gmail.com Tue Oct 19 13:48:34 2004 From: mi.janssen at gmail.com (Michael Janssen) Date: Tue Oct 19 13:48:37 2004 Subject: [Tutor] modified readline()??? In-Reply-To: <4174AB77.4030302@h-lab.net> References: <4174AB77.4030302@h-lab.net> Message-ID: <1ff2dfbf0410190448305e9ac@mail.gmail.com> On Tue, 19 Oct 2004 00:51:51 -0500, Hugo Gonz?lez Monteverde wrote: > filep = popen ("/mypath/cdrecord yabba yabba yabba") > while True: > can_line = filep.readline() > #here I'd look for the XX% string in the output, regexp or something > if percentage == "100%": > break > > But the program just puts some kind of terminal control between status > lines. Can I redefine the "CR" in readline() as to read up to that > character??? I cannot simply use read() and block with some buffer size > since that does not guarante I'm getting the whole "50%" string so that > I can parse it.... I could be getting just 5 in one pass, and then 0% > in the next.... read one char at a time and stop reading when you found the stop character. Meanwhile store the read chars somewhere. Michael From kent_johnson at skillsoft.com Tue Oct 19 13:55:43 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Tue Oct 19 13:55:46 2004 Subject: [Tutor] Why doesn't this filter FutureWarning? In-Reply-To: References: Message-ID: <6.1.0.6.0.20041019074746.02891cf0@mail4.skillsoft.com> Wow, this one had me stumped for a while! It turns out that this warning is generated at *compile* time, not at runtime! Here is a way to demonstrate this: In FW.py: def foo(): num=0x1234 num=num & 0xffffffff print 'foo' In the interpreter: >>> import FW FW.py:3: FutureWarning: hex/oct constants > sys.maxint will return positive values in Python 2.4 and up num=num & 0xffffffff >>> FW.foo() foo Notice I get the warning on import, even though all the code in FW is in a function which is not executed! Then when I execute foo(), I *don't* get the warning. When you run from the command line, each line of input is compiled independently. So setting the warning filter affects everything after. When you run from a file, the whole file is compiled, generating the warning, then the file is executed, disabling the warning. The warning filter isn't set until after the file is compiled, so it is too late. Two workarounds: - Use 0xffffffffL and avoid the warning completely - Put the call to filterwarnings() in a separate file. Call filterwarnings(), then import the file of interest. You can simulate this from the command line: >>> import warnings >>> warnings.filterwarnings(action='ignore', category=FutureWarning) >>> import FW >>> FW.foo() foo Kent At 06:00 PM 10/17/2004 -0700, Terry Carroll wrote: >Here's what I get in the interactive session: > > >>> num=0x1234 > >>> import warnings > >>> num=num & 0xffffffff >:1: FutureWarning: hex/oct constants > sys.maxint will return >positive va >lues in Python 2.4 and up > >>> warnings.filterwarnings('ignore', "hex/oct constants", FutureWarning) > >>> num=num & 0xffffffff > > >That's just what I'd expect. I get the FutureWarning on the first try, >but after invoking filterwarnings, I no longer get it. > >But when I do the same code from inside a file: > > > >C:\test>cat fw.py >num=0x1234 >import warnings >num=num & 0xffffffff >warnings.filterwarnings('ignore', "hex/oct constants", FutureWarning) >num=num & 0xffffffff > >C:\test>python fw.py >fw.py:3: FutureWarning: hex/oct constants > sys.maxint will return >positive valu >es in Python 2.4 and up > num=num & 0xffffffff >fw.py:5: FutureWarning: hex/oct constants > sys.maxint will return >positive valu >es in Python 2.4 and up > num=num & 0xffffffff > > > >What gives? Why would this work in an interactive session, but not from >a file? > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From cyresse at gmail.com Tue Oct 19 14:10:00 2004 From: cyresse at gmail.com (Liam Clarke) Date: Tue Oct 19 14:10:12 2004 Subject: [Tutor] Catching warnings? Message-ID: Hi all, Just a quick question, catching errors is easy, but how to go about catching errors? I'd like to squelch a deprecation warning. I know the module's deprecated, but it's useful for the moment. So far I've filtered it with Warnings.filterwarnings, but the docs state that warning are technically exceptions. Can you catch them the same way you can catch error codes? Oh, and personally, I think I just met the most subtle way of saying 'You're missing a closed bracket' - Token Error: EOF in multi-line statement Grrrr From cyresse at gmail.com Tue Oct 19 14:11:59 2004 From: cyresse at gmail.com (Liam Clarke) Date: Tue Oct 19 14:12:01 2004 Subject: [Tutor] Re: Catching warnings? In-Reply-To: References: Message-ID: Oops, "Just a quick question, catching errors is easy, but how to go about catching errors?" I meant, of course, catching warnings.... (it's late, that's my excuse and I'm sticking to it.) On Wed, 20 Oct 2004 01:10:00 +1300, Liam Clarke wrote: > Hi all, > > Just a quick question, catching errors is easy, but how to go about > catching errors? I'd like to squelch a deprecation warning. I know the > module's deprecated, but it's useful for the moment. > > So far I've filtered it with Warnings.filterwarnings, but the docs > state that warning are technically exceptions. Can you catch them the > same way you can catch error codes? > > Oh, and personally, I think I just met the most subtle way of saying > 'You're missing a closed bracket' - > > Token Error: EOF in multi-line statement > > Grrrr > From jerimed at myrealbox.com Tue Oct 19 14:45:38 2004 From: jerimed at myrealbox.com (Eri Mendz) Date: Tue Oct 19 14:45:48 2004 Subject: [Tutor] isbetween function chapter 5 How to Think Like Computer Scientist Message-ID: <41750C72.7040703@myrealbox.com> Hello all, I'm a newbie trying to learn Python at my own pace. I work in sales NOT programming so please excuse me of obvious things i may overlook in the course of my self-teaching. Here is the code i made trying to solve the exercise mentioned in the subject of my email. I made it like so as i think pure if-elif-else statement is unwieldy. Of course its just me and pros here got something to correct my statement: #!/usr/bin/env python # filename: isbetween.py # description: make function with 3 parameters & determine the median # Author: Eri Mendz # Tue Oct 19 15:07:22 AST 2004 # CYGWIN_NT-5.0 def test1(x,y,z): if x > y and x > z: # x is highest if y > z: # z-y-x print y, "is between", z, "and", x else: # y-z-x print z, "is between", y, "and", x def test2(x,y,z): if y > x and y > z: # y is highest if x > z: # z-x-y print x, "is between", z, "and", y else: print z, "is between", x, "and", y def test3(x,y,z): if z > x and z > y: # z is highest if x > y: # y-x-z print x, "is between", y, "and", z else: print y, "is between", x, "and", z def isbetween(x,y,z): test1() test2() test3() # test isbetween() isbetween(23,10,56) I get: TypeError: test1() takes exactly 3 arguments (0 given) Dumb me i didnt supplied arguments as required. But do i really have to do that? I like the 3 functions to act as dummy functions (sort of) and let the real work happen inside isbetween(). Kindly enlighten me how to do it right. -- Regards, erimendz ** use firefox/thunderbird ** http://www.spreadfirefox.com/?q=affiliates&id=6670&t=58 From flaxeater at yahoo.com Tue Oct 19 15:30:10 2004 From: flaxeater at yahoo.com (Chad Crabtree) Date: Tue Oct 19 15:30:15 2004 Subject: [Tutor] isbetween function chapter 5 How to Think Like Computer Scientist Message-ID: <20041019133010.52435.qmail@web54310.mail.yahoo.com> Eri Mendz wrote: > Hello all, > > I'm a newbie trying to learn Python at my own pace. I work in sales > NOT programming so please excuse me of obvious things i may overlook > in the course of my self-teaching. > > Here is the code i made trying to solve the exercise mentioned in the > subject of my email. I made it like so as i think pure if-elif-else > statement is unwieldy. Of course its just me and pros here got > something to correct my statement: > > #!/usr/bin/env python > # filename: isbetween.py > # description: make function with 3 parameters & determine the median > # Author: Eri Mendz > # Tue Oct 19 15:07:22 AST 2004 > # CYGWIN_NT-5.0 > > def test1(x,y,z): > if x > y and x > z: # x is highest > if y > z: # z-y-x > print y, "is between", z, "and", x > else: # y-z-x > print z, "is between", y, "and", x > > def test2(x,y,z): > if y > x and y > z: # y is highest > if x > z: # z-x-y > print x, "is between", z, "and", y > else: > print z, "is between", x, "and", y > > def test3(x,y,z): > if z > x and z > y: # z is highest > if x > y: # y-x-z > print x, "is between", y, "and", z > else: > print y, "is between", x, "and", z > > def isbetween(x,y,z): > test1() > test2() > test3() > > # test isbetween() > isbetween(23,10,56) > > I get: > TypeError: test1() takes exactly 3 arguments (0 given) > > Dumb me i didnt supplied arguments as required. But do i really have > to do that? I like the 3 functions to act as dummy functions (sort of) > and let the real work happen inside isbetween(). Kindly enlighten me > how to do it right. > I would rewrite isbetween() as thus def isbetween(x,y,z): test1(x,y,z) test2(x,y,z) test3(x,y,z) as far as I know there really is no way around it. I thought up another one just for the heck of it using lists and [].sort() def isbetween(x,y,z): lst=[x,y,z] lst.sort() print lst[1], "is between" , lst[0],"and",lst[2] isbetween(3,7,4) 4 is between 3 and 7 I put the values in a list then use [x,y,z].sort() to put the items in order then I print it out. If you want to see how sort works better go to the python command line and type help([]) or look at built-in types on the library reference. Just as a note [].sort() does it's job in place so it does not return the sorted list. Happy Hacking. _______________________________ Do you Yahoo!? Declare Yourself - Register online to vote today! http://vote.yahoo.com From pythonTutor at venix.com Tue Oct 19 15:57:49 2004 From: pythonTutor at venix.com (Lloyd Kvam) Date: Tue Oct 19 15:57:57 2004 Subject: [Tutor] isbetween function chapter 5 How to Think Like Computer Scientist In-Reply-To: <41750C72.7040703@myrealbox.com> References: <41750C72.7040703@myrealbox.com> Message-ID: <1098194268.2743.42.camel@laptop.venix.com> On Tue, 2004-10-19 at 08:45, Eri Mendz wrote: > Hello all, > > I'm a newbie trying to learn Python at my own pace. I work in sales NOT > programming so please excuse me of obvious things i may overlook in the > course of my self-teaching. > > Here is the code i made trying to solve the exercise mentioned in the > subject of my email. I made it like so as i think pure if-elif-else > statement is unwieldy. Of course its just me and pros here got something > to correct my statement: > > #!/usr/bin/env python > # filename: isbetween.py > # description: make function with 3 parameters & determine the median > # Author: Eri Mendz > # Tue Oct 19 15:07:22 AST 2004 > # CYGWIN_NT-5.0 > > def test1(x,y,z): > if x > y and x > z: # x is highest > if y > z: # z-y-x > print y, "is between", z, "and", x > else: # y-z-x > print z, "is between", y, "and", x > > def test2(x,y,z): > if y > x and y > z: # y is highest > if x > z: # z-x-y > print x, "is between", z, "and", y > else: > print z, "is between", x, "and", y > > def test3(x,y,z): > if z > x and z > y: # z is highest > if x > y: # y-x-z > print x, "is between", y, "and", z > else: > print y, "is between", x, "and", z > > def isbetween(x,y,z): > test1() > test2() > test3() > > # test isbetween() > isbetween(23,10,56) > > I get: > TypeError: test1() takes exactly 3 arguments (0 given) > > Dumb me i didnt supplied arguments as required. But do i really have to > do that? I like the 3 functions to act as dummy functions (sort of) and > let the real work happen inside isbetween(). Kindly enlighten me how to > do it right. This is the best way (to my mind) to adjust your code: def isbetween(x,y,z): def test1(): # the values for x,y,z are picked up from the enclosing isbetween function if x > y and x > z: # x is highest if y > z: # z-y-x print y, "is between", z, "and", x else: # y-z-x print z, "is between", y, "and", x # repeat for test2 & test3 test1() test2() test3() However, there are a couple of points to notice. Python supports statements like: if x > y > z: print "x is highest and y is between z and x" This program really relates labels to values. There is not a lot of benefit to using python variable names to match the labels. So if you had a list of (value, label) pairs, you could simply sort the list. And then display the labels in the correct order. Given: value_label_list = [(23,'x'),(10,'y'),(56,'z')] value_label_list.sort() value_label_list.reverse() print "Variables from largest to smallest:" for value,label in value_label_list: print " ", label (This glosses over possible equalities, but so does the original code) Now the problem changes to one of creating the list. I took a look at the problem definition. It simply requests testing one particular order of variables and returning a boolean - a true / false value. I'm not sure where list handling comes in the book. -- Lloyd Kvam Venix Corp From H.FANGOHR at soton.ac.uk Tue Oct 19 16:29:45 2004 From: H.FANGOHR at soton.ac.uk (Hans Fangohr) Date: Tue Oct 19 16:30:26 2004 Subject: [Tutor] methods versus functions (using lists as an example) Message-ID: Dear all, I was looking at what you can do with lists in Python. There are basically two sets of commands: (i) methods doing something with a list (such as sort(), reverse(), count(), ...) and (ii) functions that take a list as an argument (such as sum(), max(), min()). I would expect that there is a rationale behind this choice -- would anyone know what this is or where I can find more information? Many thanks, Hans From cowboycody016 at verizon.net Tue Oct 19 16:57:17 2004 From: cowboycody016 at verizon.net (Cody) Date: Tue Oct 19 16:57:19 2004 Subject: [Tutor] has anybody....... Message-ID: <001f01c39651$43588d20$6400a8c0@cody368747> has anybody ever did any hacking with python., if so how would u program with it to do so. just cirouis. thanks,cody -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20041019/929f74ef/attachment.html From bill.mill at gmail.com Tue Oct 19 17:03:07 2004 From: bill.mill at gmail.com (Bill Mill) Date: Tue Oct 19 17:03:11 2004 Subject: [Tutor] methods versus functions (using lists as an example) In-Reply-To: References: Message-ID: <797fe3d404101908032466f8ec@mail.gmail.com> Hans, max() and min() are not class methods because they are useful outside the context of lists. For example: >>> max(1,2,3,4,5,4) 5 Thus, making max and min methods of the list class (or of all sequence classes) doesn't really make sense. Now, sum() is a bit more complicated at first blush, but not really. We want sum to work with all numerical sequence types - namely, lists *and* tuples. Since tuples have no public methods, and we don't want to repeat ourselves by including sum() as a method for both lists and tuples, we make it a global function. Peace Bill Mill bill.mill at gmail.com PS I don't know the exact reason behind sum(), so I took a shot at it. That's just how I made sense of it; if you know better please contradict me. On Tue, 19 Oct 2004 15:29:45 +0100 (BST), Hans Fangohr wrote: > Dear all, > > I was looking at what you can do with lists in Python. There are > basically two sets of commands: (i) methods doing something with a > list (such as sort(), reverse(), count(), ...) and (ii) functions that > take a list as an argument (such as sum(), max(), min()). > > I would expect that there is a rationale behind this choice -- would > anyone know what this is or where I can find more information? > > Many thanks, > > Hans > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From maxnoel_fr at yahoo.fr Tue Oct 19 17:05:19 2004 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Tue Oct 19 17:05:26 2004 Subject: [Tutor] methods versus functions (using lists as an example) In-Reply-To: References: Message-ID: <4AD3462A-21E0-11D9-952E-000393CBC88E@yahoo.fr> On Oct 19, 2004, at 15:29, Hans Fangohr wrote: > Dear all, > > I was looking at what you can do with lists in Python. There are > basically two sets of commands: (i) methods doing something with a > list (such as sort(), reverse(), count(), ...) and (ii) functions that > take a list as an argument (such as sum(), max(), min()). > > I would expect that there is a rationale behind this choice -- would > anyone know what this is or where I can find more information? > > Many thanks, > > Hans It's a matter of legacy. IIRC, Python was not, in its original design, fully object-oriented. Which is why some functions haven't been implemented as base class methods yet. This makes Python slightly less elegant than Ruby, but it's quite easy to get the hang of. Hopefully this problem will be corrected in subsequent versions of the language? -- Wild_Cat maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From bill.mill at gmail.com Tue Oct 19 17:09:29 2004 From: bill.mill at gmail.com (Bill Mill) Date: Tue Oct 19 17:09:32 2004 Subject: [Tutor] Re: Catching warnings? In-Reply-To: References: Message-ID: <797fe3d404101908091dfa30b6@mail.gmail.com> Liam, The 'rotor' module is deprecated: >>> import rotor __main__:1: DeprecationWarning: the rotor module uses an insecure algorithm and is deprecated If we want to ignore the error, we can simply catch it as we do any other exception: >>> try: ... import rotor ... except DeprecationWarning: ... pass ... >>> Peace Bill Mill bill.mill at gmail.com On Wed, 20 Oct 2004 01:11:59 +1300, Liam Clarke wrote: > Oops, "Just a quick question, catching errors is easy, but how to go about > catching errors?" > > I meant, of course, catching warnings.... (it's late, that's my > excuse and I'm sticking to it.) > > > > > On Wed, 20 Oct 2004 01:10:00 +1300, Liam Clarke wrote: > > Hi all, > > > > Just a quick question, catching errors is easy, but how to go about > > catching errors? I'd like to squelch a deprecation warning. I know the > > module's deprecated, but it's useful for the moment. > > > > So far I've filtered it with Warnings.filterwarnings, but the docs > > state that warning are technically exceptions. Can you catch them the > > same way you can catch error codes? > > > > Oh, and personally, I think I just met the most subtle way of saying > > 'You're missing a closed bracket' - > > > > Token Error: EOF in multi-line statement > > > > Grrrr > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From Nicholas.Montpetit at deluxe.com Tue Oct 19 17:12:49 2004 From: Nicholas.Montpetit at deluxe.com (Nicholas.Montpetit@deluxe.com) Date: Tue Oct 19 17:12:57 2004 Subject: [Tutor] Hello from a beginner! Message-ID: I'm completely new to this list (and Python) so I just wanted to say hello and introduce myself. I have a lot of experience with Perl, but I've been hearing enough good stuff about Python that it seems like I'm overdue time to pick it up. My early readings (from O'Reilly's LEARNING PYTHON) lead me to believe that it should be an excellent language for GUI apps, scientific computing, and cross-platform apps. Along with reading the O'Reilly book, I hope this list will get me up to speed quickly. Does anyone have an opinion on the MIGRATING FROM PERL TO PYTHON (or something like that; has a snake on the cover) book out there? I'm considering picking that one up. Thanks, and I look forward to learning Python and participating in this list! Nicholas Montpetit Deluxe Business Services 651-787-1008 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20041019/2a5f44a7/attachment.htm From rdm at rcblue.com Tue Oct 19 17:15:34 2004 From: rdm at rcblue.com (Dick Moores) Date: Tue Oct 19 17:15:38 2004 Subject: [Tutor] isbetween function chapter 5 How to Think Like Computer Scientist In-Reply-To: <41750C72.7040703@myrealbox.com> References: <41750C72.7040703@myrealbox.com> Message-ID: <6.1.2.0.2.20041019081358.045fc7a0@rcblue.com> Try changing isbetween to def isbetween(x,y,z): test1(x,y,z) test2(x,y,z) test3(x,y,z) Dick Moores Eri Mendz wrote at 05:45 10/19/2004: >Hello all, > >I'm a newbie trying to learn Python at my own pace. I work in sales NOT >programming so please excuse me of obvious things i may overlook in the >course of my self-teaching. > >Here is the code i made trying to solve the exercise mentioned in the >subject of my email. I made it like so as i think pure if-elif-else >statement is unwieldy. Of course its just me and pros here got something >to correct my statement: > >#!/usr/bin/env python ># filename: isbetween.py ># description: make function with 3 parameters & determine the median ># Author: Eri Mendz ># Tue Oct 19 15:07:22 AST 2004 ># CYGWIN_NT-5.0 > >def test1(x,y,z): > if x > y and x > z: # x is highest > if y > z: # z-y-x > print y, "is between", z, "and", x > else: # y-z-x > print z, "is between", y, "and", x > >def test2(x,y,z): > if y > x and y > z: # y is highest > if x > z: # z-x-y > print x, "is between", z, "and", y > else: > print z, "is between", x, "and", y > >def test3(x,y,z): > if z > x and z > y: # z is highest > if x > y: # y-x-z > print x, "is between", y, "and", z > else: > print y, "is between", x, "and", z > >def isbetween(x,y,z): > test1() > test2() > test3() > ># test isbetween() >isbetween(23,10,56) > >I get: >TypeError: test1() takes exactly 3 arguments (0 given) > >Dumb me i didnt supplied arguments as required. But do i really have to >do that? I like the 3 functions to act as dummy functions (sort of) and >let the real work happen inside isbetween(). Kindly enlighten me how to >do it right. > >-- >Regards, >erimendz ** use firefox/thunderbird ** >http://www.spreadfirefox.com/?q=affiliates&id=6670&t=58 > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From ghenry at python.me.uk Tue Oct 19 17:16:55 2004 From: ghenry at python.me.uk (Gavin Henry) Date: Tue Oct 19 17:17:41 2004 Subject: [Tutor] Hello from a beginner! In-Reply-To: References: Message-ID: <56473.193.195.148.66.1098199015.squirrel@193.195.148.66> Nicholas.Montpetit@deluxe.com said: > I'm completely new to this list (and Python) so I just wanted to say hello > and introduce myself. > > I have a lot of experience with Perl, but I've been hearing enough good > stuff about Python that it seems like I'm overdue time to pick it up. My > early readings (from O'Reilly's LEARNING PYTHON) lead me to believe that > it should be an excellent language for GUI apps, scientific computing, and > cross-platform apps. Along with reading the O'Reilly book, I hope this > list will get me up to speed quickly. > I'm in exactly the same situation, just coming from perl and starting the O'reilly book. Gavin. -- Just getting into the python language.... Fancy a yourname@python.me.uk? Just ask!!! From cybersamurai at terra.com.br Tue Oct 19 16:24:48 2004 From: cybersamurai at terra.com.br (Luiz Siqueira) Date: Tue Oct 19 17:26:39 2004 Subject: [Tutor] methods versus functions (using lists as an example) In-Reply-To: References: Message-ID: Em 19/10/2004, ?s 12:29, Hans Fangohr escreveu: > Dear all, > > I was looking at what you can do with lists in Python. There are > basically two sets of commands: (i) methods doing something with a > list (such as sort(), reverse(), count(), ...) and (ii) functions that > take a list as an argument (such as sum(), max(), min()). > > I would expect that there is a rationale behind this choice -- would > anyone know what this is or where I can find more information? > > Many thanks, > > Hans > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > Esta mensagem foi verificada pelo E-mail Protegido Terra. > Scan engine: VirusScan / Atualizado em 14/10/2004 / Vers?o: 1.5.2 > Proteja o seu e-mail Terra: http://www.emailprotegido.terra.com.br/ > Well, if is you a beginner, you can start using the method "help" with list as argument like "help(list)", there you can find the basic to work with lists. Another good place is look to a beginner tutorial in python.org, there are good and shorts materials for explain techniques and resources of each class related with lists. ------------------------------------------------------------------- Luiz Siqueira Neto Cyber Samurai Brazil - ES MSN Messenger - cybersamurai_br@hotmail.com Yahoo Messenger - cybersamurai_br@yahoo.com.br Skype - cybersamurai_br ICQ Messenger - 8923567 From maxnoel_fr at yahoo.fr Tue Oct 19 17:27:17 2004 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Tue Oct 19 17:27:19 2004 Subject: [Tutor] has anybody....... In-Reply-To: <001f01c39651$43588d20$6400a8c0@cody368747> References: <001f01c39651$43588d20$6400a8c0@cody368747> Message-ID: <5C2D19B4-21E3-11D9-952E-000393CBC88E@yahoo.fr> On Oct 19, 2003, at 15:57, Cody wrote: > has anybody ever did any hacking with python., if so how would u > program with it to do so. > just cirouis. Depends on your definition of "hacking"... If you use the real definition of the word (where "hacking" refers to coding nifty programs for the sheer fun of it), then we all have, yes. If, as I suspect, by "hacking" you actually mean "cracking" (participating in destructive and usually illegal activities such as computer highjacking -- which is *not* a valid sense of the word "hacking"), then: 1) Some of us may have. 2) However, I suspect that very few of us would pride themselves on doing so. 3) The reasoning behind 2) is that helping to build things is always more rewarding (intellect-, moral-, karma- and respect-wise) than destroying them. To put it another way, if Python was a brand of automobiles, this would be a mailing-list for (beginner) mechanics, and you'd basically be asking "have you guys ever done any car-jacking?". 4) As for "how", all of course depends on what you want to do. AFAIK there is no magic "crack" command in Python (or in any other programming language for that matter) that allows you to crack computers like in movies. Anyway, that doesn't really matter. If you want to become a Python mechanic, you'll find plenty of people here willing to help you out. Welcome aboard! -- Wild_Cat maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From gustabares at verizon.net Tue Oct 19 17:28:43 2004 From: gustabares at verizon.net (Gus Tabares) Date: Tue Oct 19 17:28:48 2004 Subject: [Tutor] Hello from a beginner! In-Reply-To: References: Message-ID: <417532AB.3070904@verizon.net> Nicholas.Montpetit@deluxe.com wrote: > > I'm completely new to this list (and Python) so I just wanted to say > hello and introduce myself. > > I have a lot of experience with Perl, but I've been hearing enough > good stuff about Python that it seems like I'm overdue time to pick it > up. My early readings (from O'Reilly's LEARNING PYTHON) lead me to > believe that it should be an excellent language for GUI apps, > scientific computing, and cross-platform apps. Along with reading the > O'Reilly book, I hope this list will get me up to speed quickly. > > Does anyone have an opinion on the MIGRATING FROM PERL TO PYTHON (or > something like that; has a snake on the cover) book out there? I'm > considering picking that one up. > > Thanks, and I look forward to learning Python and participating in > this list! > > Nicholas Montpetit > Deluxe Business Services > 651-787-1008 > >------------------------------------------------------------------------ > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > IMO I think the only books you'll need for general Python programming are Learning Python and Programming Python. Of course if you plan on using Tkinter extensively you might consider picking up a Tkinter book. I don't think you should have a big problem converting from Perl to Python. Python handles OOP nicely (as opposed to being "globbed" on afterwards) and has a very clean syntax. Best of all, it's simple to learn! Coming from Perl you should be able to pick it up within a week or less. I think in the end you'll be glad you made the "conversion". And may I be the first to say, Welcome to Python!:) Good Luck, Gus From maxnoel_fr at yahoo.fr Tue Oct 19 17:41:55 2004 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Tue Oct 19 17:41:58 2004 Subject: Fwd: [Tutor] has anybody....... Message-ID: <67ABD0AC-21E5-11D9-952E-000393CBC88E@yahoo.fr> (note: use the "reply to all" command if you want your message to go to the list as well) Begin forwarded message: > From: "Cody" > Date: October 19, 2003 16:36:09 BST > To: "Max Noel" > Subject: Re: [Tutor] has anybody....... > > thanks im just wanting todo a little bit of programing and dont know > what to > start off with so i thought maybee hacking but i desided i wated to > write a > usefull program that some people i koe need. > i sent out a requests here for help 2 days ago. > but didnt realy get anywhere but this is want i want to make. > > ok i want a program to put a audio file and a video file together on a > track. i have a program but i want one for other ppl that need it. i do > video stuff, witch saves it to .avi and audio to .wav i need to > combine them > to .wmv on a track.and i want it to have like an interface i can make > them > in photoshop and save as .jpeg for the program or whatever format it > needs. > > plz help me make one theres tons of programs out there that do so, but > i > want my own. > > thanks,cody > > ----- Original Message ----- > From: "Max Noel" > To: "Cody" > Cc: > Sent: Tuesday, October 19, 2004 11:27 AM > Subject: Re: [Tutor] has anybody....... > > >> >> On Oct 19, 2003, at 15:57, Cody wrote: >> >>> has anybody ever did any hacking with python., if so how would u >>> program with it to do so. >>> just cirouis. >> >> Depends on your definition of "hacking"... >> If you use the real definition of the word (where "hacking" refers to >> coding nifty programs for the sheer fun of it), then we all have, yes. >> If, as I suspect, by "hacking" you actually mean "cracking" >> (participating in destructive and usually illegal activities such as >> computer highjacking -- which is *not* a valid sense of the word >> "hacking"), then: >> >> 1) Some of us may have. >> 2) However, I suspect that very few of us would pride themselves on >> doing so. >> 3) The reasoning behind 2) is that helping to build things is always >> more rewarding (intellect-, moral-, karma- and respect-wise) than >> destroying them. To put it another way, if Python was a brand of >> automobiles, this would be a mailing-list for (beginner) mechanics, >> and >> you'd basically be asking "have you guys ever done any car-jacking?". >> 4) As for "how", all of course depends on what you want to do. AFAIK >> there is no magic "crack" command in Python (or in any other >> programming language for that matter) that allows you to crack >> computers like in movies. >> >> Anyway, that doesn't really matter. If you want to become a Python >> mechanic, you'll find plenty of people here willing to help you out. >> Welcome aboard! >> >> -- Wild_Cat >> maxnoel_fr at yahoo dot fr -- ICQ #85274019 >> "Look at you hacker... A pathetic creature of meat and bone, panting >> and sweating as you run through my corridors... How can you challenge >> a >> perfect, immortal machine?" >> > > -- maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From bvande at po-box.mcgill.ca Tue Oct 19 17:47:25 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Tue Oct 19 17:47:15 2004 Subject: [Tutor] Hello from a beginner! In-Reply-To: References: Message-ID: <4175370D.3030406@po-box.mcgill.ca> Nicholas.Montpetit@deluxe.com said unto the world upon 2004-10-19 11:12: > Does anyone have an opinion on the MIGRATING FROM PERL TO PYTHON (or > something like that; has a snake on the cover) book out there? I'm > considering picking that one up. > > Thanks, and I look forward to learning Python and participating in this > list! > > Nicholas Montpetit Hi Nicholas, still a learner myself and blissfully ignorant of Perl ;-) So I don't know if it is useful, but you might want to check out: Best, Brian vdB From mhansen at cso.atmel.com Tue Oct 19 18:57:01 2004 From: mhansen at cso.atmel.com (Mike Hansen) Date: Tue Oct 19 18:56:58 2004 Subject: [Tutor] Re: Hello from a beginner! In-Reply-To: <20041019152852.BAFE01E4007@bag.python.org> References: <20041019152852.BAFE01E4007@bag.python.org> Message-ID: <4175475D.3060601@cso.atmel.com> > Subject: > [Tutor] Hello from a beginner! > From: > Nicholas.Montpetit@deluxe.com > Date: > Tue, 19 Oct 2004 10:12:49 -0500 > To: > tutor@python.org > > To: > tutor@python.org > > > > I'm completely new to this list (and Python) so I just wanted to say > hello and introduce myself. > > I have a lot of experience with Perl, but I've been hearing enough > good stuff about Python that it seems like I'm overdue time to pick it > up. My early readings (from O'Reilly's LEARNING PYTHON) lead me to > believe that it should be an excellent language for GUI apps, > scientific computing, and cross-platform apps. Along with reading the > O'Reilly book, I hope this list will get me up to speed quickly. > > Does anyone have an opinion on the MIGRATING FROM PERL TO PYTHON (or > something like that; has a snake on the cover) book out there? I'm > considering picking that one up. > > Thanks, and I look forward to learning Python and participating in > this list! > > Hi Nicholas, I had some experience with Perl before I found Python. The Perl to Python Migration book didn't really click with me. What really clicked with me was Dive Into Python(http://diveintopython.org/). Also, the tutorial on the Python web site was pretty helpful too.(http://docs.python.org/tut/tut.html). This list is also very helpful. Mike From cowboycody016 at verizon.net Tue Oct 19 18:57:30 2004 From: cowboycody016 at verizon.net (Cody) Date: Tue Oct 19 18:57:31 2004 Subject: [Tutor] has anybody....... Message-ID: <002101c39662$0e0e85a0$6400a8c0@cody368747> ----- Original Message ----- From: "Cody" To: "Max Noel" Sent: Sunday, October 19, 2003 11:36 AM Subject: Re: [Tutor] has anybody....... > thanks im just wanting todo a little bit of programing and dont know what to > start off with so i thought maybee hacking but i desided i wated to write a > usefull program that some people i koe need. > i sent out a requests here for help 2 days ago. > but didnt realy get anywhere but this is want i want to make. > > ok i want a program to put a audio file and a video file together on a > track. i have a program but i want one for other ppl that need it. i do > video stuff, witch saves it to .avi and audio to .wav i need to combine them > to .wmv on a track.and i want it to have like an interface i can make them > in photoshop and save as .jpeg for the program or whatever format it needs. > > plz help me make one theres tons of programs out there that do so, but i > want my own. > > thanks,cody > > ----- Original Message ----- > From: "Max Noel" > To: "Cody" > Cc: > Sent: Tuesday, October 19, 2004 11:27 AM > Subject: Re: [Tutor] has anybody....... > > > > > > On Oct 19, 2003, at 15:57, Cody wrote: > > > > > has anybody ever did any hacking with python., if so how would u > > > program with it to do so. > > > just cirouis. > > > > Depends on your definition of "hacking"... > > If you use the real definition of the word (where "hacking" refers to > > coding nifty programs for the sheer fun of it), then we all have, yes. > > If, as I suspect, by "hacking" you actually mean "cracking" > > (participating in destructive and usually illegal activities such as > > computer highjacking -- which is *not* a valid sense of the word > > "hacking"), then: > > > > 1) Some of us may have. > > 2) However, I suspect that very few of us would pride themselves on > > doing so. > > 3) The reasoning behind 2) is that helping to build things is always > > more rewarding (intellect-, moral-, karma- and respect-wise) than > > destroying them. To put it another way, if Python was a brand of > > automobiles, this would be a mailing-list for (beginner) mechanics, and > > you'd basically be asking "have you guys ever done any car-jacking?". > > 4) As for "how", all of course depends on what you want to do. AFAIK > > there is no magic "crack" command in Python (or in any other > > programming language for that matter) that allows you to crack > > computers like in movies. > > > > Anyway, that doesn't really matter. If you want to become a Python > > mechanic, you'll find plenty of people here willing to help you out. > > Welcome aboard! > > > > -- Wild_Cat > > maxnoel_fr at yahoo dot fr -- ICQ #85274019 > > "Look at you hacker... A pathetic creature of meat and bone, panting > > and sweating as you run through my corridors... How can you challenge a > > perfect, immortal machine?" > > > From pythonTutor at venix.com Tue Oct 19 19:31:42 2004 From: pythonTutor at venix.com (Lloyd Kvam) Date: Tue Oct 19 19:31:50 2004 Subject: [Tutor] methods versus functions (using lists as an example) In-Reply-To: <797fe3d404101908032466f8ec@mail.gmail.com> References: <797fe3d404101908032466f8ec@mail.gmail.com> Message-ID: <1098207101.2743.74.camel@laptop.venix.com> Not contradicting you, but it goes beyond lists and tuples. Don't forget about generators. >>> def evens(limit=10): ... x = 0 ... while x < limit: ... x += 2 ... yield x ... >>> evens() >>> list(evens()) [2, 4, 6, 8, 10] >>> sum(evens()) 30 A generator can be used to create a list. However, sum will process the generator directly. Note that with a list or a tuple ALL of the elements must be exist at the same time. sum with a generator can accumulate the total using one element at a time. On Tue, 2004-10-19 at 11:03, Bill Mill wrote: > Hans, > > max() and min() are not class methods because they are useful outside > the context of lists. For example: > > >>> max(1,2,3,4,5,4) > 5 > > Thus, making max and min methods of the list class (or of all sequence > classes) doesn't really make sense. > Now, sum() is a bit more complicated at first blush, but not really. > We want sum to work with all numerical sequence types - namely, lists > *and* tuples. Since tuples have no public methods, and we don't want > to repeat ourselves by including sum() as a method for both lists and > tuples, we make it a global function. > > Peace > Bill Mill > bill.mill at gmail.com > > PS I don't know the exact reason behind sum(), so I took a shot at it. > That's just how I made sense of it; if you know better please > contradict me. > > > On Tue, 19 Oct 2004 15:29:45 +0100 (BST), Hans Fangohr > wrote: > > Dear all, > > > > I was looking at what you can do with lists in Python. There are > > basically two sets of commands: (i) methods doing something with a > > list (such as sort(), reverse(), count(), ...) and (ii) functions that > > take a list as an argument (such as sum(), max(), min()). > > > > I would expect that there is a rationale behind this choice -- would > > anyone know what this is or where I can find more information? > > > > Many thanks, > > > > Hans > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp From klappnase at freenet.de Tue Oct 19 20:24:06 2004 From: klappnase at freenet.de (Michael Lange) Date: Tue Oct 19 20:19:46 2004 Subject: [Tutor] has anybody....... In-Reply-To: <002101c39662$0e0e85a0$6400a8c0@cody368747> References: <002101c39662$0e0e85a0$6400a8c0@cody368747> Message-ID: <20041019202406.7438908f.klappnase@freenet.de> On Sun, 19 Oct 2003 12:57:17 -0400 "Cody" wrote: > > ok i want a program to put a audio file and a video file together on a > > track. i have a program but i want one for other ppl that need it. i do > > video stuff, witch saves it to .avi and audio to .wav i need to combine > them > > to .wmv on a track.and i want it to have like an interface i can make them > > in photoshop and save as .jpeg for the program or whatever format it > needs. > > > > plz help me make one theres tons of programs out there that do so, but i > > want my own. > > > > thanks,cody > > Hi, Cody, maybe the PyMedia module can help you here: http://pymedia.org/index.html I don't have any experience with PyMedia, but it seems to look promising. Good luck to you! Michael From jerimed at myrealbox.com Tue Oct 19 20:17:49 2004 From: jerimed at myrealbox.com (Eri Mendz) Date: Tue Oct 19 20:21:22 2004 Subject: [Tutor] isbetween function chapter 5 How to Think Like In-Reply-To: <6.1.2.0.2.20041019081358.045fc7a0@rcblue.com> References: <41750C72.7040703@myrealbox.com> <6.1.2.0.2.20041019081358.045fc7a0@rcblue.com> Message-ID: <41755A4D.5040805@myrealbox.com> Thank you guys for all the replies. Will post back after i play around your code tips. Dick Moores wrote: > Try changing isbetween to > > def isbetween(x,y,z): > test1(x,y,z) > test2(x,y,z) > test3(x,y,z) > > Dick Moores > > Eri Mendz wrote at 05:45 10/19/2004: > >> Hello all, >> >> I'm a newbie trying to learn Python at my own pace. I work in sales >> NOT programming so please excuse me of obvious things i may overlook >> in the course of my self-teaching. >> >> Here is the code i made trying to solve the exercise mentioned in the >> subject of my email. I made it like so as i think pure if-elif-else >> statement is unwieldy. Of course its just me and pros here got >> something to correct my statement: >> >> #!/usr/bin/env python >> # filename: isbetween.py >> # description: make function with 3 parameters & determine the median >> # Author: Eri Mendz >> # Tue Oct 19 15:07:22 AST 2004 >> # CYGWIN_NT-5.0 >> >> def test1(x,y,z): >> if x > y and x > z: # x is highest >> if y > z: # z-y-x >> print y, "is between", z, "and", x >> else: # y-z-x >> print z, "is between", y, "and", x >> >> def test2(x,y,z): >> if y > x and y > z: # y is highest >> if x > z: # z-x-y >> print x, "is between", z, "and", y >> else: >> print z, "is between", x, "and", y >> >> def test3(x,y,z): >> if z > x and z > y: # z is highest >> if x > y: # y-x-z >> print x, "is between", y, "and", z >> else: >> print y, "is between", x, "and", z >> >> def isbetween(x,y,z): >> test1() >> test2() >> test3() >> >> # test isbetween() >> isbetween(23,10,56) >> >> I get: >> TypeError: test1() takes exactly 3 arguments (0 given) >> >> Dumb me i didnt supplied arguments as required. But do i really have >> to do that? I like the 3 functions to act as dummy functions (sort >> of) and let the real work happen inside isbetween(). Kindly enlighten >> me how to do it right. >> >> -- >> Regards, >> erimendz ** use firefox/thunderbird ** >> http://www.spreadfirefox.com/?q=affiliates&id=6670&t=58 >> >> _______________________________________________ >> Tutor maillist - Tutor@python.org >> http://mail.python.org/mailman/listinfo/tutor > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From jeff at ccvcorp.com Tue Oct 19 23:02:44 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Tue Oct 19 23:00:26 2004 Subject: [Tutor] methods versus functions (using lists as an example) In-Reply-To: <4AD3462A-21E0-11D9-952E-000393CBC88E@yahoo.fr> References: <4AD3462A-21E0-11D9-952E-000393CBC88E@yahoo.fr> Message-ID: <417580F4.3020604@ccvcorp.com> Max Noel wrote: > > On Oct 19, 2004, at 15:29, Hans Fangohr wrote: > >> I was looking at what you can do with lists in Python. There are >> basically two sets of commands: (i) methods doing something with a >> list (such as sort(), reverse(), count(), ...) and (ii) functions that >> take a list as an argument (such as sum(), max(), min()). >> >> I would expect that there is a rationale behind this choice -- would >> anyone know what this is or where I can find more information? > > > It's a matter of legacy. IIRC, Python was not, in its original > design, fully object-oriented. Which is why some functions haven't > been implemented as base class methods yet. Not true. Python is object-oriented from the ground up, and everything in Python (including basic data types, functions, modules, and even class definitions themselves) is an object. The reason that some of these things are done as functions and some as methods of list objects, is that some of the operations make sense on a much wider range of things than just lists. If you want to be able to conveniently sum a sequence, you can pass that sequence to sum() and everything just works. If sum() were a method instead of a function, then *every* type of sequence would have to define a sum() method that would be essentially identical. Even worse, if a programmer defines his own sequence type, then he'd have to write a sum() method on that custom type before it could be summed. Not much of a problem if it's known ahead of time that sum() is needed, but what if you're writing a library? You don't know how that type is going to be used, which means you need to implement methods for every possible type of action that could be done on a sequence... what a pain! Especially since those methods will be identical to the methods on built-in lists and tuples... In other words, using functions instead of methods can make generic programming much easier. Python's design is carefully tuned to encourage generic programming, which makes it easier to re-use code, which means that you'll end up being more productive. > This makes Python slightly less elegant than Ruby, but it's quite > easy to get the hang of. I don't know Ruby, but I can certainly say that I think that Python's current form (using functions for generic operations and methods only for type-specific operations) is far more elegant than it would be if everything were forced into methods, thus requiring many classes to sprout swarms of tiny, repetitious methods... But I *do* agree that Python is quite easy to get the hang of. ;) Jeff Shannon Technician/Programmer Credit International From maxnoel_fr at yahoo.fr Wed Oct 20 00:01:17 2004 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Wed Oct 20 00:01:28 2004 Subject: [Tutor] methods versus functions (using lists as an example) In-Reply-To: <417580F4.3020604@ccvcorp.com> References: <4AD3462A-21E0-11D9-952E-000393CBC88E@yahoo.fr> <417580F4.3020604@ccvcorp.com> Message-ID: <66E13DA4-221A-11D9-952E-000393CBC88E@yahoo.fr> On Oct 19, 2004, at 22:02, Jeff Shannon wrote: > Max Noel wrote: > >> It's a matter of legacy. IIRC, Python was not, in its original >> design, fully object-oriented. Which is why some functions haven't >> been implemented as base class methods yet. > > > Not true. Python is object-oriented from the ground up, and > everything in Python (including basic data types, functions, modules, > and even class definitions themselves) is an object. Ah. My bad. I stand corrected. > The reason that some of these things are done as functions and some as > methods of list objects, is that some of the operations make sense on > a much wider range of things than just lists. If you want to be able > to conveniently sum a sequence, you can pass that sequence to sum() > and everything just works. If sum() were a method instead of a > function, then *every* type of sequence would have to define a sum() > method that would be essentially identical. Even worse, if a > programmer defines his own sequence type, then he'd have to write a > sum() method on that custom type before it could be summed. You have a point there. However, I don't really see why str() and repr() are functions and not methods, given that you have to implement methods for them to work anyway. > I don't know Ruby, but I can certainly say that I think that Python's > current form (using functions for generic operations and methods only > for type-specific operations) is far more elegant than it would be if > everything were forced into methods, thus requiring many classes to > sprout swarms of tiny, repetitious methods... Ruby ( http://www.ruby-lang.org/ ) is another object-oriented "scripting" language. I find it extremely elegant, and in fact can't decide which one I prefer, Ruby or Python (I'm learning both at the same time). Both are extremely flexible, very fun to program in, and produce code that's compact and easy to read. So far I've been getting more work done in Python, though, because it's been around for longer and as a result has a lot more usable modules than Ruby. > But I *do* agree that Python is quite easy to get the hang of. ;) It is, indeed. I was getting work done just a few hours after starting to read Guido's tutorial on python.org. The same thing can be said of Ruby. However, I find Python's documentation vastly superior in both quantity and quality, which means advanced topics can be grasped more easily. I'm hitting a roadblock, though, when it comes to web programming with mod_python. The documentation I've found about it is quite terse, and mod_python's logic seems completely alien to me (I was expecting something that works exactly like CGI but faster). Are there any good tutorials on the subject, by the way? -- Wild_Cat maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From jeff at ccvcorp.com Wed Oct 20 01:47:43 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Wed Oct 20 01:45:26 2004 Subject: [Tutor] methods versus functions (using lists as an example) In-Reply-To: <66E13DA4-221A-11D9-952E-000393CBC88E@yahoo.fr> References: <4AD3462A-21E0-11D9-952E-000393CBC88E@yahoo.fr> <417580F4.3020604@ccvcorp.com> <66E13DA4-221A-11D9-952E-000393CBC88E@yahoo.fr> Message-ID: <4175A79F.6080001@ccvcorp.com> Max Noel wrote: > > On Oct 19, 2004, at 22:02, Jeff Shannon wrote: > >> The reason that some of these things are done as functions and some >> as methods of list objects, is that some of the operations make sense >> on a much wider range of things than just lists. If you want to be >> able to conveniently sum a sequence, you can pass that sequence to >> sum() and everything just works. If sum() were a method instead of a >> function, then *every* type of sequence would have to define a sum() >> method that would be essentially identical. Even worse, if a >> programmer defines his own sequence type, then he'd have to write a >> sum() method on that custom type before it could be summed. > > > You have a point there. However, I don't really see why str() and > repr() are functions and not methods, given that you have to implement > methods for them to work anyway. Well, if you're defining your own class, you need to implement methods to be able to add and subtract, as well, but you wouldn't think that those should be methods, would you? It's a philosophical point, as much as anything -- using repr() is telling Python "give me a string that represents this object"; the fact that the function may need to ask the object how it wants to be represented is an implementation detail. The intent is that repr() functions on pretty much any argument, so tying it directly to any particular (set of) type/class definitions doesn't convey the intended meaning. And besides, since repr() is a function, that means that if a class *doesn't* define a method to help it, it can have a fallback response. If it were a method, then attempting to call it on a class that didn't define anything for that purpose would throw an AttributeError. (And technically, str() is not a function -- it's a type. Using it is asking Python to generate a new string object, using the argument to determine the contents of that string. Definitely a nitpick, especially as one *could* argue that a type object is not much more than a factory function... but often understanding the nits can really help to make sense out of the whole structure.) >> I don't know Ruby, [...] > > > Ruby ( http://www.ruby-lang.org/ ) is another object-oriented > "scripting" language. Heh. I should have said, I haven't really looked at Ruby yet. ;) I have heard about it, and it does often get compared to Python. At this point, I find it more useful to concentrate my efforts, so picking up more languages is a low priority for me. (And if I *were* to try to pick up a new language, I'd probably go for something with a new-to-me paradigm, such as Lisp/Scheme or Haskell...) Not that I have anything against Ruby, just a matter of most efficient use of limited resources (time and brainpower). > I'm hitting a roadblock, though, when it comes to web programming > with mod_python. The documentation I've found about it is quite terse, > and mod_python's logic seems completely alien to me (I was expecting > something that works exactly like CGI but faster). Are there any good > tutorials on the subject, by the way? Sorry, I can't help you on that -- I've never needed to do any web programming, myself, so I haven't investigated that area at all. Some day when I have all the free time that I'd like..... ;) Jeff Shannon Technician/Programmer Credit International From dyoo at hkn.eecs.berkeley.edu Wed Oct 20 02:01:45 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Oct 20 02:01:48 2004 Subject: [Tutor] methods versus functions (using lists as an example) In-Reply-To: <66E13DA4-221A-11D9-952E-000393CBC88E@yahoo.fr> Message-ID: > I'm hitting a roadblock, though, when it comes to web programming > with mod_python. The documentation I've found about it is quite terse, > and mod_python's logic seems completely alien to me (I was expecting > something that works exactly like CGI but faster). Are there any good > tutorials on the subject, by the way? Hi Max, Have you worked through: http://www.modpython.org/live/current/doc-html/tutorial.html If you are getting stuck on sections in the mod_python tutorial, it'll be good to bring those problems up. Their documentation may need some more work: perhaps we can help to improve their documentation by working through an example with you? Good luck to you! From dyoo at hkn.eecs.berkeley.edu Wed Oct 20 03:20:30 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Oct 20 03:20:33 2004 Subject: [Tutor] Re: Catching warnings? In-Reply-To: <797fe3d404101908091dfa30b6@mail.gmail.com> Message-ID: On Tue, 19 Oct 2004, Bill Mill wrote: > The 'rotor' module is deprecated: > > >>> import rotor > __main__:1: DeprecationWarning: the rotor module uses an insecure algorithm and > is deprecated > > If we want to ignore the error, we can simply catch it as we do any > other exception: > > >>> try: > ... import rotor > ... except DeprecationWarning: > ... pass > ... > >>> As a warning, when something's labeled as "deprecated" in Python, the implementors really mean it: 'rotor' is gone in the upcoming Python 2.4 release. So, unless there's an overriding reason, don't ignore DeprecationWarnings, because there is a strong chance that code that uses a deprecated feature won't work in the future. Warnings are there for a reason! *grin* From dyoo at hkn.eecs.berkeley.edu Wed Oct 20 03:36:15 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Oct 20 03:36:21 2004 Subject: [Tutor] how to play arrays as audio signal In-Reply-To: Message-ID: On Tue, 19 Oct 2004, Hans Fangohr wrote: > I would like to 'acoustically play' values in an array (or list, tupel, > ...) as if the position of the speaker membrane at different times was > given by the value in that array. Is there a module (in the best case a > standard module) that would do this for me? (I will need this on > Windows.) Hi Hans, Your best bet is probably the pygame module: http://pygame.org/ In fact: http://pygame.org/docs/ref/pygame_sndarray.html uses Numeric Python arrays to generate sounds. http://archives.seul.org/pygame/users/Nov-2002/msg00120.html shows sample code to play a sound out of a Numeric Python array. However, PyGame has not have adopted 'numarray' yet: it looks like they're still using the older Numeric Python 'numpy' library. The switch to 'numarray' appears to be a TODO for the PyGame folks: http://www.pygame.org/readme.html Until then, it might be easiest to use Numeric Python's arrays with PyGame. Good luck to you! From cyresse at gmail.com Wed Oct 20 05:00:24 2004 From: cyresse at gmail.com (Liam Clarke) Date: Wed Oct 20 05:00:27 2004 Subject: [Tutor] Re: Catching warnings? In-Reply-To: References: <797fe3d404101908091dfa30b6@mail.gmail.com> Message-ID: I'm only using rotor because I couldn't get the a2b_uu functions to work : ) I just need to render something into not-plaintext. It's not hugely important, all the email passwords are defaults anyway.... And Bill - try: import rotor except: pass which is now replaced with - from warnings import * filterwarnings('ignore',"", DeprecationWarning, "", 0) But yes, any suggestions on what to replace rotor with would be appreciated. Regards, Liam Clarke On Tue, 19 Oct 2004 18:20:30 -0700 (PDT), Danny Yoo wrote: > > > On Tue, 19 Oct 2004, Bill Mill wrote: > > > The 'rotor' module is deprecated: > > > > >>> import rotor > > __main__:1: DeprecationWarning: the rotor module uses an insecure algorithm and > > is deprecated > > > > If we want to ignore the error, we can simply catch it as we do any > > other exception: > > > > >>> try: > > ... import rotor > > ... except DeprecationWarning: > > ... pass > > ... > > >>> > > > As a warning, when something's labeled as "deprecated" in Python, the > implementors really mean it: 'rotor' is gone in the upcoming Python 2.4 > release. > > So, unless there's an overriding reason, don't ignore DeprecationWarnings, > because there is a strong chance that code that uses a deprecated feature > won't work in the future. Warnings are there for a reason! *grin* > > From flaxeater at yahoo.com Wed Oct 20 05:41:19 2004 From: flaxeater at yahoo.com (Chad Crabtree) Date: Wed Oct 20 05:41:22 2004 Subject: [Tutor] mod_python question Was: methods versus functions (using lists as an example) Message-ID: <20041020034119.77800.qmail@web54302.mail.yahoo.com> Max Noel wrote: > I'm hitting a roadblock, though, when it comes to web programming > with mod_python. The documentation I've found about it is quite terse, > and mod_python's logic seems completely alien to me (I was expecting > something that works exactly like CGI but faster). Are there any good > tutorials on the subject, by the way? > I to had trouble with mod_python at first. However in the documentation it tells you how to install it's CGI_HANDLER that behaves the same as CGi except for one gotcha that I've discovered. This idiom does not work. if __name__=="__main__": Apparently the handler is the main and the cgi script is more like a module (just a guess). _______________________________ Do you Yahoo!? Declare Yourself - Register online to vote today! http://vote.yahoo.com From tmclaughlin at csu.edu.au Wed Oct 20 06:25:41 2004 From: tmclaughlin at csu.edu.au (McLaughlin, Toby) Date: Wed Oct 20 06:25:59 2004 Subject: [Tutor] Hello from a beginner! Message-ID: <211F78EFD1D870409CC3E4158F4881DA08B32E12@xcww01.riv.csu.edu.au> I'm currently learning Python from a Perl background and I think you can't go too far wrong with "Learning Python". In fact, I suspect that making the conceptual links between the two languages without any explicit help from the book helps to develop a deeper understanding of programming concepts in general. There have been a few nice introductions from people on the list recently, which has filled me with guilt for not introducing myself. I'm a Linux (and sometimes Windows) sysadmin who often needs scripts to solve little problems. I hope that if I write enough of these (and make them elegant enough), I'll one day be able to call myself a programmer. Recently, I've decided to try using Python to for the sort of things for which I'd normally use Perl, particularly in the realm of text processing. For extra fun, I'm learning Emacs at the same time, so I'm migrating from Perl in Vim to Python in Emacs. So far, I'm loving the language and am delighted to see that this list contains such friendly and enthusiastic people. Toby McLaughlin. -----Original Message----- From: tutor-bounces@python.org [mailto:tutor-bounces@python.org] On Behalf Of Nicholas.Montpetit@deluxe.com Sent: Wednesday, 20 October 2004 1:13 AM To: tutor@python.org Subject: [Tutor] Hello from a beginner! I'm completely new to this list (and Python) so I just wanted to say hello and introduce myself. I have a lot of experience with Perl, but I've been hearing enough good stuff about Python that it seems like I'm overdue time to pick it up. My early readings (from O'Reilly's LEARNING PYTHON) lead me to believe that it should be an excellent language for GUI apps, scientific computing, and cross-platform apps. Along with reading the O'Reilly book, I hope this list will get me up to speed quickly. Does anyone have an opinion on the MIGRATING FROM PERL TO PYTHON (or something like that; has a snake on the cover) book out there? I'm considering picking that one up. Thanks, and I look forward to learning Python and participating in this list! Nicholas Montpetit Deluxe Business Services 651-787-1008 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20041020/6012a359/attachment.html From CryptoLevel9 at aol.com Wed Oct 20 06:44:18 2004 From: CryptoLevel9 at aol.com (CryptoLevel9@aol.com) Date: Wed Oct 20 06:44:23 2004 Subject: [Tutor] matrix insertion routine for MNA Message-ID: <1d4.2d3730dc.2ea74722@aol.com> I originally posted under the subject Values in matrices. The two responses that I received from that topic were excellent and helped me a lot, but I have run into a problem that I did not anticipate having when I first asked the question. What I need help with now is how to assign multiple values to the same locations in a pre-constructed matrix and then sum the values at those points. Unfortunately, there is no way to determine which values will need to be summed before placing them into the matrix without defeating the entire purpose of the program, that is why the values have to be summed after they are placed in the matrix. My rational behind writing a program that does this is that I am trying to implement the MNA (Modified Nodal Analysis) Algorithm (a technique for "solving" electrical circuits) in a program making the assumptions that the circuit to be solved is planar, that the user already knows the values for every element in the circuit and which nodes the element is connected to. I have looked through the owners manual for numarray and saw that "The numarray constructor takes a data argument, an optional type, and an optional shape argument. If the data argument is a sequence, then array creates a new object of type numarray, and fills the array with the elements of the data object. The shape of the array is determined by the size and nesting arrangement of the elements of data." This gives me the impression that what I am asking cannot be done by making every point in the matrix a list and then summing the individual lists after the values have been placed in them, which is what I thought of doing first. I would prefer not making any more variable names than I had listed in my original post in order to keep from confusing myself as too what each internal variable means. Any help either on how to do what I am asking or how to circumvent the need to sum values after they have placed in placed in the matrix would be appreciated. Joseph -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20041020/9fae8eb8/attachment.htm From carroll at tjc.com Wed Oct 20 06:48:41 2004 From: carroll at tjc.com (Terry Carroll) Date: Wed Oct 20 06:48:44 2004 Subject: [Tutor] Why doesn't this filter FutureWarning? In-Reply-To: <6.1.0.6.0.20041019074746.02891cf0@mail4.skillsoft.com> Message-ID: On Tue, 19 Oct 2004, Kent Johnson wrote: > Wow, this one had me stumped for a while! You and me both! Thanks for the response. > num=num & 0xffffffff You know, it occurred to me that ANDing a value with all ones was essentially a no-op, so I just deleted the line and everything was fine. (This was from a Python implementation of ping that I found on the web.) But even after I deleted that, it bugged me that I couldn't account for why the error could be masked off in the interactive session, but not in the file. From dyoo at hkn.eecs.berkeley.edu Wed Oct 20 07:59:30 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Oct 20 07:59:32 2004 Subject: [Tutor] Re: Catching warnings? In-Reply-To: Message-ID: On Wed, 20 Oct 2004, Liam Clarke wrote: > I'm only using rotor because I couldn't get the a2b_uu functions to work : ) > I just need to render something into not-plaintext. It's not hugely > important, all the email passwords are defaults anyway.... Hi Liam, Hmmm... Ok, if this isn't too serious, you can always use ROT13. *grin* It's built in: ### >>> 'helloworld'.encode('rot13') 'uryybjbeyq' ### There's a corresponding 'decode()' string method to go the other way around. This 'codecs' system that Python has is pretty rich: rot13 is one of the silly codecs, but there are quite a few others: http://www.python.org/doc/lib/node127.html including one for uu encoding. If you really need strong encryption, then something like amkCrypto might fit the bill: http://www.amk.ca/python/code/crypto.html I hope this helps! From cyresse at gmail.com Wed Oct 20 09:39:01 2004 From: cyresse at gmail.com (Liam Clarke) Date: Wed Oct 20 09:39:04 2004 Subject: [Tutor] Re: Catching warnings? In-Reply-To: References: Message-ID: It certainly does Danny, thanks very much. And thanks to everyone else also. On Tue, 19 Oct 2004 22:59:30 -0700 (PDT), Danny Yoo wrote: > > > On Wed, 20 Oct 2004, Liam Clarke wrote: > > > I'm only using rotor because I couldn't get the a2b_uu functions to work : ) > > I just need to render something into not-plaintext. It's not hugely > > important, all the email passwords are defaults anyway.... > > Hi Liam, > > Hmmm... Ok, if this isn't too serious, you can always use ROT13. *grin* > It's built in: > > ### > >>> 'helloworld'.encode('rot13') > 'uryybjbeyq' > ### > > There's a corresponding 'decode()' string method to go the other way > around. This 'codecs' system that Python has is pretty rich: rot13 is one > of the silly codecs, but there are quite a few others: > > http://www.python.org/doc/lib/node127.html > > including one for uu encoding. > > If you really need strong encryption, then something like amkCrypto might > fit the bill: > > http://www.amk.ca/python/code/crypto.html > > I hope this helps! > > From Michael.Dunn at mpi.nl Wed Oct 20 10:50:56 2004 From: Michael.Dunn at mpi.nl (Michael Dunn) Date: Wed Oct 20 10:51:00 2004 Subject: [Tutor] processing lines and polygons Message-ID: Hi Tutors, I'm doing some GIS work using coastlines extracted from the nifty web form at: http://rimmer.ngdc.noaa.gov/mgg/coast/getcoast.html It produces a huge list of longtitude-latitude points joined up in sections delimited by "# -b" (representing zigzag lines) . These can be easily converted into e.g. MapInfo import format. However the data is slightly messy--some of the lines are broken up into smaller lines, which means that once imported into MapInfo I can't easily select what should be a single piece of coastline. It seems like it should be a reasonably simple piece of text-processing to get them all together: if I have a sequence of points (a, b, c) and a sequence (c, d, a) then I just need to transform them into a sequence (a, b, c, d, a). However I've spend while working on it, and I can't come up with a suitable algorithm to do this. Any pointers? My problem is algorithmic rather than syntactic, so I won't post any of the code I've already written until I've got a better handle on what how I'm trying to go about it. This is a simplified example of the data (I've deleted ~5MB of points): the first section is a polygon (i.e. the startpoint is the same as the endpoint) and so can be left untouched; the next two are lines which should be joined up to make a polygon, and the last three are lines which should be joined up to make a line # -b 146.781336 -19.195938 146.781336 -19.194178 146.781336 -19.195938 # -b 146.929480 -19.296558 146.931534 -19.298025 146.932414 -19.296265 # -b 146.932414 -19.296265 146.930947 -19.295385 146.929480 -19.296558 # -b 146.752881 -19.119079 146.753468 -19.119666 # -b 146.754054 -19.119666 146.754934 -19.118786 146.756108 -19.117612 # -b 146.756108 -19.117612 146.755815 -19.117026 146.752881 -19.118199 Looking forward to hearing any ideas... Michael From kent_johnson at skillsoft.com Wed Oct 20 11:35:46 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Wed Oct 20 11:35:53 2004 Subject: [Tutor] Why doesn't this filter FutureWarning? In-Reply-To: References: <6.1.0.6.0.20041019074746.02891cf0@mail4.skillsoft.com> Message-ID: <6.1.0.6.0.20041020053414.02901f68@mail4.skillsoft.com> At 09:48 PM 10/19/2004 -0700, Terry Carroll wrote: > > num=num & 0xffffffff > >You know, it occurred to me that ANDing a value with all ones was >essentially a no-op as long as num <= 0xffffffff ... Kent From kent_johnson at skillsoft.com Wed Oct 20 12:05:37 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Wed Oct 20 12:05:50 2004 Subject: [Tutor] processing lines and polygons In-Reply-To: References: Message-ID: <6.1.0.6.0.20041020055453.02901a48@mail4.skillsoft.com> Dictionaries are very helpful with this type of problem. I would try building a dictionary that maps individual points to the sequence containing the point. When you create a new sequence from the input, look up each of its points in the dict. If you find any of them, then combine the two sequences. Finally add the new points to the dict. Something like this: map = {} for each sequence s: sfinal = s for each point p in s: s2 = map.get(p) if s2: add the points in s to s2 sfinal = s2 # remember the new sequence containing points of the original s break for each point p in s: map[p] = sfinal When you are done, map.values() is the list of consolidated sequences. Two things that could complicate the algorithm - if the test for whether to join to sequences is more complicated than just having points in common then you will have to make the test 'if s2:' more complex - if a point can be in two sequences that should not be joined, then the map entries have to be lists of sequences rather than single sequences. This will add a little complexity but not much. HTH Kent At 10:50 AM 10/20/2004 +0200, Michael Dunn wrote: >Hi Tutors, > >I'm doing some GIS work using coastlines extracted from the nifty web form at: > >http://rimmer.ngdc.noaa.gov/mgg/coast/getcoast.html > >It produces a huge list of longtitude-latitude points joined up in sections >delimited by "# -b" (representing zigzag lines) . These can be easily >converted into e.g. MapInfo import format. However the data is slightly >messy--some of the lines are broken up into smaller lines, which means that >once imported into MapInfo I can't easily select what should be a single piece >of coastline. It seems like it should be a reasonably simple piece of >text-processing to get them all together: if I have a sequence of points >(a, b, >c) and a sequence (c, d, a) then I just need to transform them into a sequence >(a, b, c, d, a). However I've spend while working on it, and I can't come >up with a suitable algorithm to do this. Any pointers? > >My problem is algorithmic rather than syntactic, so I won't post any of the >code I've already written until I've got a better handle on what how I'm >trying >to go about it. > >This is a simplified example of the data (I've deleted ~5MB of points): the >first section is a polygon (i.e. the startpoint is the same as the endpoint) >and so can be left untouched; the next two are lines which should be joined up >to make a polygon, and the last three are lines which should be joined up to >make a line > ># -b >146.781336 -19.195938 >146.781336 -19.194178 >146.781336 -19.195938 ># -b >146.929480 -19.296558 >146.931534 -19.298025 >146.932414 -19.296265 ># -b >146.932414 -19.296265 >146.930947 -19.295385 >146.929480 -19.296558 ># -b >146.752881 -19.119079 >146.753468 -19.119666 ># -b >146.754054 -19.119666 >146.754934 -19.118786 >146.756108 -19.117612 ># -b >146.756108 -19.117612 >146.755815 -19.117026 >146.752881 -19.118199 > >Looking forward to hearing any ideas... > >Michael > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From kent_johnson at skillsoft.com Wed Oct 20 13:39:14 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Wed Oct 20 13:39:18 2004 Subject: [Tutor] processing lines and polygons In-Reply-To: <6.1.0.6.0.20041020055453.02901a48@mail4.skillsoft.com> References: <6.1.0.6.0.20041020055453.02901a48@mail4.skillsoft.com> Message-ID: <6.1.0.6.0.20041020073658.02905a68@mail4.skillsoft.com> Actually at the end of this algorithm map.values() will be a list of consolidated sequences, but each sequence will appear once for each point in the sequence. It would be easy to keep a separate list with just the unique sequences. Kent At 06:05 AM 10/20/2004 -0400, Kent Johnson wrote: >Dictionaries are very helpful with this type of problem. I would try >building a dictionary that maps individual points to the sequence >containing the point. When you create a new sequence from the input, look >up each of its points in the dict. If you find any of them, then combine >the two sequences. Finally add the new points to the dict. Something like this: > >map = {} >for each sequence s: > sfinal = s > for each point p in s: > s2 = map.get(p) > if s2: > add the points in s to s2 > sfinal = s2 # remember the new sequence containing points of the > original s > break > for each point p in s: > map[p] = sfinal > >When you are done, map.values() is the list of consolidated sequences. > >Two things that could complicate the algorithm >- if the test for whether to join to sequences is more complicated than >just having points in common then you will have to make the test 'if s2:' >more complex > - if a point can be in two sequences that should not be joined, then the > map entries have to be lists of sequences rather than single sequences. > This will add a little complexity but not much. > >HTH >Kent > >At 10:50 AM 10/20/2004 +0200, Michael Dunn wrote: >>Hi Tutors, >> >>I'm doing some GIS work using coastlines extracted from the nifty web >>form at: >> >>http://rimmer.ngdc.noaa.gov/mgg/coast/getcoast.html >> >>It produces a huge list of longtitude-latitude points joined up in sections >>delimited by "# -b" (representing zigzag lines) . These can be easily >>converted into e.g. MapInfo import format. However the data is slightly >>messy--some of the lines are broken up into smaller lines, which means that >>once imported into MapInfo I can't easily select what should be a single >>piece >>of coastline. It seems like it should be a reasonably simple piece of >>text-processing to get them all together: if I have a sequence of points >>(a, b, >>c) and a sequence (c, d, a) then I just need to transform them into a >>sequence >>(a, b, c, d, a). However I've spend while working on it, and I can't come >>up with a suitable algorithm to do this. Any pointers? >> >>My problem is algorithmic rather than syntactic, so I won't post any of the >>code I've already written until I've got a better handle on what how I'm >>trying >>to go about it. >> >>This is a simplified example of the data (I've deleted ~5MB of points): the >>first section is a polygon (i.e. the startpoint is the same as the endpoint) >>and so can be left untouched; the next two are lines which should be >>joined up >>to make a polygon, and the last three are lines which should be joined up to >>make a line >> >># -b >>146.781336 -19.195938 >>146.781336 -19.194178 >>146.781336 -19.195938 >># -b >>146.929480 -19.296558 >>146.931534 -19.298025 >>146.932414 -19.296265 >># -b >>146.932414 -19.296265 >>146.930947 -19.295385 >>146.929480 -19.296558 >># -b >>146.752881 -19.119079 >>146.753468 -19.119666 >># -b >>146.754054 -19.119666 >>146.754934 -19.118786 >>146.756108 -19.117612 >># -b >>146.756108 -19.117612 >>146.755815 -19.117026 >>146.752881 -19.118199 >> >>Looking forward to hearing any ideas... >> >>Michael >> >>_______________________________________________ >>Tutor maillist - Tutor@python.org >>http://mail.python.org/mailman/listinfo/tutor > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From Michael.Dunn at mpi.nl Wed Oct 20 16:48:20 2004 From: Michael.Dunn at mpi.nl (Michael Dunn) Date: Wed Oct 20 16:48:24 2004 Subject: [Tutor] Re: processing lines and polygons Message-ID: Thanks Kent, that's solved my problem nicely (although I now realize I've got a new one, see below). Here's my code -- I've learnt python mostly from lurking on this list, and although I find myself using python a lot, I've never shown any of my code to anyone before, so I'd also appreciate general comments: #!/usr/bin/env python """Take matlab/splus or mapgen vector and join broken lines""" import re, sys class Sequence: trace = False # append list of contributing input sequences to output output_format = "matlab" # matlab, mapgen, mif (MapInfo Interchange Format) def __init__(self, segment): self.points = [tuple(point.split("\t")) for point\ in segment.strip().split("\n")] self.start = self.points[0] self.end = self.points[-1] self.history = [] return def append(self, other): # only called if self is already in the output_sequences list self.history.extend(other.history) # 1. do the join if self.start == other.start or self.end == other.end: other.points.reverse() other.start, other.end = other.end, other.start if self.start == other.end: self.points = other.points[:-1] + self.points elif self.end == other.start: self.points = self.points + other.points[1:] # 2. update endpoints dictionary if self.points[0] == self.points[-1]: # it's become a closed polygon endpoints.pop(s.start) elif self.start != self.points[0]: endpoints.pop(self.start) self.start = self.points[0] endpoints[self.start] = self elif self.end != self.points[-1]: endpoints.pop(self.end) self.end = self.points[-1] endpoints[self.end] = self return def __str__(self): if Sequence.output_format == "mif": divider = "PLine\n %s" % len(self.points) elif Sequence.output_format == "matlab": divider = "NA NA" elif Sequence.output_format == "mapgen": divider = "# -b" if Sequence.trace: divider = "%s <-- %s" % (divider, str(self.history)) s = [divider] for point in self.points: s.append("%s\t%s" % point) return "\n".join(s) endpoints = {} output_sequences = [] mif_header = """version 3 Coordsys earth projection 1,104 Columns 1 SEG_ID integer Data """ if __name__ == "__main__": f = file(sys.argv[1], "rU") data = f.read() f.close() print >> sys.stderr, "Processing sequences" input_sequences = re.split("NA NA|# -b", data.strip()) for i, s in enumerate(input_sequences[1:]): s = Sequence(s) s.history.append(i) if s.start in endpoints.keys(): endpoints[s.start].append(s) elif s.end in endpoints.keys(): endpoints[s.end].append(s) else: endpoints[s.start] = s endpoints[s.end] = s output_sequences.append(s) print mif_header Sequence.output_format = "mif" for s in output_sequences: print s print >> sys.stderr, "Original: %s sequences\nJoined: %s sequences" %\ (len(input_sequences), len(output_sequences)) # examined output for missing input (there was none) # L = [] # for s in output_sequences: # L.extend(s.history) # for i in range(len(input_sequences[1:])): # if i not in L: # print i, I've rebooted into windows (yawn) and tested the output in MapInfo, and it's a lot better, but there are still bits of coastline not joined up. When I zoom in to the bits where the join should be, it looks like the points don't actually match. The separation distance is much less than the resolution of the map however, so I should be able to join them up automatically too. I would have to change the lines testing whether s.start, s.end are in endpoints.keys() to something testing whether they are in a radius of the endpoints. Or is there a simpler way...? Just thinking out loud, it occurs to me I could give the Sequence object additional attributes snap_to_grid_start and snap_to_grid_end and use these to determine whether lines should be joined, but join them using their original, more precise, values. Hmmm. More tomorrow. Big thanks to all the contributors on the tutor list! It's an amazing resource. Michael From Jeremiah.Rushton at gmail.com Wed Oct 20 17:33:58 2004 From: Jeremiah.Rushton at gmail.com (Jeremiah Rushton) Date: Wed Oct 20 17:34:03 2004 Subject: [Tutor] Loops Message-ID: <6e30826f04102008335d8c29e4@mail.gmail.com> I'm trying to write a program that will act like an instant messaging thing. I can't get the program (socket module) to continuously recieve while sending whenever the user wants it to. I wanted to know if I can code part of the program to stay in a while loop while the rest of the program is preforming other tasks. If there is a different more efficient way to accomplish this than while loops, please tell me. I'm thinking I might have to run two programs at the same time but I'm making the program in Tkinter to be more user friendly, and I wanted all the text recieved and sent to appear in a text box. I don't know how to make two programs run in the same Tkinter window, if that is the best way to do it. Please HELP Jeremiah From Jeremiah.Rushton at gmail.com Wed Oct 20 17:37:33 2004 From: Jeremiah.Rushton at gmail.com (Jeremiah Rushton) Date: Wed Oct 20 17:37:35 2004 Subject: [Tutor] Tkinter Text Boxes Message-ID: <6e30826f04102008373e8ab1c6@mail.gmail.com> I wanted to make a Text box where I can continuously enter information but the user could not edit the information in the text box. Is there a command/method to disable interaction with the Text box while still being able to insert strings into it? Or would it be easier just to use the Listbox, and if that is the case, how can I stop the Listbox from putting a line or dot at the end of each list line in the Listbox? From kent_johnson at skillsoft.com Wed Oct 20 18:09:09 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Wed Oct 20 18:09:17 2004 Subject: [Tutor] Loops In-Reply-To: <6e30826f04102008335d8c29e4@mail.gmail.com> References: <6e30826f04102008335d8c29e4@mail.gmail.com> Message-ID: <6.1.0.6.0.20041020120704.02a87400@mail4.skillsoft.com> You need to use threads to allow your program to do more than one thing at a time. See the recent Tutor thread on Network Programming for a discussion of this. http://mail.python.org/pipermail/tutor/2004-September/031796.html Kent At 08:33 AM 10/20/2004 -0700, Jeremiah Rushton wrote: >I'm trying to write a program that will act like an instant messaging >thing. I can't get the program (socket module) to continuously >recieve while sending whenever the user wants it to. I wanted to know >if I can code part of the program to stay in a while loop while the >rest of the program is preforming other tasks. If there is a >different more efficient way to accomplish this than while loops, >please tell me. I'm thinking I might have to run two programs at the >same time but I'm making the program in Tkinter to be more user >friendly, and I wanted all the text recieved and sent to appear in a >text box. I don't know how to make two programs run in the same >Tkinter window, if that is the best way to do it. > >Please HELP > >Jeremiah >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From carroll at tjc.com Wed Oct 20 20:08:15 2004 From: carroll at tjc.com (Terry Carroll) Date: Wed Oct 20 20:08:19 2004 Subject: [Tutor] Why doesn't this filter FutureWarning? In-Reply-To: <6.1.0.6.0.20041020053414.02901f68@mail4.skillsoft.com> Message-ID: On Wed, 20 Oct 2004, Kent Johnson wrote: > At 09:48 PM 10/19/2004 -0700, Terry Carroll wrote: > > > num=num & 0xffffffff > > > >You know, it occurred to me that ANDing a value with all ones was > >essentially a no-op > > as long as num <= 0xffffffff ... You mean as an unsigned number, right? i.e., as long as it's a 32-bit number? I'm fairly certain I can count on that. As it turns out, if that's wrong, worst case is the function returns incorrect data, which I don't use anyway, so I can deal with it. (The code is a ping routine at ftp://ftp.visi.com/users/mdc/ping.py ; I don't care about the time, so much as connectivity.) From RenX99 at gmail.com Wed Oct 20 20:10:11 2004 From: RenX99 at gmail.com (Rene Lopez) Date: Wed Oct 20 20:10:14 2004 Subject: [Tutor] Design Question... from a newbie Message-ID: <555128ce04102011103dc7b79@mail.gmail.com> For the last couple weeks I have been teaching myself python and trying to get a better grasp in programming in general. I'm beginning to realize that there is more to it then learning a programming language. I may know how a lot of English words, and how to write a sentence but I won't be able to write a novel right a way... the same goes with programming I suppose. I'm trying to write a small RPG game similar to D&D or whatever. So I'm trying to figure out how to best keep track of a character and all of the attributes/variables for that character. I think the key to this is going to be using a class to create a customer data type, but I'm not sure if there is a better way. For example I'm using something like this: class Character: def __init__(self, name=' ', job = 1, race = 1): self.name = name # assign job if job == 1: self.job = job self.jobdesc = "Fighter" elif job == 2: self.job = class self.job = "Mage" # assign race if race == 1: self.race = race self.racedesc = "Human" if race == 2: self.race = race self.racedesc = "Elf" player = Character(name= 'Bob', job=2, race=2) Would it make more sense to have the class just handle the attributes and do all of the assignment via a separate function? The example I gave is very simple.. I imagine as the character information gets more in depth the list of attributes will grow and grow...so I'm concerned that it might start to get confusing. What do you gurus think? PS: I apologize for any programming errors I made...as made the code up as i went.. and didn't test it... but i figured you'd get the idea. -- Rene From hugonz-lists at h-lab.net Wed Oct 20 20:14:22 2004 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Wed Oct 20 20:14:26 2004 Subject: [Tutor] Tkinter Text Boxes In-Reply-To: <6e30826f04102008373e8ab1c6@mail.gmail.com> References: <6e30826f04102008373e8ab1c6@mail.gmail.com> Message-ID: <4176AAFE.9000903@h-lab.net> There is an "enable" configuration option for the text box. When you disble it, you won't be able to print anything to it, and so won't the user. You then have to do: enable put text in the box diable I believe this would be it: mytextbox.configure(state="enabled") #DO your widget updating here... mytextbox.configure(state="disabled") Jeremiah Rushton wrote: > I wanted to make a Text box where I can continuously enter information > but the user could not edit the information in the text box. Is there > a command/method to disable interaction with the Text box while still > being able to insert strings into it? Or would it be easier just to > use the Listbox, and if that is the case, how can I stop the Listbox > from putting a line or dot at the end of each list line in the > Listbox? > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From my.mailing.lists at noos.fr Wed Oct 20 21:08:11 2004 From: my.mailing.lists at noos.fr (nik) Date: Wed Oct 20 21:08:13 2004 Subject: [Tutor] Design Question... from a newbie In-Reply-To: <555128ce04102011103dc7b79@mail.gmail.com> References: <555128ce04102011103dc7b79@mail.gmail.com> Message-ID: <4176B79B.9000401@noos.fr> Another person on the list is asking about good examples for using object orientated programming. This could be a good chance to try something like that. A base class could be person (with basic attributes like 'first name'), and then you create derived classes being mage, warrior etc each with attributes appropriate to that type of character. Another base class could be item, with derived classes weapon, armor, food etc, and then derived from that further specifics (ie sword, staff from the weapon class). This makes it easier when it comes to expanding into new classes (ie if you wanted to add another character type, ie dwarf, you wouldn't have to re-do all the basic attributes that apply to all characters, like health points etc, just the stuff that is unique to a dwarf). Each level in the class heirachy will introduce it's own relevent attributes. Then, when someone decides to be a dwarf, a lot of the attributes will be automatically set just because they're using the dwarf class. That doesn't answer your question though, but it might help look at things a bit differently. nik Rene Lopez wrote: >For the last couple weeks I have been teaching myself python and >trying to get a better grasp in programming in general. I'm beginning >to realize that there is more to it then learning a programming >language. I may know how a lot of English words, and how to write a >sentence but I won't be able to write a novel right a way... the same >goes with programming I suppose. > >I'm trying to write a small RPG game similar to D&D or whatever. So >I'm trying to figure out how to best keep track of a character and all >of the attributes/variables for that character. I think the key to >this is going to be using a class to create a customer data type, but >I'm not sure if there is a better way. For example I'm using >something like this: > >class Character: > def __init__(self, name=' ', job = 1, race = 1): > self.name = name > # assign job > if job == 1: > self.job = job > self.jobdesc = "Fighter" > elif job == 2: > self.job = class > self.job = "Mage" > # assign race > if race == 1: > self.race = race > self.racedesc = "Human" > if race == 2: > self.race = race > self.racedesc = "Elf" > >player = Character(name= 'Bob', job=2, race=2) > >Would it make more sense to have the class just handle the attributes >and do all of the assignment via a separate function? The example I >gave is very simple.. I imagine as the character information gets more >in depth the list of attributes will grow and grow...so I'm concerned >that it might start to get confusing. What do you gurus think? > >PS: I apologize for any programming errors I made...as made the code >up as i went.. and didn't test it... but i figured you'd get the idea. > > > From klappnase at freenet.de Wed Oct 20 21:20:54 2004 From: klappnase at freenet.de (Michael Lange) Date: Wed Oct 20 21:16:33 2004 Subject: [Tutor] Tkinter Text Boxes In-Reply-To: <4176AAFE.9000903@h-lab.net> References: <6e30826f04102008373e8ab1c6@mail.gmail.com> <4176AAFE.9000903@h-lab.net> Message-ID: <20041020212054.732c9a7e.klappnase@freenet.de> On Wed, 20 Oct 2004 13:14:22 -0500 Hugo Gonz?lez Monteverde wrote: > There is an "enable" configuration option for the text box. When you > disble it, you won't be able to print anything to it, and so won't the > user. You then have to do: > > enable > put text in the box > diable > > I believe this would be it: > > mytextbox.configure(state="enabled") > #DO your widget updating here... > mytextbox.configure(state="disabled") > > That's almost correct, except the "enabled" state must be "normal", so this should be changed to: mytextbox.configure(state="normal") #DO your widget updating here... mytextbox.configure(state="disabled") Best regards Michael From python at bernardlebel.com Wed Oct 20 22:44:56 2004 From: python at bernardlebel.com (Bernard Lebel) Date: Wed Oct 20 21:42:06 2004 Subject: [Tutor] Tuple iteration index Message-ID: <008e01c4b6e5$aac54ec0$2901a8c0@atyss> Hello, Let say I have a tuple of lists: aTuple = ( [0.2, 0.8, 0], [0.8, 0.8, 0], [0.8,0.2, 0], [0.2, 0.2, 0] ) Now I wish to perform an iteration over this list. If I use something like: for aList in aTuple: I get a new item (in this case a list) at each line. This is fine, but I also need to know the index of that item in the tuple. for aList in aTuple: print aList # something like print aTuple(aList.index) How do you do that? Thanks Bernard From bgailer at alum.rpi.edu Wed Oct 20 22:09:34 2004 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Wed Oct 20 22:07:41 2004 Subject: [Tutor] Tuple iteration index In-Reply-To: <008e01c4b6e5$aac54ec0$2901a8c0@atyss> References: <008e01c4b6e5$aac54ec0$2901a8c0@atyss> Message-ID: <6.1.2.0.0.20041020140451.045a9cc0@mail.mric.net> At 02:44 PM 10/20/2004, Bernard Lebel wrote: >Hello, > >Let say I have a tuple of lists: > >aTuple = ( [0.2, 0.8, 0], [0.8, 0.8, 0], [0.8,0.2, 0], [0.2, 0.2, 0] ) > >Now I wish to perform an iteration over this list. >If I use something like: > >for aList in aTuple: > >I get a new item (in this case a list) at each line. This is fine, but I >also need to know the index of that item in the tuple. > >for aList in aTuple: > print aList > # something like > print aTuple(aList.index) Use enumerate: >for index, aList in enumerate(aTuple): > print aList > # something like > print aTuple[index] ## note I changed () to [] - () denote a function > call. Use [] for indexing Bob Gailer bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell From bwinton at latte.ca Wed Oct 20 22:08:38 2004 From: bwinton at latte.ca (Blake Winton) Date: Wed Oct 20 22:08:42 2004 Subject: [Tutor] Design Question... from a newbie In-Reply-To: <4176B79B.9000401@noos.fr> References: <555128ce04102011103dc7b79@mail.gmail.com> <4176B79B.9000401@noos.fr> Message-ID: <4176C5C6.8060009@latte.ca> nik wrote: >> def __init__(self, name=' ', job = 1, race = 1): > A base class could be person (with basic attributes like 'first name'), > and then you create derived classes being mage, warrior etc each with > attributes appropriate to that type of character. Just as a side point, I think I would make subclasses based on race, as opposed to job, because I've worked in several jobs, and expect to change jobs at least twice more before I'm done working, but I've never been able to not be an Elf. ;) Later, Blake. From kent_johnson at skillsoft.com Wed Oct 20 22:08:56 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Wed Oct 20 22:09:13 2004 Subject: [Tutor] Tuple iteration index In-Reply-To: <008e01c4b6e5$aac54ec0$2901a8c0@atyss> References: <008e01c4b6e5$aac54ec0$2901a8c0@atyss> Message-ID: <6.1.0.6.0.20041020160617.02885e80@mail4.skillsoft.com> use the built-in function enumerate. enumerate(aList) returns an iterator that yields tuples of (index, value): >>> aTuple = ( [0.2, 0.8, 0], [0.8, 0.8, 0], [0.8,0.2, 0], [0.2, 0.2, 0] ) >>> for i, aList in enumerate(aTuple): ... print i, aList ... 0 [0.20000000000000001, 0.80000000000000004, 0] 1 [0.80000000000000004, 0.80000000000000004, 0] 2 [0.80000000000000004, 0.20000000000000001, 0] 3 [0.20000000000000001, 0.20000000000000001, 0] You could also use aTuple.find(aList) but if you are iterating anyway enumerate() is better. Kent At 09:44 PM 10/20/2004 +0100, Bernard Lebel wrote: >Hello, > >Let say I have a tuple of lists: > >aTuple = ( [0.2, 0.8, 0], [0.8, 0.8, 0], [0.8,0.2, 0], [0.2, 0.2, 0] ) > >Now I wish to perform an iteration over this list. >If I use something like: > >for aList in aTuple: > >I get a new item (in this case a list) at each line. This is fine, but I >also need to know the index of that item in the tuple. > >for aList in aTuple: > print aList > # something like > print aTuple(aList.index) > > >How do you do that? > >Thanks >Bernard > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From cyresse at gmail.com Wed Oct 20 22:31:16 2004 From: cyresse at gmail.com (Liam Clarke) Date: Wed Oct 20 22:31:18 2004 Subject: [Tutor] Design Question... from a newbie In-Reply-To: <4176B79B.9000401@noos.fr> References: <555128ce04102011103dc7b79@mail.gmail.com> <4176B79B.9000401@noos.fr> Message-ID: That other person would be me.... ...ah, RPG's... I can create the next text based Morrowind. : ) But seriously, I can see how (programming) classes would be useful in a RPG. Might have to potter. Renee, perhaps it would be easier for your comprehension if your jobs and race were just assigned in text i.e. class Character def __init__(self, job ='Fighter', race = 'Human', alignment="Lawful Good", level=0, gold=500): self.job=job self.race=race self.alignment=alignment self.level=level self.gold=gold (I'd use the name of the character for the object name, but that's just me, and it may not be any good for random generation of NPC's. For NPC's you could have a list of names, and it randomly picks one when creating NPC object. ) So, Vlad=Character('Mage', 'Elf', 'Neutral','Evil', 4, ) I only vaguely understand how classes etc work, but I assume you could create an inventory object associated with Vlad, which is a list of his items, an itemSword object for the basic definitions of swords..., skillsVlad to store his skills, expVlad to calculate his experience, and watch to see if he gains a level (Assuming AD&D type characters.) You can still test later for the text values i.e. if Vlad.race=='Elf': print "%s says: 'We don't like your kind around here. This is dwarf country!' % NPC.name elif Vlad.race=='Dwarf': print "%s claps his arm around your shoulder and shouts 'Let us drink together, my brother!'" %s NPC.name or if Vlad.race=='Elf' and NPC.race =='Dwarf": NPC.attack ("We don't take to pointy eared toffs here boy!", Vlad) etc. etc. etc. But I'd be curious to see how it goes for you. I'd recommend keeping it small, and being very specific about what you're going to track, perhaps even use an old rule set like the old D&D ones. But that's just because I can see any RPG becoming huuuge. cf Morrowind. Good luck, happy coding, and thanks for pointing me in an OO understanding direction. Liam On Wed, 20 Oct 2004 21:08:11 +0200, nik wrote: > Another person on the list is asking about good examples for using > object orientated programming. This could be a good chance to try > something like that. > > A base class could be person (with basic attributes like 'first name'), > and then you create derived classes being mage, warrior etc each with > attributes appropriate to that type of character. Another base class > could be item, with derived classes weapon, armor, food etc, and then > derived from that further specifics (ie sword, staff from the weapon > class). This makes it easier when it comes to expanding into new classes > (ie if you wanted to add another character type, ie dwarf, you wouldn't > have to re-do all the basic attributes that apply to all characters, > like health points etc, just the stuff that is unique to a dwarf). Each > level in the class heirachy will introduce it's own relevent attributes. > Then, when someone decides to be a dwarf, a lot of the attributes will > be automatically set just because they're using the dwarf class. > > That doesn't answer your question though, but it might help look at > things a bit differently. > > nik > > > > Rene Lopez wrote: > > >For the last couple weeks I have been teaching myself python and > >trying to get a better grasp in programming in general. I'm beginning > >to realize that there is more to it then learning a programming > >language. I may know how a lot of English words, and how to write a > >sentence but I won't be able to write a novel right a way... the same > >goes with programming I suppose. > > > >I'm trying to write a small RPG game similar to D&D or whatever. So > >I'm trying to figure out how to best keep track of a character and all > >of the attributes/variables for that character. I think the key to > >this is going to be using a class to create a customer data type, but > >I'm not sure if there is a better way. For example I'm using > >something like this: > > > >class Character: > > def __init__(self, name=' ', job = 1, race = 1): > > self.name = name > > # assign job > > if job == 1: > > self.job = job > > self.jobdesc = "Fighter" > > elif job == 2: > > self.job = class > > self.job = "Mage" > > # assign race > > if race == 1: > > self.race = race > > self.racedesc = "Human" > > if race == 2: > > self.race = race > > self.racedesc = "Elf" > > > >player = Character(name= 'Bob', job=2, race=2) > > > >Would it make more sense to have the class just handle the attributes > >and do all of the assignment via a separate function? The example I > >gave is very simple.. I imagine as the character information gets more > >in depth the list of attributes will grow and grow...so I'm concerned > >that it might start to get confusing. What do you gurus think? > > > >PS: I apologize for any programming errors I made...as made the code > >up as i went.. and didn't test it... but i figured you'd get the idea. > > > > > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From python at bernardlebel.com Wed Oct 20 23:35:00 2004 From: python at bernardlebel.com (Bernard Lebel) Date: Wed Oct 20 22:32:11 2004 Subject: [Tutor] Tuple iteration index References: <008e01c4b6e5$aac54ec0$2901a8c0@atyss> <6.1.0.6.0.20041020160617.02885e80@mail4.skillsoft.com> Message-ID: <00a901c4b6ec$a9281550$2901a8c0@atyss> Thanks everyone, it works like a charm. Cheers Bernard ----- Original Message ----- From: "Kent Johnson" To: Sent: Wednesday, October 20, 2004 9:08 PM Subject: Re: [Tutor] Tuple iteration index > use the built-in function enumerate. enumerate(aList) returns an iterator > that yields tuples of (index, value): > >>> aTuple = ( [0.2, 0.8, 0], [0.8, 0.8, 0], [0.8,0.2, 0], [0.2, 0.2, 0] ) > >>> for i, aList in enumerate(aTuple): > ... print i, aList > ... > 0 [0.20000000000000001, 0.80000000000000004, 0] > 1 [0.80000000000000004, 0.80000000000000004, 0] > 2 [0.80000000000000004, 0.20000000000000001, 0] > 3 [0.20000000000000001, 0.20000000000000001, 0] > > You could also use aTuple.find(aList) but if you are iterating anyway > enumerate() is better. > > Kent > > > At 09:44 PM 10/20/2004 +0100, Bernard Lebel wrote: > >Hello, > > > >Let say I have a tuple of lists: > > > >aTuple = ( [0.2, 0.8, 0], [0.8, 0.8, 0], [0.8,0.2, 0], [0.2, 0.2, 0] ) > > > >Now I wish to perform an iteration over this list. > >If I use something like: > > > >for aList in aTuple: > > > >I get a new item (in this case a list) at each line. This is fine, but I > >also need to know the index of that item in the tuple. > > > >for aList in aTuple: > > print aList > > # something like > > print aTuple(aList.index) > > > > > >How do you do that? > > > >Thanks > >Bernard > > > >_______________________________________________ > >Tutor maillist - Tutor@python.org > >http://mail.python.org/mailman/listinfo/tutor > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From alan.gauld at freenet.co.uk Wed Oct 20 22:52:23 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed Oct 20 22:52:15 2004 Subject: [Tutor] methods versus functions (using lists as an example) References: <4AD3462A-21E0-11D9-952E-000393CBC88E@yahoo.fr> <417580F4.3020604@ccvcorp.com> Message-ID: <006c01c4b6e6$b33206b0$6aa98651@xp> > > This makes Python slightly less elegant than Ruby, but it's quite > > easy to get the hang of. > > > I don't know Ruby, but I can certainly say that I think that Python's > current form (using functions for generic operations and methods only > for type-specific operations) is far more elegant than it would be if > everything were forced into methods, thus requiring many classes to > sprout swarms of tiny, repetitious methods... Yep I'll second that. I have played with Ruby but not done any serious coding, but I can say that I found several places where I found myself forced into an "OOP" style of prigramming because Ruby offrs no alternative, evebn when a functional approach was more natural. Java and Ruby both suffer under the delusion that OOP is somehow a superior paradigm so you should write everything as objects, but it just aint so. Python usually gets the balance of function vv objects right (for me at least!) OTOH Ruby is much better than Python(and Java) at anonymous code blocks and closures. It really shows up the limitations of Python lambdas. Alan G. From dyoo at hkn.eecs.berkeley.edu Wed Oct 20 22:53:42 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Oct 20 22:53:52 2004 Subject: [Tutor] Design Question... from a newbie In-Reply-To: <555128ce04102011103dc7b79@mail.gmail.com> Message-ID: On Wed, 20 Oct 2004, Rene Lopez wrote: > I'm trying to write a small RPG game similar to D&D or whatever. So > I'm trying to figure out how to best keep track of a character and all > of the attributes/variables for that character. Hi Rene, One improvement that might help clean up the code is to us a table-based approach to handle the different choices. At the moment, the code is doing something like: > if job == 1: > self.job = job > self.jobdesc = "Fighter" > elif job == 2: > self.job = job > self.job = "Mage" > # assign race > if race == 1: > self.race = race > self.racedesc = "Human" > if race == 2: > self.race = race > self.racedesc = "Elf" As we add more jobs and races, this might get larger. Since the logic is pretty similar, we might want to do something like this instead: ### """A mapping from job numbers to job descriptions.""" job_lookup_table = { 1 : 'Fighter', 2 : 'Mage' } """A mapping from race numbers to race descriptions.""" race_lookup_table = { 1 : 'Human', 2 : 'Elf' } ### What we are trying to do here is keep the thing that's really different, the variation, in a table. This can often be a win: the code of the Character initializer can be written as: ### if job in job_lookup_table: self.job = job self.jobdesc = job_lookup_table[job] if race in race_lookup_table: self.race = race self.racedesc = race_lookup_table[race] ### This "table-driven" approach makes it a little easier to extend the system with more jobs and races, because it's easy to add new entries in a data table. An alternative approach that an OOP person might suggest is to make the jobs and races themselves as distinct objects. For example, we can represent those two jobs as the following classes: ### class Job: def __init__(self, desc): self.desc = desc FIGHTER = Job("Fighter") MAGE = Job("Mage") ### If we had this, then our Character construction can take a Job instance directly, instead of taking integers and figuring out which job we're taking: ### (Simplified example) class Character: def __init__(self, name=' ', job = FIGHTER): self.name = name self.job = job ### The advantage of this approach is that we can consolidate the job-specific stuff of a character within each job class. It also means that adding new Jobs is also possible without having to touch the Character class. Again, I'm not positive if this is an appropriate design --- it actually might be overkill! --- but I hope it gives some useful ideas. Good luck! From alan.gauld at freenet.co.uk Wed Oct 20 22:54:30 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed Oct 20 22:54:21 2004 Subject: [Tutor] Hello from a beginner! References: <211F78EFD1D870409CC3E4158F4881DA08B32E12@xcww01.riv.csu.edu.au> Message-ID: <008201c4b6e6$ff71adf0$6aa98651@xp> > processing. For extra fun, I'm learning Emacs at the same time, > so I'm migrating from Perl in Vim to Python in Emacs. Ah, wait till you start writing macros in Emacs Lisp (elisp). Your Python skills will definitely help there, Lisp and Python have a lot of philosophical common ground. Alan G. From cyresse at gmail.com Wed Oct 20 22:55:23 2004 From: cyresse at gmail.com (Liam Clarke) Date: Wed Oct 20 22:55:25 2004 Subject: [Tutor] Design Question... from a newbie In-Reply-To: References: <555128ce04102011103dc7b79@mail.gmail.com> <4176B79B.9000401@noos.fr> Message-ID: Heh self.name is a legitimate website. On Thu, 21 Oct 2004 09:31:16 +1300, Liam Clarke wrote: > That other person would be me.... > > ...ah, RPG's... I can create the next text based Morrowind. : ) > > But seriously, I can see how (programming) classes would be useful in > a RPG. Might have to potter. > > Renee, perhaps it would be easier for your comprehension if your jobs > and race were just assigned in text i.e. > > class Character > > def __init__(self, job ='Fighter', race = 'Human', alignment="Lawful > Good", level=0, gold=500): > self.job=job > self.race=race > self.alignment=alignment > self.level=level > self.gold=gold > > (I'd use the name of the character for the object name, but that's > just me, and it may not be any good for random generation of NPC's. > For NPC's you could have a list of names, and it randomly picks one > when creating NPC object. ) > > So, Vlad=Character('Mage', 'Elf', 'Neutral','Evil', 4, ) > > I only vaguely understand how classes etc work, but I assume you could > create an inventory object associated with Vlad, which is a list of > his items, an itemSword object for the basic definitions of swords..., > skillsVlad to store his skills, expVlad to calculate his experience, > and watch to see if he gains a level > > (Assuming AD&D type characters.) You can still test later for the text > values i.e. > > if Vlad.race=='Elf': > print "%s says: 'We don't like your kind around here. This is dwarf > country!' % NPC.name > elif Vlad.race=='Dwarf': > print "%s claps his arm around your shoulder and shouts 'Let us > drink together, my brother!'" %s NPC.name > > or > > if Vlad.race=='Elf' and NPC.race =='Dwarf": > NPC.attack ("We don't take to pointy eared toffs here boy!", Vlad) > > etc. etc. etc. > > But I'd be curious to see how it goes for you. I'd recommend keeping > it small, and being very specific about what you're going to track, > perhaps even use an old rule set like the old > D&D ones. But that's just because I can see any RPG becoming huuuge. > cf Morrowind. > > Good luck, happy coding, and thanks for pointing me in an OO > understanding direction. > > Liam > > > > On Wed, 20 Oct 2004 21:08:11 +0200, nik wrote: > > Another person on the list is asking about good examples for using > > object orientated programming. This could be a good chance to try > > something like that. > > > > A base class could be person (with basic attributes like 'first name'), > > and then you create derived classes being mage, warrior etc each with > > attributes appropriate to that type of character. Another base class > > could be item, with derived classes weapon, armor, food etc, and then > > derived from that further specifics (ie sword, staff from the weapon > > class). This makes it easier when it comes to expanding into new classes > > (ie if you wanted to add another character type, ie dwarf, you wouldn't > > have to re-do all the basic attributes that apply to all characters, > > like health points etc, just the stuff that is unique to a dwarf). Each > > level in the class heirachy will introduce it's own relevent attributes. > > Then, when someone decides to be a dwarf, a lot of the attributes will > > be automatically set just because they're using the dwarf class. > > > > That doesn't answer your question though, but it might help look at > > things a bit differently. > > > > nik > > > > > > > > Rene Lopez wrote: > > > > >For the last couple weeks I have been teaching myself python and > > >trying to get a better grasp in programming in general. I'm beginning > > >to realize that there is more to it then learning a programming > > >language. I may know how a lot of English words, and how to write a > > >sentence but I won't be able to write a novel right a way... the same > > >goes with programming I suppose. > > > > > >I'm trying to write a small RPG game similar to D&D or whatever. So > > >I'm trying to figure out how to best keep track of a character and all > > >of the attributes/variables for that character. I think the key to > > >this is going to be using a class to create a customer data type, but > > >I'm not sure if there is a better way. For example I'm using > > >something like this: > > > > > >class Character: > > > def __init__(self, name=' ', job = 1, race = 1): > > > self.name = name > > > # assign job > > > if job == 1: > > > self.job = job > > > self.jobdesc = "Fighter" > > > elif job == 2: > > > self.job = class > > > self.job = "Mage" > > > # assign race > > > if race == 1: > > > self.race = race > > > self.racedesc = "Human" > > > if race == 2: > > > self.race = race > > > self.racedesc = "Elf" > > > > > >player = Character(name= 'Bob', job=2, race=2) > > > > > >Would it make more sense to have the class just handle the attributes > > >and do all of the assignment via a separate function? The example I > > >gave is very simple.. I imagine as the character information gets more > > >in depth the list of attributes will grow and grow...so I'm concerned > > >that it might start to get confusing. What do you gurus think? > > > > > >PS: I apologize for any programming errors I made...as made the code > > >up as i went.. and didn't test it... but i figured you'd get the idea. > > > > > > > > > > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > From alan.gauld at freenet.co.uk Wed Oct 20 22:59:22 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed Oct 20 22:59:22 2004 Subject: [Tutor] methods versus functions (using lists as an example) References: <4AD3462A-21E0-11D9-952E-000393CBC88E@yahoo.fr><417580F4.3020604@ccvcorp.com> <66E13DA4-221A-11D9-952E-000393CBC88E@yahoo.fr> Message-ID: <008d01c4b6e7$ad4c5ce0$6aa98651@xp> > The same thing can be said of Ruby. However, I find Python's > documentation vastly superior in both quantity and quality, which means > advanced topics can be grasped more easily. That has a lot to do with Ruby being invented in Japan! Documentation has to be translated into English... The biggest bug bear I have with Ruby is its Perl-like tendency to use symbols as part of names (@foo) for special purposes - like class members etc. But otherwise I do like it, but although I keep going back for another play, I never seem to do any real work with it... Alan G. From alan.gauld at freenet.co.uk Wed Oct 20 23:08:46 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed Oct 20 23:08:37 2004 Subject: [Tutor] Design Question... from a newbie References: <555128ce04102011103dc7b79@mail.gmail.com> Message-ID: <00aa01c4b6e8$fd1de800$6aa98651@xp> > language. I may know how a lot of English words, and how to write a > sentence but I won't be able to write a novel right a way... the same > goes with programming I suppose. Absolutely. That is one reason I added a chapter on software design in my book. It doesn't teach design (what in one chapter? Come on! :) but it explains the need for it... > class Character: > def __init__(self, name=' ', job = 1, race = 1): > self.name = name > # assign job > if job == 1: > self.job = job > self.jobdesc = "Fighter" > elif job == 2: > self.job = class > self.job = "Mage" You might find it easier to use dictionaries here (assuming you will eventually have more than 2 jobs/races) jobdesc = { 1: 'Fighter', 2: 'Mage' } class Character: def __init__... self.job = job # you may not even need this now self.jobdesc = jobdesc[job] It saves an ever growing if/elif chain. > Would it make more sense to have the class just handle the attributes > and do all of the assignment via a separate function? The example I > gave is very simple.. I imagine as the character information gets more > in depth the list of attributes will grow and grow...so I'm concerned > that it might start to get confusing. What do you gurus think? I'd definitely go the way you are moving but use dictionaries. Also you can start to add methods to characters, for example if you want a character to decribe themselves you could add a say() method, or if characters can move around why not put the move code ina move() method of the character? And of course you may decide to have special types of characters with their own rules, thats where inheritance comes in... So longer term the class/OOP based approach has a lot more potential. Alan G. From jfabiani at yolo.com Thu Oct 21 00:14:30 2004 From: jfabiani at yolo.com (John Fabiani) Date: Thu Oct 21 00:14:41 2004 Subject: [Tutor] Design Question... from a newbie In-Reply-To: <4176B79B.9000401@noos.fr> References: <555128ce04102011103dc7b79@mail.gmail.com> <4176B79B.9000401@noos.fr> Message-ID: <200410201514.30681.jfabiani@yolo.com> On Wednesday 20 October 2004 12:08, nik wrote: > Another person on the list is asking about good examples for using > object orientated programming. This could be a good chance to try > something like that. > > A base class could be person (with basic attributes like 'first name'), > and then you create derived classes being mage, warrior etc each with > attributes appropriate to that type of character. Another base class > could be item, with derived classes weapon, armor, food etc, and then > derived from that further specifics (ie sword, staff from the weapon > class). This makes it easier when it comes to expanding into new classes > (ie if you wanted to add another character type, ie dwarf, you wouldn't > have to re-do all the basic attributes that apply to all characters, > like health points etc, just the stuff that is unique to a dwarf). Each > level in the class heirachy will introduce it's own relevent attributes. > Then, when someone decides to be a dwarf, a lot of the attributes will > be automatically set just because they're using the dwarf class. > > That doesn't answer your question though, but it might help look at > things a bit differently. > > nik > This sounds like "interfaces". John From maxnoel_fr at yahoo.fr Thu Oct 21 02:07:56 2004 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Thu Oct 21 02:08:09 2004 Subject: [Tutor] methods versus functions (using lists as an example) In-Reply-To: <008d01c4b6e7$ad4c5ce0$6aa98651@xp> References: <4AD3462A-21E0-11D9-952E-000393CBC88E@yahoo.fr><417580F4.3020604@ccvcorp.com> <66E13DA4-221A-11D9-952E-000393CBC88E@yahoo.fr> <008d01c4b6e7$ad4c5ce0$6aa98651@xp> Message-ID: <42C5DF13-22F5-11D9-A5E3-000393CBC88E@yahoo.fr> On Oct 20, 2004, at 21:59, Alan Gauld wrote: > The biggest bug bear I have with Ruby is its Perl-like tendency to > use symbols as part of names (@foo) for special purposes - like > class members etc. Strangely, that's a feature I actually like. It makes it easier to identify what a variable is. Besides, the use of symbols is IMO far less baroque than what's done in Perl, and if you think about it it's more or less something we already would do (just like the whitespace thing in Python). I don't know about you, but I always use conventions such as: fooBar: variable FOOBAR: constant FooBar: class _fooBar: instance variable I mostly use the latter in Python, though, as a placebo response to what is my only big gripe with the language (yeah, contrarily to most people, I've always thought of the whitespace thing as the best thing ever): the lack of proper private variables/methods (Ruby does have such a thing). > But otherwise I do like it, but although I keep going back for > another play, I never seem to do any real work with it... I see what you mean, it's about the same for me. Python has much more documentation and already-written modules than Ruby (especially when it comes to integrating with OS X -- Tkinter works out of the box), and as things stand now this outweighs the advantages Ruby has over Python. I'm told, though, that as far as web programming is concerned, Rails is an absolute gem. We'll have to see what happens when Parrot finally hits 1.0 and we can use the CPAN modules with Python and Ruby (not to mention the added speed)... We'll dig that thread out in about ten years, I guess... :p -- Wild_Cat (actually, the 3DRealms guys forgot to tell us that Duke Nukem Forever will run using a Parrot implementation of Befunge ^^) From maxnoel_fr at yahoo.fr Thu Oct 21 02:28:01 2004 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Thu Oct 21 02:28:12 2004 Subject: [Tutor] methods versus functions (using lists as an example) In-Reply-To: <4175A79F.6080001@ccvcorp.com> References: <4AD3462A-21E0-11D9-952E-000393CBC88E@yahoo.fr> <417580F4.3020604@ccvcorp.com> <66E13DA4-221A-11D9-952E-000393CBC88E@yahoo.fr> <4175A79F.6080001@ccvcorp.com> Message-ID: <10C01E4D-22F8-11D9-A5E3-000393CBC88E@yahoo.fr> On Oct 20, 2004, at 00:47, Jeff Shannon wrote: >> You have a point there. However, I don't really see why str() and >> repr() are functions and not methods, given that you have to >> implement methods for them to work anyway. > > > Well, if you're defining your own class, you need to implement methods > to be able to add and subtract, as well, but you wouldn't think that > those should be methods, would you? They could be. And actually, in Ruby, they are. (when you type 2+2, what's actually executed is 2.+(2) ) But that's not my point. What I mean is, if I recall correctly, when you use repr(foo), what actually happens is a method call (foo.__str__() IIRC). It doesn't really make that much sense to me. Though I understand the logic behind sum() (and to a certain extent, behind len(), although that one is less convincing to me), I don't see where the advantage of calling repr(foo) is over something in the lines of foo.toString(). > It's a philosophical point, as much as anything -- using repr() is > telling Python "give me a string that represents this object"; the > fact that the function may need to ask the object how it wants to be > represented is an implementation detail. The intent is that repr() > functions on pretty much any argument, so tying it directly to any > particular (set of) type/class definitions doesn't convey the intended > meaning. Since a "helper" function has to be implemented for each class on which you intend to use it, repr() *is* inherently tied to a particular set of type/class definitions. It's probably a philosophical choice, as you say. I can live with it, but I don't like it. However, it starts to become more problematic with functions such as int(), because IIRC you can't define custom "helper" methods for this one (__int__(), perhaps?). > And besides, since repr() is a function, that means that if a class > *doesn't* define a method to help it, it can have a fallback response. > If it were a method, then attempting to call it on a class that > didn't define anything for that purpose would throw an AttributeError. Not really. Unless I'm missing something, all classes in Python are subclasses of a root class (like Object in Java). If repr() was a method, chances are it'd be implemented in the root class as a fallback. Object.repr() would display what you see when you call repr() now on an object which doesn't define a method to help it, and all you'd have to do to get your object to display itself would be to override this method. I think that's how it's done in Java (the toString() method). > (And technically, str() is not a function -- it's a type. Using it is > asking Python to generate a new string object, using the argument to > determine the contents of that string. Definitely a nitpick, > especially as one *could* argue that a type object is not much more > than a factory function... but often understanding the nits can really > help to make sense out of the whole structure.) Mmh. I hadn't realized this. It also destroys the point I make a few paragraphs above in this post, but I'll leave it anyways because it might spark some interesting answers. This, in any case, is an interesting discussion. I like that place. ^^ -- Wild_Cat maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From andre.roberge at ns.sympatico.ca Thu Oct 21 02:36:44 2004 From: andre.roberge at ns.sympatico.ca (=?ISO-8859-1?Q?Andr=E9_Roberge?=) Date: Thu Oct 21 02:36:48 2004 Subject: [Tutor] Puzzled by execfile() Message-ID: <4177049C.7070802@ns.sympatico.ca> Dear Tutors, I have the following two Python files ===Script1.py === def printfoo(): print "foo" execfile("Script2.py") ===Script2.py=== from Script1 import * print "starting" printfoo() print "done" ============== When I run Script1 for the FIRST time (from within IDLE or PythonWin), I get starting foo done starting foo done When I run it again, I only get starting foo done each time that I run it. I don't understand why Script2 seems to be run twice the first time around Andr? Roberge From andre.roberge at ns.sympatico.ca Thu Oct 21 02:54:06 2004 From: andre.roberge at ns.sympatico.ca (=?ISO-8859-1?Q?Andr=E9_Roberge?=) Date: Thu Oct 21 02:54:11 2004 Subject: [Tutor] Puzzled by execfile(): solved (?) Message-ID: <417708AE.3050907@ns.sympatico.ca> Dear Tutors, (I won't repeat the whole message, which you should just have gotten - or is above in the digest version) I changed the first script, added a third and it now works the way I expect when I run the third. Below is my attempt at explaining what happened - I would really appreciate any correction! ===Script1.py === def printfoo(): print "foo" def run_test(): # this line is the only change, other than indent execfile("Script2.py") ===Script2.py=== # no change here from Script1 import * print "starting" printfoo() print "done" ====Script3.py====== from Script1 import * run_test() ===================== Before, when I ran script1 (without the def run_test()), execfile(...) was run *once* when Script2 was executed and imported Script1 in turn. So, execfile was first run from the "import" statement in Script2, and then from its natural place in Script1. Since modules are only imported once, on subsequent runs, the import statement in Script2 was ignored, and I got the expected behaviour. Now, in this new version, Script1 only contains definitions. When it is imported in Script2 [line 1], nothing is printed. When lines 2-4 are executed, I get the three printed lines, i.e. starting foo done which is what I wanted. Is this close to being correct? Andr? Roberge From tmclaughlin at csu.edu.au Thu Oct 21 02:56:45 2004 From: tmclaughlin at csu.edu.au (McLaughlin, Toby) Date: Thu Oct 21 02:57:04 2004 Subject: [Tutor] Puzzled by execfile() Message-ID: <211F78EFD1D870409CC3E4158F4881DA09602B16@xcww01.riv.csu.edu.au> When Script2.py runs, the first thing that it does is: from Script1 import * Importing a file executes it's contents. The first time you run the code, Script1.py gets run once by you and once by "from Script1 import *". Thereafter the script is already imported, so it doesn't get run again. Here's a way to avoid this happening def printfoo(): print "foo" if __name__ == "__main__": execfile("Script2.py") Now execfile("Script2.py") is only called if Script1.py is the main program, not if it's imported as a module. (I hope I've not botched this explanation. Gurus?) Toby McLaughlin. > -----Original Message----- > From: tutor-bounces+tmclaughlin=csu.edu.au@python.org > [mailto:tutor-bounces+tmclaughlin=csu.edu.au@python.org] On > Behalf Of Andr? Roberge > Sent: Thursday, 21 October 2004 10:37 AM > To: tutor@python.org > Subject: [Tutor] Puzzled by execfile() > > > Dear Tutors, > > I have the following two Python files > > ===Script1.py === > def printfoo(): > print "foo" > execfile("Script2.py") > > ===Script2.py=== > from Script1 import * > print "starting" > printfoo() > print "done" > ============== > > When I run Script1 for the FIRST time (from within IDLE or > PythonWin), I get > > starting > foo > done > starting > foo > done > > When I run it again, I only get > > starting > foo > done > > each time that I run it. I don't understand why Script2 > seems to be run > twice the first time around > > Andr? Roberge > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From dyoo at hkn.eecs.berkeley.edu Thu Oct 21 03:13:47 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Oct 21 03:13:55 2004 Subject: [Tutor] Puzzled by execfile() In-Reply-To: <4177049C.7070802@ns.sympatico.ca> Message-ID: On Wed, 20 Oct 2004, [ISO-8859-1] Andr=E9 Roberge wrote: > Dear Tutors, > > I have the following two Python files > > =3D=3D=3DScript1.py =3D=3D=3D > def printfoo(): > print "foo" > execfile("Script2.py") > > =3D=3D=3DScript2.py=3D=3D=3D > from Script1 import * > print "starting" > printfoo() > print "done" > =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D Hi Andre, The problem is circularity: Script1.py uses Script2.py, and Script2 uses Script1.py! This is a no-no. *grin* Python tries to do something reasonable by keeping track of what modules have already been imported, and it'll break the circularity at some point to keep the system from doing a recursive import. We can sorta simulate this in our heads. Let's imagine this record as some list: LIST_OF_IMPORTED_MODULES =3D [] Script1: The first time you execute Script1, it gets to the execfile() statement, and now executes Script2. Script2: We now hit the 'from Script1 import *' line. That's an import, and since the LIST_OF_IMPORTED_MODULES is empty, now it'll try to import Script1. Let's mark that. LIST_OF_IMPORTED_MODULES =3D [Script1]. Since this is an import, we'd better import the module. Script1: Ok, we're back in Script1. Ok, we hit the execfile again. Time to execute Script2 again. Script2: Ok, we hit the 'from Script1 import *' line again. Now if Python had not been keeping track of what modules are imported, you can imagine that we'll be doing this cycle forever. Thankfully, we don't. LIST_OF_IMPORTED_MODULES already has Script1, so we don't do the import. We go onto the next statements, which accounts for seeing: > starting > foo > done ... and now we get out of the execfile. ... and now we get out of the Script1 import Now that the import is inished, we go onto the next statements, which accounts for us seeing: > starting > foo > done ... And now we get out of the execfile. and now we're done. So that's why we see the output twice when we initially run Script1. But the second time we execute Script1, we only see the outputs once, because the LIST_OF_IMPORTED_MODULES lives on in the PythonWin or IDLE environment. In summary, don't do that. *grin* Don't make your programs depend on each other like that: it makes things REALLY darn confusing. Instead of having: ### > =3D=3D=3DScript1.py =3D=3D=3D > def printfoo(): > print "foo" > execfile("Script2.py") > > =3D=3D=3DScript2.py=3D=3D=3D > from Script1 import * > print "starting" > printfoo() > print "done" ### break the circularity, and just execute Script2.py directly: ### =3D=3D=3DScript1.py =3D=3D=3D def printfoo(): print "foo" =3D=3D=3DScript2.py=3D=3D=3D from Script1 import * print "starting" printfoo() print "done" ### Anyway, hope that make things a little clearer. Good luck! From cyresse at gmail.com Thu Oct 21 03:27:41 2004 From: cyresse at gmail.com (Liam Clarke) Date: Thu Oct 21 03:27:44 2004 Subject: [Tutor] Puzzled by execfile(): solved (?) In-Reply-To: <417708AE.3050907@ns.sympatico.ca> References: <417708AE.3050907@ns.sympatico.ca> Message-ID: That makes my head hurt trying to follow that. What exactly are you trying to do? If it's doing what you want it to do, the code is fine. There are myriad different ways you could reconstruct that, and they'd all have the same effect. My question is, can a module called with execfile return a value if it has the if __name__==main() thing? My golden rule is "If it does what I want, it's fine." My silver rule is "There's always a better way to do it, but ignorance is bliss." My bronze rule is "Please refer to the aforementioned two rules." On Wed, 20 Oct 2004 21:54:06 -0300, Andr? Roberge wrote: > Dear Tutors, > > (I won't repeat the whole message, which you should just have gotten - > or is above in the digest version) > > I changed the first script, added a third and it now works the way I > expect when I run the third. Below is my attempt at explaining what > happened - I would really appreciate any correction! > > ===Script1.py === > def printfoo(): > print "foo" > def run_test(): # this line is the only change, other than indent > execfile("Script2.py") > > ===Script2.py=== # no change here > from Script1 import * > print "starting" > printfoo() > print "done" > > ====Script3.py====== > from Script1 import * > run_test() > ===================== > > Before, when I ran script1 (without the def run_test()), > execfile(...) was run *once* when Script2 was executed and imported > Script1 in turn. So, execfile was first run from the "import" statement > in Script2, and then from its natural place in Script1. > Since modules are only imported once, on subsequent runs, the import > statement in Script2 was ignored, and I got the expected behaviour. > > Now, in this new version, Script1 only contains definitions. When it is > imported in Script2 [line 1], nothing is printed. When lines 2-4 are > executed, I get the three printed lines, i.e. > > starting > foo > done > > which is what I wanted. > > Is this close to being correct? > > Andr? Roberge > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From lysdexia at crackrabbit.com Thu Oct 21 06:47:26 2004 From: lysdexia at crackrabbit.com (Douglas N. Shawhan) Date: Thu Oct 21 06:48:38 2004 Subject: [Tutor] Tuple ordering: What is going on here? Message-ID: <41773F5E.3020704@crackrabbit.com> Hi, I am writing a simple little blog script using gadfly. (I know, it's overkill! I'm playing here!) My problem is, when I run it on one machine, the inserts go in in one order, on the other it is reversed. To wit: -------------------------------------------------- import time, gadfly ,kjbuckets, os, time if not os.path.isfile('blogDB/blog.gfd'): connection= gadfly.gadfly() connection.startup('blog','blogDB') c=connection.cursor() c.execute("create table default (entryTime varchar, entry varchar)") connection.commit() connection= gadfly.gadfly('blog','blogDB') c=connection.cursor() t=(time.time(), 'Happy Happy') c.execute("insert into default(entryTime, entry) values('%s','%s')"%t) c.execute("select * from default order by entryTime desc") for each in c.fetchall(): print each[0] print each[1] connection.commit() ----------------------------- Machine 1 output: 1098333356.12 Happy Happy 1098333355.03 Happy Happy 1098333354.01 Happy Happy 1098333275.99 Happy Happy 1098333275.06 Happy Happy 1098333273.85 Happy Happy 1098333272.3 Happy Happy Machine 2 output: Happy Happy 1098333442.39 Happy Happy 1098333356.12 Happy Happy 1098333355.03 Happy Happy 1098333354.01 Happy Happy 1098333275.99 Happy Happy 1098333275.06 Happy Happy 1098333273.85 Happy Happy 1098333272.3 ------------- My question: is the reversal occouring in the tuple or in gadfly's output? Both machines are OpenBSD. machine1= OpenBSD 3.5 GENERIC#34 i386 machine 2 = OpenBSD 3.3 MERCURY#5 i386 Weird, man. From glamorgan24 at hotmail.com Thu Oct 21 09:24:30 2004 From: glamorgan24 at hotmail.com (Nabil Hassoun) Date: Thu Oct 21 09:25:11 2004 Subject: [Tutor] (no subject) Message-ID: Thank you _________________________________________________________________ Stay in touch with absent friends - get MSN Messenger http://www.msn.co.uk/messenger From alan.gauld at freenet.co.uk Thu Oct 21 09:36:43 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu Oct 21 09:36:33 2004 Subject: [Tutor] methods versus functions (using lists as an example) References: <4AD3462A-21E0-11D9-952E-000393CBC88E@yahoo.fr><417580F4.3020604@ccvcorp.com> <66E13DA4-221A-11D9-952E-000393CBC88E@yahoo.fr> <008d01c4b6e7$ad4c5ce0$6aa98651@xp> <42C5DF13-22F5-11D9-A5E3-000393CBC88E@yahoo.fr> Message-ID: <00c201c4b740$b6d29320$6aa98651@xp> > > use symbols as part of names (@foo) for special purposes - like > > class members etc. > > Strangely, that's a feature I actually like. It makes it easier to > identify what a variable is. Besides, the use of symbols is IMO far > less baroque than what's done in Perl, NO argument there, its only a couple of cases in Ruby, in Perl its virtually everything that gets line noise added. > fooBar: variable > FOOBAR: constant > FooBar: class > _fooBar: instance variable I use all of those except the latter. However none of these conventions reduces the readability of the words, they are still plain English.But I guess you could counter with the double __ magic variable thing in Python but an underscore is visually separate from the letters since its on the baseline of the word - like the ruled lines on a page... > ever): the lack of proper private variables/methods (Ruby does have > such a thing). Ah but I never see that as a problem. I've never quite understood the paranoia that drives people to make things private. I guess its because all the OOP languages I first used (with the exception of Smalltalk) all had public members. (They were mainly Lisp variants and some early C bolt ons) I can honestly say that in 15 years of using OOP I've never had a single bug due to something being public rather than private. But I've had dozens of bugs due to things being declared private when they should have been 'protected' instead. > We'll have to see what happens when Parrot finally hits 1.0 and we can > use the CPAN modules with Python and Ruby (not to mention the added > speed)... We'll dig that thread out in about ten years, I guess... :p Indeed, but much will depend on it working performantly as well as functionally. The harsh reality is that people will rarely accept any significant performance hit to use foreign modules - even if the performance isn't critical! :-) Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld/tutor2/ From cajuntechie at gmail.com Thu Oct 21 09:39:05 2004 From: cajuntechie at gmail.com (Anthony P.) Date: Thu Oct 21 09:39:13 2004 Subject: [Tutor] MS Word and MS Excel on Linux Message-ID: Hello Everyone, Does anyone know of a module that will let me read MS Word and MS Excel files via a network share but from a Linux server? Thanks, Anthony From eric at digitalert.net Thu Oct 21 09:50:46 2004 From: eric at digitalert.net (Eric) Date: Thu Oct 21 09:49:46 2004 Subject: [Tutor] A way to restart a script after it runs? In-Reply-To: References: Message-ID: <41776A56.7020802@digitalert.net> Hi, I'm wondering if there is a ways to restart a script once it completes running, and then have it reexecute frorm the beginning again? I figure there is most likely multiple ways to do this, but I have not been able to find anything other than this.. http://www.entrian.com/goto/ "*The "goto" module was an April Fool's joke, published on 1st April 2004. Yes, it works, but it's a joke nevertheless. Please don't use it in real code!*"** So any suggestions? From alan.gauld at freenet.co.uk Thu Oct 21 09:53:35 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu Oct 21 09:55:40 2004 Subject: [Tutor] Design Question... from a newbie References: <555128ce04102011103dc7b79@mail.gmail.com><4176B79B.9000401@noos.fr> <200410201514.30681.jfabiani@yolo.com> Message-ID: <00fe01c4b743$11b9fd30$6aa98651@xp> > > like health points etc, just the stuff that is unique to a dwarf). Each > > level in the class heirachy will introduce it's own relevent attributes. > > Then, when someone decides to be a dwarf, a lot of the attributes will > > be automatically set just because they're using the dwarf class. > This sounds like "interfaces". Nope, interfaces are a specific type of abstract base class with the added distinction that they have no implementation of the methods they declare as well as no data members. A base class: class Shape: Location = (0,0) Color = BLACK def move(self, x,y): self.lOcation = (x,y) compared to an interface: class iShape: def move(self, x,y): pass Base classes are useful things in their own right, interfaces are IMHO only useful as a form of loosening static typing in languages like Java which don't support multiple inheritance. Alan G. From shitizb at yahoo.com Thu Oct 21 10:37:09 2004 From: shitizb at yahoo.com (Shitiz Bansal) Date: Thu Oct 21 10:37:12 2004 Subject: [Tutor] A way to restart a script after it runs? In-Reply-To: <41776A56.7020802@digitalert.net> Message-ID: <20041021083709.66386.qmail@web53802.mail.yahoo.com> I have done it by using while(1) loop many times. it is usually helpful to insert a sleep()with appropriate interval at the end of the script( inside the while loop) to avoid too much CPU usage. Eric wrote: Hi, I'm wondering if there is a ways to restart a script once it completes running, and then have it reexecute frorm the beginning again? I figure there is most likely multiple ways to do this, but I have not been able to find anything other than this.. http://www.entrian.com/goto/ "*The "goto" module was an April Fool's joke, published on 1st April 2004. Yes, it works, but it's a joke nevertheless. Please don't use it in real code!*"** So any suggestions? _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor --------------------------------- Do you Yahoo!? vote.yahoo.com - Register online to vote today! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20041021/88bb7fc8/attachment.html From my.mailing.lists at noos.fr Thu Oct 21 11:59:52 2004 From: my.mailing.lists at noos.fr (nik) Date: Thu Oct 21 11:59:57 2004 Subject: [Tutor] A way to restart a script after it runs? In-Reply-To: <20041021083709.66386.qmail@web53802.mail.yahoo.com> References: <20041021083709.66386.qmail@web53802.mail.yahoo.com> Message-ID: <41778898.9060807@noos.fr> This is a bit of a diversion from the original question, but I've always wondered how the duration of that sleep makes a difference -I've always used 1s, and it's kept the CPU happy, but if was 10ms would that work just as well? It must depend on how long the process takes before it calls the sleep and how many other processes are working hard as well, or does it? Is there any way of balancing the CPU load, like some kind of dynamic sleep? nik Shitiz Bansal wrote: > I have done it by using while(1) loop many times. > it is usually helpful to insert a sleep()with appropriate interval at > the end of the script( inside the while loop) to avoid too much CPU usage. > > */Eric /* wrote: > > Hi, I'm wondering if there is a ways to restart a script once it > completes running, and then have it reexecute frorm the beginning > again? > I figure there is most likely multiple ways to do this, but I have > not > been able to find anything other than this.. > > http://www.entrian.com/goto/ > > "*The "goto" module was an April Fool's joke, published on 1st April > 2004. Yes, it works, but it's a joke nevertheless. Please don't > use it > in real code!*"** > > > So any suggestions? > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > ------------------------------------------------------------------------ > Do you Yahoo!? > vote.yahoo.com - Register online to vote today! > >------------------------------------------------------------------------ > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > From amonroe at columbus.rr.com Thu Oct 21 12:41:28 2004 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Thu Oct 21 12:41:41 2004 Subject: [Tutor] Simple Question... In-Reply-To: <857d01c4b6b3$b5a1af50$3bc8020a@ecb01.ecb.de> References: <20041016174645.31391.qmail@web61009.mail.yahoo.com> <8464C062-1F9E-11D9-8BDA-000393CBC88E@yahoo.fr> <47856308316.20041016165216@columbus.rr.com> <857d01c4b6b3$b5a1af50$3bc8020a@ecb01.ecb.de> Message-ID: <1151251660342.20041021064128@columbus.rr.com> > To do this without loading the file into memory, and without relying > on wc (which ought to be very fast even with large files, if you need > that), you could do: > import random > def linecount(f): > """count the number of lines in the file then rewind it""" > l = ' ' > c = 0 > while l: > l = f.readline() > if l[-1:] == '\n': c +=1 #I don't think the 'if' is necessary, > #but for safety's sake we'll leave it > f.seek(0) > return c > def getrandline(f): > """get a random line from f (assumes file pointer is at beginning)""" > lines = linecount(f) > r = random.randint(0,int(lines)) > for i in range(1, r): f.readline() > return f.readline() > anybody have a faster implementation? I thought maybe it would be neat to try creating an index file if one doesn't exist, and using it if it does exist. It would just be a picked dictionary of byte offsets for each line in the file. Pick a random entry from the dictionary and seek to that offset in the main file. Haven't actually tried it though. Alan From cyresse at gmail.com Thu Oct 21 14:13:25 2004 From: cyresse at gmail.com (Liam Clarke) Date: Thu Oct 21 14:13:28 2004 Subject: [Tutor] COM ports? Message-ID: Hi all, I've met my first real frustrating moment (RFC 3502 protocols aside) with Python. I am running a win32 OS. I would like to access a COM port, and pass AT-Hayes commands to my modem, and send sound through when appropriate. (Basically, I want to make my computer a $1000 answering machine.) Do you think I can find anything in the documentation that lets me dial my modem? Hehe, perhaps it is the *nix background of Python showing. I understand thet *nix modems are just another file type thing in another directory. *sigh* They've got sockets, and SMTP, and IMAP, and POP3, but I can't figure out how to dial my modem... I found this, but I can't get the zips to work, and the exe installs won't certain things in registry that I don't have. (Specifically, an earlier version of Python.) http://starship.python.net/crew/roger/ So basically, does anyone know of any resources I can access? I've looked through Parnassus, but had no luck either. Cheers, Liam Clarke -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From John.Gooch at echostar.com Thu Oct 21 17:05:15 2004 From: John.Gooch at echostar.com (Gooch, John) Date: Thu Oct 21 17:05:28 2004 Subject: [Tutor] Accessing Functions By Reference Message-ID: <15A1FDA26DAD524DA7A7AF77313EBA8F07BC00AE@riv-excha5.echostar.com> Is it possible to access a function by reference? I.e. it's address in memory? What I would like to do it pass in a reference to a function when creating an instance of a class, so that the class can make use of that function via that reference. e.g. def somefunction( blah ): do something with blah return something myclass = SomeClass( ) print str( myclass.referenceToSomeFunction( someValue ) ) John A. Gooch Systems Administrator IT - Tools EchoStar Satellite L.L.C. 9601 S. Meridian Blvd. Englewood, CO 80112 Desk: 720-514-5708 From pythonTutor at venix.com Thu Oct 21 17:23:42 2004 From: pythonTutor at venix.com (Lloyd Kvam) Date: Thu Oct 21 17:23:55 2004 Subject: [Tutor] Accessing Functions By Reference In-Reply-To: <15A1FDA26DAD524DA7A7AF77313EBA8F07BC00AE@riv-excha5.echostar.com> References: <15A1FDA26DAD524DA7A7AF77313EBA8F07BC00AE@riv-excha5.echostar.com> Message-ID: <1098372222.2599.27.camel@laptop.venix.com> somefunction is a reference to the function somefunction() calls the function. a = somefunction # binds the name a to the function a() # calls the function I've usually seen the ability to process functions using variables (i.e. just another form of data) described as having "first class functions". On Thu, 2004-10-21 at 11:05, Gooch, John wrote: > Is it possible to access a function by reference? I.e. it's address in > memory? What I would like to do it pass in a reference to a function when > creating an instance of a class, so that the class can make use of that > function via that reference. > > e.g. def somefunction( blah ): > do something with blah > return something > > myclass = SomeClass( ) > print str( myclass.referenceToSomeFunction( someValue ) ) > > > > > John A. Gooch > Systems Administrator > IT - Tools > EchoStar Satellite L.L.C. > 9601 S. Meridian Blvd. > Englewood, CO 80112 > Desk: 720-514-5708 > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp From kent_johnson at skillsoft.com Thu Oct 21 17:59:50 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Thu Oct 21 18:00:00 2004 Subject: [Tutor] COM ports? In-Reply-To: References: Message-ID: <6.1.0.6.0.20041021115631.0289c128@mail4.skillsoft.com> Several options: The pywin32 library has a demo showing how to access the COM ports with win32file Get pywin32 from http://sourceforge.net/projects/pywin32/, install it and look at C:\Python23\Lib\site-packages\win32\Demos\win32comport_demo.py Universal Serial Port Python Library - http://balder.prohosting.com/ibarona/en/python/uspp/uspp_en.html winioport - http://www.geocities.com/dinceraydin/python/indexeng.html I haven't tried any of these but they should give you a place to start. Kent At 01:13 AM 10/22/2004 +1300, Liam Clarke wrote: >Hi all, > >I've met my first real frustrating moment (RFC 3502 protocols aside) >with Python. > >I am running a win32 OS. > >I would like to access a COM port, and pass AT-Hayes commands to my >modem, and send sound through when appropriate. (Basically, I want to >make my computer a $1000 answering machine.) Do you think I can find >anything in the documentation that lets me dial my modem? > >Hehe, perhaps it is the *nix background of Python showing. I >understand thet *nix modems are just another file type thing in >another directory. *sigh* They've got sockets, and SMTP, and IMAP, >and POP3, but I can't figure out how to dial my modem... > >I found this, but I can't get the zips to work, and the exe installs >won't certain things in registry that I don't have. (Specifically, an >earlier version of Python.) http://starship.python.net/crew/roger/ > >So basically, does anyone know of any resources I can access? I've >looked through Parnassus, but had no luck either. > >Cheers, > >Liam Clarke > > > >-- >'There is only one basic human right, and that is to do as you damn well >please. >And with it comes the only basic human duty, to take the consequences. >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From John.Ertl at fnmoc.navy.mil Thu Oct 21 18:44:37 2004 From: John.Ertl at fnmoc.navy.mil (Ertl, John) Date: Thu Oct 21 18:41:21 2004 Subject: [Tutor] can not get subtype? Message-ID: I am working on a simple web service that uses SOAP with attachments and the attachment is a multi part mime message. The MIME has some text and a png image. I have recently transferred everything including rebuilding python (same version as old system 2.3.4) and now the email MIMEImage can not automatically figure out the image type (it worked on the old system). I had to add '_subtype="png"' to the MIMEImage line (see below). For now I guess that is OK but I am wondering if something else is going on that I should know about. This also precludes me from producing other types without changing my code. ###### error I was getting before I add _subtype to MIMEImage ######### File "/gpfs3/opt/webservices/apache/app/tmd/cgi-bin/TMD/checking/makeMIME.py", line 64, in mimeMe img = MIMEImage(fp.read()) File "/home/ertlj/ertljVersion/lib/python2.3/email/MIMEImage.py", line 42, in __init__ raise TypeError, 'Could not guess image MIME subtype' TypeError: Could not guess image MIME subtype ######## Fixed MIMEImage ######### fp = open(pngfullpath, 'rb') img = MIMEImage(fp.read(),_subtype="png") fp.close() Thanks for the help. John Ertl From abli at freemail.hu Thu Oct 21 19:10:54 2004 From: abli at freemail.hu (Abel Daniel) Date: Thu Oct 21 19:11:07 2004 Subject: [Tutor] Re: matrix insertion routine for MNA In-Reply-To: <1d4.2d3730dc.2ea74722@aol.com> (CryptoLevel9@aol.com's message of "Wed, 20 Oct 2004 00:44:18 EDT") References: <1d4.2d3730dc.2ea74722@aol.com> Message-ID: CryptoLevel9@aol.com writes: [ ...description of problem (how to store multiple elements in a matrix so they can be summed later) snipped... ] (Note that I don't actually use numarray, but it should be able to handle the following suggestions) Any reason you can't have a 'running sum'? That is, create an empty matrix (M[i][j]), then for each value to be placed at the (x,y) koordinates do an: M[x][y] = M[x][y] + value If you are only interested in the sum, you might as well be doing the summing when inserting the elements. In fact, this should be more efficient as you aren't storing numbers you don't really need. Another possibility: if you know the maximum number of elements that should be placed at a given location, (and this number is small) you could create a matrix which is of one higher dimension. That is, instead of a matrix of N rows and M columns with each element being an L lenght list, create one that is NxMxL big. (Which would mean a three-dimensional matrix.) Of course, it would need to be filled with zeroes so that the undefined elements won't matter when doing the summing. -- Abel Daniel http://abeld.web.elte.hu From dyoo at hkn.eecs.berkeley.edu Thu Oct 21 19:18:43 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Oct 21 19:18:50 2004 Subject: [Tutor] Accessing Functions By Reference In-Reply-To: <1098372222.2599.27.camel@laptop.venix.com> Message-ID: On Thu, 21 Oct 2004, Lloyd Kvam wrote: > somefunction is a reference to the function > somefunction() calls the function. > > a = somefunction # binds the name a to the function > a() # calls the function > > I've usually seen the ability to process functions using variables (i.e. > just another form of data) described as having "first class functions". Hi John, Here's a classic example of a "first class" function: ### >>> def compose(f, g): ... """Given functions f and g, returns a new function that ... takes an x and calls f(g(x)).""" ... def newFunction(x): ... return f(g(x)) ... return newFunction ... ### Now we have a way of "composing" functions together: ### >>> f = compose(str.split, str.upper) >>> f("hello world this is a test") ['HELLO', 'WORLD', 'THIS', 'IS', 'A', 'TEST'] >>> >>> def square(x): ... return x * x ... >>> def sqrt(x): ... return x ** (0.5) ... >>> abs = compose(sqrt, square) >>> abs(-42) 42.0 >>> abs(17) 17.0 ### So yes, Python does make it convenient to treat functions as values: they can be passed around to other functions, and returned as values. Hope this helps! From dyoo at hkn.eecs.berkeley.edu Thu Oct 21 19:32:02 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Oct 21 19:32:05 2004 Subject: [Tutor] can not get subtype? In-Reply-To: Message-ID: On Thu, 21 Oct 2004, Ertl, John wrote: > I have recently transferred everything including rebuilding python (same > version as old system 2.3.4) and now the email MIMEImage can not > automatically figure out the image type (it worked on the old system). > I had to add '_subtype="png"' to the MIMEImage line (see below). For > now I guess that is OK but I am wondering if something else is going on > that I should know about. This also precludes me from producing other > types without changing my code. Hi John, I looked at the MIMEImage code --- it uses the 'imghdr' Standard Library module to try to guess what a particular byte stream might be. http://www.python.org/doc/lib/module-imghdr.html My best guess about the problem is that 'imghdr' isn't recognizing your files anymore. Here's the particular test that 'imghdr' does for pngs: ### def test_png(h, f): if h[:8] == "\211PNG\r\n\032\n": return 'png' ### Hmmm... and that seems to be correct. From the PNG format page, I'm reading that every PNG file needs to have an eight byte header with the following hexadecimal values: 89h 50h 4Eh 47h 0Dh 0Ah 1Ah 0Ah. Can you check to see if imghdr is still correctly identifying your png files as pngs? Good luck! From nick at javacat.f2s.com Thu Oct 21 21:12:30 2004 From: nick at javacat.f2s.com (Nick Lunt) Date: Thu Oct 21 21:12:32 2004 Subject: [Tutor] get the mode of a list Message-ID: Hi folks, I really have been putting off posting this to the list cos Im sure there's an easy way to do it, but I give up... :( I want to return the mode of a list, just to clarify the mode is the most frequently occurring member of a list in my case. Here's a function that 90% works: [code] >>> def mode(alist): # this only works for a single most freq item, ie [1,2,3333] but not [1,2,2,3,3] start = 1 current = 0 new = 0 for i in alist: if alist.count(i) > start: current = alist.count(i) start = current new = i if new > 1: return new else: return "All members of [%s] are modes." %alist >>> mode([10,20,30]) 'All members of [[10, 20, 30]] are modes.' >>> mode([9,9,9,8]) 9 >>> mode([10,10,20,20,5,6,7]) # ***** 10 [/code] As you can see it doesn't do a good job of recognising a list which is multimodal. The line near the end of the code section above (*****) is a multimodal list, I want the mode function to return [10,20] in these cases. So after all that waffling, what I want to do is return the modes of a mulitmodal list. I'd appreciate some help here, before I pull whats left of my hair out :) Cheers Nick. --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.778 / Virus Database: 525 - Release Date: 15/10/2004 From dyoo at hkn.eecs.berkeley.edu Thu Oct 21 21:39:29 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Oct 21 21:39:33 2004 Subject: [Tutor] get the mode of a list In-Reply-To: Message-ID: On Thu, 21 Oct 2004, Nick Lunt wrote: > I really have been putting off posting this to the list cos Im sure > there's an easy way to do it, but I give up... :( > > I want to return the mode of a list, just to clarify the mode is the > most frequently occurring member of a list in my case. Hi Nick, Here's a more general problem that might be easier to solve: can you write a function that generates a "histogram"? That is, can you get the frequencies of all the elements in a list? For example, something like: ### >>> histogram([10, 10, 20, 5, 6, 7]) { 10 : 2, 20 : 2, 5 : 1, 6 : 1, 7 : 1} ### If you have something that can generate histogram dictionaries, then you can use it to solve for modes with relative ease, I think. Good luck! From dyoo at hkn.eecs.berkeley.edu Thu Oct 21 21:54:24 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Oct 21 21:54:28 2004 Subject: [Tutor] can not get subtype? In-Reply-To: Message-ID: On Thu, 21 Oct 2004, Ertl, John wrote: > Thanks. The header thing might be the place to start. I am using > another program to make the png and the person that wrote that code said > they did not make any changes but knowing them they might have. [keeping tutor@python.org in CC] Hi John, It might also have to do with the way the files are transferred between machines. Note that the PNG standard deliberately puts '\r\n' as part of the header. This makes it easy to detect damage from improper newline conversions (a side-effect of treating a PNG file as text instead of binary.) The PNG standard explains their rationale here: http://www.libpng.org/pub/png/spec/1.2/PNG-Rationale.html#R.PNG-file-signature From John.Gooch at echostar.com Thu Oct 21 22:47:12 2004 From: John.Gooch at echostar.com (Gooch, John) Date: Thu Oct 21 22:47:23 2004 Subject: [Tutor] Python Version of "enum" ? Message-ID: <15A1FDA26DAD524DA7A7AF77313EBA8F07BC00B2@riv-excha5.echostar.com> Is there an equivalent of C++'s 'enum' keyword to set a number of named constants ( like so ) enum { OFF, ON, UNKNOWN }; in Python? It makes reading the code a lot simpler, as opposed to having to look up what a status of "1" means, it can be replaced with "ON", which is much easier to understand. If not, can you declare named constants another way? Perhaps 'const MONDAY = 1', for example. Thank You, John A. Gooch Systems Administrator IT - Tools EchoStar Satellite L.L.C. 9601 S. Meridian Blvd. Englewood, CO 80112 Desk: 720-514-5708 From jeff at ccvcorp.com Thu Oct 21 22:50:58 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu Oct 21 22:48:42 2004 Subject: [Tutor] methods versus functions (using lists as an example) In-Reply-To: <10C01E4D-22F8-11D9-A5E3-000393CBC88E@yahoo.fr> References: <4AD3462A-21E0-11D9-952E-000393CBC88E@yahoo.fr> <417580F4.3020604@ccvcorp.com> <66E13DA4-221A-11D9-952E-000393CBC88E@yahoo.fr> <4175A79F.6080001@ccvcorp.com> <10C01E4D-22F8-11D9-A5E3-000393CBC88E@yahoo.fr> Message-ID: <41782132.400@ccvcorp.com> Max Noel wrote: > > It doesn't really make that much sense to me. Though I understand > the logic behind sum() (and to a certain extent, behind len(), > although that one is less convincing to me), I don't see where the > advantage of calling repr(foo) is over something in the lines of > foo.toString(). I'll grant that the reasoning is less compelling for repr() than for things like sum() and len(). But at the same time, I can't really see an advantage in calling foo.toString() over repr(foo) -- they're relatively equivalent in my mind, except that each shows a different programming paradigm. Python is designed to be paradigm-flexible, which may be why the OO-specific spelling was not chosen. >> And besides, since repr() is a function, that means that if a class >> *doesn't* define a method to help it, it can have a fallback >> response. If it were a method, then attempting to call it on a class >> that didn't define anything for that purpose would throw an >> AttributeError. > > > Not really. Unless I'm missing something, all classes in Python > are subclasses of a root class (like Object in Java). If repr() was a > method, chances are it'd be implemented in the root class as a > fallback. Object.repr() would display what you see when you call > repr() now on an object which doesn't define a method to help it, and > all you'd have to do to get your object to display itself would be to > override this method. Well, new-style classes are all derived from object, though I think that was as much an implementation detail (to separate them from old-style classes) as a philosophical decision. Before Python 2.2, there was a strong distinction between types (built-in, C-coded data such as ints, strings, lists, dicts, etc), and classes. In 2.2, this difference was eliminated, but the need to maintain backwards compatibility meant that old-style classes were still the default, and thus it was necessary to have a way to specify which classes were intended to be new-style. This was done by deriving new-style classes from a newly-created abstract base type, object. I think (though I could be wrong) that the intent was only to enable this class/type unification, and not to philosophically root all objects into a single class heirarchy (as Java does). I think that the point here is that, while Python was indeed designed to be object-oriented from the ground up, it was not designed to be *exclusively* object-oriented. Java and Smalltalk, etc, were designed to be exclusively object-oriented, but Python wanted to allow other paradigms like functional programming as well. Thus, while objects are a major part of the language and their use is encouraged, there isn't an attempt to present *everything* in an OO style. Jeff Shannon Technician/Programmer Credit International From dyoo at hkn.eecs.berkeley.edu Thu Oct 21 23:43:18 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Oct 21 23:43:22 2004 Subject: [Tutor] Python Version of "enum" ? In-Reply-To: <15A1FDA26DAD524DA7A7AF77313EBA8F07BC00B2@riv-excha5.echostar.com> Message-ID: On Thu, 21 Oct 2004, Gooch, John wrote: > Is there an equivalent of C++'s 'enum' keyword to set a number of named > constants ( like so ) > enum { > OFF, > ON, > UNKNOWN > }; > > in Python? It makes reading the code a lot simpler, as opposed to having > to look up what a status of "1" means, it can be replaced with "ON", > which is much easier to understand. Hi John, Peter Norvig has written an answer for this infrequently answered question. *grin* Here you go: http://www.norvig.com/python-iaq.html I hope this helps! From pythonTutor at venix.com Fri Oct 22 00:03:15 2004 From: pythonTutor at venix.com (Lloyd Kvam) Date: Fri Oct 22 00:03:23 2004 Subject: [Tutor] Python Version of "enum" ? In-Reply-To: <15A1FDA26DAD524DA7A7AF77313EBA8F07BC00B2@riv-excha5.echostar.com> References: <15A1FDA26DAD524DA7A7AF77313EBA8F07BC00B2@riv-excha5.echostar.com> Message-ID: <1098396195.2599.127.camel@laptop.venix.com> Enum is not built in to Python. Here is my little Enum module. Google should turn up others. #enum.py class Enum(object): def __init__(self, codes): for ndx,code in enumerate(codes): setattr(self, code, ndx) self.length = len(codes) if '_codes' not in codes: self._codes = codes def __len__(self): return self.length typically, usage works like so: bulb = Enum("OFF,ON".split(',')) bulb.OFF == 0 bulb.ON == 1 It is usually most convenient to keep the Enum instance names fairly short. Creating other variations from a list of strings is pretty easy. enumerate and setattr are the keys to making this work. enumerate numbers the names in a list. setattr creates object attribute names on the fly. The main pitfall is that the Enum strings MUST be valid Python names. On Thu, 2004-10-21 at 16:47, Gooch, John wrote: > Is there an equivalent of C++'s 'enum' keyword to set a number of named > constants ( like so ) > enum { > OFF, > ON, > UNKNOWN > }; > > in Python? It makes reading the code a lot simpler, as opposed to having to > look up what a status of "1" means, it can be replaced with "ON", which is > much easier to understand. > > If not, can you declare named constants another way? Perhaps 'const MONDAY = > 1', for example. > > Thank You, > > > John A. Gooch > Systems Administrator > IT - Tools > EchoStar Satellite L.L.C. > 9601 S. Meridian Blvd. > Englewood, CO 80112 > Desk: 720-514-5708 > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp From Jeremiah.Rushton at gmail.com Fri Oct 22 01:03:42 2004 From: Jeremiah.Rushton at gmail.com (Jeremiah Rushton) Date: Fri Oct 22 01:03:44 2004 Subject: [Tutor] Connections with socket, Tkinter Message-ID: <6e30826f04102116035c6948c7@mail.gmail.com> I'm using threading, tkinter, and socket to make an 'instant messaging' program. Here is the code for the client... ------------------------------------------------------------------------------------------ from Tkinter import * from socket import * from threading import * class Receive(Thread): def __init__(self,client): Thread.__init__(self) while 1: try: text = client.recv(1024) App.__init__.gettext.configure(state='normal') App.__init__.gettext.insert(END,'%s\n'%text) App.__init__.gettext.configure(state='disabled') except: pass class App: client = socket(AF_INET,SOCK_STREAM) ip = 'localhost' server = (ip, 285) client.connect(server) def __init__(self, master): frame = Frame(master) frame.grid(row=2,column=3) self.quitbutton = Button(frame, text="QUIT", fg='red', command=frame.quit) self.quitbutton.grid(row=1,column=2) self.button = Button(frame, text="SEND", command=self.Send) self.button.grid(row=1,column=1) self.sendtext = Entry(frame,width=60) self.sendtext.grid(row=1,column=0) gettext = Text(frame,height=10,width=80,wrap=WORD) self.gettext = gettext gettext.grid(row=0,columnspan=3) gettext.insert(END,'Welcome to my Instant Messaging Program\n') gettext.configure(state='disabled') def Send(self): self.gettext.configure(state='normal') text = self.sendtext.get() self.gettext.insert(END,'%s\n'%text) self.sendtext.delete(0,END) self.client.send(text) self.gettext.configure(state='disabled') root = Tk() root.title('Client') app = App(root) root.mainloop() ------------------------------------------------------------------------------------------ And here is the code for the server side... ------------------------------------------------------------------------------------------ from Tkinter import * from socket import * from threading import * class Receive(Thread): def __init__(self, server, gettext): Thread.__init__(self) self.server = server self.gettext = gettext def run(self): while 1: try: text = self.server.recv(1024) if not text: break self.gettext.configure(state='normal') self.gettext.insert(END,'%s\n'%text) self.gettext.configure(state='disabled') except: break class App(Thread): server = socket(AF_INET,SOCK_STREAM) server.bind(('', 285)) server.listen(5) client,addr = server.accept() def __init__(self, master): Thread.__init__(self) frame = Frame(master) frame.grid(row=2,column=3) self.quitbutton = Button(frame, text="QUIT", fg='red', command=frame.quit) self.quitbutton.grid(row=1,column=2) self.button = Button(frame, text="SEND", command=self.Send) self.button.grid(row=1,column=1) self.sendtext = Entry(frame,width=60) self.sendtext.grid(row=1,column=0) self.gettext = Text(frame,height=10,width=80,wrap=WORD) self.gettext.grid(row=0,columnspan=3) self.gettext.insert(END,'Welcome to my Instant Messaging Program\n') self.gettext.configure(state='disabled') def Send(self): self.gettext.configure(state='normal') text = self.sendtext.get() self.gettext.insert(END,'%s \n'%text) self.sendtext.delete(0,END) self.server.send(text) self.gettext.configure(state='disabled') def run(self): Receive(self.server, self.gettext).start() root = Tk() root.title('Server') app = App(root).start() root.mainloop() ------------------------------------------------------------------------------------------ Whenever I run them both and I try to send from either one, it doesn't work. If I try to send from the server it tells me that there the socket is not connected. When I run the client with this server program it works though... ------------------------------------------------------------------------------------------ from socket import * from time import sleep def Server(): ss = socket(AF_INET,SOCK_STREAM); ss.bind(("",285)); ss.listen(5); n = 0; while n != 1: client,addr = ss.accept(); n += 1; if n == 1: print "Got a connection from ", addr client.send("Welcome to JRAM Instant Messaging"); while 1: text = raw_input('> ') client.send(text) def Server() ------------------------------------------------------------------------------------------ I have no idea what I am doing wrong, any help would be appreciated. Thankyou. From RenX99 at gmail.com Fri Oct 22 01:05:10 2004 From: RenX99 at gmail.com (Rene Lopez) Date: Fri Oct 22 01:05:13 2004 Subject: [Tutor] newbie: help unkludge me Message-ID: <555128ce041021160572a84956@mail.gmail.com> Here is the code that seems a bit kludgey to me: class blah def __init__(self) set_table = { 1: ("bob", "bill", 1, 2, 3), 2: ("gill", "sally", 5, 6, 7)} wanted = 1 if wanted in set_table: set1 = set_table[wanted] self.person1 = set1[0] self.person2 = set1[1] self.number1 = set1[2] self.number2 = set1[3] self.number3 = set1[4] Is there a way to assign the info from set1 to the person/number variables using a loop or something? I considered trying something like this: myset = (self.person1, self.person2, self.number1, self.number2, self.number3) so I could trying copying the data over with something like this: while x < 5: myset[x-1] = set1[x-1] but that doesn't work because I get an error saying that myset has no instance of "person1" In other words...they don't exist yet, so they can't be put into a list. I hope this makes some sense, because reading it sounds weird even to me :-) -- Rene From Jeremiah.Rushton at gmail.com Fri Oct 22 01:06:53 2004 From: Jeremiah.Rushton at gmail.com (Jeremiah Rushton) Date: Fri Oct 22 01:06:58 2004 Subject: [Tutor] I may have sent the wrong client program before Message-ID: <6e30826f041021160640762f25@mail.gmail.com> here it is if the other one doesn't work.... ------------------------------------------------------------------------------------------ from Tkinter import * from socket import * from threading import * class Receive(Thread): def __init__(self, client, gettext): Thread.__init__(self) self.client = client self.gettext = gettext def run(self): while 1: try: text = self.client.recv(1024) if not text: break self.gettext.configure(state='normal') self.gettext.insert(END,'%s\n'%text) self.gettext.configure(state='disabled') except: break class App(Thread): client = socket(AF_INET,SOCK_STREAM) ip = 'localhost' server = (ip, 285) client.connect(server) def __init__(self, master): Thread.__init__(self) frame = Frame(master) frame.grid(row=2,column=3) self.quitbutton = Button(frame, text="QUIT", fg='red', command=frame.quit) self.quitbutton.grid(row=1,column=2) self.button = Button(frame, text="SEND", command=self.Send) self.button.grid(row=1,column=1) self.sendtext = Entry(frame,width=60) self.sendtext.grid(row=1,column=0) self.gettext = Text(frame,height=10,width=80,wrap=WORD) self.gettext.grid(row=0,columnspan=3) self.gettext.insert(END,'Welcome to my Instant Messaging Program\n') self.gettext.configure(state='disabled') def Send(self): text = self.sendtext.get() self.sendtext.delete(0,END) self.gettext.configure(state='normal') self.gettext.insert(END,'%s\n'%text) self.gettext.configure(state='disabled') self.client.send(text) def run(self): Receive(self.client, self.gettext).start() root = Tk() root.title('Client') app = App(root).start() root.mainloop() ------------------------------------------------------------------------------------------ From keridee at jayco.net Fri Oct 22 01:07:59 2004 From: keridee at jayco.net (Jacob S.) Date: Fri Oct 22 01:08:01 2004 Subject: [Tutor] A way to restart a script after it runs? References: <41776A56.7020802@digitalert.net> Message-ID: <001601c4b7c2$e8b9ddd0$ec5328cf@JSLAPTOP> You might try something like: >>> import myscript ## Myscript will have an if __name__ = "myscript" check because you are importing it... >>> print myscript >>> ## This means it's an object. So we should be able to free the memory and delete it >>> del myscript >>>import myscript etc. HTH, Jacob Schmidt From keridee at jayco.net Fri Oct 22 01:28:38 2004 From: keridee at jayco.net (Jacob S.) Date: Fri Oct 22 01:28:14 2004 Subject: [Tutor] get the mode of a list References: Message-ID: <002f01c4b7c5$c1f6e500$ec5328cf@JSLAPTOP> Hi, I hope I don't spoil a learning experience by giving you this, but I will anyway. I want you to look it over and see that it works and why it works so as not to spoil that learning experience ;-) def getmode(li): li.sort() numbers = {} for x in li: num = li.count(x) numbers[x] = num highest = max(numbers.values()) n = [] for m in numbers.keys(): if numbers[m] == highest: n.append(m) return n If you want it to tell you specifically when all of the list members are modes, then you can check for that by seeing if the list before is equal to the return list. If you want it to return an integer instead of a list, you might try print statements or int(). Have fun. Sincerely, Jacob Schmidt From alan.gauld at freenet.co.uk Fri Oct 22 01:34:39 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri Oct 22 01:34:38 2004 Subject: [Tutor] Python Version of "enum" ? References: <15A1FDA26DAD524DA7A7AF77313EBA8F07BC00B2@riv-excha5.echostar.com> Message-ID: <017601c4b7c6$89130830$6aa98651@xp> > Is there an equivalent of C++'s 'enum' keyword to set a number of named > constants ( like so ) > enum { > OFF, > ON, > UNKNOWN > }; Not as such but dictionaries can do much the same thing... > If not, can you declare named constants another way? Perhaps 'const MONDAY = > 1', for example. I think that I read somewhere that there is a const construct coming in Python soon? Don't think its in 2.4 yet but maybe 2.5? But you can fake consts with classes if you need to. Personally I take the consenting adults approach and just use uppercase variable names to signify that "you change this one at your peril..." Alan G. From kent_johnson at skillsoft.com Fri Oct 22 02:02:59 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Fri Oct 22 02:03:07 2004 Subject: [Tutor] A way to restart a script after it runs? In-Reply-To: <001601c4b7c2$e8b9ddd0$ec5328cf@JSLAPTOP> References: <41776A56.7020802@digitalert.net> <001601c4b7c2$e8b9ddd0$ec5328cf@JSLAPTOP> Message-ID: <6.1.0.6.0.20041021195926.02a220d0@mail4.skillsoft.com> I'm not sure what the OP wants to accomplish, but this probably won't do it. Imported modules are cached in sys.modules. 'del myscript' unbinds the name myscript from in the current namespace; it doesn't actually unload the module itself. reload(myscript) may do what you want, it will force the module to be reloaded. A better description of the problem would help. Kent At 06:07 PM 10/21/2004 -0500, Jacob S. wrote: >You might try something like: > > >>> import myscript ## Myscript will have an if __name__ = "myscript" >check because you are importing it... > >>> print myscript > > >>> ## This means it's an object. So we should be able to free the >memory and delete it > >>> del myscript > >>>import myscript > >etc. > >HTH, >Jacob Schmidt > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From keridee at jayco.net Fri Oct 22 02:10:32 2004 From: keridee at jayco.net (Jacob S.) Date: Fri Oct 22 02:09:57 2004 Subject: [Tutor] how to play arrays as audio signal References: Message-ID: <008d01c4b7cb$94c9be30$ec5328cf@JSLAPTOP> Okay, If you're just trying to sound off notes at particular frequencies, and you're on Windows, I can help you. Else, I can't. >>> import winsound >>> frequency = 440 >>> length = 1000 # This is in thousands of a second >>> winsound.Beep(frequency, length) Hope this helps, as always, Jacob Schmidt From kent_johnson at skillsoft.com Fri Oct 22 02:10:04 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Fri Oct 22 02:10:09 2004 Subject: [Tutor] newbie: help unkludge me In-Reply-To: <555128ce041021160572a84956@mail.gmail.com> References: <555128ce041021160572a84956@mail.gmail.com> Message-ID: <6.1.0.6.0.20041021200429.02992b28@mail4.skillsoft.com> Tuple assignment is what you want: self.person1, self.person2, self.number1, self.number2, self.number3 = set1 You could use a loop with setattr, but it is a bit awkward. Note that the list contains strings, the actual attribute names: names = ('person1', 'person2', 'number1', 'number2', 'self.number3') for name, value in zip(names, values): setattr(self, name, value) Kent At 07:05 PM 10/21/2004 -0400, Rene Lopez wrote: >Here is the code that seems a bit kludgey to me: > >class blah > def __init__(self) > set_table = { 1: ("bob", "bill", 1, 2, 3), > 2: ("gill", "sally", 5, 6, 7)} > > wanted = 1 > > if wanted in set_table: > set1 = set_table[wanted] > > self.person1 = set1[0] > self.person2 = set1[1] > self.number1 = set1[2] > self.number2 = set1[3] > self.number3 = set1[4] > > >Is there a way to assign the info from set1 to the person/number >variables using a loop or something? I considered trying something >like this: > >myset = (self.person1, self.person2, self.number1, self.number2, self.number3) > >so I could trying copying the data over with something like this: > >while x < 5: > myset[x-1] = set1[x-1] > >but that doesn't work because I get an error saying that myset has no >instance of "person1" In other words...they don't exist yet, so they >can't be put into a list. I hope this makes some sense, because >reading it sounds weird even to me :-) > >-- > >Rene >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From keridee at jayco.net Fri Oct 22 02:14:58 2004 From: keridee at jayco.net (Jacob S.) Date: Fri Oct 22 02:14:12 2004 Subject: [Tutor] A way to restart a script after it runs? Message-ID: <009901c4b7cc$2e269b70$ec5328cf@JSLAPTOP> >I'm not sure what the OP wants to accomplish, but this probably won't do >it. Imported modules are cached in sys.modules. 'del myscript' unbinds the >name myscript from in the current namespace; it doesn't >actually unload the module itself. > >reload(myscript) may do what you want, it will force the module to be >reloaded. A better description of the problem would help. I ran it on the interpreter, and it tested out okay. I don't know if that matters any, but it stands with me. Jacob From kent_johnson at skillsoft.com Fri Oct 22 02:23:00 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Fri Oct 22 02:23:06 2004 Subject: [Tutor] how to play arrays as audio signal In-Reply-To: References: Message-ID: <6.1.0.6.0.20041021202216.029924c0@mail4.skillsoft.com> The wav module might help. You would have to learn enough about the wav format to write your data into a wav file. Then you can play it with winsound. Kent At 10:32 AM 10/19/2004 +0100, Hans Fangohr wrote: >Greetings, > >I would like to 'acoustically play' values in an array (or list, >tupel, ...) as if the position of the speaker membrane at different >times was given by the value in that array. Is there a module (in the >best case a standard module) that would do this for me? (I will need >this on Windows.) > >Here is an example: > > >import numarray > >freq=110 #frequency in Hertz > >samplerate = 1000 #Hertz > >x=numarray.arange(0,1,1.0/samplerate) >y=numarray.sin(x*2*numarray.pi*freq) > > >What is missing, is something along the following lines: > >import sound? >sound?.playvector( y, samplerate ) > > >Looking forward to hearing any suggestions, > >Hans >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From kent_johnson at skillsoft.com Fri Oct 22 02:29:42 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Fri Oct 22 02:29:45 2004 Subject: [Tutor] Re: processing lines and polygons In-Reply-To: References: Message-ID: <6.1.0.6.0.20041021202801.02a3b250@mail4.skillsoft.com> Michael, The problem with snap-to-grid is you can still have two points that are close but snap to different grid points. Maybe you could put all the points into a sorted list and go through it looking for points that are close? If the list contained the point and the list containing the point, you could merge them... Kent At 04:48 PM 10/20/2004 +0200, Michael Dunn wrote: >Thanks Kent, > >that's solved my problem nicely (although I now realize I've got a new >one, see >below). Here's my code -- I've learnt python mostly from lurking on this list, >and although I find myself using python a lot, I've never shown any of my code >to anyone before, so I'd also appreciate general comments: > >#!/usr/bin/env python >"""Take matlab/splus or mapgen vector and join broken lines""" >import re, sys > >class Sequence: > trace = False # append list of contributing input sequences to output > output_format = "matlab" # matlab, mapgen, mif (MapInfo Interchange > Format) > > def __init__(self, segment): > self.points = [tuple(point.split("\t")) for point\ > in segment.strip().split("\n")] > self.start = self.points[0] > self.end = self.points[-1] > self.history = [] > return > > def append(self, other): > # only called if self is already in the output_sequences list > self.history.extend(other.history) > # 1. do the join > if self.start == other.start or self.end == other.end: > other.points.reverse() > other.start, other.end = other.end, other.start > if self.start == other.end: > self.points = other.points[:-1] + self.points > elif self.end == other.start: > self.points = self.points + other.points[1:] > # 2. update endpoints dictionary > if self.points[0] == self.points[-1]: > # it's become a closed polygon > endpoints.pop(s.start) > elif self.start != self.points[0]: > endpoints.pop(self.start) > self.start = self.points[0] > endpoints[self.start] = self > elif self.end != self.points[-1]: > endpoints.pop(self.end) > self.end = self.points[-1] > endpoints[self.end] = self > return > > def __str__(self): > if Sequence.output_format == "mif": > divider = "PLine\n %s" % len(self.points) > elif Sequence.output_format == "matlab": > divider = "NA NA" > elif Sequence.output_format == "mapgen": > divider = "# -b" > if Sequence.trace: > divider = "%s <-- %s" % (divider, str(self.history)) > s = [divider] > for point in self.points: > s.append("%s\t%s" % point) > return "\n".join(s) > >endpoints = {} >output_sequences = [] >mif_header = """version 3 >Coordsys earth projection 1,104 >Columns 1 > SEG_ID integer >Data >""" > >if __name__ == "__main__": > > f = file(sys.argv[1], "rU") > data = f.read() > f.close() > > print >> sys.stderr, "Processing sequences" > input_sequences = re.split("NA NA|# -b", data.strip()) > for i, s in enumerate(input_sequences[1:]): > s = Sequence(s) > s.history.append(i) > if s.start in endpoints.keys(): > endpoints[s.start].append(s) > elif s.end in endpoints.keys(): > endpoints[s.end].append(s) > else: > endpoints[s.start] = s > endpoints[s.end] = s > output_sequences.append(s) > > print mif_header > Sequence.output_format = "mif" > for s in output_sequences: > print s > print >> sys.stderr, "Original: %s sequences\nJoined: %s sequences" %\ > (len(input_sequences), len(output_sequences)) > > # examined output for missing input (there was none) > # L = [] > # for s in output_sequences: > # L.extend(s.history) > # for i in range(len(input_sequences[1:])): > # if i not in L: > # print i, > >I've rebooted into windows (yawn) and tested the output in MapInfo, and it's a >lot better, but there are still bits of coastline not joined up. When I >zoom in >to the bits where the join should be, it looks like the points don't actually >match. The separation distance is much less than the resolution of the map >however, so I should be able to join them up automatically too. I would >have to >change the lines testing whether s.start, s.end are in endpoints.keys() to >something testing whether they are in a radius of the endpoints. Or is there a >simpler way...? > >Just thinking out loud, it occurs to me I could give the Sequence object >additional attributes snap_to_grid_start and snap_to_grid_end and use these to >determine whether lines should be joined, but join them using their original, >more precise, values. Hmmm. More tomorrow. > >Big thanks to all the contributors on the tutor list! It's an amazing >resource. > >Michael >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From kent_johnson at skillsoft.com Fri Oct 22 02:35:55 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Fri Oct 22 02:35:59 2004 Subject: [Tutor] A way to restart a script after it runs? In-Reply-To: <009901c4b7cc$2e269b70$ec5328cf@JSLAPTOP> References: <009901c4b7cc$2e269b70$ec5328cf@JSLAPTOP> Message-ID: <6.1.0.6.0.20041021203400.02a3ae78@mail4.skillsoft.com> It runs, but what does it do? If test.py contains the single line print 'this is a test' then from the interpreter we have this: >>> import test this is a test >>> del test >>> import test Note it doesn't print anything here >>> reload(test) this is a test Now it prints again. Kent At 07:14 PM 10/21/2004 -0500, Jacob S. wrote: > >I'm not sure what the OP wants to accomplish, but this probably won't do > >it. Imported modules are cached in sys.modules. 'del myscript' unbinds the > >name myscript from in the current namespace; it doesn't > >actually unload the module itself. > > > >reload(myscript) may do what you want, it will force the module to be > >reloaded. A better description of the problem would help. > >I ran it on the interpreter, and it tested out okay. I don't know if that >matters any, but it stands with me. >Jacob > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From carroll at tjc.com Fri Oct 22 02:46:14 2004 From: carroll at tjc.com (Terry Carroll) Date: Fri Oct 22 02:46:17 2004 Subject: [Tutor] get the mode of a list In-Reply-To: Message-ID: On Thu, 21 Oct 2004, Nick Lunt wrote: > I want to return the mode of a list, just to clarify the mode is the most > frequently occurring member of a list in my case. Here's my take. I'll bet it has some limitations I'm not aware of. It returns a list with two elements. The first is the number of times the mode value occurs, and the second is a list of modes. For the example below, mode([1, 2, 4, 2, 4, 5, 2, 4, 100]), where 2 and 3 are the modes, each occuring 3 times, it returns [3, [2, 4]] def mode(mylist): _hist_dict={} for item in mylist: _hist_dict[item]=_hist_dict.get(item,0)+1 _modevalue=max(_hist_dict.values()) _returned_list=[] for key in _hist_dict.keys(): if _hist_dict[key] == _modevalue: _returned_list.append(key) return [_modevalue, _returned_list] if __name__ == "__main__": testlist = [1, 2, 4, 2, 4, 5, 2, 4, 100] modelist = mode(testlist) print modelist From carroll at tjc.com Fri Oct 22 02:52:25 2004 From: carroll at tjc.com (Terry Carroll) Date: Fri Oct 22 02:52:28 2004 Subject: [Tutor] get the mode of a list In-Reply-To: Message-ID: On Thu, 21 Oct 2004, Terry Carroll wrote: > For the example below, mode([1, 2, 4, 2, 4, 5, 2, 4, 100]), where 2 and 3 > are the modes, each occuring 3 times, it returns [3, [2, 4]] Oops. Code correct; commentary wrong. That should read: For the example below, mode([1, 2, 4, 2, 4, 5, 2, 4, 100]), where 2 and 4 are the modes, each occuring 3 times, it returns [3, [2, 4]] From kent_johnson at skillsoft.com Fri Oct 22 03:09:26 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Fri Oct 22 03:09:30 2004 Subject: [Tutor] methods versus functions (using lists as an example) In-Reply-To: References: Message-ID: <6.1.0.6.0.20041021210700.0299b3e0@mail4.skillsoft.com> There is a current thread on comp.lang.python that talks about this. Alex Martelli's post at http://groups.google.com/groups?hl=en&lr=&c2coff=1&selm=1gm05gb.1251x8o3h0barN%25aleaxit%40yahoo.com&rnum=6 is especially interesting but I recommend the entire thread. His main point is that using builtin functions that dispatch to member functions allows more than one method to be tried and it allows the behavior of the builtin to be refined over time. Kent At 03:29 PM 10/19/2004 +0100, Hans Fangohr wrote: >Dear all, > >I was looking at what you can do with lists in Python. There are >basically two sets of commands: (i) methods doing something with a >list (such as sort(), reverse(), count(), ...) and (ii) functions that >take a list as an argument (such as sum(), max(), min()). > >I would expect that there is a rationale behind this choice -- would >anyone know what this is or where I can find more information? > >Many thanks, > >Hans >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From keridee at jayco.net Fri Oct 22 02:57:10 2004 From: keridee at jayco.net (Jacob S.) Date: Fri Oct 22 03:16:07 2004 Subject: [Tutor] moving focus away from a raw_input dialog box References: <6.1.2.0.1.20041013213245.01998140@pop.mail.yahoo.com> Message-ID: <010d01c4b7d4$d453ada0$ec5328cf@JSLAPTOP> Hello, I'm not exactly sure of the code conditions you have, but I might be able to help. Instead of making 0 the exit of the whole while loop, set up a while 1 loop. Then you can set up if, elif, else commands to search for different commands received from the raw_input box. ex. while 1: ask = raw_input("What is your hair color? ") if ask == "quit" or ask == "exit": break ## This breaks out of the while loop elif ask == 'green': print "Wow! I don't know anyone with green hair!" elif ask == 'blonde' or ask == 'blond': ## Since people spell it differently, check for both spellings print "Your hair color is the same as mine." else: print "Your hair color is obviously not important enough to make it in my program." You can make one of the commands 'print list of commands' to print out possible entries for ask or something like that. Many of my programs are structured like that. It is probably frowned on by the more professional programmers, though. Hope this helps, Jacob Schmidt From keridee at jayco.net Fri Oct 22 03:10:05 2004 From: keridee at jayco.net (Jacob S.) Date: Fri Oct 22 03:16:13 2004 Subject: [Tutor] What is a cricket match? Message-ID: <010e01c4b7d4$d5547bd0$ec5328cf@JSLAPTOP> I'm sorry that it's not on the topic of Python, but what exactly is a cricket match? It's obviously a game of some sort. Another thing. Can anyone give me a list of the abbreviations used in emails, like I can guess... IMHO IMO - In My Opinion OTOH - On The Other Hand HTH - Hope This Helps Jacob Schmidt P.S. I'm a deprived and neglected boy when it comes to physical activities and games. ;-) From keridee at jayco.net Fri Oct 22 03:22:36 2004 From: keridee at jayco.net (Jacob S.) Date: Fri Oct 22 03:22:11 2004 Subject: [Tutor] A way to restart a script after it runs? References: <009901c4b7cc$2e269b70$ec5328cf@JSLAPTOP> <6.1.0.6.0.20041021203400.02a3ae78@mail4.skillsoft.com> Message-ID: <011301c4b7d5$ae27d6a0$ec5328cf@JSLAPTOP> Thanks, I didn't look that far into it I guess. Jacob From kent_johnson at skillsoft.com Fri Oct 22 03:55:01 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Fri Oct 22 03:55:13 2004 Subject: [Tutor] moving focus away from a raw_input dialog box In-Reply-To: <010d01c4b7d4$d453ada0$ec5328cf@JSLAPTOP> References: <6.1.2.0.1.20041013213245.01998140@pop.mail.yahoo.com> <010d01c4b7d4$d453ada0$ec5328cf@JSLAPTOP> Message-ID: <6.1.0.6.0.20041021215039.02981238@mail4.skillsoft.com> There is nothing wrong with structuring your program like this! If you do it a lot you might be interested in the cmd module. It adds support for help and automatic command dispatch. Here is your sample written with cmd. It's a little longer but maybe better structured.... from cmd import Cmd class Hair(Cmd): def __init__(self): Cmd.__init__(self) self.prompt = "What is your hair color? " def do_green(self, line): print "Wow! I don't know anyone with green hair!" def help_green(self): print "green - use this command if you have green hair" def do_blonde(self, line): print "Your hair color is the same as mine." do_blond = do_blonde # Allow alternate spelling of blonde def do_quit(self, line): return True # flag to exit cmdloop do_exit = do_quit def default(self, line): print "Your hair color is obviously not important enough to make it in my program." Hair().cmdloop() Here is a sample interaction: D:\Personal\Tutor>python hair.py What is your hair color? green Wow! I don't know anyone with green hair! What is your hair color? brown Your hair color is obviously not important enough to make it in my program. What is your hair color? blond Your hair color is the same as mine. What is your hair color? help Documented commands (type help ): ======================================== green Undocumented commands: ====================== blond blonde exit help quit What is your hair color? help green green - use this command if you have green hair What is your hair color? quit Kent At 07:57 PM 10/21/2004 -0500, Jacob S. wrote: >Hello, > > I'm not exactly sure of the code conditions you have, but I might be >able to help. > >Instead of making 0 the exit of the whole while loop, set up a while 1 loop. >Then you can set up if, elif, else commands to search for different commands >received from the raw_input box. > >ex. > > while 1: > ask = raw_input("What is your hair color? ") > if ask == "quit" or ask == "exit": > break ## This breaks out of the while loop > elif ask == 'green': > print "Wow! I don't know anyone with green hair!" > elif ask == 'blonde' or ask == 'blond': ## Since people spell it >differently, check for both spellings > print "Your hair color is the same as mine." > else: > print "Your hair color is obviously not important enough to make >it in my program." > >You can make one of the commands 'print list of commands' to print out >possible entries for ask or something like that. >Many of my programs are structured like that. It is probably frowned on by >the more professional programmers, though. > >Hope this helps, >Jacob Schmidt > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From keridee at jayco.net Fri Oct 22 04:00:13 2004 From: keridee at jayco.net (Jacob S.) Date: Fri Oct 22 03:59:30 2004 Subject: [Tutor] Simple Question... References: <20041016174645.31391.qmail@web61009.mail.yahoo.com><8464C062-1F9E-11D9-8BDA-000393CBC88E@yahoo.fr><47856308316.20041016165216@columbus.rr.com><797fe3d4041016143034feddd3@mail.gmail.com><135873078670.20041016213147@columbus.rr.com><797fe3d404101619306051e62a@mail.gmail.com><41730CE4.9050907@yahoo.com> <797fe3d4041018125855d54b3c@mail.gmail.com> Message-ID: <015601c4b7da$e3a71cf0$ec5328cf@JSLAPTOP> Hi. I see one problem. >def wcslow(f): > line = ' ' > c = 0 > while line: > line = f.read(1024) > c += line.count('\n') Your while loop will never execute because line == None. You can fix this by making line equal to "l" or some other string not equal to None. From keridee at jayco.net Fri Oct 22 04:12:25 2004 From: keridee at jayco.net (Jacob S.) Date: Fri Oct 22 04:11:42 2004 Subject: [Tutor] moving focus away from a raw_input dialog box References: <6.1.2.0.1.20041013213245.01998140@pop.mail.yahoo.com> <010d01c4b7d4$d453ada0$ec5328cf@JSLAPTOP> <6.1.0.6.0.20041021215039.02981238@mail4.skillsoft.com> Message-ID: <015b01c4b7dc$97bbc550$ec5328cf@JSLAPTOP> Hi Kent. >>> print "Thanks\n"*60 Or maybe >>> for x in range(60): print "Thanks" Possibly >>> a = "".join(["Thanks\n"*60]) >>> print a etc. I didn't know about that and I like it alot! Jacob Schmidt From tmclaughlin at csu.edu.au Fri Oct 22 04:31:59 2004 From: tmclaughlin at csu.edu.au (McLaughlin, Toby) Date: Fri Oct 22 04:32:20 2004 Subject: [Tutor] Python Version of "enum" ? Message-ID: <211F78EFD1D870409CC3E4158F4881DA09602B21@xcww01.riv.csu.edu.au> Perhaps this: "Unpacking assignment also gives rise to another common coding idiom in Python: assigning an integer series to a set of variables: >>> red, green, blue = range(3) >>> red, blue (0, 2) This initializes the three names to integer codes 0, 1, and 2, respectively (it's Python's equivalent of enumerated data types you may have seen in other languages)." >From "Learning Python, 2nd Edition" by David Ascher & Mark Lutz. Toby McLaughlin > -----Original Message----- > From: tutor-bounces@python.org > [mailto:tutor-bounces@python.org] On Behalf Of Gooch, John > Sent: Friday, 22 October 2004 6:47 AM > To: 'tutor@python.org' > Subject: [Tutor] Python Version of "enum" ? > > > Is there an equivalent of C++'s 'enum' keyword to set a > number of named > constants ( like so ) > enum { > OFF, > ON, > UNKNOWN > }; > > in Python? It makes reading the code a lot simpler, as > opposed to having to > look up what a status of "1" means, it can be replaced with > "ON", which is > much easier to understand. > > If not, can you declare named constants another way? Perhaps > 'const MONDAY = > 1', for example. > > Thank You, > > > John A. Gooch > Systems Administrator > IT - Tools > EchoStar Satellite L.L.C. > 9601 S. Meridian Blvd. > Englewood, CO 80112 > Desk: 720-514-5708 > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From bill.mill at gmail.com Fri Oct 22 07:14:17 2004 From: bill.mill at gmail.com (Bill Mill) Date: Fri Oct 22 07:14:22 2004 Subject: [Tutor] Simple Question... In-Reply-To: <015601c4b7da$e3a71cf0$ec5328cf@JSLAPTOP> References: <20041016174645.31391.qmail@web61009.mail.yahoo.com> <8464C062-1F9E-11D9-8BDA-000393CBC88E@yahoo.fr> <47856308316.20041016165216@columbus.rr.com> <797fe3d4041016143034feddd3@mail.gmail.com> <135873078670.20041016213147@columbus.rr.com> <797fe3d404101619306051e62a@mail.gmail.com> <41730CE4.9050907@yahoo.com> <797fe3d4041018125855d54b3c@mail.gmail.com> <015601c4b7da$e3a71cf0$ec5328cf@JSLAPTOP> Message-ID: <797fe3d404102122147cb0aec5@mail.gmail.com> line = ' ' there is a space inside the quotes, so line != None. An easy enough mistake to make, since your email reader probably has a font set for reading, not programming. Peace Bill Mill bill.mill at gmail.com On Thu, 21 Oct 2004 21:00:13 -0500, Jacob S. wrote: > Hi. I see one problem. > > >def wcslow(f): > > line = ' ' > > c = 0 > > while line: > > line = f.read(1024) > > c += line.count('\n') > > Your while loop will never execute because line == None. You can fix this by > making line equal to "l" or some other string not equal to None. > > From kraus at hagen-partner.de Fri Oct 22 08:56:35 2004 From: kraus at hagen-partner.de (Wolfram Kraus) Date: Fri Oct 22 08:56:42 2004 Subject: [Tutor] Re: What is a cricket match? In-Reply-To: <010e01c4b7d4$d5547bd0$ec5328cf@JSLAPTOP> References: <010e01c4b7d4$d5547bd0$ec5328cf@JSLAPTOP> Message-ID: Jacob S. wrote: > I'm sorry that it's not on the topic of Python, but what exactly is a > cricket match? It's obviously a game of some sort. http://en.wikipedia.org/wiki/Cricket > Another thing. Can anyone give me a list of the abbreviations used in > emails, like I can guess... > > IMHO IMO - In My Opinion OTOH - On The Other Hand HTH - Hope This > Helps http://www.acronymfinder.com/ (or just use google ;-)) > > Jacob Schmidt > > P.S. I'm a deprived and neglected boy when it comes to physical > activities and games. ;-) > HTH, Wolfram From nkoponen at yahoo.co.uk Fri Oct 22 09:34:50 2004 From: nkoponen at yahoo.co.uk (Niklas Koponen) Date: Fri Oct 22 09:34:52 2004 Subject: [Tutor] Recording wav using ossaudiodev and wave Message-ID: <20041022073450.58194.qmail@web25701.mail.ukl.yahoo.com> Hi! I've been programming with python for a while and I am able to do most of the stuff I want to. Now I'm a bit stuck with a problem, or too tired :-/ I want to record audio from a microphone to a wav-file. I read from the library documentation that I can read audio data from the audio device object using the read method. I also read that I can write to a wav file using the writeframes method. I can't figure out how to combine these two so I could record from the microphone and write to a wav file. If somebody would have some pointer to some source-code where this is done it would help a lot. -Niklas ___________________________________________________________ALL-NEW Yahoo! Messenger - all new features - even more fun! http://uk.messenger.yahoo.com From Michael.Dunn at mpi.nl Fri Oct 22 09:49:41 2004 From: Michael.Dunn at mpi.nl (Michael Dunn) Date: Fri Oct 22 09:49:45 2004 Subject: [Tutor] Re: Tutor Digest, Vol 8, Issue 67 In-Reply-To: <20041022003604.307991E4008@bag.python.org> References: <20041022003604.307991E4008@bag.python.org> Message-ID: > Message: 9 > Date: Thu, 21 Oct 2004 20:29:42 -0400 > From: Kent Johnson > Subject: Re: [Tutor] Re: processing lines and polygons > > Michael, > > The problem with snap-to-grid is you can still have two points that are > close but snap to different grid points. Maybe you could put all the points > into a sorted list and go through it looking for points that are close? If > the list contained the point and the list containing the point, you could > merge them... > > Kent Hi Kent, Yeah, the problem with points snapping to different grid points occurred to me before I got too far, so I went with just iterating through the list of endpoints searching for near points (I specifically don't want to join any lines by their middles, which makes the task easier). Current problems: 1. This search is very slow, which is only a bit of a problem, since I don't need to run this script many times once it's working. However, maybe you (or anybody else interested) could take a look at the get_distance function. There must be some way of sorting the list of points so I don't have to iterate through the entire thing. 2. The endpoint matching routine fails if a segment should be matched at both ends. I think I can get around this by filtering the data through the script a few times (i.e. until no further changes are made) before doing the format conversion. Here's where things stand: #!/usr/bin/env python """Take matlab/splus or mapgen vector and join broken lines Input data from: http://rimmer.ngdc.noaa.gov/mgg/coast/getcoast.html""" import re, sys from math import sqrt class Sequence: _trace = False # append list of contributing input sequences to output output_format = "matlab" # matlab, mapgen, mif (MapInfo Interchange Format) distance = 0.005 # join open ends <= Sequence.distance def __init__(self, segment): self.points = [tuple(point.split("\t")) for point\ in segment.strip().split("\n")] self.start = self.points[0] self.end = self.points[-1] self._history = [] return def append(self, other): # only called if self is already in the output_sequences list self._history.extend(other._history) # reverse the candidate sequence if necessary if get_distance(self.start, other.start) <= Sequence.distance or\ get_distance(self.end, other.end) <= Sequence.distance: other.points.reverse() other.start, other.end = other.end, other.start # do the join add_key, remove_key = None, None if self.start == other.end: self.points = other.points[:-1] + self.points add_key, remove_key = other.start, self.start elif get_distance(self.start, other.end) <= Sequence.distance: self.points = other.points + self.points add_key, remove_key = other.start, self.start elif self.end == other.start: self.points = self.points + other.points[1:] add_key, remove_key = other.end, self.end elif get_distance(self.end, other.start) <= Sequence.distance: self.points = self.points + other.points add_key, remove_key = other.end, self.end # close up near-polygons if get_distance(self.points[0], self.points[-1]) <= Sequence.distance and\ self.points[0] != self.points[-1]: # close but not coincident self.points.append(self.points[0]) # update endpoints dictionary if self.points[0] == self.points[-1]: try: endpoints.pop(s.start) except KeyError: pass # I don't understand why this exc. is called if remove_key: try: endpoints.pop(remove_key) except KeyError: pass # Likewise... if add_key: endpoints[add_key] = self self.start = self.points[0] self.end = self.points[-1] return def __str__(self): if Sequence.output_format == "mif": divider = "PLine\n %s" % len(self.points) elif Sequence.output_format == "matlab": divider = "NA NA" elif Sequence.output_format == "mapgen": divider = "# -b" if Sequence._trace: divider = "%s <-- %s" % (divider, str(self._history)) s = [divider] for point in self.points: s.append("%s\t%s" % point) return "\n".join(s) def get_distance(a, b): (ax, ay), (bx, by) = a, b return sqrt((float(ax)-float(bx))**2 + (float(ay)-float(by))**2) def get_nearest(value, points): # print >> sys.stderr, "Checking for nearest point to", value try: nearest_point = points[0] except IndexError: return (0,0) distance = get_distance(value, nearest_point) for point in points[1:]: if get_distance(value, point) < distance: nearest_point = point distance = get_distance(value, point) return nearest_point endpoints = {} output_sequences = [] mif_header = """version 3 Coordsys earth projection 1,104 Columns 1 SEG_ID integer Data """ if __name__ == "__main__": f = file(sys.argv[1], "rU") data = f.read() f.close() print >> sys.stderr, "Processing sequences" input_sequences = re.split("NA NA|# -b", data.strip()) for i, s in enumerate(input_sequences[1:]): s = Sequence(s) s._history.append(i) start_snap, end_snap = None, None if s.start in endpoints.keys(): endpoints[s.start].append(s) elif s.end in endpoints.keys(): endpoints[s.end].append(s) else: start_snap = get_nearest(s.start, endpoints.keys()) end_snap = get_nearest(s.end, endpoints.keys()) # this fails if a new sequence should be joined at both ends # a possible workaround would be to filter the data through the program # a few times before converting to .mif if start_snap and get_distance(s.start, start_snap) <= Sequence.distance: endpoints[start_snap].append(s) elif end_snap and get_distance(s.end, end_snap) <= Sequence.distance: endpoints[end_snap].append(s) else: endpoints[s.start] = s endpoints[s.end] = s output_sequences.append(s) # print mif_header # Sequence.output_format = "mif" for s in output_sequences: print s print >> sys.stderr, "Original: %s sequences\nJoined: %s sequences" %\ (len(input_sequences), len(output_sequences)) From eric at digitalert.net Fri Oct 22 10:00:26 2004 From: eric at digitalert.net (Eric) Date: Fri Oct 22 09:59:12 2004 Subject: [Tutor] A way to restart a script after it runs? In-Reply-To: <6.1.0.6.0.20041021195926.02a220d0@mail4.skillsoft.com> References: <41776A56.7020802@digitalert.net> <001601c4b7c2$e8b9ddd0$ec5328cf@JSLAPTOP> <6.1.0.6.0.20041021195926.02a220d0@mail4.skillsoft.com> Message-ID: <4178BE1A.4040209@digitalert.net> I ended up just putting in a while loop at the start of the script that will always be "true", and then indented everything else below it. I kinda figured that would be how I would have to do it, but either way it works just fine. And without further adu here is my first completed Python project that I didn't copy out of a book.. . import os import time z = 2 while z ==2: connected = False while not connected: o=os.popen("netstat -an") for l in o: try: if l.split()[1].endswith("192.168.0.250:21"): print "\a\a\a\a\aMatch!" connected = True else: print "Nothing" except IndexError: print "Index Exception" time.sleep(1) amount=0 while connected: o=os.popen("netstat -an") for l in o: try: if l.split()[1].endswith("192.168.0.250:21"): print "Still There" connected = True amount +=1 print amount else: print "Nothing" except IndexError: print "Index Exception" time.sleep(1) if amount == 1: amount -=1 else: print "It's Gone" connected = False print "\a\a" raw_input("Press Enter to close") Nothing fancy, but a good learning experience none the less. From alan.gauld at freenet.co.uk Fri Oct 22 09:59:22 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri Oct 22 09:59:15 2004 Subject: [Tutor] What is a cricket match? References: <010e01c4b7d4$d5547bd0$ec5328cf@JSLAPTOP> Message-ID: <01b101c4b80d$0b687fe0$6aa98651@xp> > I'm sorry that it's not on the topic of Python, but what exactly is a > cricket match? > It's obviously a game of some sort. Yes, it originated in England and infected the rest of the British Empire during the 1800's. In large parts of the world Cricket is now the national sport. As a Scotsman (we don't do cricket on principle! :-) I only vaguely understand the rules despite the best endeavours of my sports teacher. Essentially two teams take turns at batting and bowling. There are two batsmen at each end of a runway and the bowler bowls a small, hard wooden ball at a set of wooden posts called stumps. The batsman tries to stop him hitting the stumps (by hitting the ball not the bowler!) and while the ball is thus deflected will score runs (somewhat like baseball). The rest of the bowlers team are distributed as fielders (with very strange position names like "silly mid-off") who try to catch the batsmans ball (in which case he is out) or return it as fast as possible to the bowler to resume play and minimise the runs. Every 6 balls (an 'over') play swaps end so that the other batsman gets a chance to play. If there are no runs scored then the over is a "maiden" and the bowler has "bowled a maiden over" which has become a common ENglish saying for a successful mission. Games can go on for up to 3 days! The team with most runs after a set number of 'innings' played is deemed the winner. > I can guess... > > IMHO > IMO - In My Opinion > OTOH - On The Other Hand > HTH - Hope This Helps There is a web site: http://www.netlingo.com/inframes.cfm Which has all the words/acronyms/abbreviations used by netters. Alan G. From kent_johnson at skillsoft.com Fri Oct 22 11:35:59 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Fri Oct 22 11:36:04 2004 Subject: [Tutor] A way to restart a script after it runs? In-Reply-To: <4178BE1A.4040209@digitalert.net> References: <41776A56.7020802@digitalert.net> <001601c4b7c2$e8b9ddd0$ec5328cf@JSLAPTOP> <6.1.0.6.0.20041021195926.02a220d0@mail4.skillsoft.com> <4178BE1A.4040209@digitalert.net> Message-ID: <6.1.0.6.0.20041022053328.029c50d8@mail4.skillsoft.com> Congratulations! You've been working on this for a while! This use of a while loop is fine. You don't have to invent a true condition, though; "while True:" works just fine. Kent At 04:00 AM 10/22/2004 -0400, Eric wrote: >I ended up just putting in a while loop at the start of the script that >will always be "true", and then indented everything else below it. I kinda >figured that would be how I would have to do it, but either way it works >just fine. > >And without further adu here is my first completed Python project that I >didn't copy out of a book.. . > > >import os >import time > >z = 2 > >while z ==2: > > connected = False > while not connected: > o=os.popen("netstat -an") > for l in o: > try: > if l.split()[1].endswith("192.168.0.250:21"): > print "\a\a\a\a\aMatch!" > connected = True > else: > print "Nothing" > except IndexError: > print "Index Exception" > time.sleep(1) > > amount=0 > while connected: > o=os.popen("netstat -an") > for l in o: > try: > if l.split()[1].endswith("192.168.0.250:21"): > print "Still There" > connected = True > amount +=1 > print amount > else: > print "Nothing" > except IndexError: > print "Index Exception" > time.sleep(1) > if amount == 1: > amount -=1 > else: > print "It's Gone" > connected = False > > print "\a\a" > >raw_input("Press Enter to close") > > > > > >Nothing fancy, but a good learning experience none the less. > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From kent_johnson at skillsoft.com Fri Oct 22 12:03:28 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Fri Oct 22 12:03:42 2004 Subject: [Tutor] Re: Tutor Digest, Vol 8, Issue 67 In-Reply-To: References: <20041022003604.307991E4008@bag.python.org> Message-ID: <6.1.0.6.0.20041022055357.02a23778@mail4.skillsoft.com> A few tweaks for your current algorithm: - Don't do the sqrt in get_distance(), you don't need the actual distance. Change Sequence.distance to 0.005**2 and everything will work the same. - Keep the dict keys as floats so you don't have to convert every time in get_distance(), the conversion is likely to be expensive. - This is gross abuse of a dictionary! You are getting the keys as a list and searching the list!! if s.start in endpoints.keys(): endpoints[s.start].append(s) instead use if s.start in endpoints: endpoints[s.start].append(s) or my preference which only looks up s.start once: try: endpoints[s.start].append(s) except KeyError: pass Not sure why you have this. s.start will only be in endpoints once: > if self.points[0] == self.points[-1]: > try: endpoints.pop(s.start) > except KeyError: pass # I don't understand why this exc. is > called Kent At 09:49 AM 10/22/2004 +0200, Michael Dunn wrote: > > Message: 9 > > Date: Thu, 21 Oct 2004 20:29:42 -0400 > > From: Kent Johnson > > Subject: Re: [Tutor] Re: processing lines and polygons > > > > Michael, > > > > The problem with snap-to-grid is you can still have two points that are > > close but snap to different grid points. Maybe you could put all the points > > into a sorted list and go through it looking for points that are close? If > > the list contained the point and the list containing the point, you could > > merge them... > > > > Kent > >Hi Kent, > >Yeah, the problem with points snapping to different grid points occurred to me >before I got too far, so I went with just iterating through the list of >endpoints searching for near points (I specifically don't want to join any >lines by their middles, which makes the task easier). Current problems: > >1. This search is very slow, which is only a bit of a problem, since I don't >need to run this script many times once it's working. However, maybe you (or >anybody else interested) could take a look at the get_distance function. There >must be some way of sorting the list of points so I don't have to iterate >through the entire thing. > >2. The endpoint matching routine fails if a segment should be matched at both >ends. I think I can get around this by filtering the data through the script a >few times (i.e. until no further changes are made) before doing the format >conversion. > >Here's where things stand: > >#!/usr/bin/env python >"""Take matlab/splus or mapgen vector and join broken lines >Input data from: http://rimmer.ngdc.noaa.gov/mgg/coast/getcoast.html""" >import re, sys >from math import sqrt > >class Sequence: > _trace = False # append list of contributing input sequences to output > output_format = "matlab" # matlab, mapgen, mif (MapInfo Interchange > Format) > distance = 0.005 # join open ends <= Sequence.distance > > def __init__(self, segment): > self.points = [tuple(point.split("\t")) for point\ > in segment.strip().split("\n")] > self.start = self.points[0] > self.end = self.points[-1] > self._history = [] > return > > def append(self, other): > # only called if self is already in the output_sequences list > self._history.extend(other._history) > # reverse the candidate sequence if necessary > if get_distance(self.start, other.start) <= Sequence.distance or\ > get_distance(self.end, other.end) <= Sequence.distance: > other.points.reverse() > other.start, other.end = other.end, other.start > # do the join > add_key, remove_key = None, None > if self.start == other.end: > self.points = other.points[:-1] + self.points > add_key, remove_key = other.start, self.start > elif get_distance(self.start, other.end) <= Sequence.distance: > self.points = other.points + self.points > add_key, remove_key = other.start, self.start > elif self.end == other.start: > self.points = self.points + other.points[1:] > add_key, remove_key = other.end, self.end > elif get_distance(self.end, other.start) <= Sequence.distance: > self.points = self.points + other.points > add_key, remove_key = other.end, self.end > # close up near-polygons > if get_distance(self.points[0], self.points[-1]) <= > Sequence.distance and\ > self.points[0] != self.points[-1]: # close but not coincident > self.points.append(self.points[0]) > # update endpoints dictionary > if self.points[0] == self.points[-1]: > try: endpoints.pop(s.start) > except KeyError: pass # I don't understand why this exc. is > called > if remove_key: > try: endpoints.pop(remove_key) > except KeyError: pass # Likewise... > if add_key: > endpoints[add_key] = self > self.start = self.points[0] > self.end = self.points[-1] > return > > def __str__(self): > if Sequence.output_format == "mif": > divider = "PLine\n %s" % len(self.points) > elif Sequence.output_format == "matlab": > divider = "NA NA" > elif Sequence.output_format == "mapgen": > divider = "# -b" > if Sequence._trace: > divider = "%s <-- %s" % (divider, str(self._history)) > s = [divider] > for point in self.points: > s.append("%s\t%s" % point) > return "\n".join(s) > >def get_distance(a, b): > (ax, ay), (bx, by) = a, b > return sqrt((float(ax)-float(bx))**2 + (float(ay)-float(by))**2) > >def get_nearest(value, points): > # print >> sys.stderr, "Checking for nearest point to", value > try: nearest_point = points[0] > except IndexError: return (0,0) > distance = get_distance(value, nearest_point) > for point in points[1:]: > if get_distance(value, point) < distance: > nearest_point = point > distance = get_distance(value, point) > return nearest_point > >endpoints = {} >output_sequences = [] >mif_header = """version 3 >Coordsys earth projection 1,104 >Columns 1 > SEG_ID integer >Data >""" > >if __name__ == "__main__": > f = file(sys.argv[1], "rU") > data = f.read() > f.close() > print >> sys.stderr, "Processing sequences" > input_sequences = re.split("NA NA|# -b", data.strip()) > for i, s in enumerate(input_sequences[1:]): > s = Sequence(s) > s._history.append(i) > start_snap, end_snap = None, None > if s.start in endpoints.keys(): > endpoints[s.start].append(s) > elif s.end in endpoints.keys(): > endpoints[s.end].append(s) > else: > start_snap = get_nearest(s.start, endpoints.keys()) > end_snap = get_nearest(s.end, endpoints.keys()) > # this fails if a new sequence should be joined at both ends > # a possible workaround would be to filter the data through the > program > # a few times before converting to .mif > if start_snap and get_distance(s.start, start_snap) <= > Sequence.distance: > endpoints[start_snap].append(s) > elif end_snap and get_distance(s.end, end_snap) <= Sequence.distance: > endpoints[end_snap].append(s) > else: > endpoints[s.start] = s > endpoints[s.end] = s > output_sequences.append(s) > # print mif_header > # Sequence.output_format = "mif" > for s in output_sequences: > print s > print >> sys.stderr, "Original: %s sequences\nJoined: %s sequences" %\ > (len(input_sequences), len(output_sequences)) > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From chandrakirti at gmail.com Fri Oct 22 12:16:43 2004 From: chandrakirti at gmail.com (Lloyd Hugh Allen) Date: Fri Oct 22 12:16:46 2004 Subject: [Tutor] A way to restart a script after it runs? In-Reply-To: <6.1.0.6.0.20041022053328.029c50d8@mail4.skillsoft.com> References: <41776A56.7020802@digitalert.net> <001601c4b7c2$e8b9ddd0$ec5328cf@JSLAPTOP> <6.1.0.6.0.20041021195926.02a220d0@mail4.skillsoft.com> <4178BE1A.4040209@digitalert.net> <6.1.0.6.0.20041022053328.029c50d8@mail4.skillsoft.com> Message-ID: <24d253d9041022031612440f6b@mail.gmail.com> There's also a fairly common convention, done = False while not done: {do stuff} then if you want to set an exit condition (perhaps the user selects "quit" from a menu), the loop will stop repeating if you ever set done = True. On Fri, 22 Oct 2004 05:35:59 -0400, Kent Johnson wrote: > Congratulations! You've been working on this for a while! > > This use of a while loop is fine. You don't have to invent a true > condition, though; "while True:" works just fine. > > Kent > > > > At 04:00 AM 10/22/2004 -0400, Eric wrote: > >I ended up just putting in a while loop at the start of the script that > >will always be "true", and then indented everything else below it. I kinda > >figured that would be how I would have to do it, but either way it works > >just fine. > > > >And without further adu here is my first completed Python project that I > >didn't copy out of a book.. . > > > > > >import os > >import time > > > >z = 2 > > > >while z ==2: > > > > connected = False > > while not connected: > > o=os.popen("netstat -an") > > for l in o: > > try: > > if l.split()[1].endswith("192.168.0.250:21"): > > print "\a\a\a\a\aMatch!" > > connected = True > > else: > > print "Nothing" > > except IndexError: > > print "Index Exception" > > time.sleep(1) > > > > amount=0 > > while connected: > > o=os.popen("netstat -an") > > for l in o: > > try: > > if l.split()[1].endswith("192.168.0.250:21"): > > print "Still There" > > connected = True > > amount +=1 > > print amount > > else: > > print "Nothing" > > except IndexError: > > print "Index Exception" > > time.sleep(1) > > if amount == 1: > > amount -=1 > > else: > > print "It's Gone" > > connected = False > > > > print "\a\a" > > > >raw_input("Press Enter to close") > > > > > > > > > > > >Nothing fancy, but a good learning experience none the less. > > > > > >_______________________________________________ > >Tutor maillist - Tutor@python.org > >http://mail.python.org/mailman/listinfo/tutor > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From abra9823 at mail.usyd.edu.au Fri Oct 22 12:32:18 2004 From: abra9823 at mail.usyd.edu.au (Ajay) Date: Fri Oct 22 12:32:24 2004 Subject: [Tutor] What is a cricket match? In-Reply-To: <01b101c4b80d$0b687fe0$6aa98651@xp> References: <010e01c4b7d4$d5547bd0$ec5328cf@JSLAPTOP> <01b101c4b80d$0b687fe0$6aa98651@xp> Message-ID: <1098441138.4178e1b2789f3@www-mail.usyd.edu.au> some corrections Quoting Alan Gauld : > > > I'm sorry that it's not on the topic of Python, but what exactly is > a > > cricket match? > > It's obviously a game of some sort. > > Yes, it originated in England and infected the rest of the > British Empire during the 1800's. In large parts of the world > Cricket is now the national sport. > > As a Scotsman (we don't do cricket on principle! :-) I only > vaguely understand the rules despite the best endeavours of > my sports teacher. Essentially two teams take turns at batting > and bowling. There are two batsmen at each end of a runway and > the bowler bowls a small, hard wooden ball at a set of wooden > posts called stumps. its a leather ball, wooden wouldn't bounce (and these balls do) > The batsman tries to stop him hitting the > stumps (by hitting the ball not the bowler!) and while the > ball is thus deflected will score runs (somewhat like baseball). runs are scored by running to the opposite end > The rest of the bowlers team are distributed as fielders > (with very strange position names like "silly mid-off") > who try to catch the batsmans ball (in which case he is out) only if they catch the ball before it hits the ground. he is also out if the ball hits the stumps and there are a few more ways > or return it as fast as possible to the bowler to resume play > and minimise the runs. Every 6 balls (an 'over') play swaps > end so that the other batsman gets a chance to play. If there > are no runs scored then the over is a "maiden" and the bowler > has "bowled a maiden over" which has become a common ENglish > saying for a successful mission. > > Games can go on for up to 3 days! The team with most runs > after a set number of 'innings' played is deemed the winner. there are two versions. one, called the one-day is more popular and takes most of one day. each side gets 50 overs (an over is the 6 ball term mentioned earlier) so a team faces 300 balls. the other called a Test match is much much more complicated. suffice to say, it takes 5 days. a game for those with time on their hands is how i would describe it. > > > I can guess... > > > > IMHO > > IMO - In My Opinion > > OTOH - On The Other Hand > > HTH - Hope This Helps > > There is a web site: > > http://www.netlingo.com/inframes.cfm > > Which has all the words/acronyms/abbreviations used by netters. > > Alan G. > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > ---------------------------------------------------------------- This message was sent using IMP, the Internet Messaging Program. From mi.janssen at gmail.com Fri Oct 22 13:22:59 2004 From: mi.janssen at gmail.com (Michael Janssen) Date: Fri Oct 22 13:23:02 2004 Subject: [Tutor] Run a script without much CPU impact -was: A way to restart a script after it runs? In-Reply-To: <41778898.9060807@noos.fr> References: <20041021083709.66386.qmail@web53802.mail.yahoo.com> <41778898.9060807@noos.fr> Message-ID: <1ff2dfbf04102204226a8f24ea@mail.gmail.com> On Thu, 21 Oct 2004 11:59:52 +0200, nik wrote: [discussion of using time.sleep to reduce CPU load] > Is there any way of balancing the CPU load, like some kind of dynamic sleep? You can ask for CPU load (OS specific. On GNU/Linux read /proc/loadavg) and wait accordingly, which will increase-decrease the CPU load. You can use os.nice in order to instruct your script, that is shall run but not increase CPU load much. os.nice will set the "nice" value of the process (I don't know if all operating system have this value, at least unixe have it). The "nice" value is best described by the meaning of the word "nice" ;-) A process with an increased nice value runs a little slower and adds very little to CPU load. It behaves "nicer" in the competition for system ressources. Especially for scripts that runs in intervalls much longer than their runtimes but hits the CPU load much it could be a good choice to increase their nice value and trade script runtime against overall system performance. Cronjobs (Scheduled jobs on unixlike OS) are typically run with a nice value of 5. Make shure you've read the documentation for os.nice and OS specific documentation (manpages for nice and renice) Michael From kent_johnson at skillsoft.com Fri Oct 22 13:38:54 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Fri Oct 22 13:38:58 2004 Subject: [Tutor] Re: Tutor Digest, Vol 8, Issue 67 In-Reply-To: <6.1.0.6.0.20041022055357.02a23778@mail4.skillsoft.com> References: <20041022003604.307991E4008@bag.python.org> <6.1.0.6.0.20041022055357.02a23778@mail4.skillsoft.com> Message-ID: <6.1.0.6.0.20041022073234.028aa930@mail4.skillsoft.com> A couple more quick ideas: You may not even need to take the sum of squares in get_distance(). max(abs(ax-bx), abs(ay-by)) would probably work fine for your purposes, since you are just trying to find points that are visually close. You could keep a sorted list of (x, y) coordinates and use that for finding the nearest neighbor. Use the bisect module to find where to insert a new point in the list. To find the closest point search both ways in the list looking for points that are close. If you use the distance metric above you can stop searching when abs(ax-bx) is greater than your "closeness" cutoff. HTH Kent At 06:03 AM 10/22/2004 -0400, Kent Johnson wrote: >A few tweaks for your current algorithm: > >- Don't do the sqrt in get_distance(), you don't need the actual distance. >Change Sequence.distance to 0.005**2 and everything will work the same. > >- Keep the dict keys as floats so you don't have to convert every time in >get_distance(), the conversion is likely to be expensive. > >- This is gross abuse of a dictionary! You are getting the keys as a list >and searching the list!! > if s.start in endpoints.keys(): > endpoints[s.start].append(s) > >instead use > if s.start in endpoints: > endpoints[s.start].append(s) > >or my preference which only looks up s.start once: > try: > endpoints[s.start].append(s) > except KeyError: pass > >Not sure why you have this. s.start will only be in endpoints once: >> if self.points[0] == self.points[-1]: >> try: endpoints.pop(s.start) >> except KeyError: pass # I don't understand why this exc. is >> called > >Kent > >At 09:49 AM 10/22/2004 +0200, Michael Dunn wrote: >> > Message: 9 >> > Date: Thu, 21 Oct 2004 20:29:42 -0400 >> > From: Kent Johnson >> > Subject: Re: [Tutor] Re: processing lines and polygons >> > >> > Michael, >> > >> > The problem with snap-to-grid is you can still have two points that are >> > close but snap to different grid points. Maybe you could put all the >> points >> > into a sorted list and go through it looking for points that are close? If >> > the list contained the point and the list containing the point, you could >> > merge them... >> > >> > Kent >> >>Hi Kent, >> >>Yeah, the problem with points snapping to different grid points occurred >>to me >>before I got too far, so I went with just iterating through the list of >>endpoints searching for near points (I specifically don't want to join any >>lines by their middles, which makes the task easier). Current problems: >> >>1. This search is very slow, which is only a bit of a problem, since I don't >>need to run this script many times once it's working. However, maybe you (or >>anybody else interested) could take a look at the get_distance function. >>There >>must be some way of sorting the list of points so I don't have to iterate >>through the entire thing. >> >>2. The endpoint matching routine fails if a segment should be matched at both >>ends. I think I can get around this by filtering the data through the >>script a >>few times (i.e. until no further changes are made) before doing the format >>conversion. From bvande at po-box.mcgill.ca Fri Oct 22 14:59:00 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Fri Oct 22 15:14:48 2004 Subject: [Tutor] What is a cricket match? In-Reply-To: <010e01c4b7d4$d5547bd0$ec5328cf@JSLAPTOP> References: <010e01c4b7d4$d5547bd0$ec5328cf@JSLAPTOP> Message-ID: <41790414.5050105@po-box.mcgill.ca> Jacob S. said unto the world upon 2004-10-21 21:10: > I'm sorry that it's not on the topic of Python, but what exactly is a > cricket match? > It's obviously a game of some sort. Cricket is a sport notable chiefly for its ability to make baseball look exciting. ;-) (To be fair, it has also given English a number of nice idioms -- "sticky wicket" being a favourite.) Best, Brian vdB From Michael.Dunn at mpi.nl Fri Oct 22 16:11:11 2004 From: Michael.Dunn at mpi.nl (Michael Dunn) Date: Fri Oct 22 16:11:14 2004 Subject: [Tutor] Re: processing lines and polygons In-Reply-To: <20041022131452.4D2551E400D@bag.python.org> References: <20041022131452.4D2551E400D@bag.python.org> Message-ID: > Message: 1 > Date: Fri, 22 Oct 2004 06:03:28 -0400 > From: Kent Johnson > Subject: Re: [Tutor] Re: Tutor Digest, Vol 8, Issue 67 > > A few tweaks for your current algorithm: > > - Don't do the sqrt in get_distance(), you don't need the actual distance. > Change Sequence.distance to 0.005**2 and everything will work the same. Of course! Lovely! > - Keep the dict keys as floats so you don't have to convert every time in > get_distance(), the conversion is likely to be expensive. Good idea too. > - This is gross abuse of a dictionary! You are getting the keys as a list > and searching the list!! > if s.start in endpoints.keys(): > endpoints[s.start].append(s) > > instead use > if s.start in endpoints: > endpoints[s.start].append(s) > > or my preference which only looks up s.start once: > try: > endpoints[s.start].append(s) > except KeyError: pass Oh dear. I'm a professional lexicographer, and I've certainly never been accused of dictionary abuse before. That really smarts ;). The try/except version is much nicer. > Not sure why you have this. s.start will only be in endpoints once: > > if self.points[0] == self.points[-1]: > > try: endpoints.pop(s.start) > > except KeyError: pass # I don't understand why this exc. is > > called If the first point in a sequence is the same as the last point in a sequence then the sequence is a closed polygon, and I thought I wouldn't need to join anything else to it. Now I'm forcing sequences to close up when their endpoints are within the snap tolerance I should probably not do this any more. > Message: 5 > Date: Fri, 22 Oct 2004 07:38:54 -0400 > From: Kent Johnson > Subject: Re: [Tutor] Re: Tutor Digest, Vol 8, Issue 67 > > A couple more quick ideas: > > You may not even need to take the sum of squares in get_distance(). > max(abs(ax-bx), abs(ay-by)) would probably work fine for your purposes, > since you are just trying to find points that are visually close. I get it--this would find the closest point on the horizontal or the vertical axis rather than measuring the diagonal. Part of me doesn't like that as an approximation, since the data points we are dealing with are real places in real space, and it seems disrespectful. But thinking about it I'd be amazed if this ever caused a problem, since the pairs of points I want to join are all likely to be long way from other pairs that need joining. So I'm convinced. > You could keep a sorted list of (x, y) coordinates and use that for finding > the nearest neighbor. Use the bisect module to find where to insert a new > point in the list. To find the closest point search both ways in the list > looking for points that are close. If you use the distance metric above you > can stop searching when abs(ax-bx) is greater than your "closeness" cutoff. I've never looked at the bisect module before, but from the docs I can see what you mean. I'll have a play with it and see what I can do. > HTH A great deal, TYVM, Michael From kent_johnson at skillsoft.com Fri Oct 22 16:28:29 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Fri Oct 22 16:29:14 2004 Subject: [Tutor] Re: processing lines and polygons In-Reply-To: References: <20041022131452.4D2551E400D@bag.python.org> Message-ID: <6.1.0.6.0.20041022102601.02a36290@mail4.skillsoft.com> After what you did to the dictionary, I don't know why you are so worried about hurting the feelings of a few points... :-) But seriously, you are just trying to find points that look like they belong together. It's a somewhat vague notion to begin with, it doesn't have to be computed with any great accuracy. Kent At 04:11 PM 10/22/2004 +0200, Michael Dunn wrote: > > You may not even need to take the sum of squares in get_distance(). > > max(abs(ax-bx), abs(ay-by)) would probably work fine for your purposes, > > since you are just trying to find points that are visually close. > >I get it--this would find the closest point on the horizontal or the vertical >axis rather than measuring the diagonal. Part of me doesn't like that as an >approximation, since the data points we are dealing with are real places in >real space, and it seems disrespectful. But thinking about it I'd be amazed if >this ever caused a problem, since the pairs of points I want to join are all >likely to be long way from other pairs that need joining. So I'm convinced. From nick at javacat.f2s.com Fri Oct 22 18:36:55 2004 From: nick at javacat.f2s.com (Nick Lunt) Date: Fri Oct 22 18:36:57 2004 Subject: [Tutor] get the mode of a list In-Reply-To: Message-ID: Hi Danny, Jacob and Terry, thankyou for your help. Danny: I had looked at using a dictionary for this, as here: >>> def mode(alist): modes = {} for i in alist: modes[i] = alist.count(i) return modes so for example >>> mode([10,10,10,20,10,30,45,346,45]) {10: 4, 346: 1, 20: 1, 45: 2, 30: 1} The problem I had here was not getting the max value in the dictionary, but getting the max when there was >1 max value :) However, now that you have hinted that using a dictionary is a good way to do it, I will do so, thankyou. Jacob and Terry: Many thanks for you solutions. I will look at them after I've come up with my own solution ;) Python is a learning curve for me, even tho I do use it fairly often in my day job. This project I'm working on is to eventually work out the standard deviation to help out a friend, and getting the mode/median/mean working first seemed a sensible thing to do... Many thanks for all your help, Nick. -----Original Message----- From: Danny Yoo [mailto:dyoo@hkn.eecs.berkeley.edu] Sent: 21 October 2004 20:39 To: Nick Lunt Cc: Python Tutor Subject: Re: [Tutor] get the mode of a list On Thu, 21 Oct 2004, Nick Lunt wrote: > I really have been putting off posting this to the list cos Im sure > there's an easy way to do it, but I give up... :( > > I want to return the mode of a list, just to clarify the mode is the > most frequently occurring member of a list in my case. Hi Nick, Here's a more general problem that might be easier to solve: can you write a function that generates a "histogram"? That is, can you get the frequencies of all the elements in a list? For example, something like: ### >>> histogram([10, 10, 20, 5, 6, 7]) { 10 : 2, 20 : 2, 5 : 1, 6 : 1, 7 : 1} ### If you have something that can generate histogram dictionaries, then you can use it to solve for modes with relative ease, I think. Good luck! --- Incoming mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.778 / Virus Database: 525 - Release Date: 15/10/2004 --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.778 / Virus Database: 525 - Release Date: 15/10/2004 From kent_johnson at skillsoft.com Sat Oct 23 01:40:36 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Sat Oct 23 01:40:39 2004 Subject: [Tutor] BeautifulSoup: cut first n tags? In-Reply-To: <200410181957.45655.cepl@surfbest.net> References: <200410181957.45655.cepl@surfbest.net> Message-ID: <6.1.0.6.0.20041022193853.02a44f30@mail4.skillsoft.com> I would say, if you have something that works, be happy. With website scraping you are always at the mercy of the site authors. Your script could break in many ways if the site changes. I wouldn't try to guess what those are. When it breaks, you can figure out how to fix it. Kent At 07:57 PM 10/18/2004 -0400, Matej Cepl wrote: >Hi, > >I am quite amazed by the beauty of your BeautifulSoup (it is truly >beautiful), but still I have one problem which I would like to resolve: > >I have a not so bad webpage (Boston Globe story, version for print) on >http://www.ceplovi.cz/matej/tmp/globe.html and I would to get some very >clean stuff from it. It is not problem to get some interesting information >from the
    element, but I haven't figure out how to get >the story. Let's see what I have: > > from BeautifulSoup import BeautifulSoup > def get_content(soup,element,cls): > return string.strip(str(ent.first(element,{'class':cls}).contents[0])) > > html = open("globe.html","r").read() > soup = BeautifulSoup() > soup.feed(html) > story = soup.first("div",{'class':'story'}) > headline = get_content(story,'h1','mainHead') > subhead = get_content(story,'h2','subHead') > author = get_content(story,'p','byline') > date = string.strip(str(story.first('span',\ > {'style':'white-space: nowrap;'}) > >So far, surprisingly easy. But how can I get "all remaining tags (not only >

    s) in story after (and without)

    element which is class 'byline' and >no, I don't need any elements, thanks!"? Is there any way how to >work with the ALL elements as a simple list? I know, that I can do >something like > > body = story.fetch('p')[1:] > >but what if some unfortunate author unexepctedly decides that he doesn't >want to make such ugly soup after all and uses some other tag than

    >(

    ,
    , or even
      comes to mind)? > > Thanks a lot, > > Matej > >-- >Matej Cepl, http://www.ceplovi.cz/matej >GPG Finger: 89EF 4BC6 288A BF43 1BAB 25C3 E09F EF25 D964 84AC >138 Highland Ave. #10, Somerville, Ma 02143, (617) 623-1488 > >The function of the expert is not to be more right than other >people, but to be wrong for more sophisticated reasons. > -- Dr. David Butler, British psephologist >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From kent_johnson at skillsoft.com Sat Oct 23 02:46:17 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Sat Oct 23 02:46:23 2004 Subject: [Tutor] Would an OOP approach be simpler? In-Reply-To: References: Message-ID: <6.1.0.6.0.20041022204024.02a38558@mail4.skillsoft.com> Your approach looks fine to me. The functions are clean and distinct. Beginners seem to have a lot of trouble understanding when to use classes. I have written an article showing some common reasons for using classes. You can read it here: http://www.pycs.net/users/0000323/stories/15.html Kent At 10:22 PM 10/18/2004 +1300, you wrote: >Hi all, > >This module (code below), is comprised of functions, which are run by >a main function, which just passes bits of data around. > >http://rafb.net/paste/results/mpCxox91.html > >Still trying to 'reconfigure my brain' (as several OOP tutorials put >it), to understand >the 'OOP paradigm' as nearly every OOP site puts it. At the very >least, repartition my brain and install an OOP OS in a separate >section. : ) > >My module is pretty much going to do one thing (get emails, and dump >their attachments in a directory for another module to extract info, >which will pass the info to another module which will generate a csv >of the extracted data, and email it again, all feeding back at >appropriate times to a small GUI), and all the bits of data being >flung from function to function (in quite a linear sequence), will be >self-contained within that module. > >I can see two functions which may be used by other modules, but the >values they use won't change, they'll just hand them to different >functions to play with (i.e the load cfg module will load the config >file, and pass the information to a function which allows the user to >change the config, and the second function will then save the config) > >I really need a situation that screams 'objects are the only way' to >work on to comprehend why OOP = good I think. The OOP tutorials I've >found tend to be OOP for the sake of OOP... > >Thoughts appreciated. (And there are several errors in the posted >code, like my except clause when trying to login, but that's because I >haven't gotten around to that yet. And some are typos. : ) ) >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From kent_johnson at skillsoft.com Sat Oct 23 02:49:17 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Sat Oct 23 02:49:21 2004 Subject: [Tutor] MS Word and MS Excel on Linux In-Reply-To: References: Message-ID: <6.1.0.6.0.20041022204810.027f01f8@mail4.skillsoft.com> Can you give a few more details? Are the MS files on the Linux server? What kind of computer is reading the files? Are they accessible through file sharing? Kent At 02:39 AM 10/21/2004 -0500, Anthony P. wrote: >Hello Everyone, > >Does anyone know of a module that will let me read MS Word and MS >Excel files via a network share but from a Linux server? > >Thanks, >Anthony >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From kent_johnson at skillsoft.com Sat Oct 23 02:53:01 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Sat Oct 23 02:53:04 2004 Subject: [Tutor] Tuple ordering: What is going on here? In-Reply-To: <41773F5E.3020704@crackrabbit.com> References: <41773F5E.3020704@crackrabbit.com> Message-ID: <6.1.0.6.0.20041022205110.027eff68@mail4.skillsoft.com> Are you sure the two databases were created the same way? Anyway it is bad practice to rely on the results of select *. Code that relies on this will break when the database is changed. You should list the specific fields you want to read, then you won't have this problem. Kent At 11:47 PM 10/20/2004 -0500, Douglas N. Shawhan wrote: >Hi, I am writing a simple little blog script using gadfly. (I know, it's >overkill! I'm playing here!) > >My problem is, when I run it on one machine, the inserts go in in one >order, on the other it is reversed. > >To wit: > >-------------------------------------------------- >import time, gadfly ,kjbuckets, os, time > >if not os.path.isfile('blogDB/blog.gfd'): > connection= gadfly.gadfly() > connection.startup('blog','blogDB') > c=connection.cursor() > c.execute("create table default (entryTime varchar, entry varchar)") > connection.commit() > >connection= gadfly.gadfly('blog','blogDB') >c=connection.cursor() > >t=(time.time(), 'Happy Happy') > >c.execute("insert into default(entryTime, entry) values('%s','%s')"%t) >c.execute("select * from default order by entryTime desc") > >for each in c.fetchall(): > print each[0] > print each[1] >connection.commit() >----------------------------- > >Machine 1 output: >1098333356.12 >Happy Happy >1098333355.03 >Happy Happy >1098333354.01 >Happy Happy >1098333275.99 >Happy Happy >1098333275.06 >Happy Happy >1098333273.85 >Happy Happy >1098333272.3 >Happy Happy > >Machine 2 output: > >Happy Happy >1098333442.39 >Happy Happy >1098333356.12 >Happy Happy >1098333355.03 >Happy Happy >1098333354.01 >Happy Happy >1098333275.99 >Happy Happy >1098333275.06 >Happy Happy >1098333273.85 >Happy Happy >1098333272.3 > >------------- > >My question: is the reversal occouring in the tuple or in gadfly's output? > >Both machines are OpenBSD. > >machine1= OpenBSD 3.5 GENERIC#34 i386 >machine 2 = OpenBSD 3.3 MERCURY#5 i386 > >Weird, man. >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From cyresse at gmail.com Sat Oct 23 03:30:52 2004 From: cyresse at gmail.com (Liam Clarke) Date: Sat Oct 23 03:30:55 2004 Subject: [Tutor] Would an OOP approach be simpler? In-Reply-To: <6.1.0.6.0.20041022204024.02a38558@mail4.skillsoft.com> References: <6.1.0.6.0.20041022204024.02a38558@mail4.skillsoft.com> Message-ID: Thanks very much for the article link Kent, it's the sort of thing I've been looking for. Cheers, Liam Clarke On Fri, 22 Oct 2004 20:46:17 -0400, Kent Johnson wrote: > Your approach looks fine to me. The functions are clean and distinct. > > Beginners seem to have a lot of trouble understanding when to use classes. > I have written an article showing some common reasons for using classes. > You can read it here: http://www.pycs.net/users/0000323/stories/15.html > > Kent > > > > At 10:22 PM 10/18/2004 +1300, you wrote: > >Hi all, > > > >This module (code below), is comprised of functions, which are run by > >a main function, which just passes bits of data around. > > > >http://rafb.net/paste/results/mpCxox91.html > > > >Still trying to 'reconfigure my brain' (as several OOP tutorials put > >it), to understand > >the 'OOP paradigm' as nearly every OOP site puts it. At the very > >least, repartition my brain and install an OOP OS in a separate > >section. : ) > > > >My module is pretty much going to do one thing (get emails, and dump > >their attachments in a directory for another module to extract info, > >which will pass the info to another module which will generate a csv > >of the extracted data, and email it again, all feeding back at > >appropriate times to a small GUI), and all the bits of data being > >flung from function to function (in quite a linear sequence), will be > >self-contained within that module. > > > >I can see two functions which may be used by other modules, but the > >values they use won't change, they'll just hand them to different > >functions to play with (i.e the load cfg module will load the config > >file, and pass the information to a function which allows the user to > >change the config, and the second function will then save the config) > > > >I really need a situation that screams 'objects are the only way' to > >work on to comprehend why OOP = good I think. The OOP tutorials I've > >found tend to be OOP for the sake of OOP... > > > >Thoughts appreciated. (And there are several errors in the posted > >code, like my except clause when trying to login, but that's because I > >haven't gotten around to that yet. And some are typos. : ) ) > >_______________________________________________ > >Tutor maillist - Tutor@python.org > >http://mail.python.org/mailman/listinfo/tutor > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From zmerch at 30below.com Sat Oct 23 04:32:31 2004 From: zmerch at 30below.com (Roger Merchberger) Date: Sat Oct 23 04:33:25 2004 Subject: [Tutor] What is a cricket match? In-Reply-To: <01b101c4b80d$0b687fe0$6aa98651@xp> References: <010e01c4b7d4$d5547bd0$ec5328cf@JSLAPTOP> Message-ID: <5.1.0.14.2.20041022222948.04d9d2a8@mail.30below.com> Rumor has it that Alan Gauld may have mentioned these words: >... >There is a web site: >http://www.netlingo.com/inframes.cfm >Which has all the words/acronyms/abbreviations used by netters. To continue the tradition of this particular off-topic thread, shouldn't what you stated above be: "used by Nutters" instead? :-)) Laterz, (and thanks all for the cricket lessons...) Roger "Merch" Merchberger -- Roger "Merch" Merchberger | A new truth in advertising slogan sysadmin, Iceberg Computers | for MicroSoft: "We're not the oxy... zmerch@30below.com | ...in oxymoron!" From cyresse at gmail.com Sat Oct 23 05:36:06 2004 From: cyresse at gmail.com (Liam Clarke) Date: Sat Oct 23 05:36:09 2004 Subject: [Tutor] Would an OOP approach be simpler? In-Reply-To: References: <6.1.0.6.0.20041022204024.02a38558@mail4.skillsoft.com> Message-ID: Well thanks to all for their help, my first module of my first project is completed. For anyone who's curious, the results are below - http://rafb.net/paste/results/qHyVC360.html Once again, thanks very much to all. Liam Clarke __ 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From seanf at email.arizona.edu Sat Oct 23 08:00:33 2004 From: seanf at email.arizona.edu (seanf@email.arizona.edu) Date: Sat Oct 23 08:00:37 2004 Subject: [Tutor] Text Boxes - deleting and inserting In-Reply-To: <4176AAFE.9000903@h-lab.net> References: <6e30826f04102008373e8ab1c6@mail.gmail.com> <4176AAFE.9000903@h-lab.net> Message-ID: <1098511233.7ecb372d111d4@www.email.arizona.edu> Hey guys, First of all a quick intro: My name is Sean Fioritto. I'm a CS major at the University of Arizona. My dad has been trying to get me to learn Python since my freshman year...about 3 years ago. I was finally able to put all the books he gave me to use because we're using Python in my AI class - and I have to say that if it were possible to have a crush on a programming language, I would be drooling over Python at this point. I've only been at it for about a week and I already feel like buying Python t-shirts and telling all my CS professors to stop teaching Java and teach Python! So here is my problem. I'm creating a program that uses the model, view, controller pattern and the class that isn't working is going to be an obvserver. The text box will populate itself with a String that represents the model every time the model tells the text box to update. I decided to use Python's nifty multiple inheritance feature: so cView is both a Text object and an Observer object. The problem is with the Text class, specifically in Update when it calls self.delete(1.0, END). This, according to google, should delete the entire box. Here's the error (m is a model object): >>> v = CritterView.cView() >>> v.update(m) Traceback (most recent call last): File "", line 1, in -toplevel- v.update(m) File "C:\home\projects\CritterView.py", line 18, in update self.delete(1.0, END) NameError: global name 'END' is not defined I've tried self.END to no avail. The most frustrating thing is that it worked before, then I changed something and broke it. When I create a regular Text object, t = Text(), and call t.delete(1.0, END), it doesn't puke all over me and works perfectly. Apparently Python just can't digest my code. I'm up for any suggestions. Also, if I'm doing anything goofy and 'unpythonic' let me know. Sincerely, Sean Fioritto Here is the code: from pObservable import Observer from Tkinter import Text class cView(Observer, Text): def __init__(self, parent=None): Observer.__init__(self) Text.__init__(self, parent) self.config(state='disabled') self.pack() def update(self, model, event = None, message=None): self.myHeight = model.height self.myWidth = model.width self.config(state='normal') self.delete(1.0, END) self.s = "" for self.i in range(self.myWidth): for self.j in range(self.myHeight): self.s = self.s + model.getChar(self.i, self.j) self.s = self.s + '\n' print self.s self.insert(END, self.s) self.config(state='disabled') -- Albert Einstein, when asked to describe radio, replied: "You see, wire telegraph is a kind of a very, very long cat. You pull his tail in New York and his head is meowing in Los Angeles. Do you understand this? And radio operates exactly the same way: you send signals here, they receive them there. The only difference is that there is no cat." From alan.gauld at freenet.co.uk Sat Oct 23 12:31:53 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat Oct 23 12:33:10 2004 Subject: [Tutor] Text Boxes - deleting and inserting References: <6e30826f04102008373e8ab1c6@mail.gmail.com><4176AAFE.9000903@h-lab.net> <1098511233.7ecb372d111d4@www.email.arizona.edu> Message-ID: <020201c4b8eb$840aeb70$6aa98651@xp> > First of all a quick intro: My name is Sean Fioritto. Welcome Sean, > an Observer object. The problem is with the Text class, specifically in Update > when it calls self.delete(1.0, END). This, according to google, should delete > the entire box. > > Here's the error (m is a model object): > > >>> v = CritterView.cView() > >>> v.update(m) > > Traceback (most recent call last): > File "", line 1, in -toplevel- > v.update(m) > File "C:\home\projects\CritterView.py", line 18, in update > self.delete(1.0, END) > NameError: global name 'END' is not defined > > Here is the code: > > from pObservable import Observer > from Tkinter import Text You need to import END too... Tkinter is one of the few occasions when I recommend the from Tkinter import * approach... Alternatively just import the module and use Tkinter.END HTH, Alan G From kent_johnson at skillsoft.com Sat Oct 23 12:44:05 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Sat Oct 23 12:44:12 2004 Subject: [Tutor] Text Boxes - deleting and inserting In-Reply-To: <1098511233.7ecb372d111d4@www.email.arizona.edu> References: <6e30826f04102008373e8ab1c6@mail.gmail.com> <4176AAFE.9000903@h-lab.net> <1098511233.7ecb372d111d4@www.email.arizona.edu> Message-ID: <6.1.0.6.0.20041023062405.028afff0@mail4.skillsoft.com> Sean, END is defined in the Tkinter module. You need to import it to use it. My guess is that the version that worked had from Tkinter import * What that does is import all the names defined by the Tkinter module into the current namespace. So things like Tkinter.Text and Tkinter.END are accessible through the bare names Text and END. Your current program has from Tkinter import Text This just makes one name from Tkinter available in the current scope - Text. You should change this to say from Tkinter import Text, END or just the blanket import from Tkinter import * You might want to review the Tutorial section on imports: http://docs.python.org/tut/node8.html Looking at the rest of your code, you are overusing self (abusing your self? ;). Normally you only use self for variables that need to be shared between two methods or that need to persist between method calls. Temporary variables don't have to be stored in the instance. For example this code > self.s = "" > for self.i in range(self.myWidth): > for self.j in range(self.myHeight): > self.s = self.s + model.getChar(self.i, self.j) > self.s = self.s + '\n' > > print self.s > self.insert(END, self.s) would be better written without all those self's. The only ones needed are to access myWidth and myHeight (which may not need to be member variables either) and at the end to call self.insert(): s = "" for i in range(self.myWidth): for j in range(self.myHeight): s = s + model.getChar(i, j) s = s + '\n' print s self.insert(END, s) BTW Python has what it takes to keep the flame burning for many years, but it'll spoil you. Java looks like an ugly hack in comparison and I can't bear to even look at C++. If you want help or suggestions about using Python in CS, you might want to venture over to edu-sig, lots of folks over there think Python is far better than Java as a first teaching language. Kent At 11:00 PM 10/22/2004 -0700, seanf@email.arizona.edu wrote: >Hey guys, > >First of all a quick intro: My name is Sean Fioritto. I'm a CS major at the >University of Arizona. My dad has been trying to get me to learn Python since >my freshman year...about 3 years ago. I was finally able to put all the books >he gave me to use because we're using Python in my AI class - and I have >to say >that if it were possible to have a crush on a programming language, I would be >drooling over Python at this point. I've only been at it for about a week >and I >already feel like buying Python t-shirts and telling all my CS professors to >stop teaching Java and teach Python! > >So here is my problem. I'm creating a program that uses the model, view, >controller pattern and the class that isn't working is going to be an >obvserver. The text box will populate itself with a String that represents the >model every time the model tells the text box to update. I decided to use >Python's nifty multiple inheritance feature: so cView is both a Text >object and >an Observer object. The problem is with the Text class, specifically in Update >when it calls self.delete(1.0, END). This, according to google, should delete >the entire box. > >Here's the error (m is a model object): > > >>> v = CritterView.cView() > >>> v.update(m) > >Traceback (most recent call last): > File "", line 1, in -toplevel- > v.update(m) > File "C:\home\projects\CritterView.py", line 18, in update > self.delete(1.0, END) >NameError: global name 'END' is not defined > >I've tried self.END to no avail. The most frustrating thing is that it worked >before, then I changed something and broke it. When I create a regular Text >object, t = Text(), and call t.delete(1.0, END), it doesn't puke all over me >and works perfectly. Apparently Python just can't digest my code. > >I'm up for any suggestions. Also, if I'm doing anything goofy and 'unpythonic' >let me know. > >Sincerely, >Sean Fioritto > >Here is the code: > >from pObservable import Observer >from Tkinter import Text > > > >class cView(Observer, Text): > > def __init__(self, parent=None): > Observer.__init__(self) > Text.__init__(self, parent) > self.config(state='disabled') > self.pack() > > def update(self, model, event = None, message=None): > self.myHeight = model.height > self.myWidth = model.width > self.config(state='normal') > self.delete(1.0, END) > > self.s = "" > for self.i in range(self.myWidth): > for self.j in range(self.myHeight): > self.s = self.s + model.getChar(self.i, self.j) > self.s = self.s + '\n' > > print self.s > self.insert(END, self.s) > self.config(state='disabled') > >-- >Albert Einstein, when asked to describe radio, replied: >"You see, wire telegraph is a kind of a very, very long cat. You pull his tail >in New York and his head is meowing in Los Angeles. Do you understand this? >And radio operates exactly the same way: you send signals here, they receive >them there. The only difference is that there is no cat." > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From kent_johnson at skillsoft.com Sat Oct 23 12:45:18 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Sat Oct 23 12:45:21 2004 Subject: [Tutor] MS Word and MS Excel on Linux In-Reply-To: References: <6.1.0.6.0.20041022204810.027f01f8@mail4.skillsoft.com> Message-ID: <6.1.0.6.0.20041023064417.028afad0@mail4.skillsoft.com> I'm sorry, I still don't understand what you are trying to do, what the problem is, or how you think Python might help. Kent At 02:09 AM 10/23/2004 -0500, you wrote: >Hi Kent, > >Thanks for your response to my query. The files will be on a mixed >network that uses Windows, Linux, and maybe some Solaris. File sharing >will be enabled on all of the machines. Does this give you any more >insight? > >Thanks! >Anthony > > >On Fri, 22 Oct 2004 20:49:17 -0400, Kent Johnson > wrote: > > Can you give a few more details? Are the MS files on the Linux server? What > > kind of computer is reading the files? Are they accessible through file > > sharing? > > > > Kent > > > > > > > > At 02:39 AM 10/21/2004 -0500, Anthony P. wrote: > > >Hello Everyone, > > > > > >Does anyone know of a module that will let me read MS Word and MS > > >Excel files via a network share but from a Linux server? > > > > > >Thanks, > > >Anthony > > >_______________________________________________ > > >Tutor maillist - Tutor@python.org > > >http://mail.python.org/mailman/listinfo/tutor > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > From zmerch at 30below.com Sat Oct 23 16:15:44 2004 From: zmerch at 30below.com (Roger Merchberger) Date: Sat Oct 23 16:16:39 2004 Subject: [Tutor] MS Word and MS Excel on Linux In-Reply-To: <6.1.0.6.0.20041023064417.028afad0@mail4.skillsoft.com> References: <6.1.0.6.0.20041022204810.027f01f8@mail4.skillsoft.com> Message-ID: <5.1.0.14.2.20041023101224.04eea4a8@mail.30below.com> Rumor has it that Kent Johnson may have mentioned these words: >I'm sorry, I still don't understand what you are trying to do, what the >problem is, or how you think Python might help. About the only decent "best guess stab" at this I could add is: One of the latest versions of OpenOffice (1.1.2) for windows has a module that will let it interface with Python, and it will open MSWord and MSExcel files. Maybe the Linux version has the same module? Also, for the OP: Sharing files and directories is all built into the network functionality, not something derived internally in Python. Hope this helps, Roger "Merch" Merchberger -- Roger "Merch" Merchberger | A new truth in advertising slogan sysadmin, Iceberg Computers | for MicroSoft: "We're not the oxy... zmerch@30below.com | ...in oxymoron!" From hugonz-lists at h-lab.net Sat Oct 23 19:43:20 2004 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Sat Oct 23 19:43:28 2004 Subject: [Tutor] Controlling a process and then killing it Message-ID: <417A9838.3090401@h-lab.net> Hi Tutors, Is there any way to get the process id of something you run using popen*??? I'm writing a front end to MPlayer, and I'm lucky that MPlayer lets me send a "quit" command to it... If I did not have this, how could I get the process ID in order to send a SIGTERM later on and (maybe) reap the children?? mystdin, mystdout = os.popen2(myprogram) time.sleep (20) #I'd like to kill the process here Is this available as any attribute in any module? I'm aware of the functions in the sys module, but they will give me info only if the popen call throws an exception... Hugo From hugonz-lists at h-lab.net Sat Oct 23 19:49:23 2004 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Sat Oct 23 19:49:27 2004 Subject: [Tutor] Text Boxes - deleting and inserting In-Reply-To: <1098511233.7ecb372d111d4@www.email.arizona.edu> References: <6e30826f04102008373e8ab1c6@mail.gmail.com> <4176AAFE.9000903@h-lab.net> <1098511233.7ecb372d111d4@www.email.arizona.edu> Message-ID: <417A99A3.20900@h-lab.net> seanf@email.arizona.edu wrote: > Hey guys, > > First of all a quick intro: My name is Sean Fioritto. I'm a CS major at the > University of Arizona. My dad has been trying to get me to learn Python since > my freshman year...about 3 years ago. I was finally able to put all the books > he gave me to use because we're using Python in my AI class - and I have to say > that if it were possible to have a crush on a programming language, I would be > drooling over Python at this point. I've only been at it for about a week and I > already feel like buying Python t-shirts and telling all my CS professors to > stop teaching Java and teach Python! Feel exactly the same way....! > Traceback (most recent call last): > File "", line 1, in -toplevel- > v.update(m) > File "C:\home\projects\CritterView.py", line 18, in update > self.delete(1.0, END) > NameError: global name 'END' is not defined This is Tkinter, right? END is a constant that equals 'end', but you must import that symbol... I think it's in the Tkconstants module, but you should get the same result if you do: END = 'end' so that it will be translated. or do from Tkconstants import END at the beginning Happy hacking, Hugo From seanf at email.arizona.edu Sat Oct 23 22:13:11 2004 From: seanf at email.arizona.edu (seanf@email.arizona.edu) Date: Sat Oct 23 22:13:15 2004 Subject: [Tutor] using a Timer In-Reply-To: <6.1.0.6.0.20041023062405.028afff0@mail4.skillsoft.com> References: <6e30826f04102008373e8ab1c6@mail.gmail.com> <4176AAFE.9000903@h-lab.net> <1098511233.7ecb372d111d4@www.email.arizona.edu> <6.1.0.6.0.20041023062405.028afff0@mail4.skillsoft.com> Message-ID: <1098562391.851424717c9aa@www.email.arizona.edu> Quoting Kent Johnson : > Looking at the rest of your code, you are overusing self (abusing your > self? ;). Normally you only use self for variables that need to be shared > between two methods or that need to persist between method calls. Temporary > variables don't have to be stored in the instance. ahh, thank you. It seemed excessive. I just had a general misconception about scope in Python, but I seem to have it straight now. Also, the text box is working great now. Here's the new problem. I want to create a button that will change the model every 1 second or so, and then another button to stop it. I thought maybe a timer would work, but it only seems to run once. Here is the code: class cFrame(Frame): def __init__(self, aModel, parent = None): Frame.__init__(self, parent) self.pack() self.model = aModel self.view = cView(self) self.view.pack(side=TOP) self.model.addObserver(self.view) self.model.notifyObservers() t = Timer(1, self.tick) start = Button(self, text='Start', command = t.start) start.pack(side=LEFT) stop = Button(self, text='Stop', command = t.cancel) stop.pack(side=LEFT) step = Button(self, text='Step', command = self.tick) step.pack(side=LEFT) quit = Button(self, text='Quit', command=self.quit) quit.pack(side=RIGHT) def tick(self): self.model.tick() if __name__ == '__main__': cFrame().mainloop() With my new knowledge, I guess view doesn't have to be self.view. Basically I just want to call model.tick() over and over. Another problem: for some reason when I press the quit button, it freezes the program: any ideas? There are no errors or anything, I just am not sure how to implement this in Python. thanks for all the help, Sean -- Albert Einstein, when asked to describe radio, replied: "You see, wire telegraph is a kind of a very, very long cat. You pull his tail in New York and his head is meowing in Los Angeles. Do you understand this? And radio operates exactly the same way: you send signals here, they receive them there. The only difference is that there is no cat." From seanf at email.arizona.edu Sat Oct 23 23:24:30 2004 From: seanf at email.arizona.edu (seanf@email.arizona.edu) Date: Sat Oct 23 23:24:34 2004 Subject: [Tutor] using a Timer In-Reply-To: <1098562391.851424717c9aa@www.email.arizona.edu> References: <6e30826f04102008373e8ab1c6@mail.gmail.com> <4176AAFE.9000903@h-lab.net> <1098511233.7ecb372d111d4@www.email.arizona.edu> <6.1.0.6.0.20041023062405.028afff0@mail4.skillsoft.com> <1098562391.851424717c9aa@www.email.arizona.edu> Message-ID: <1098566670.82b124fe693a9@www.email.arizona.edu> I should also say that the reason I'm not using a loop is because I would like to be able to adjust how fast or how slow the ticks happen. I thought about something like this. self.t = Timer(1.0, aTick) t.start() def aTick(self, time): self.model.tick() t = Timer(time, aTick) This way I could adjust the waiting period on the fly by changing the time parameter. A few problems: - First, I don't know if I can pass parameters through the Timer to aTick. I also left myself no way to change the time parameter. Maybe I could define some variable self.time above aTick and use that inside aTick? Then I could change self.tmie with some sort of gui widget, and not use the time paramter at all? - I'm not sure how I would get it to stop. - I have no idea how this is working with memory, because the Timer uses threading, and I've never really done any programming with threads before. I dunno, maybe it would work great. What I'm really hoping is there is something built in that will make this a fairly easy problem. thanks all, Sean Quoting seanf@email.arizona.edu: > Quoting Kent Johnson : > > > > Looking at the rest of your code, you are overusing self (abusing your > > self? ;). Normally you only use self for variables that need to be shared > > between two methods or that need to persist between method calls. Temporary > > variables don't have to be stored in the instance. > > ahh, thank you. It seemed excessive. I just had a general misconception about > scope in Python, but I seem to have it straight now. Also, the text box is > working great now. > > Here's the new problem. I want to create a button that will change the model > every 1 second or so, and then another button to stop it. I thought maybe a > timer would work, but it only seems to run once. > > Here is the code: > > class cFrame(Frame): > > def __init__(self, aModel, parent = None): > Frame.__init__(self, parent) > self.pack() > > self.model = aModel > self.view = cView(self) > self.view.pack(side=TOP) > self.model.addObserver(self.view) > self.model.notifyObservers() > > t = Timer(1, self.tick) > start = Button(self, text='Start', command = t.start) > start.pack(side=LEFT) > > stop = Button(self, text='Stop', command = t.cancel) > stop.pack(side=LEFT) > > step = Button(self, text='Step', command = self.tick) > step.pack(side=LEFT) > > quit = Button(self, text='Quit', command=self.quit) > quit.pack(side=RIGHT) > > > def tick(self): > self.model.tick() > > if __name__ == '__main__': cFrame().mainloop() > > With my new knowledge, I guess view doesn't have to be self.view. Basically I > just want to call model.tick() over and over. > > Another problem: for some reason when I press the quit button, it freezes the > program: any ideas? > > There are no errors or anything, I just am not sure how to implement this in > Python. > > thanks for all the help, > Sean > > > -- > Albert Einstein, when asked to describe radio, replied: > "You see, wire telegraph is a kind of a very, very long cat. You pull his > tail > in New York and his head is meowing in Los Angeles. Do you understand this? > And radio operates exactly the same way: you send signals here, they receive > them there. The only difference is that there is no cat." > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- Albert Einstein, when asked to describe radio, replied: "You see, wire telegraph is a kind of a very, very long cat. You pull his tail in New York and his head is meowing in Los Angeles. Do you understand this? And radio operates exactly the same way: you send signals here, they receive them there. The only difference is that there is no cat." From alipolatel at yahoo.com Sat Oct 23 23:36:46 2004 From: alipolatel at yahoo.com (Ali Polatel) Date: Sat Oct 23 23:36:50 2004 Subject: [Tutor] Mail Server Message-ID: <20041023213646.41162.qmail@web61002.mail.yahoo.com> hi dear tutors, I have learned the smtp module to send e-mails with Python... but for this we need a mail server... can't a programmer write a mail server that can send e-mails with Python? if yes how? Regards, Ali Polatel __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20041023/602eba6d/attachment.html From chema at sl-form.com Sat Oct 23 23:37:16 2004 From: chema at sl-form.com (=?iso-8859-1?Q?Jos=E9_Mar=EDa?= Mateos) Date: Sat Oct 23 23:37:22 2004 Subject: [Tutor] META: Tutor is set not to munge reply-to In-Reply-To: References: Message-ID: <20041023213716.GC10930@chema.homelinux.org> El viernes 15 de octubre a las 17:40, Terry Carroll escribi?: > > Yes, but there are good reasons for not munging the reply-to headers: > > I like the munging, so I do it myself in procmail. Other option is using a mail client that has some "reply to list" function (such as mutt :-)). Best regards. -- ** Las Penas del Agente Smith: http://blogs.eurielec.etsit.upm.es/chema ** http://EuropeSwPatentFree.hispalinux.es - EuropeSwPatentFree GPG key ID: 0x2948FA19 | Please encrypt private mail Software Libre Formaci?n - http://www.sl-form.com -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Digital signature Url : http://mail.python.org/pipermail/tutor/attachments/20041023/596aa8ff/attachment.pgp From dyoo at hkn.eecs.berkeley.edu Sun Oct 24 01:12:11 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun Oct 24 01:17:18 2004 Subject: [Tutor] Would an OOP approach be simpler? In-Reply-To: Message-ID: On Sat, 23 Oct 2004, Liam Clarke wrote: > Well thanks to all for their help, my first module of my first project > is completed. > > For anyone who's curious, the results are below - > > http://rafb.net/paste/results/qHyVC360.html > > Once again, thanks very much to all. Hi Liam, Thanks for posting up your code! I took a look at it; looks pretty good. Do you mind if I give a few suggestions? If you do mind, um... skip this message. *grin* The only big target I can see so far is getReturns(): it's a bit long. It might be useful to break it up a little, by using helper functions to extract blocks of related statements. For example, there's a block here: if os.path.exists('./archives/wb%s' % weekstart): done=file('./archives/wb%s/got.lst' %weekstart, 'rb') donelist=done.readlines() done.close() list=donelist[0].split('/') doesExist=1 I'm not too familiar with what this is doing, but let's describe this block of code as something like checkIfDoesExist(). We can reform it as a function: ### def checkIfDoesExist(weekstart): if os.path.exists('./archives/wb%s' % weekstart): done=file('./archives/wb%s/got.lst' %weekstart, 'rb') donelist=done.readlines() done.close() list=donelist[0].split('/') return (list, 1) else: return (None, 0) ### and then, back in getReturns(), we can use it like this: (list, doesExist) = checkIfDoesExist(weekstart) The reason this extraction ("refactoring") might be worthwhile is because the code doesn't make clear what value the 'list' should have if the directory doesn't exist. The refactored code tries to make sure that 'list' does have some known value, regardless if 'doesExist' is true or not. Another block in getReturns() that looks promising is the one that connects to the mail server. This block here: success = 0 session = imaplib.IMAP4(hostname) while not success: try: session.login(user[account], pwd[account]) except: pass else: success = 1 looks like it is making darn sure that it connects and logs into the server. We can call this something like connectToImap(): ### def connectToImap(hostname, username, password): success = 0 session = imaplib.IMAP4(hostname) while not success: try: session.login(username, password) except: pass else: success = 1 return session ### I made a few cosmetic changes here, mostly to reduce its direct ties to the user and pwd collections. Back in getReturns(), we can replace the block with: session = connectToImap(hostname, user[account], pwd[account]) Again, this refactoring helps readability because it's clear that the block initializes a 'session' value. The other variable, the 'success' variable, doesn't leak out into the rest of the getReturns() function. 'success' is a temporary variable that's used only to get that while loop working. By refactoring the block out into a separate connectToImap() function, we get to make its local role very clear to a reader of the code. Are these kinds of structural changes useful? They don't add anything technically new, but they do make the code easier to read. With those two blocks extracted out, getReturns() now reads like: ### def getReturns(hostname, user, pwd, searchstring, weekstart): sender = [] msgdata = [] (list, doesExist) = checkIfDoesExist(weekstart) for account in range(len(user)): session = connectToImap(hostname, user[account], pwd[account]) session.select() ... ### So my main advice is to look out for places where "paragraph" blocks of code tend to appear, and see if those blocks can be extracted out as real functions. I hope this helps! From dyoo at hkn.eecs.berkeley.edu Sun Oct 24 01:29:26 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun Oct 24 01:29:31 2004 Subject: [Tutor] Text Boxes - deleting and inserting In-Reply-To: <1098511233.7ecb372d111d4@www.email.arizona.edu> Message-ID: On Fri, 22 Oct 2004 seanf@email.arizona.edu wrote: > First of all a quick intro: My name is Sean Fioritto. I'm a CS major at > the University of Arizona. My dad has been trying to get me to learn > Python since my freshman year...about 3 years ago. I was finally able to > put all the books he gave me to use because we're using Python in my AI > class - and I have to say that if it were possible to have a crush on a > programming language, I would be drooling over Python at this point. Hi Sean, Welcome aboard! Glad that you're enjoying Python. > Here's the error (m is a model object): > > >>> v = CritterView.cView() > >>> v.update(m) > > Traceback (most recent call last): > File "", line 1, in -toplevel- > v.update(m) > File "C:\home\projects\CritterView.py", line 18, in update > self.delete(1.0, END) > NameError: global name 'END' is not defined Ah, this one isn't too bad. END is defined in the Tkinter module, so you either need to fully qualify it: self.delete(1.0, Tkinter.END) or yank it into the namespace, during the import: from Tkinter import Text, END On a side note, there's a block of code here that can be improved: > self.s = "" > for self.i in range(self.myWidth): > for self.j in range(self.myHeight): > self.s = self.s + model.getChar(self.i, self.j) > self.s = self.s + '\n' Repeated string concatentation can be expensive, depending on how large self.myWidth and self.myHeight gets. You may want to use a "buffer" approach to accumulate that string variable instead. In Java, there's a java.lang.StringBuffer class that's designed for doing this kind of accumulation. Python has a similar feature that using a string's built-in join() method: ### >>> buffer = [] >>> buffer.append("hello, this is") >>> buffer.append("\n") >>> buffer.append("a test") >>> ''.join(buffer) 'hello, this is\na test' ### I hope this helps! From seanf at email.arizona.edu Sun Oct 24 01:36:14 2004 From: seanf at email.arizona.edu (seanf@email.arizona.edu) Date: Sun Oct 24 01:36:18 2004 Subject: [Tutor] Text Boxes - deleting and inserting In-Reply-To: References: Message-ID: <1098574574.70edbddb2cbc4@www.email.arizona.edu> Very cool. Thanks! - Sean Quoting Danny Yoo : > > > On Fri, 22 Oct 2004 seanf@email.arizona.edu wrote: > > > First of all a quick intro: My name is Sean Fioritto. I'm a CS major at > > the University of Arizona. My dad has been trying to get me to learn > > Python since my freshman year...about 3 years ago. I was finally able to > > put all the books he gave me to use because we're using Python in my AI > > class - and I have to say that if it were possible to have a crush on a > > programming language, I would be drooling over Python at this point. > > > Hi Sean, > > Welcome aboard! Glad that you're enjoying Python. > > > > > Here's the error (m is a model object): > > > > >>> v = CritterView.cView() > > >>> v.update(m) > > > > Traceback (most recent call last): > > File "", line 1, in -toplevel- > > v.update(m) > > File "C:\home\projects\CritterView.py", line 18, in update > > self.delete(1.0, END) > > NameError: global name 'END' is not defined > > > > Ah, this one isn't too bad. END is defined in the Tkinter module, so you > either need to fully qualify it: > > self.delete(1.0, Tkinter.END) > > > or yank it into the namespace, during the import: > > from Tkinter import Text, END > > > > On a side note, there's a block of code here that can be improved: > > > self.s = "" > > for self.i in range(self.myWidth): > > for self.j in range(self.myHeight): > > self.s = self.s + model.getChar(self.i, self.j) > > self.s = self.s + '\n' > > > Repeated string concatentation can be expensive, depending on how large > self.myWidth and self.myHeight gets. > > You may want to use a "buffer" approach to accumulate that string > variable instead. In Java, there's a java.lang.StringBuffer class that's > designed for doing this kind of accumulation. Python has a similar > feature that using a string's built-in join() method: > > ### > >>> buffer = [] > >>> buffer.append("hello, this is") > >>> buffer.append("\n") > >>> buffer.append("a test") > >>> ''.join(buffer) > 'hello, this is\na test' > ### > > > I hope this helps! > > -- Albert Einstein, when asked to describe radio, replied: "You see, wire telegraph is a kind of a very, very long cat. You pull his tail in New York and his head is meowing in Los Angeles. Do you understand this? And radio operates exactly the same way: you send signals here, they receive them there. The only difference is that there is no cat." From dyoo at hkn.eecs.berkeley.edu Sun Oct 24 01:36:49 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun Oct 24 01:36:52 2004 Subject: [Tutor] Controlling a process and then killing it In-Reply-To: <417A9838.3090401@h-lab.net> Message-ID: On Sat, 23 Oct 2004, [ISO-8859-1] Hugo Gonz=E1lez Monteverde wrote: > Is there any way to get the process id of something you run using > popen*??? Hi Hugo, Yes, you can use the 'popen2' module with its enhanced versions of popen. It contains several popen variants, and these remember their pids: http://www.python.org/doc/lib/popen3-objects.html Good luck to you! From dyoo at hkn.eecs.berkeley.edu Sun Oct 24 01:56:53 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun Oct 24 01:56:58 2004 Subject: [Tutor] Mail Server In-Reply-To: <20041023213646.41162.qmail@web61002.mail.yahoo.com> Message-ID: On Sat, 23 Oct 2004, Ali Polatel wrote: > hi dear tutors, > I have learned the smtp module to send e-mails with Python... Hi Ali, Yes, 'smtplib' should do the trick: http://www.python.org/doc/faq/library.html#how-do-i-send-mail-from-a-python-script > but for this we need a mail server... can't a programmer write a mail > server that can send e-mails with Python? Yes, it's possible. There is even an undocumented one in the Standard Libary as 'smtpd', although I think it might just be a proxy, and not a full-fledged mail server. There's a program called 'tmda': http://tmda.net/ but I have no personal experience with it. And it, too, looks like it depends on a dedicated Mail Transfer Agent (MTA). There are several free ones out there, including 'qmail', 'postfix', and 'sendmail'. But mail servers are actually a bit complicated to set up, and perhaps thankfully so: the spam mail problem might be even more acute than it is now if it were casually easy to set up a fly-by-night mail server. If you want to set up your own mail server, you'll probably need some specialized help to set up your own MTA. You might want to, instead, use the one you have from your internet service provider. Hope this helps! From jinlin555 at msn.com Sun Oct 24 02:32:16 2004 From: jinlin555 at msn.com (Lin Jin) Date: Sun Oct 24 02:33:04 2004 Subject: [Tutor] how to add string into the specified position of the original string Message-ID: if i define a function: def setposition(post,outter,string): i want to call the function setposition(3,"S", "0S0 0SSSS") that return the"OSOSOSSSS" HOW COULD I DEFINE THE FUNCTION TO MAKE THAT.THX _________________________________________________________________ ÓëÁª»úµÄÅóÓѽøÐн»Á÷£¬ÇëʹÓà MSN Messenger: http://messenger.msn.com/cn From dyoo at hkn.eecs.berkeley.edu Sun Oct 24 02:44:28 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun Oct 24 02:44:31 2004 Subject: [Tutor] how to add string into the specified position of the original string In-Reply-To: Message-ID: On Sun, 24 Oct 2004, Lin Jin wrote: > if i define a function: > def setposition(post,outter,string): > > i want to call the function setposition(3,"S", "0S0 0SSSS") that return > the"OSOSOSSSS" Hi Lin, This sounds slightly like a homework problem, so I'll have to be a little vague. Are you familiar with lists yet? If so, you may want to try converting your string into a list of characters, and manipulate that. See: http://www.python.org/doc/lib/built-in-funcs.html#l2h-43 Good luck to you. From maxnoel_fr at yahoo.fr Sun Oct 24 02:44:47 2004 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Sun Oct 24 02:44:55 2004 Subject: [Tutor] how to add string into the specified position of the original string In-Reply-To: References: Message-ID: On Oct 24, 2004, at 01:32, Lin Jin wrote: > if i define a function: > def setposition(post,outter,string): > > i want to call the function setposition(3,"S", "0S0 0SSSS") that > return the"OSOSOSSSS" > HOW COULD I DEFINE THE FUNCTION TO MAKE THAT.THX Mmh... Could you give us more details about what your function does? Like, some other examples? -- Wild_Cat maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From bgailer at alum.rpi.edu Sun Oct 24 02:43:26 2004 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Sun Oct 24 02:46:20 2004 Subject: [Tutor] how to add string into the specified position of the original string In-Reply-To: References: Message-ID: <6.1.2.0.0.20041023184051.0473a9c0@mail.mric.net> At 06:32 PM 10/23/2004, Lin Jin wrote: >if i define a function: >def setposition(post,outter,string): > >i want to call the function setposition(3,"S", "0S0 0SSSS") that return >the"OSOSOSSSS" >HOW COULD I DEFINE THE FUNCTION TO MAKE THAT.THX I can't determine the desired behavior from the example. Please explain. The closest I can imagine is that you want to replace the character in position post with outter. The names make it a little hard to understand, and how/why do the zeroes get replaced with ohs? Bob Gailer bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell From chandrakirti at gmail.com Sun Oct 24 02:54:38 2004 From: chandrakirti at gmail.com (Lloyd Hugh Allen) Date: Sun Oct 24 02:54:42 2004 Subject: [Tutor] how to add string into the specified position of the original string In-Reply-To: <6.1.2.0.0.20041023184051.0473a9c0@mail.mric.net> References: <6.1.2.0.0.20041023184051.0473a9c0@mail.mric.net> Message-ID: <24d253d904102317543c1f7bcc@mail.gmail.com> Be aware that your input uses 0 (zero) and your output has capital letter "o". People don't always notice that, but computers will get angry. On Sat, 23 Oct 2004 18:43:26 -0600, Bob Gailer wrote: > At 06:32 PM 10/23/2004, Lin Jin wrote: > >if i define a function: > >def setposition(post,outter,string): > > > >i want to call the function setposition(3,"S", "0S0 0SSSS") that return > >the"OSOSOSSSS" > >HOW COULD I DEFINE THE FUNCTION TO MAKE THAT.THX > > I can't determine the desired behavior from the example. Please explain. > The closest I can imagine is that you want to replace the character in > position post with outter. The names make it a little hard to understand, > and how/why do the zeroes get replaced with ohs? > > > Bob Gailer > bgailer@alum.rpi.edu > 303 442 2625 home > 720 938 2625 cell > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From dyoo at hkn.eecs.berkeley.edu Sun Oct 24 03:01:33 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun Oct 24 03:01:36 2004 Subject: [Tutor] how to add string into the specified position of the original string (fwd) Message-ID: [Forwarding to tutor@python.org] Hi Lin, Thanks for being truthful. Since this is defintely homework, we can't give you an "answer". We're restricted to gently point you in a direction that should help you on your way. But other than that, you have to do your work: we will not do your homework for you. What you need to solve that problem is pretty straightforward. In particular, you'll want to read about list and string manipulation. You may find the following tutorials useful: http://www.python.org/moin/BeginnersGuide_2fNonProgrammers If you go through one of the tutorials there, you should be able to figure out how to define setPosition(). If you have questions on tutorial material, please feel free to ask us about it on the Tutor list. Again, we can't give homework answers, but we can clarify points that are confusing to you. Good luck. ---------- Forwarded message ---------- Date: Sun, 24 Oct 2004 08:49:44 +0800 From: Lin Jin To: dyoo@hkn.eecs.berkeley.edu Subject: Re: [Tutor] how to add string into the specified position of the original string the question is like this: Create a function called setPosition which takes the marks data structure, sets the the particular position (character 0 to 8 of the string) to the given player's mark symbol (X or O). This function should return this modified marks data structure. For example, the function call=A1=AD setPosition(0, "X", " OOXOXO X") =A1=AD should return "XOOXOXO X": the original marks string with position z= ero set to X From dyoo at hkn.eecs.berkeley.edu Sun Oct 24 03:30:49 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun Oct 24 03:30:52 2004 Subject: [Tutor] using a Timer In-Reply-To: <1098562391.851424717c9aa@www.email.arizona.edu> Message-ID: On Sat, 23 Oct 2004 seanf@email.arizona.edu wrote: > Quoting Kent Johnson : > > > > Looking at the rest of your code, you are overusing self (abusing your > > self? ;). Normally you only use self for variables that need to be shared > > between two methods or that need to persist between method calls. Temporary > > variables don't have to be stored in the instance. > > ahh, thank you. It seemed excessive. I just had a general misconception about > scope in Python, but I seem to have it straight now. Also, the text box is > working great now. > > Here's the new problem. I want to create a button that will change the model > every 1 second or so, and then another button to stop it. I thought maybe a > timer would work, but it only seems to run once. Hi Sean, Ah, it sounds like you want to use the after() method in Tkinter. Don't use Timer(): it's meant for use with threads. There's an alternative way to do the kind of interactive update you're doing, and this involves after(). after() tells Tkinter to call some function "after" some timed delay. For example, here is a small clock that updates itself every second: ### """Small clock application. Shows how to use after() to keep a repeated event going.""" from Tkinter import * import time class MyFrame(Frame): def __init__(self, root): Frame.__init__(self, root) self.label = Label(self) self.label.pack() def update_and_repeat(self): """Updates the text in the label, and reschedules another update after a second.""" self.label.configure(text="The time is: " + time.ctime()) self.after(1, self.update_and_repeat) if __name__ == '__main__': root = Tk() frame = MyFrame(root) frame.pack() frame.update_and_repeat() mainloop() ### Note that it keeps itself alive by rescheduling another update_and_repeat(), over an over. That rescheduling can be easily controlled by some condition. In pseudocode: if we_should_keep_going: self.after(1, self.update_and_repeat) An alternative approach uses threads, but I don't like talking about them. *grin* They often make things much more complicated than the situation warrants, and for your problem, threads are overkill. Hope this helps! From scot at possum.in-berlin.de Sun Oct 24 21:58:04 2004 From: scot at possum.in-berlin.de (Scot W. Stevenson) Date: Sun Oct 24 20:27:47 2004 Subject: [Tutor] What is a cricket match? In-Reply-To: <41790414.5050105@po-box.mcgill.ca> References: <010e01c4b7d4$d5547bd0$ec5328cf@JSLAPTOP> <41790414.5050105@po-box.mcgill.ca> Message-ID: <200410241958.05046.scot@possum.in-berlin.de> Hello Brian, > Cricket is a sport notable chiefly for its ability to make baseball look > exciting. ;-) A British friend of the family, pressed for the rules of cricket, under duress finally admitted that there are none: The British, he confessed, just pretend that there are rules and always make sure that they sound terribly, terribly complicated so that everybody else thinks that the British are so much more intelligent than they are. To that we replied: Well, if that is so, why does India keep winning? Cheers, Y, Scot -- In the real version, Han Solo shot first Scot W. Stevenson Panketal, Germany From kent_johnson at skillsoft.com Sun Oct 24 23:45:23 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Sun Oct 24 23:45:29 2004 Subject: [Tutor] Controlling a process and then killing it In-Reply-To: <417A9838.3090401@h-lab.net> References: <417A9838.3090401@h-lab.net> Message-ID: <6.1.0.6.0.20041024174329.029d5e10@mail4.skillsoft.com> Python 2.4 has a replacement for popen, the subprocess module, that gives access to the pid. There is a reference implementation available which presumably runs under Python 2.3. See PEP 324 for details. http://www.python.org/peps/pep-0324.html Kent At 12:43 PM 10/23/2004 -0500, Hugo Gonz?lez Monteverde wrote: >Hi Tutors, > >Is there any way to get the process id of something you run using popen*??? > >I'm writing a front end to MPlayer, and I'm lucky that MPlayer lets me >send a "quit" command to it... If I did not have this, how could I get the >process ID in order to send a SIGTERM later on and (maybe) reap the children?? > >mystdin, mystdout = os.popen2(myprogram) >time.sleep (20) >#I'd like to kill the process here > >Is this available as any attribute in any module? I'm aware of the >functions in the sys module, but they will give me info only if the popen >call throws an exception... > >Hugo >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From kent_johnson at skillsoft.com Sun Oct 24 23:55:15 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Sun Oct 24 23:55:24 2004 Subject: [Tutor] matrix insertion routine for MNA In-Reply-To: <1d4.2d3730dc.2ea74722@aol.com> References: <1d4.2d3730dc.2ea74722@aol.com> Message-ID: <6.1.0.6.0.20041024174913.029c6ce8@mail4.skillsoft.com> Joseph, You could make the elements of your matrix themselves lists. This would not be a numarray matrix, just a Python list of lists - actually a list of lists of lists. Like this: >>> a=[] >>> for i in range(5): ... col = [] ... for j in range(5): ... col.append([]) ... a.append(col) ... >>> a [[[], [], [], [], []], [[], [], [], [], []], [[], [], [], [], []], [[], [], [], [], []], [[], [], [], [], []]] You can think of a as a 5x5 array each of whose elements is a list. You can append elements to the list: >>> a[1][2] [] >>> a[1][2].append(3) >>> a[1][2].append(4) >>> a[1][2] [3, 4] When you are done appending you can loop through a and replace the lists with the sums of their elements >>> a[1][2] = sum(a[1][2]) >>> a[1][2] 7 If you do that for each list in a, you will end up with a 5x5 array of numbers. HTH Kent At 12:44 AM 10/20/2004 -0400, CryptoLevel9@aol.com wrote: >I originally posted under the subject Values in matrices. The two >responses that I received from that topic were excellent and helped me a >lot, but I have run into a problem that I did not anticipate having when I >first asked the question. What I need help with now is how to assign >multiple values to the same locations in a pre-constructed matrix and then >sum the values at those points. Unfortunately, there is no way to >determine which values will need to be summed before placing them into the >matrix without defeating the entire purpose of the program, that is why >the values have to be summed after they are placed in the matrix. My >rational behind writing a program that does this is that I am trying to >implement the MNA (Modified Nodal Analysis) Algorithm (a technique for >"solving" electrical circuits) in a program making the assumptions that >the circuit to be solved is planar, that the user already knows the values >for every element in the circuit and which nodes the element is connected >to. I have looked through the owners manual for numarray and saw that >"The numarray constructor takes a data argument, an optional type, and an >optional shape argument. If the data argument is a sequence, then array >creates a new object of type numarray, and fills the array with the >elements of the data object. The shape of the array is determined by the >size and nesting arrangement of the elements of data." This gives me the >impression that what I am asking cannot be done by making every point in >the matrix a list and then summing the individual lists after the values >have been placed in them, which is what I thought of doing first. I would >prefer not making any more variable names than I had listed in my original >post in order to keep from confusing myself as too what each internal >variable means. Any help either on how to do what I am asking or how to >circumvent the need to sum values after they have placed in placed in the >matrix would be appreciated. > >Joseph >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From alan.gauld at freenet.co.uk Mon Oct 25 00:45:50 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon Oct 25 00:45:28 2004 Subject: [Tutor] jython slowness Message-ID: <004901c4ba1b$36940490$2cb98851@xp> I occasionally play with jython, especialy when testing java code. I've been reading the recent New Riders book on Jython and noticed a couple of the programs could be much shorter using list comprehensions so I tried it - wow! Jython is usually between 2-10 times slower than regular python but comprehensions seem to be at least 50 times slower! [i for i in [1,2,3]] took about 5 seconds on my 2Ghz XP box under jython. Under CPython the same code was nearly instantaneous. In jython (v2.1) the "equivalent" code: l=[] for i in [1,2,3]: l.append(i) is also near instant. Does anyone on the list know why the comprehension version is soooo slow? Alan G. From jinlin555 at msn.com Mon Oct 25 00:58:45 2004 From: jinlin555 at msn.com (Lin Jin) Date: Mon Oct 25 01:00:31 2004 Subject: [Tutor] about the function Message-ID: i am new in python.just learn how to defining the function.i want to know that if i define three functions.how can i use read the data from one function to the other funtion.it;s like if i have function draw(pic),setposition(position,pic).if i want to used the data in setposition for the draw.how i could do that. _________________________________________________________________ Ãâ·ÑÏÂÔØ MSN Explorer: http://explorer.msn.com/lccn/ From bvande at po-box.mcgill.ca Mon Oct 25 01:20:19 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Mon Oct 25 01:20:18 2004 Subject: [Tutor] about the function In-Reply-To: References: Message-ID: <417C38B3.6010409@po-box.mcgill.ca> Lin Jin said unto the world upon 2004-10-24 18:58: > i am new in python.just learn how to defining the function.i want to > know that if i define three functions.how can i use read the data from > one function to the other funtion.it;s like if i have function > draw(pic),setposition(position,pic).if i want to used the data in > setposition for the draw.how i could do that. > > _________________________________________________________________ > Ãâ·ÑÏÂÔØ MSN Explorer: http://explorer.msn.com/lccn/ > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > Hi Lin Jin, I am not sure I understand your question. But this silly example might be helpful: def get_the_number_2(): return 2 def get_the_number_3(): return 3 def multiply_two_numbers(x, y): return x * y print multiply_two_numbers(get_the_number_2(), get_the_number_3()) >>> 6 So, one way is to use a call to one function in the argument place of another. You could also do: first_arg = get_the_number_2() second_arg = get_the_number_3() multiply_two_numbers(first_arg, second_arg) Are these techniques the sort of thing you were wanting? One other thing: it is much easier to read a post if a space follows each period. Like that. :-) Best, Brian vdB From kent_johnson at skillsoft.com Mon Oct 25 05:22:06 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Mon Oct 25 05:22:12 2004 Subject: [Tutor] jython slowness In-Reply-To: <004901c4ba1b$36940490$2cb98851@xp> References: <004901c4ba1b$36940490$2cb98851@xp> Message-ID: <6.1.0.6.0.20041024231501.029c9fe8@mail4.skillsoft.com> That's very strange. I timed the same loop and jython only took about 50% longer than python (the timeit module from python 2.3 works fine in jython): D:\Projects\CB\lib\Lib>jython timeit.py "[i for i in [1,2,3]]" 100000 loops, best of 3: 1.7 usec per loop D:\Projects>python24 -m timeit "[i for i in [1,2,3]]" 1000000 loops, best of 3: 1.25 usec per loop The for loop version is considerably slower in jython, a bit slower in python: D:\Projects\CB\lib\Lib>jython timeit.py -s "l=[]" "for i in [1,2,3]: l.append(i)" 100000 loops, best of 3: 4.6 usec per loop D:\Projects>python24 -m timeit -s "l=[]" "for i in [1,2,3]: l.append(i)" 1000000 loops, best of 3: 1.84 usec per loop I use Jython 2.1 a lot and I haven't found any serious performance problems. Kent At 11:45 PM 10/24/2004 +0100, Alan Gauld wrote: >I occasionally play with jython, especialy when testing java code. > >I've been reading the recent New Riders book on Jython and noticed >a couple of the programs could be much shorter using list >comprehensions >so I tried it - wow! Jython is usually between 2-10 times slower than >regular python but comprehensions seem to be at least 50 times slower! > >[i for i in [1,2,3]] > >took about 5 seconds on my 2Ghz XP box under jython. >Under CPython the same code was nearly instantaneous. > >In jython (v2.1) the "equivalent" code: > >l=[] >for i in [1,2,3]: > l.append(i) > >is also near instant. > >Does anyone on the list know why the comprehension version is soooo >slow? > >Alan G. > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From orbitz at ezabel.com Mon Oct 25 05:26:10 2004 From: orbitz at ezabel.com (orbitz) Date: Mon Oct 25 05:26:35 2004 Subject: [Tutor] Mail Server In-Reply-To: References: Message-ID: <417C7252.6030307@ezabel.com> www.twistedmatrix.com has an smtpd class and is easy to use and powerful enough to handle a good amount of connections. Danny Yoo wrote: >On Sat, 23 Oct 2004, Ali Polatel wrote: > > > >>hi dear tutors, >>I have learned the smtp module to send e-mails with Python... >> >> > >Hi Ali, > >Yes, 'smtplib' should do the trick: > >http://www.python.org/doc/faq/library.html#how-do-i-send-mail-from-a-python-script > > > > > >>but for this we need a mail server... can't a programmer write a mail >>server that can send e-mails with Python? >> >> > >Yes, it's possible. There is even an undocumented one in the Standard >Libary as 'smtpd', although I think it might just be a proxy, and not a >full-fledged mail server. There's a program called 'tmda': > > http://tmda.net/ > >but I have no personal experience with it. And it, too, looks like it >depends on a dedicated Mail Transfer Agent (MTA). There are several free >ones out there, including 'qmail', 'postfix', and 'sendmail'. > > >But mail servers are actually a bit complicated to set up, and perhaps >thankfully so: the spam mail problem might be even more acute than it is >now if it were casually easy to set up a fly-by-night mail server. > >If you want to set up your own mail server, you'll probably need some >specialized help to set up your own MTA. You might want to, instead, use >the one you have from your internet service provider. > > > >Hope this helps! > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > From kent_johnson at skillsoft.com Mon Oct 25 05:27:08 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Mon Oct 25 05:27:14 2004 Subject: [Tutor] about the function In-Reply-To: References: Message-ID: <6.1.0.6.0.20041024232336.029db720@mail4.skillsoft.com> If I understand your question, it sounds like maybe pic should be a class. Then it would keep its position in instance variable and draw itself. Your code would be pic.setposition(position) pic.draw() Otherwise setposition(position, pic) could modify pic in some way so that draw(pic) knows where to draw it. Or you could pass the position to draw: draw(pic, position) More detail about pic would help. Kent At 06:58 AM 10/25/2004 +0800, Lin Jin wrote: >i am new in python.just learn how to defining the function.i want to know >that if i define three functions.how can i use read the data from one >function to the other funtion.it;s like if i have function >draw(pic),setposition(position,pic).if i want to used the data in >setposition for the draw.how i could do that. > >_________________________________________________________________ >???????? MSN Explorer: http://explorer.msn.com/lccn/ > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From bvande at po-box.mcgill.ca Mon Oct 25 06:50:12 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Mon Oct 25 06:50:21 2004 Subject: [Fwd: Re: [Tutor] about the function] Message-ID: <417C8604.7040904@po-box.mcgill.ca> Hi Lin Jin, you are welcome. You replied to me personally; it is late here, so I am forwarding it to the list. That way everyone can see your more detailed question. (You will get much better help from the entire list than from just me ;-) Best, Brian vdB -------- Original Message -------- Subject: Re: [Tutor] about the function Date: Mon, 25 Oct 2004 08:50:44 +0800 From: Lin Jin To: bvande@po-box.mcgill.ca thx for you reply.so if i want to make a tictactoe game,and i write code like this: def drawBoard(marks): """Output the board represented by marks.""" print "0|1|2 ",marks[0],"|",marks[1],"|",marks[2] print "----- ","-----" print "3|4|5 ",marks[3],"|",marks[4],"|",marks[5] print "----- ","-----" print "6|7|8 ",marks[6],"|",marks[7],"|",marks[8] def setPosition(position,symbol,marks): """Set the particular position to the player's mark symbol.""" marks=marks[:int(position)]+symbol+marks[int(position)+1:] return marks def playerTurn(symbol,marks): """Output the players'symbol choice on the board""" symbol=raw_input("Player ") position=raw_input("choose where you want to make your mark (0-8): ") marks=marks[:int(position)]+symbol+marks[int(position)+1:] return marks print "TIC TAC TOE: " print "0|1|2 "," | | " print "----- ","-----" print "3|4|5 "," | | " print "----- ","-----" print "6|7|8 "," | | " how can i implement them in order to let players alternate turn and draws on the board each turn.i dun know how to get the position and the symbol from the other function >From: Brian van den Broek >To: Lin Jin >CC: tutor@python.org >Subject: Re: [Tutor] about the function >Date: Sun, 24 Oct 2004 19:20:19 -0400 > >Lin Jin said unto the world upon 2004-10-24 18:58: > > i am new in python.just learn how to defining the function.i want to > > know that if i define three functions.how can i use read the data from > > one function to the other funtion.it;s like if i have function > > draw(pic),setposition(position,pic).if i want to used the data in > > setposition for the draw.how i could do that. > > > > _________________________________________________________________ > > Ãâ·ÑÏÂÔØ MSN Explorer: http://explorer.msn.com/lccn/ > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > >Hi Lin Jin, > >I am not sure I understand your question. But this silly example might >be helpful: > >def get_the_number_2(): > return 2 >def get_the_number_3(): > return 3 >def multiply_two_numbers(x, y): > return x * y >print multiply_two_numbers(get_the_number_2(), get_the_number_3()) > >>> >6 > >So, one way is to use a call to one function in the argument place of >another. > >You could also do: > >first_arg = get_the_number_2() >second_arg = get_the_number_3() >multiply_two_numbers(first_arg, second_arg) > >Are these techniques the sort of thing you were wanting? > >One other thing: it is much easier to read a post if a space follows >each period. Like that. :-) > >Best, > >Brian vdB > > _________________________________________________________________ ÏíÓÃÊÀ½çÉÏ×î´óµÄµç×ÓÓʼþϵͳ¡ª MSN Hotmail¡£ http://www.hotmail.com From kent_johnson at skillsoft.com Mon Oct 25 11:49:50 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Mon Oct 25 11:49:55 2004 Subject: [Tutor] MS Word and MS Excel on Linux In-Reply-To: References: <6.1.0.6.0.20041022204810.027f01f8@mail4.skillsoft.com> <6.1.0.6.0.20041023064417.028afad0@mail4.skillsoft.com> Message-ID: <6.1.0.6.0.20041025054054.02892918@mail4.skillsoft.com> OK, I think I get it now. I'm replying to the whole list so everyone can help From your original post it sounds like the Python program is going to run on a Linux machine. So I think your question is, How can a Python program running on a Linux computer find and open MS Word and Excel files located on network shares? If the Python program is running on Windows you will have an easier time of it. You can use the Python win32all library and MS COM interface to read Word and Excel files. Without COM, I know of a Java solution that reads and writes Excel files - the Jakarta Poi project - http://jakarta.apache.org/poi/ You could write your program in Jython and use this library. Poi has a Word component also but it is immature. Anyone else have an idea? Kent At 01:58 AM 10/25/2004 -0500, Anthony P. wrote: >Hi Kent, > >Basically, I am wanting to search out fileshares on a network and then >find all of the files of certain types within those file shares. I >will then open each file and create a searchable index of the files >contents. > >I think Python can help because it will allow me to easily find and >index word and excel files. > >Anthony > > >On Sat, 23 Oct 2004 06:45:18 -0400, Kent Johnson > wrote: > > I'm sorry, I still don't understand what you are trying to do, what the > > problem is, or how you think Python might help. > > > > Kent > > > > > > > > At 02:09 AM 10/23/2004 -0500, you wrote: > > >Hi Kent, > > > > > >Thanks for your response to my query. The files will be on a mixed > > >network that uses Windows, Linux, and maybe some Solaris. File sharing > > >will be enabled on all of the machines. Does this give you any more > > >insight? > > > > > >Thanks! > > >Anthony > > > > > > > > >On Fri, 22 Oct 2004 20:49:17 -0400, Kent Johnson > > > wrote: > > > > Can you give a few more details? Are the MS files on the Linux > server? What > > > > kind of computer is reading the files? Are they accessible through file > > > > sharing? > > > > > > > > Kent > > > > > > > > > > > > > > > > At 02:39 AM 10/21/2004 -0500, Anthony P. wrote: > > > > >Hello Everyone, > > > > > > > > > >Does anyone know of a module that will let me read MS Word and MS > > > > >Excel files via a network share but from a Linux server? > > > > > > > > > >Thanks, > > > > >Anthony > > > > >_______________________________________________ > > > > >Tutor maillist - Tutor@python.org > > > > >http://mail.python.org/mailman/listinfo/tutor > > > > > > > > _______________________________________________ > > > > Tutor maillist - Tutor@python.org > > > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > > _______________________________________________ > > > > > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > From s.venter at ntlworld.com Mon Oct 25 13:01:01 2004 From: s.venter at ntlworld.com (Gerhard Venter) Date: Mon Oct 25 13:00:16 2004 Subject: [Tutor] MS Word and MS Excel on Linux In-Reply-To: <6.1.0.6.0.20041025054054.02892918@mail4.skillsoft.com> References: <6.1.0.6.0.20041022204810.027f01f8@mail4.skillsoft.com> <6.1.0.6.0.20041023064417.028afad0@mail4.skillsoft.com> <6.1.0.6.0.20041025054054.02892918@mail4.skillsoft.com> Message-ID: <417CDCED.9000209@ntlworld.com> How about xlhtml and wvware. These easy to use programs can be called from os.popen, and run on Linux and Windows http://chicago.sourceforge.net/xlhtml/ wvware - http://wvware.sourceforge.net/ Gerhard Kent Johnson wrote: > OK, I think I get it now. I'm replying to the whole list so everyone > can help > > From your original post it sounds like the Python program is going to > run on a Linux machine. So I think your question is, How can a Python > program running on a Linux computer find and open MS Word and Excel > files located on network shares? > > If the Python program is running on Windows you will have an easier > time of it. You can use the Python win32all library and MS COM > interface to read Word and Excel files. > > Without COM, I know of a Java solution that reads and writes Excel > files - the Jakarta Poi project - http://jakarta.apache.org/poi/ > You could write your program in Jython and use this library. Poi has a > Word component also but it is immature. > > Anyone else have an idea? > Kent > > At 01:58 AM 10/25/2004 -0500, Anthony P. wrote: > >> Hi Kent, >> >> Basically, I am wanting to search out fileshares on a network and then >> find all of the files of certain types within those file shares. I >> will then open each file and create a searchable index of the files >> contents. >> >> I think Python can help because it will allow me to easily find and >> index word and excel files. >> >> Anthony >> >> >> On Sat, 23 Oct 2004 06:45:18 -0400, Kent Johnson >> wrote: >> > I'm sorry, I still don't understand what you are trying to do, what >> the >> > problem is, or how you think Python might help. >> > >> > Kent >> > >> > >> > >> > At 02:09 AM 10/23/2004 -0500, you wrote: >> > >Hi Kent, >> > > >> > >Thanks for your response to my query. The files will be on a mixed >> > >network that uses Windows, Linux, and maybe some Solaris. File >> sharing >> > >will be enabled on all of the machines. Does this give you any more >> > >insight? >> > > >> > >Thanks! >> > >Anthony >> > > >> > > >> > >On Fri, 22 Oct 2004 20:49:17 -0400, Kent Johnson >> > > wrote: >> > > > Can you give a few more details? Are the MS files on the Linux >> server? What >> > > > kind of computer is reading the files? Are they accessible >> through file >> > > > sharing? >> > > > >> > > > Kent >> > > > >> > > > >> > > > >> > > > At 02:39 AM 10/21/2004 -0500, Anthony P. wrote: >> > > > >Hello Everyone, >> > > > > >> > > > >Does anyone know of a module that will let me read MS Word and MS >> > > > >Excel files via a network share but from a Linux server? >> > > > > >> > > > >Thanks, >> > > > >Anthony >> > > > >_______________________________________________ >> > > > >Tutor maillist - Tutor@python.org >> > > > >http://mail.python.org/mailman/listinfo/tutor >> > > > >> > > > _______________________________________________ >> > > > Tutor maillist - Tutor@python.org >> > > > http://mail.python.org/mailman/listinfo/tutor >> > > > >> > >> > _______________________________________________ >> > >> > >> > Tutor maillist - Tutor@python.org >> > http://mail.python.org/mailman/listinfo/tutor >> > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From cyresse at gmail.com Mon Oct 25 14:12:10 2004 From: cyresse at gmail.com (Liam Clarke) Date: Mon Oct 25 14:12:13 2004 Subject: [Tutor] What is a cricket match? In-Reply-To: <200410241958.05046.scot@possum.in-berlin.de> References: <010e01c4b7d4$d5547bd0$ec5328cf@JSLAPTOP> <41790414.5050105@po-box.mcgill.ca> <200410241958.05046.scot@possum.in-berlin.de> Message-ID: Hi all, Cricket is big in New Zealand, my place of residence. Well, it was big, until our national team kept losing repeatedly, even to Zimbabwe. My theory is that cricket was designed by the British to punish countries that sought to leave the British Empire - it's played in summer, and while standing in an open field for a day may be alright in a British 'summer', in an African/Indian/Australian/West Indies/New Zealand summer, it is somewhat inadvisable. Yet they still do it. Mad dogs, Englishmen, and cricket teams... As for the actual game mechanics - There is an oval shaped large piece of flat grass, and in the centre is where the batting and bowling occur. This is where the action usually occurs. There are two teams, with 11 people from each team taking part. So, This is a top down view....you have two wickets as such, about 5 metres apart - | | And two batsmen (x's), (and there must always be 2) |x1 x2| And a bowler, who bowls from one end i.e. - |x1 x2| <-----B So, the bowler, B, runs up to roughly where batter x2 is, and throws the ball at the batsman, in this case x1. (Although he doesn't throw it, he 'bowls' it, which involves bouncing it on the ground first.) So, |x1 <--o x2|B (the 'o' is the ball, which is travelling at a ludicrous speed) Now, the bowler is trying to get the batsman 'out'. When 10 out of the 11 batters are out, then the other teams takes it's turn batting. Why only 10 out of 11? Because there must always be 2 batters. I don't know why, cricket was the prototype for Calvinball. You can be 'out' as a batter in two ways - You can hit the ball, and a member of the opposing team can catch it 'on the full', i.e. before it hits the ground. And then there's the wicket.... A wicket looks like this (front on view) batsman stands in front of wicket- [----][---][----] == == == == == == == == == The == parts are 3 wooden cylindrical poles, about 1 m high called stumps, and the [---] are solid cylinders of wood, They rest in grooves on top of the stumps. For a hit on the wicket to put you 'out', the hit has to knock a bail off. Now... the batsman doesn't actually stand in front of the wicket, he stands slightly offset, with his bat in front of the wicket. Enlarged bird's eye view - (0's are stumps, The single line is the bat, and the B is the batsman. 0 0 | 0 | BB BB The bat is held like a golf club, and it looks like this (front on view)- [] [] [ ] [ ] [ ] [ ] [__ ] You can be also out if you are 'leg before wicket'. A cricket batsman wears padding in certain areas for safety, as those balls have been clocked at 120km/hr, and they're hard. A batsman has padding on the front of his legs, from his ankles to just above his knees. If the ball hits this padding, and the umpire determines that the ball would have hit the wicket if your leg hadn't been in the way, then you are out, leg before wicket. The batsman always stands a certain distance in front of the wicket. There is usually a line marked here. This is called the 'crease'. When a batsman has the bottom of his bat behind the 'crease', then he is safe from the third kind of 'out', which is - When the batsman is not on or behind his crease(see below for why he wouldn't be), any member of the opposing team can throw or touch the wickets with the ball, and if a stump is knocked off, the batsman is out. So basically, the bowler is trying to hit the wicket, and you are trying to stop him by hitting the ball, and if possible, scoring some points by getting 'runs'. Runs? Well, let's step back a bit to |x1 <--o x2|B The bowler (B) has just bowled the ball to batter x1. Now that we know what happens if x1 misses the ball, let's see what happens if he hits it. A run is scored liked this - |x1--> <--x2| |x2 x1| So one run is scored, when the batters swap ends. Now, they can do this for as long as they like after the ball has been hit, and each successful swap is a run scored. But, once they leave their 'crease' to run to the other wicket (they both have creases), both of them are vulnerable to being made 'out'. They don't have to run; the batter can hit the ball, and choose whether or not to attempt to score a run. Obviously if the ball rolled straight to a nearby fielder, it would be silly to leave your crease. And that's how you score runs. Hit the ball, run backwards and forth, hit the ball again... You can also score runs by hitting the ball well. If you hit it out of the field 'on the full' i.e. it doesn't touch the ground before leaving the field, you score 6 runs. This has given the phrase 'hit for 6" or 'knocked it for 6" to indicate that someone has put in a lot of effort and suceeded. But, being 'knocked for 6' means that you have taken a blow. If you hit the ball, and it leaves the field, (the edge of the field is determined by a line drawn on the grass around the field; this is called the boundary), but it touches the ground inside the boundary, then you score 4 points. There are a whole lot of cricket fielding positions, with very silly names - "I'm silly mid-wicket off", but that's just funny names for standing in a field trying to catch a ball. As for the actual scoring, in one day games, it's the number of runs scored that matters. (I believe.) For multi day games, it the number of runs AND the number of batters who were 'not out' that count, and it involves a very arcane formula that I can't understand. Hope that helps, and in next week's 1000 word essay, we'll discuss rugby. Regards, Liam Clarke Resident of Otautahi in the South Island of Aotearoa/New Zealand. Who also hates cricket with a loathing, unless we're winning. On Sun, 24 Oct 2004 19:58:04 +0000, Scot W. Stevenson wrote: > Hello Brian, > > > Cricket is a sport notable chiefly for its ability to make baseball look > > exciting. ;-) > > A British friend of the family, pressed for the rules of cricket, under > duress finally admitted that there are none: The British, he confessed, just > pretend that there are rules and always make sure that they sound terribly, > terribly complicated so that everybody else thinks that the British are so > much more intelligent than they are. > > To that we replied: Well, if that is so, why does India keep winning? > > Cheers, > Y, Scot > > -- > In the real version, Han Solo shot first > Scot W. Stevenson Panketal, Germany > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From lonetwin at gmail.com Mon Oct 25 15:33:20 2004 From: lonetwin at gmail.com (Steve) Date: Mon Oct 25 15:33:26 2004 Subject: [Tutor] What is a cricket match? In-Reply-To: <41790414.5050105@po-box.mcgill.ca> References: <010e01c4b7d4$d5547bd0$ec5328cf@JSLAPTOP> <41790414.5050105@po-box.mcgill.ca> Message-ID: <5a309bd30410250633207ce9a2@mail.gmail.com> Some more trivia ... > (To be fair, it has also given English a number of nice idioms -- > "sticky wicket" being a favourite.) Cricket used to be played by the young men coming from the more affluent families of the British empire and so was also called 'The Gentleman's' game'. The fair play and spirit of the game led to the idiom, 'that's not cricket', to describe anything unfair. Regards Steve From rmkrauter at yahoo.com Mon Oct 25 15:45:08 2004 From: rmkrauter at yahoo.com (Rich Krauter) Date: Mon Oct 25 15:45:01 2004 Subject: [Tutor] nested lists of data In-Reply-To: References: <41748167.2060403@yahoo.com> Message-ID: <417D0364.8060706@yahoo.com> Scott Melnyk wrote: > Hello Rich! > Question about the program, I would like it pulled out only if it is > in ALL the transcripts for a given gene. Does this not pull out exons > that match in any two transcripts? > > So if there are four transcripts it would have to be in all four to be > pulled out. > > I had received a past demo with lists from Kent Johnson which was the > first I had heard of sets > First some raw data: > [sets examples cut] > Which is what I have based my plans on. Sorry to be new to this and a > bit slow in picking it up, No apologies necessary - and you are right about what you think it does; you seem to have picked it up pretty quickly to me. :) [code snippets cut] > i think it would pull out any intersection between two transcripts. That's right - sorry, I misunderstood what you needed to do. Try something like this instead: def getintersections(fname='D:/rk/exons.txt'): exonSets = {} f = open(fname) for line in f: if line.startswith('ENS'): parts = line.split() gene = parts[0] transcript = parts[1] exons = parts[2:] exonSets.setdefault(gene, sets.Set(exons)).intersection(sets.Set(exons)) return exonSets Hope that helps. Rich From jeffpeery at yahoo.com Mon Oct 25 18:09:27 2004 From: jeffpeery at yahoo.com (Jeff Peery) Date: Mon Oct 25 18:09:31 2004 Subject: [Tutor] Binary math? In-Reply-To: <417D0364.8060706@yahoo.com> Message-ID: <20041025160927.64475.qmail@web60107.mail.yahoo.com> Hello, will python work with binary math? i.e., add subtract binary numbers? is there a specific type that I have to use to define a binary number? thanks. Jeff -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20041025/103a3594/attachment.htm From bill.mill at gmail.com Mon Oct 25 18:23:57 2004 From: bill.mill at gmail.com (Bill Mill) Date: Mon Oct 25 18:24:00 2004 Subject: [Tutor] Binary math? In-Reply-To: <20041025160927.64475.qmail@web60107.mail.yahoo.com> References: <417D0364.8060706@yahoo.com> <20041025160927.64475.qmail@web60107.mail.yahoo.com> Message-ID: <797fe3d40410250923383ecd3@mail.gmail.com> Jeff, There isn't a built-in type, but it's fairly easy to do. Have a look at http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/219300 for some ideas on how to do it. If you don't understand those, ask and I'll try to clarify them for you. Peace Bill Mill bill.mill at gmail.com On Mon, 25 Oct 2004 09:09:27 -0700 (PDT), Jeff Peery wrote: > > > > > Hello, > > will python work with binary math? i.e., add subtract binary numbers? is > there a specific type that I have to use to define a binary number? thanks. > > > > Jeff > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > > From jeffpeery at yahoo.com Mon Oct 25 18:54:07 2004 From: jeffpeery at yahoo.com (Jeff Peery) Date: Mon Oct 25 18:54:11 2004 Subject: [Tutor] Binary math? In-Reply-To: <797fe3d40410250923383ecd3@mail.gmail.com> Message-ID: <20041025165407.60833.qmail@web60104.mail.yahoo.com> Bill, I am confused, could you explain the first line of code. I can probably then figure out the remaining. all I need to do is find the difference of two binary numbers, converting them to decimal is easy to do. here is the first line of code from the link you sent: # bstr_pos: only positive integers # zero -> '' # negative -> '' bstr_pos = lambda n: n>0 and bstr_pos(n>>1)+str(n&1) or '' thanks. Jeff Bill Mill wrote: Jeff, There isn't a built-in type, but it's fairly easy to do. Have a look at http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/219300 for some ideas on how to do it. If you don't understand those, ask and I'll try to clarify them for you. Peace Bill Mill bill.mill at gmail.com On Mon, 25 Oct 2004 09:09:27 -0700 (PDT), Jeff Peery wrote: > > > > > Hello, > > will python work with binary math? i.e., add subtract binary numbers? is > there a specific type that I have to use to define a binary number? thanks. > > > > Jeff > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > > _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20041025/46b9fc19/attachment.htm From dyoo at hkn.eecs.berkeley.edu Mon Oct 25 20:01:01 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Oct 25 20:01:04 2004 Subject: [Tutor] Binary math? In-Reply-To: <20041025160927.64475.qmail@web60107.mail.yahoo.com> Message-ID: On Mon, 25 Oct 2004, Jeff Peery wrote: > will python work with binary math? Hi Jeff, Just to clarify: most computers work on the principle of binary. There's a layer of abstraction that hides the bit-twiddling from us. When we say something like 42, the computer is using a bit pattern to represent the number 42: 42 <====> 101010 (2**5 + 2**3 + 2**1) Python (and most computer systems) will do work using the bit-patterns, and a separate program converts those bit-patterns back into a decimal representation that's comfortable for humans. > i.e., add subtract binary numbers? is there a specific type that I have > to use to define a binary number? thanks. What are you trying to do? If you're trying to understand how binary math works, I'd recommend looking at "Code": http://www.charlespetzold.com/code/index.html And if you have a string with the proper bit pattern, then you can use the int() builtin: ### >>> int('101010', 2) 42 ### But I have to admit: I'm still a little confused at what you're asking. Please tell us more why you're trying to do binary arithmetic, so we can give better help. Good luck to you! From bill.mill at gmail.com Mon Oct 25 19:55:29 2004 From: bill.mill at gmail.com (Bill Mill) Date: Mon Oct 25 20:02:17 2004 Subject: [Tutor] Binary math? In-Reply-To: <20041025165407.60833.qmail@web60104.mail.yahoo.com> References: <797fe3d40410250923383ecd3@mail.gmail.com> <20041025165407.60833.qmail@web60104.mail.yahoo.com> Message-ID: <797fe3d40410251055b956b3c@mail.gmail.com> Jeff, Ok, first off, if I understand you correctly, what you want is to find the difference between, for example, 1001101 and 10101011? If so, try a look at this recipe: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/111286 . (I don't normally give all my answers in recipes, but I happened to find 2 that were relevant) This code will let you convert it into an integer, perform the subtraction, and reformat it as a binary. Again, if you don't understand the code, ask me and I'll explain it as best I can. Secondly, I knew that the code presented at the link I gave you was confusing, so I'll try and translate it for you. Even if it wasn't what you were looking for; it may help you wrap your head around python a little better. First off, the "lambda" keyword means make an unnamed function and return it. Thus, we can rewrite the code in a similar, but far simpler way like: def bstr_pos(n): return n > 0 and bstr_pos(n>>1)+str(n&1) or '' The first bit of logic is "n > 0 and ...". What this means is that if n<0, the 'and' is false, so don't evaluate the second part of the 'and' (since it's already false). Thus, we can rewrite the function even more clearly: def bstr_pos(n): if n > 0: return bstr_pos(n >> 1) + str(n & 1) else: return '' Now it is easy to see that we have a recursive function. That is, the bstr_pos function calls itself if n > 0, but it calls itself on the next binary digit of n, which is accomplished with the '>>' operator, called the 'right shift' operator. Let's look at this briefly in the interpreter: >>> 16 >> 1 8 >>> 15 >> 1 7 The binary representation of 16 is '10000' (16 = 2**4). When we right shift, we turn '10000' into '1000' simply by dropping the last digit. '1000' is the binary representation of 8. Similarly, the binary representation of 15 is '1111', so 15>>1 turns '1111' into '111', which is the binary representation of 7. So, we call the bstr_pos function recursively for each power of 2 in the integer n. The second part of the equation, str(n & 1), returns '1' if the last binary digit of n is 1, and '0' if the last digit is 0. '&' is the binary 'and' operator. So, here's what happens overall: if n > 0, recursively call bstr_pos for each power of 2 in n, then convert the last binary digit of n into a string, and append them all together using the '+' operator on the strings. When n <= 0, just return the null string. Hope this helps. Peace Bill Mill bill.mill at gmail.com On Mon, 25 Oct 2004 09:54:07 -0700 (PDT), Jeff Peery wrote: > > Bill, I am confused, could you explain the first line of code. I can > probably then figure out the remaining. all I need to do is find the > difference of two binary numbers, converting them to decimal is easy to do. > here is the first line of code from the link you sent: > > # bstr_pos: only positive integers > # zero -> '' > # negative -> '' > > bstr_pos = lambda n: n>0 and bstr_pos(n>>1)+str(n&1) or '' > > thanks. > Jeff > > Bill Mill wrote: > > > Jeff, > > There isn't a built-in type, but it's fairly easy to do. Have a look > at http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/219300 for > some ideas on how to do it. If you don't understand those, ask and > I'll try to clarify them for you. > > Peace > Bill Mill > bill.mill at gmail.com > > > On Mon, 25 Oct 2004 09:09:27 -0700 (PDT), Jeff Peery > wrote: > > > > > > > > > > Hello, > > > > will python work with binary math? i.e., add subtract binary numbers? is > > there a specific type that I have to use to define a binary number? > thanks. > > > > > > > > Jeff > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From klappnase at freenet.de Mon Oct 25 21:15:55 2004 From: klappnase at freenet.de (Michael Lange) Date: Mon Oct 25 21:11:29 2004 Subject: [Tutor] How to find language name Message-ID: <20041025211555.30f0316c.klappnase@freenet.de> Hello tutors, I'm struggling here with a problem trying to determine the current language name. I need the ISO 639 style two letter abbreviations, like 'en' for english etc. I tried using locale.getdefaultlocale() and it seems to do just what I want: >>> import locale >>> locale.getdefaultlocale() ['de_DE', 'de'] >>> locale.getlocale() ['de_DE', 'ISO8859-1'] It looks like I could just do: langName = locale.getdefaultlocale()[1] Unfortunately the documentation for the locale module confuses me at this point: getdefaultlocale([envvars]) Tries to determine the default locale settings and returns them as a tuple of the form (language code, encoding). ^^^^^^^^ getlocale([category]) Returns the current setting for the given locale category as sequence containing language code, encoding ^^^^^^^^ My question now, is the behavior of getdefaultlocale() platform specific, in other words, may it happen that getdefaultlocale()[1] will be something like 'ISO8859-1' ? (BTW, my app is supposed to run on *nix systems exclusively.) Any hints are much appreciated. Thanks Michael From bill.mill at gmail.com Mon Oct 25 21:09:57 2004 From: bill.mill at gmail.com (Bill Mill) Date: Mon Oct 25 21:17:18 2004 Subject: [Tutor] Binary math? In-Reply-To: References: <20041025160927.64475.qmail@web60107.mail.yahoo.com> Message-ID: <797fe3d4041025120921d0ef31@mail.gmail.com> Danny, I didn't know that int() trick; that's a nice one. Thanks for showing that. Peace Bill Mill bill.mill at gmail.com On Mon, 25 Oct 2004 11:01:01 -0700 (PDT), Danny Yoo wrote: > > > On Mon, 25 Oct 2004, Jeff Peery wrote: > > > will python work with binary math? > > Hi Jeff, > > Just to clarify: most computers work on the principle of binary. There's > a layer of abstraction that hides the bit-twiddling from us. When we say > something like 42, the computer is using a bit pattern to represent the > number 42: > > 42 <====> 101010 > > (2**5 + 2**3 + 2**1) > > Python (and most computer systems) will do work using the bit-patterns, > and a separate program converts those bit-patterns back into a decimal > representation that's comfortable for humans. > > > > i.e., add subtract binary numbers? is there a specific type that I have > > to use to define a binary number? thanks. > > What are you trying to do? If you're trying to understand how binary math > works, I'd recommend looking at "Code": > > http://www.charlespetzold.com/code/index.html > > And if you have a string with the proper bit pattern, then you can use the > int() builtin: > > ### > >>> int('101010', 2) > 42 > ### > > But I have to admit: I'm still a little confused at what you're asking. > Please tell us more why you're trying to do binary arithmetic, so we can > give better help. > > Good luck to you! > > _______________________________________________ > > > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From alipolatel at yahoo.com Mon Oct 25 21:32:19 2004 From: alipolatel at yahoo.com (Ali Polatel) Date: Mon Oct 25 21:32:24 2004 Subject: [Tutor] Linux/Windows Message-ID: <20041025193219.43718.qmail@web61006.mail.yahoo.com> Dear tutors, I have written a programme for windows (no GUI but some commands which create and write things in text files) I want to modify this programme so that it will work in Linux... I think there is no need to change the usual functions and classes all I need to do is a modification in creating files outside the programme. If anyone who knows how to do this in Linux can you tell me the equivalent of the function in Linux?: "go=open('c:/test.txt','w')" go.write('Hello world\n') Another thing is in windows the programme can understand it self-directory with os.getcwd() command...Can we also do it in Linux?I mean for example when I do: import os os.getcwd() the interpreter gives "c:\python23" How to do same in Linux? And I am not someone who is acquianted with Linux..Can someone create directories in Linux?(like the mkdir() function in windows) Thanks all for your help Ali Polatel --------------------------------- Do you Yahoo!? vote.yahoo.com - Register online to vote today! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20041025/a62ddc6a/attachment.html From alipolatel at yahoo.com Mon Oct 25 21:32:36 2004 From: alipolatel at yahoo.com (Ali Polatel) Date: Mon Oct 25 21:32:39 2004 Subject: [Tutor] Linux/Windows Message-ID: <20041025193236.43842.qmail@web61006.mail.yahoo.com> Dear tutors, I have written a programme for windows (no GUI but some commands which create and write things in text files) I want to modify this programme so that it will work in Linux... I think there is no need to change the usual functions and classes all I need to do is a modification in creating files outside the programme. If anyone who knows how to do this in Linux can you tell me the equivalent of the function in Linux?: "go=open('c:/test.txt','w')" go.write('Hello world\n') Another thing is in windows the programme can understand it self-directory with os.getcwd() command...Can we also do it in Linux?I mean for example when I do: import os os.getcwd() the interpreter gives "c:\python23" How to do same in Linux? And I am not someone who is acquianted with Linux..Can someone create directories in Linux?(like the mkdir() function in windows) Thanks all for your help Ali Polatel --------------------------------- Do you Yahoo!? vote.yahoo.com - Register online to vote today! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20041025/3019b2af/attachment.htm From RenX99 at gmail.com Tue Oct 26 01:53:22 2004 From: RenX99 at gmail.com (Rene Lopez) Date: Tue Oct 26 01:53:25 2004 Subject: [Tutor] variable from input? Message-ID: <555128ce04102516535a018776@mail.gmail.com> is it possible to have the user input something with a raw_input command, and then base upon the input make that into the name of a variable? for example: answer = raw_input("what is your name?") user types in Rene, and some how we end up with a variable named Rene? -- Rene From cyresse at gmail.com Tue Oct 26 01:53:38 2004 From: cyresse at gmail.com (Liam Clarke) Date: Tue Oct 26 01:53:42 2004 Subject: [Tutor] How to find language name In-Reply-To: <20041025211555.30f0316c.klappnase@freenet.de> References: <20041025211555.30f0316c.klappnase@freenet.de> Message-ID: Hi Michael, quoted from docs --- To maintain compatibility with other platforms, not only the LANG variable is tested, but a list of variables given as envvars parameter. The first found to be defined will be used. envvars defaults to the search path used in GNU gettext; it must always contain the variable name "LANG". The GNU gettext search path contains 'LANGUAGE', 'LC_ALL', 'LC_CTYPE', and 'LANG', in that order. Unless I'm wrong, and someone will let me know very shortly if I am; the returned tuple from getdefaultlocale will always be (language code, encoding) Regards, Liam Clarke On Mon, 25 Oct 2004 21:15:55 +0200, Michael Lange wrote: > Hello tutors, > > I'm struggling here with a problem trying to determine the current language name. > I need the ISO 639 style two letter abbreviations, like 'en' for english etc. > I tried using locale.getdefaultlocale() and it seems to do just what I want: > > >>> import locale > >>> locale.getdefaultlocale() > ['de_DE', 'de'] > >>> locale.getlocale() > ['de_DE', 'ISO8859-1'] > > It looks like I could just do: > > langName = locale.getdefaultlocale()[1] > > Unfortunately the documentation for the locale module confuses me at this point: > > getdefaultlocale([envvars]) > > Tries to determine the default locale settings and returns them as a tuple of the form (language code, encoding). > ^^^^^^^^ > getlocale([category]) > > Returns the current setting for the given locale category as sequence containing language code, encoding > ^^^^^^^^ > My question now, is the behavior of getdefaultlocale() platform specific, in other words, may it happen > that getdefaultlocale()[1] will be something like 'ISO8859-1' ? (BTW, my app is supposed to run on *nix systems > exclusively.) > > Any hints are much appreciated. Thanks > > Michael > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From cyresse at gmail.com Tue Oct 26 02:12:24 2004 From: cyresse at gmail.com (Liam Clarke) Date: Tue Oct 26 02:12:27 2004 Subject: [Tutor] variable from input? In-Reply-To: <555128ce04102516535a018776@mail.gmail.com> References: <555128ce04102516535a018776@mail.gmail.com> Message-ID: That's an interesting one... You could have the variable contained in a separate module, and then when the user enters the variable name, have another function write that variable name throughout the other module, and then reimport the other module, but that would only work if the variable were entirely contained within that module. But I've wondered that myself, but the implementation doesn't seem to be worth the effort. Once again, I could be entirely wrong. Liam On Mon, 25 Oct 2004 19:53:22 -0400, Rene Lopez wrote: > is it possible to have the user input something with a raw_input > command, and then base upon the input make that into the name of a > variable? > > for example: > > answer = raw_input("what is your name?") > > user types in Rene, and some how we end up with a variable named Rene? > -- > > Rene > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From kent_johnson at skillsoft.com Tue Oct 26 02:38:38 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Tue Oct 26 02:38:44 2004 Subject: [Tutor] variable from input? In-Reply-To: <555128ce04102516535a018776@mail.gmail.com> References: <555128ce04102516535a018776@mail.gmail.com> Message-ID: <6.1.0.6.0.20041025202710.02919ce0@mail4.skillsoft.com> I'm hesitant to answer this question because I'm not sure if you understand what you are asking for or if you are confused about variables and assignment. If you just want to remember the name the user entered, it is in the name variable and you can access it from there. That is the more common usage: >>> name = raw_input('What is your name? ') What is your name? Kent >>> print name Kent But if you really want to you can access the global namespace directly with the globals() function. At first there is not much there: >>> globals() {'__builtins__': , '__name__': '__main__', '__doc__': None} Assignment adds a new entry to the namespace: >>> x = 3 >>> globals() {'__builtins__': , '__name__': '__main__', '__doc__': None, 'x': 3} It works the other way around as well - adding a key to globals() creates a named variable: >>> globals()['Rene'] = 'Rene' >>> Rene 'Rene' >>> name = raw_input('What is your name? ') What is your name? Kent >>> globals()[name] = name >>> Kent 'Kent' :-) Kent At 07:53 PM 10/25/2004 -0400, Rene Lopez wrote: >is it possible to have the user input something with a raw_input >command, and then base upon the input make that into the name of a >variable? > >for example: > >answer = raw_input("what is your name?") > >user types in Rene, and some how we end up with a variable named Rene? >-- > >Rene >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From jeff at ccvcorp.com Tue Oct 26 02:46:32 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Tue Oct 26 02:44:21 2004 Subject: [Tutor] variable from input? In-Reply-To: References: <555128ce04102516535a018776@mail.gmail.com> Message-ID: <417D9E68.5000508@ccvcorp.com> Liam Clarke wrote: >On Mon, 25 Oct 2004 19:53:22 -0400, Rene Lopez wrote: > > >>is it possible to have the user input something with a raw_input >>command, and then base upon the input make that into the name of a >>variable? >> >>for example: >> >>answer = raw_input("what is your name?") >> >>user types in Rene, and some how we end up with a variable named Rene? >> >That's an interesting one... > >You could have the variable contained in a separate module, [...] > >But I've wondered that myself, but the implementation doesn't seem to >be worth the effort. >Once again, I could be entirely wrong. > > IMHO, you're not wrong. It seems to me that, when one is looking at creating variables with names based on user input, then one should probably be looking at using either a dictionary or a class (or possibly both) instead. user_input = {} answer = raw_input("What is your name?") user_input[answer] = SomeUserSpecificInfo() Variable names only have significance to someone who's actually looking at the code (whether reading it or writing it). This means that it makes no sense to have a variable name depend on something that happens only at runtime -- you want the variable name(s) to be consistent every time the program runs. On the other hand, if you want your code to have a way to refer to a chunk of information based on something that a user types in, then dictionaries are exactly what you want. All of the information is held in a reliable variable name that the programmer can easily find, and it's stored in a way that maps the information (dictionary value) to the "name" given by the user (dictionary key) in a simple and straightforward manner. It prevents the potential problem of a user entering a variable name that's already used by the program. (Consider what might happen, for instance, if the user entered their name as "print", which is a reserved keyword and thus a syntax error to use as a variable name... or if the user entered a name that just happened to be the same as one of the functions in your program...) It also makes it very easy to store multiple copies of the information -- for example, one variable for each of several different users -- and to act on each set of data in a consistent and rational manner. (In the O.P.'s example, it would be relatively difficult to run a function for each of Rene and Thomas and Eric and John; with a dictionary, it's trivial to put the function call into a for loop.) Jeff Shannon Technician/Programmer Credit International From gew75 at hotmail.com Tue Oct 26 02:48:28 2004 From: gew75 at hotmail.com (Glen Wheeler) Date: Tue Oct 26 02:49:04 2004 Subject: [Tutor] variable from input? References: <555128ce04102516535a018776@mail.gmail.com> Message-ID: Howdy. Firstly, I cannot think of any reason why you would want to do this instead of simply having a ``name'' variable holding that person's name. Anyway, the following would work: >>> s = raw_input("Don't try this at home...") >>> exec(s+" = ''") >>> fred '' >>> But don't do it... Glen ----- Original Message ----- From: "Liam Clarke" To: "Python Tutor" Sent: Tuesday, October 26, 2004 10:12 AM Subject: Re: [Tutor] variable from input? > That's an interesting one... > > You could have the variable contained in a separate module, and then > when the user enters the variable name, have another function write > that variable name throughout the other module, and then reimport the > other module, but that would only work if the variable were entirely > contained within that module. > > But I've wondered that myself, but the implementation doesn't seem to > be worth the effort. > Once again, I could be entirely wrong. > > Liam > > > On Mon, 25 Oct 2004 19:53:22 -0400, Rene Lopez wrote: >> is it possible to have the user input something with a raw_input >> command, and then base upon the input make that into the name of a >> variable? >> >> for example: >> >> answer = raw_input("what is your name?") >> >> user types in Rene, and some how we end up with a variable named Rene? >> -- >> >> Rene >> _______________________________________________ >> Tutor maillist - Tutor@python.org >> http://mail.python.org/mailman/listinfo/tutor >> > > > -- > 'There is only one basic human right, and that is to do as you damn well > please. > And with it comes the only basic human duty, to take the consequences. > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From carroll at tjc.com Tue Oct 26 02:49:33 2004 From: carroll at tjc.com (Terry Carroll) Date: Tue Oct 26 02:49:40 2004 Subject: [Tutor] variable from input? In-Reply-To: <555128ce04102516535a018776@mail.gmail.com> Message-ID: On Mon, 25 Oct 2004, Rene Lopez wrote: > is it possible to have the user input something with a raw_input > command, and then base upon the input make that into the name of a > variable? > > for example: > > answer = raw_input("what is your name?") > > user types in Rene, and some how we end up with a variable named Rene? I don't know the answer to this, and I suspect that if it's possible, it's not straightforward. However, in general, anytime you're looking for something like this, the real answer is that you'd be better off using a dictionary, where the variable value is used as a key to the dictionary, i.e., The dictionary can index a number of objects of as much or as little complexity as you require, From bill.mill at gmail.com Tue Oct 26 03:29:48 2004 From: bill.mill at gmail.com (Bill Mill) Date: Tue Oct 26 03:29:52 2004 Subject: [Tutor] Linux/Windows In-Reply-To: <20041025193219.43718.qmail@web61006.mail.yahoo.com> References: <20041025193219.43718.qmail@web61006.mail.yahoo.com> Message-ID: <797fe3d40410251829511ecef5@mail.gmail.com> Ali, all the functions you mentioned should work just fine in linux. Linux filesystems are very similar to windows filesystems. There are, however, no c: or d: drives in linux. Instead, every file is contained below one main ('root') directory, called '/'. As such, the file you open will have to be something like '/var/temp/myfile.tmp'. For more info, read http://www.tldp.org/LDP/Linux-Filesystem-Hierarchy/html/index.html . I haven't read it, but I looked it over briefly and it seemed to contain the important information about linux filesystems. Peace Bill Mill bill.mill at gmail.com On Mon, 25 Oct 2004 12:32:19 -0700 (PDT), Ali Polatel wrote: > > Dear tutors, > I have written a programme for windows (no GUI but some commands which > create and write things in text files) > I want to modify this programme so that it will work in Linux... > I think there is no need to change the usual functions and classes all I > need to do is a modification in creating files outside the programme. > If anyone who knows how to do this in Linux can you tell me the equivalent > of the function in Linux?: > "go=open('c:/test.txt','w')" > go.write('Hello world\n') > Another thing is in windows the programme can understand it self-directory > with os.getcwd() command...Can we also do it in Linux?I mean for example > when I do: > import os > os.getcwd() > the interpreter gives "c:\python23" > How to do same in Linux? > And I am not someone who is acquianted with Linux..Can someone create > directories in Linux?(like the mkdir() function in windows) > Thanks all for your help > Ali Polatel > > ________________________________ > Do you Yahoo!? > vote.yahoo.com - Register online to vote today! > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > > From chandrakirti at gmail.com Tue Oct 26 04:01:48 2004 From: chandrakirti at gmail.com (Lloyd Hugh Allen) Date: Tue Oct 26 04:03:28 2004 Subject: Fwd: [Tutor] variable from input? In-Reply-To: <24d253d90410251901560d64ad@mail.gmail.com> References: <555128ce04102516535a018776@mail.gmail.com> <24d253d90410251901560d64ad@mail.gmail.com> Message-ID: <24d253d904102519017ac6887b@mail.gmail.com> Forgot to hit the "a" key... ---------- Forwarded message ---------- From: Lloyd Hugh Allen Date: Mon, 25 Oct 2004 22:01:26 -0400 Subject: Re: [Tutor] variable from input? To: Glen Wheeler Perhaps the variable will later be a class with attributes describing a person, and it will make sense for each person to be her/his own variable? I could see that. You can maybe even be kind of sort of safe if you can ensure that "s" is composed solely of alphanumeric characters (parens and equals are definitely dangerous; space would probably provoke an exception)... On Tue, 26 Oct 2004 10:48:28 +1000, Glen Wheeler wrote: > > Howdy. > > Firstly, I cannot think of any reason why you would want to do this > instead of simply having a ``name'' variable holding that person's name. > > Anyway, the following would work: > > >>> s = raw_input("Don't try this at home...") > >>> exec(s+" = ''") > >>> fred > '' > >>> > > But don't do it... > > Glen > > > > ----- Original Message ----- > From: "Liam Clarke" > To: "Python Tutor" > Sent: Tuesday, October 26, 2004 10:12 AM > Subject: Re: [Tutor] variable from input? > > > That's an interesting one... > > > > You could have the variable contained in a separate module, and then > > when the user enters the variable name, have another function write > > that variable name throughout the other module, and then reimport the > > other module, but that would only work if the variable were entirely > > contained within that module. > > > > But I've wondered that myself, but the implementation doesn't seem to > > be worth the effort. > > Once again, I could be entirely wrong. > > > > Liam > > > > > > On Mon, 25 Oct 2004 19:53:22 -0400, Rene Lopez wrote: > >> is it possible to have the user input something with a raw_input > >> command, and then base upon the input make that into the name of a > >> variable? > >> > >> for example: > >> > >> answer = raw_input("what is your name?") > >> > >> user types in Rene, and some how we end up with a variable named Rene? > >> -- > >> > >> Rene > >> _______________________________________________ > >> Tutor maillist - Tutor@python.org > >> http://mail.python.org/mailman/listinfo/tutor > >> > > > > > > -- > > 'There is only one basic human right, and that is to do as you damn well > > please. > > And with it comes the only basic human duty, to take the consequences. > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From jeff at ccvcorp.com Tue Oct 26 04:17:11 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Tue Oct 26 04:15:02 2004 Subject: Fwd: [Tutor] variable from input? In-Reply-To: <24d253d904102519017ac6887b@mail.gmail.com> References: <555128ce04102516535a018776@mail.gmail.com> <24d253d90410251901560d64ad@mail.gmail.com> <24d253d904102519017ac6887b@mail.gmail.com> Message-ID: <417DB3A7.1050703@ccvcorp.com> Lloyd Hugh Allen wrote: >Perhaps the variable will later be a class with attributes describing >a person, and it will make sense for each person to be her/his own >variable? I could see that. > > But I fail to see how an assortment of unrelated variables with unpredictable names could possibly be an improvement over storing those class instances in a list or dictionary. A dictionary makes them easier to store, easier to keep track of, and easier to access. Creating variables with names from user input is going to be messier, more confusing, and *much* more likely to interfere with other aspects of the program. (How many instances of this person class do we have, and what are their names? In the user-generated variable names plan, you have to manually track all of this. With a dict, you just use len(mydict) and mydict.keys(). Indeed, in order to track the names that are in use, you'd probably need to keep a list of them -- so instead of an assortment of variables and a list of variable names, why not just use a list of class instances that have a name as an attribute, or a dict of class instances with the name as the key?) Jeff Shannon Technician/Programmer Credit International From jeffpeery at yahoo.com Tue Oct 26 05:49:57 2004 From: jeffpeery at yahoo.com (Jeffrey Thomas Peery) Date: Tue Oct 26 05:50:02 2004 Subject: [Tutor] Binary math? In-Reply-To: Message-ID: <20041026035000.2090B1E4002@bag.python.org> Thanks for the help. Well I am aware of how computers use binary and such, although I have to do a little arithmetic with binary numbers, I am an engineer and I have some test data that is in hexadecimal and I need to convert that to binary and that to regular base ten numbers. I was hoping that there was a python module or commands that would do the binary addition/subtraction multiplication and such. I wrote a program that seems to work ok for what I need but I used a lot of code to do it, I was hoping for something easier to read. If you have any thoughts please let me know. Thanks. J -----Original Message----- From: Danny Yoo [mailto:dyoo@hkn.eecs.berkeley.edu] Sent: Monday, October 25, 2004 11:01 AM To: Jeff Peery Cc: tutor@python.org Subject: Re: [Tutor] Binary math? On Mon, 25 Oct 2004, Jeff Peery wrote: > will python work with binary math? Hi Jeff, Just to clarify: most computers work on the principle of binary. There's a layer of abstraction that hides the bit-twiddling from us. When we say something like 42, the computer is using a bit pattern to represent the number 42: 42 <====> 101010 (2**5 + 2**3 + 2**1) Python (and most computer systems) will do work using the bit-patterns, and a separate program converts those bit-patterns back into a decimal representation that's comfortable for humans. > i.e., add subtract binary numbers? is there a specific type that I have > to use to define a binary number? thanks. What are you trying to do? If you're trying to understand how binary math works, I'd recommend looking at "Code": http://www.charlespetzold.com/code/index.html And if you have a string with the proper bit pattern, then you can use the int() builtin: ### >>> int('101010', 2) 42 ### But I have to admit: I'm still a little confused at what you're asking. Please tell us more why you're trying to do binary arithmetic, so we can give better help. Good luck to you! From jeffpeery at yahoo.com Tue Oct 26 05:54:44 2004 From: jeffpeery at yahoo.com (Jeffrey Thomas Peery) Date: Tue Oct 26 05:54:48 2004 Subject: [Tutor] Binary math? In-Reply-To: <797fe3d40410251055b956b3c@mail.gmail.com> Message-ID: <20041026035446.644761E4002@bag.python.org> That's a big help, thanks! J -----Original Message----- From: Bill Mill [mailto:bill.mill@gmail.com] Sent: Monday, October 25, 2004 10:55 AM To: Jeff Peery Cc: tutor@python.org Subject: Re: [Tutor] Binary math? Jeff, Ok, first off, if I understand you correctly, what you want is to find the difference between, for example, 1001101 and 10101011? If so, try a look at this recipe: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/111286 . (I don't normally give all my answers in recipes, but I happened to find 2 that were relevant) This code will let you convert it into an integer, perform the subtraction, and reformat it as a binary. Again, if you don't understand the code, ask me and I'll explain it as best I can. Secondly, I knew that the code presented at the link I gave you was confusing, so I'll try and translate it for you. Even if it wasn't what you were looking for; it may help you wrap your head around python a little better. First off, the "lambda" keyword means make an unnamed function and return it. Thus, we can rewrite the code in a similar, but far simpler way like: def bstr_pos(n): return n > 0 and bstr_pos(n>>1)+str(n&1) or '' The first bit of logic is "n > 0 and ...". What this means is that if n<0, the 'and' is false, so don't evaluate the second part of the 'and' (since it's already false). Thus, we can rewrite the function even more clearly: def bstr_pos(n): if n > 0: return bstr_pos(n >> 1) + str(n & 1) else: return '' Now it is easy to see that we have a recursive function. That is, the bstr_pos function calls itself if n > 0, but it calls itself on the next binary digit of n, which is accomplished with the '>>' operator, called the 'right shift' operator. Let's look at this briefly in the interpreter: >>> 16 >> 1 8 >>> 15 >> 1 7 The binary representation of 16 is '10000' (16 = 2**4). When we right shift, we turn '10000' into '1000' simply by dropping the last digit. '1000' is the binary representation of 8. Similarly, the binary representation of 15 is '1111', so 15>>1 turns '1111' into '111', which is the binary representation of 7. So, we call the bstr_pos function recursively for each power of 2 in the integer n. The second part of the equation, str(n & 1), returns '1' if the last binary digit of n is 1, and '0' if the last digit is 0. '&' is the binary 'and' operator. So, here's what happens overall: if n > 0, recursively call bstr_pos for each power of 2 in n, then convert the last binary digit of n into a string, and append them all together using the '+' operator on the strings. When n <= 0, just return the null string. Hope this helps. Peace Bill Mill bill.mill at gmail.com On Mon, 25 Oct 2004 09:54:07 -0700 (PDT), Jeff Peery wrote: > > Bill, I am confused, could you explain the first line of code. I can > probably then figure out the remaining. all I need to do is find the > difference of two binary numbers, converting them to decimal is easy to do. > here is the first line of code from the link you sent: > > # bstr_pos: only positive integers > # zero -> '' > # negative -> '' > > bstr_pos = lambda n: n>0 and bstr_pos(n>>1)+str(n&1) or '' > > thanks. > Jeff > > Bill Mill wrote: > > > Jeff, > > There isn't a built-in type, but it's fairly easy to do. Have a look > at http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/219300 for > some ideas on how to do it. If you don't understand those, ask and > I'll try to clarify them for you. > > Peace > Bill Mill > bill.mill at gmail.com > > > On Mon, 25 Oct 2004 09:09:27 -0700 (PDT), Jeff Peery > wrote: > > > > > > > > > > Hello, > > > > will python work with binary math? i.e., add subtract binary numbers? is > > there a specific type that I have to use to define a binary number? > thanks. > > > > > > > > Jeff > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From cyresse at gmail.com Tue Oct 26 06:59:44 2004 From: cyresse at gmail.com (Liam Clarke) Date: Tue Oct 26 06:59:47 2004 Subject: [Tutor] Binary math? In-Reply-To: <20041026035446.644761E4002@bag.python.org> References: <797fe3d40410251055b956b3c@mail.gmail.com> <20041026035446.644761E4002@bag.python.org> Message-ID: >From Python's docs for Windows mapi.BinFromHex PyUnicode = BinFromHex(val) converts a hexadecimal number into a binary string Parameters val : string/PyUnicode The string to be converted. I would do the mathematics in base 10 or hex, and then convert, I think there's modules called bin2ascii and binhex which may be worth checking out, the above function is Win32 specific. I'm not sure what you're after, it seems like you have minimal binary arithmetic to do, and it's more the conversions between bases that you're looking to do efficiently. HtH Liam On Mon, 25 Oct 2004 20:54:44 -0700, Jeffrey Thomas Peery wrote: > That's a big help, thanks! > > J > > > > -----Original Message----- > From: Bill Mill [mailto:bill.mill@gmail.com] > Sent: Monday, October 25, 2004 10:55 AM > To: Jeff Peery > Cc: tutor@python.org > Subject: Re: [Tutor] Binary math? > > Jeff, > > Ok, first off, if I understand you correctly, what you want is to find > the difference between, for example, 1001101 and 10101011? If so, try > a look at this recipe: > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/111286 . (I > don't normally give all my answers in recipes, but I happened to find > 2 that were relevant) This code will let you convert it into an > integer, perform the subtraction, and reformat it as a binary. Again, > if you don't understand the code, ask me and I'll explain it as best I > can. > > Secondly, I knew that the code presented at the link I gave you was > confusing, so I'll try and translate it for you. Even if it wasn't > what you were looking for; it may help you wrap your head around > python a little better. > > First off, the "lambda" keyword means make an unnamed function and > return it. Thus, we can rewrite the code in a similar, but far simpler > way like: > > def bstr_pos(n): > return n > 0 and bstr_pos(n>>1)+str(n&1) or '' > > The first bit of logic is "n > 0 and ...". What this means is that if > n<0, the 'and' is false, so don't evaluate the second part of the > 'and' (since it's already false). Thus, we can rewrite the function > even more clearly: > > def bstr_pos(n): > if n > 0: > return bstr_pos(n >> 1) + str(n & 1) > else: > return '' > > Now it is easy to see that we have a recursive function. That is, the > bstr_pos function calls itself if n > 0, but it calls itself on the > next binary digit of n, which is accomplished with the '>>' operator, > called the 'right shift' operator. Let's look at this briefly in the > interpreter: > > >>> 16 >> 1 > 8 > >>> 15 >> 1 > 7 > > The binary representation of 16 is '10000' (16 = 2**4). When we right > shift, we turn '10000' into '1000' simply by dropping the last digit. > '1000' is the binary representation of 8. Similarly, the binary > representation of 15 is '1111', so 15>>1 turns '1111' into '111', > which is the binary representation of 7. > > So, we call the bstr_pos function recursively for each power of 2 in > the integer n. The second part of the equation, str(n & 1), returns > '1' if the last binary digit of n is 1, and '0' if the last digit is > 0. '&' is the binary 'and' operator. > > So, here's what happens overall: if n > 0, recursively call bstr_pos > for each power of 2 in n, then convert the last binary digit of n into > a string, and append them all together using the '+' operator on the > strings. When n <= 0, just return the null string. > > Hope this helps. > > Peace > Bill Mill > bill.mill at gmail.com > > On Mon, 25 Oct 2004 09:54:07 -0700 (PDT), Jeff Peery > wrote: > > > > Bill, I am confused, could you explain the first line of code. I can > > probably then figure out the remaining. all I need to do is find the > > difference of two binary numbers, converting them to decimal is easy to > do. > > here is the first line of code from the link you sent: > > > > # bstr_pos: only positive integers > > # zero -> '' > > # negative -> '' > > > > bstr_pos = lambda n: n>0 and bstr_pos(n>>1)+str(n&1) or '' > > > > thanks. > > Jeff > > > > Bill Mill wrote: > > > > > > Jeff, > > > > There isn't a built-in type, but it's fairly easy to do. Have a look > > at http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/219300 for > > some ideas on how to do it. If you don't understand those, ask and > > I'll try to clarify them for you. > > > > Peace > > Bill Mill > > bill.mill at gmail.com > > > > > > On Mon, 25 Oct 2004 09:09:27 -0700 (PDT), Jeff Peery > > wrote: > > > > > > > > > > > > > > > Hello, > > > > > > will python work with binary math? i.e., add subtract binary numbers? is > > > there a specific type that I have to use to define a binary number? > > thanks. > > > > > > > > > > > > Jeff > > > _______________________________________________ > > > Tutor maillist - Tutor@python.org > > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From alan.gauld at freenet.co.uk Tue Oct 26 09:47:14 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue Oct 26 09:46:30 2004 Subject: [Tutor] variable from input? References: <555128ce04102516535a018776@mail.gmail.com> Message-ID: <00bf01c4bb30$02ab6db0$2cb98851@xp> > On Mon, 25 Oct 2004 19:53:22 -0400, Rene Lopez wrote: > > is it possible to have the user input something with a raw_input > > command, and then base upon the input make that into the name of a > > variable? This is a very common question from beginners and 'I address it in the OOP topic of my tutor. But basically its nearly always a bad idea. At the >>> prompt it makes a little bit of sense because you use variable names dynamically but if you are writing programs into files for future execution your code will not know about the new name. The new variable will be effectively useless. It is much better, as already suggested, to use a dictionary of such names. HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld/tutor2/ From alan.gauld at freenet.co.uk Tue Oct 26 10:08:40 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue Oct 26 10:08:00 2004 Subject: [Tutor] jython slowness References: <004901c4ba1b$36940490$2cb98851@xp> <6.1.0.6.0.20041024231501.029c9fe8@mail4.skillsoft.com> Message-ID: <00de01c4bb33$01836110$2cb98851@xp> > That's very strange. I timed the same loop and jython only took about 50% > longer than python (the timeit module from python 2.3 works fine in jython): > D:\Projects\CB\lib\Lib>jython timeit.py "[i for i in [1,2,3]]" > 100000 loops, best of 3: 1.7 usec per loop E:\Jython>jython Lib\timeit.py "[i for i in [1,2,3]]" 100000 loops, best of 3: 2.2 usec per loop > The for loop version is considerably slower in jython, a bit slower in python: > D:\Projects\CB\lib\Lib>jython timeit.py -s "l=[]" "for i in [1,2,3]: > l.append(i)" > 100000 loops, best of 3: 4.6 usec per loop > E:\Jython>jython Lib\timeit.py -s "l=[]" "for i in [1,2,3]: l.append(i)" 100000 loops, best of 3: 6.51 usec per loop Yes, I now get exactly the same results as you (apart from the fact my PC is slower! :-) These are the results I'd expect to see since comprehensions are usually faster than loops. I don't know what happened yesterday but I tried it two or three times and the comp took ages, today its just as fast as I'd expect. Wierd. > I use Jython 2.1 a lot and I haven't found any serious performance problems. Neither had I in the past, it was measurably slower but not enough to notice in real usage. I'm starting to use Java beans a lot at work so I'm slowly converting from CPython to Jython and the problem yesterday just confused me completely... Thanks for the tests. Alan G. From my.mailing.lists at noos.fr Tue Oct 26 10:24:06 2004 From: my.mailing.lists at noos.fr (nik) Date: Tue Oct 26 12:43:19 2004 Subject: [Tutor] Linux/Windows In-Reply-To: <20041025193236.43842.qmail@web61006.mail.yahoo.com> References: <20041025193236.43842.qmail@web61006.mail.yahoo.com> Message-ID: <417E09A6.8020406@noos.fr> If you want to try it out for yourself, but don't have a spare computer for linux, then have a go at a 'live CD' of linux. This is a bootable CD which it runs linux on your system without touching the windows installation that you have there now (ie take the CD out and reboot and you're back to windows - it doesn't install any files to your harddisk). It sets up the hardware and graphical desktop automatically, so it shouldn't be too scary. www.knoppix.org provide a free version - just download and burn the iso image. I'm fairly sure that it has python installed on it as well, so you shouldn't need to install anything extra. nik Ali Polatel wrote: > Dear tutors, > I have written a programme for windows (no GUI but some commands > which create and write things in text files) > I want to modify this programme so that it will work in Linux... > I think there is no need to change the usual functions and classes > all I need to do is a modification in creating files outside the > programme. > If anyone who knows how to do this in Linux can you tell me the > equivalent of the function in Linux?: > "go=open('c:/test.txt','w')" > go.write('Hello world\n') > Another thing is in windows the programme can understand it > self-directory with os.getcwd() command...Can we also do it in Linux?I > mean for example when I do: > import os > os.getcwd() > the interpreter gives "c:\python23" > How to do same in Linux? > And I am not someone who is acquianted with Linux..Can someone create > directories in Linux?(like the mkdir() function in windows) > Thanks all for your help > Ali Polatel > > ------------------------------------------------------------------------ > Do you Yahoo!? > vote.yahoo.com - Register online to vote today! > >------------------------------------------------------------------------ > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > From klappnase at freenet.de Tue Oct 26 12:49:33 2004 From: klappnase at freenet.de (Michael Lange) Date: Tue Oct 26 12:45:06 2004 Subject: [Tutor] How to find language name In-Reply-To: References: <20041025211555.30f0316c.klappnase@freenet.de> Message-ID: <20041026124933.4baaf6b2.klappnase@freenet.de> On Tue, 26 Oct 2004 12:53:38 +1300 Liam Clarke wrote: Hi Liam, thanks for the reply > Hi Michael, > > quoted from docs --- > To maintain compatibility with other platforms, not only the LANG > variable is tested, but a list of variables given as envvars > parameter. The first found to be defined will be used. envvars > defaults to the search path used in GNU gettext; it must always > contain the variable name "LANG". The GNU gettext search path contains > 'LANGUAGE', 'LC_ALL', 'LC_CTYPE', and 'LANG', in that order. > > > Unless I'm wrong, and someone will let me know very shortly if I am; > the returned tuple from getdefaultlocale will always be (language > code, encoding) > That's what had confused me, like I wrote in my first post, I get: >>> import locale >>> locale.getdefaultlocale() ['de_DE', 'de'] Thanks for pointing me to the search order, this lead me to try: [pingu@localhost pingu]$ echo $LANGUAGE de_DE:de so that's obviously where my getdefaultlocale() result comes from. Maybe that's a special Mandrake goodie, now it looks to me what I need is rather getdefaultlocale()[0][:2]. Best regards Michael From RenX99 at gmail.com Tue Oct 26 17:36:43 2004 From: RenX99 at gmail.com (Rene Lopez) Date: Tue Oct 26 17:36:46 2004 Subject: [Tutor] variable from input? In-Reply-To: <00bf01c4bb30$02ab6db0$2cb98851@xp> References: <555128ce04102516535a018776@mail.gmail.com> <00bf01c4bb30$02ab6db0$2cb98851@xp> Message-ID: <555128ce0410260836522dbb87@mail.gmail.com> The reason I posted the question was I wanted to be able to identify the user by the name of the variable, but now that I've thought it through I can see that yes it is indeed a bad idea. But even still, it is useful to know :-) Maybe.... thanks for all the input, you guys rock. Rene On Tue, 26 Oct 2004 08:47:14 +0100, Alan Gauld wrote: > > On Mon, 25 Oct 2004 19:53:22 -0400, Rene Lopez > wrote: > > > is it possible to have the user input something with a raw_input > > > command, and then base upon the input make that into the name of a > > > variable? > > This is a very common question from beginners and 'I address it > in the OOP topic of my tutor. But basically its nearly always a > bad idea. > > At the >>> prompt it makes a little bit of sense because you use > variable names dynamically but if you are writing programs into > files for future execution your code will not know about the new > name. The new variable will be effectively useless. > > It is much better, as already suggested, to use a dictionary of > such names. > > HTH, > > Alan G > Author of the Learn to Program web tutor > http://www.freenetpages.co.uk/hp/alan.gauld/tutor2/ > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- Rene From olli.s.rajala at tut.fi Tue Oct 26 20:04:30 2004 From: olli.s.rajala at tut.fi (Olli Rajala) Date: Tue Oct 26 20:04:32 2004 Subject: [Tutor] getImageInfo() ? Message-ID: <20041026180429.GA11945@students.cc.tut.fi> Hi! This is my first post to this list, so I thought to say hi. :) I'm doing my own imagegallery using python and thought if there were some good/easy way to find the info of the pic, I mean the width&height, so I could put them on the page in the -tag. Pics are jpegs if that matters. TIA, -- <>< "Quite normal guy" Olli Rajala From RenX99 at gmail.com Tue Oct 26 20:20:58 2004 From: RenX99 at gmail.com (Rene Lopez) Date: Tue Oct 26 20:21:01 2004 Subject: [Tutor] jython vs CPython... what are the differences? Message-ID: <555128ce04102611206a77ad66@mail.gmail.com> I know that speed is often a difference between the two... but what else is different? I thought I'd try to run one of my scripts through jython just to see what happens.. but I get an error from jython, but the code runs just fine in regular python. Is there a tutorial out there for porting the code over, or a list of things that work in python but not jython? -- Rene From kent_johnson at skillsoft.com Tue Oct 26 21:03:46 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Tue Oct 26 21:04:09 2004 Subject: [Tutor] getImageInfo() ? In-Reply-To: <20041026180429.GA11945@students.cc.tut.fi> References: <20041026180429.GA11945@students.cc.tut.fi> Message-ID: <6.1.0.6.0.20041026150309.02925850@mail4.skillsoft.com> The Python Imaging Library (PIL) will read a jpeg image and tell you the size. http://www.pythonware.com/products/pil/index.htm Kent At 09:04 PM 10/26/2004 +0300, Olli Rajala wrote: >Hi! >This is my first post to this list, so I thought to say hi. :) > >I'm doing my own imagegallery using python and thought if there were >some good/easy way to find the info of the pic, I mean the >width&height, so I could put them on the page in the -tag. Pics >are jpegs if that matters. > >TIA, >-- ><>< >"Quite normal guy" >Olli Rajala >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From kent_johnson at skillsoft.com Tue Oct 26 21:13:07 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Tue Oct 26 21:13:26 2004 Subject: [Tutor] jython vs CPython... what are the differences? In-Reply-To: <555128ce04102611206a77ad66@mail.gmail.com> References: <555128ce04102611206a77ad66@mail.gmail.com> Message-ID: <6.1.0.6.0.20041026150403.02ac8038@mail4.skillsoft.com> There are two main reasons a Python program will not run in Jython. - Jython implements Python 2.1, so anything introduced in 2.2 or 2.3 is not supported in Jython. The best reference for these differences is the "What's New in Python 2.x" documents available at python.org. http://docs.python.org/whatsnew/whatsnew23.html http://www.python.org/doc/2.2.3/whatsnew/whatsnew22.html Perhaps the most significant and problematic differences are that Jython doesn't support new-style classes (inheriting from object) or generators (functions that use 'yield' to create iterators). - Jython does not support the full Python standard library. In general, if it is in the Python 2.1 library and implemented in Python, it is in Jython If the Python version is implemented in C, it may or may not be in Jython. Core modules such as os and re have Jython implementations (written in Java) but some libraries are missing. Note: Jython *does* support nested scopes if you put the line from __future__ import nested_scopes as the first code line in a module. Kent At 02:20 PM 10/26/2004 -0400, Rene Lopez wrote: >I know that speed is often a difference between the two... but what >else is different? > >I thought I'd try to run one of my scripts through jython just to see >what happens.. but I get an error from jython, but the code runs just >fine in regular python. Is there a tutorial out there for porting the >code over, or a list of things that work in python but not jython? > > >-- > >Rene >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From shitizb at yahoo.com Tue Oct 26 23:02:32 2004 From: shitizb at yahoo.com (Shitiz Bansal) Date: Tue Oct 26 23:02:35 2004 Subject: [Tutor] Kill a process by processname Message-ID: <20041026210232.94062.qmail@web53808.mail.yahoo.com> hi, I want to kill a process by using only the process name for the start. It is easy on linux but is there a way to do it on windows machine using python. I have already tried win32pdh module but the trouble is that it is damn slow. I want to run this as a process which checks for the process name every min or so...and works instantly instead of win32pdh which takes around a min. any help?? shitiz --------------------------------- Do you Yahoo!? Yahoo! Mail - Helps protect you from nasty viruses. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20041026/a17df5d6/attachment.html From andre.roberge at ns.sympatico.ca Tue Oct 26 23:15:28 2004 From: andre.roberge at ns.sympatico.ca (=?iso-8859-1?Q?Andr=E9_Roberge?=) Date: Tue Oct 26 23:15:37 2004 Subject: [Tutor] executing automatically a command in a PyShell Message-ID: <003c01c4bba0$ee61ba00$e0c3010a@andreroberge> I'm running a python interpreter shell in a wxPython app, (a page in a notebook) and I'd like to have the command from __future__ import * run automatically at the beginning. The way I call the python shell is through win = py.shell.Shell(self, -1, introText="") self.AddPage(win, "Python interpreter") Andr? From Christian.Wyglendowski at greenville.edu Tue Oct 26 23:19:28 2004 From: Christian.Wyglendowski at greenville.edu (Christian Wyglendowski) Date: Tue Oct 26 23:19:38 2004 Subject: [Tutor] Turning a "script" into an "application" Message-ID: Hi fellow Python programmers, I have created a network monitoring script with Python. It takes some command line arguments and captures packets from a network interface for a period of time, performs a simple analysis on the captured packets and then sends an email to me if the results are outside of set boundaries. Right now I have the script running every so often using Windows Task Scheduler. Rather than use Windows to control my script's behavior, I would like to add some larger control method to it so it can have persistent (in memory) data, the ability to control scan parameters from within the application, the ability to stop and start scans from within the application, save captured data to file, etc. I would like to leave interface options open (text, GUI, web, etc). What I hope to get from the community here is a nudge in the right direction. Do I need to use threads? Is there some sort of framework already available that I can build upon? Is there some programming construct that lends itself to this sort of problem? Other ideas that I have not even thought of? Thanks for any guidance anyone can give. This is mostly new territory for me. Christian http://www.dowski.com From bill.mill at gmail.com Tue Oct 26 23:57:18 2004 From: bill.mill at gmail.com (Bill Mill) Date: Tue Oct 26 23:57:21 2004 Subject: [Tutor] Turning a "script" into an "application" In-Reply-To: References: Message-ID: <797fe3d4041026145776023f0e@mail.gmail.com> Christian, I'm not really sure what you're asking. Do you have more concrete questions? It seems to me that, instead of messing around with threads, you may want to write an entirely seperate script to control the network script. Pseudocode: ############## #network_script_controller ############# while 1: actions = {'1': send_foo_to_network_script, #this is a function reference '2': send_bar_to_network_script #so is this #and whatever else menu options you want } print "Enter one to change foo, or two to change bar" msg = raw_input('>') actions[msg]() ############# #network_script ############ while 1: do_my_processing_loop() check_for_new_messages() And you could simply use sockets for communication between the two. Is that something like what you're looking for? Peace Bill Mill bill.mill at gmail.com On Tue, 26 Oct 2004 16:19:28 -0500, Christian Wyglendowski wrote: > Hi fellow Python programmers, > > I have created a network monitoring script with Python. It takes some > command line arguments and captures packets from a network interface for > a period of time, performs a simple analysis on the captured packets and > then sends an email to me if the results are outside of set boundaries. > Right now I have the script running every so often using Windows Task > Scheduler. > > Rather than use Windows to control my script's behavior, I would like to > add some larger control method to it so it can have persistent (in > memory) data, the ability to control scan parameters from within the > application, the ability to stop and start scans from within the > application, save captured data to file, etc. I would like to leave > interface options open (text, GUI, web, etc). > > What I hope to get from the community here is a nudge in the right > direction. > > Do I need to use threads? Is there some sort of framework already > available that I can build upon? Is there some programming construct > that lends itself to this sort of problem? Other ideas that I have not > even thought of? > > Thanks for any guidance anyone can give. This is mostly new territory > for me. > > Christian > http://www.dowski.com > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From bill.mill at gmail.com Tue Oct 26 23:59:29 2004 From: bill.mill at gmail.com (Bill Mill) Date: Tue Oct 26 23:59:31 2004 Subject: [Tutor] executing automatically a command in a PyShell In-Reply-To: <003c01c4bba0$ee61ba00$e0c3010a@andreroberge> References: <003c01c4bba0$ee61ba00$e0c3010a@andreroberge> Message-ID: <797fe3d40410261459667acf9@mail.gmail.com> Andre, This seems like a question for the wxPython people, not the Tutor list. Their mailing list is at wxpython-users@lists.wxwidgets.org . Peace Bill Mill bill.mill@gmail.com On Tue, 26 Oct 2004 18:15:28 -0300, Andr? Roberge wrote: > I'm running a python interpreter shell in a wxPython app, > (a page in a notebook) and I'd like to have the command > > from __future__ import * > > run automatically at the beginning. > > The way I call the python shell is through > win = py.shell.Shell(self, -1, introText="") > self.AddPage(win, "Python interpreter") > > Andr? > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From Christian.Wyglendowski at greenville.edu Wed Oct 27 00:27:42 2004 From: Christian.Wyglendowski at greenville.edu (Christian Wyglendowski) Date: Wed Oct 27 00:27:49 2004 Subject: [Tutor] Turning a "script" into an "application" Message-ID: > -----Original Message----- > From: Bill Mill [mailto:bill.mill@gmail.com] > Subject: Re: [Tutor] Turning a "script" into an "application" > > Christian, > > I'm not really sure what you're asking. Do you have more > concrete questions? My main question boils down to: what programming/conceptual framework I should use to turn my script into something resembling an application? I guess maybe I was a bit vague in my description. First off, the program watches the network for virus-like patterns of behavior, and alerts a user via email if it sees it during its capture window. Here is the basic flow I would like to see in the program: #RUNNING CONTROLLER |--> user can change options (captureTime, warnThreshhold, networkDevice, sleepTime, notifyAddress) |--> user can start/stop sniffer |--> user can save capture analysis | |_____ #RUNNING SNIFFER (basically a loop) |--> sniffer runs for captureTime seconds |--> sniffer analyzes captured data |--> sniffer saves analysis to memory |--> depending on analysis, sniffer sends alert via email or does nothing |--> sniffer sleeps for sleepTime, then loops Sorry for the bad ASCII diagram - but hopefully it makes some sense. > It seems to me that, instead of messing around with threads, > you may want to write an entirely seperate script to control > the network script. Pseudocode: > > ############## > #network_script_controller > ############# > while 1: > actions = {'1': send_foo_to_network_script, #this is a function reference > '2': send_bar_to_network_script #so is this > #and whatever else menu options you want > } > print "Enter one to change foo, or two to change bar" > msg = raw_input('>') > actions[msg]() > > ############# > #network_script > ############ > while 1: > do_my_processing_loop() > check_for_new_messages() > > And you could simply use sockets for communication between > the two. Is that something like what you're looking for? Thanks for the idea. Despite not reall knowing what I was asking, you answered my question pretty well! I had not considered a multi-process approach but I can see that it could be quite flexible. > Peace > Bill Mill > bill.mill at gmail.com > Thanks again. Christian http://www.dowski.com From John.Gooch at echostar.com Wed Oct 27 01:10:31 2004 From: John.Gooch at echostar.com (Gooch, John) Date: Wed Oct 27 01:10:42 2004 Subject: [Tutor] Classes Turn Strings Into Tuples for some reason Message-ID: <15A1FDA26DAD524DA7A7AF77313EBA8F07BC00CB@riv-excha5.echostar.com> With the class below: #Define Classes class Record: def __init__(self, name ): self.name = name, self.lastlogon = '' self.ipaddress = "0" self.uptime = 0 self.type = 0 self.location = "0" def printName(self): return self.name def getName(self): print self.name return self.name #End Class Record If I create an instance of the class like so - joe = Record( "joe") and then print joe.name or pring joe.getName() Instead of printing just the name, it prints ( 'joe', ) I have been reading up on functions and classes, and haven't found any information to explain this behavior. I want the value to be a scalar string, and not a tuple. Any ideas? John A. Gooch Systems Administrator IT - Tools EchoStar Satellite L.L.C. 9601 S. Meridian Blvd. Englewood, CO 80112 Desk: 720-514-5708 From cyresse at gmail.com Wed Oct 27 01:23:30 2004 From: cyresse at gmail.com (Liam Clarke) Date: Wed Oct 27 01:23:33 2004 Subject: [Tutor] Classes Turn Strings Into Tuples for some reason In-Reply-To: <15A1FDA26DAD524DA7A7AF77313EBA8F07BC00CB@riv-excha5.echostar.com> References: <15A1FDA26DAD524DA7A7AF77313EBA8F07BC00CB@riv-excha5.echostar.com> Message-ID: Hi John This part here... self.name = name, The comma tells Python that self.name is a tuple, similar to x=(4,5,6,7,) would. Are you wanting to add multiple names to the same variable i.e. (Jane, John, Jeff, Jenny)? I On Tue, 26 Oct 2004 17:10:31 -0600, Gooch, John wrote: > With the class below: > > #Define Classes > class Record: > def __init__(self, name ): > self.name = name, > self.lastlogon = '' > self.ipaddress = "0" > self.uptime = 0 > self.type = 0 > self.location = "0" > def printName(self): > return self.name > def getName(self): > print self.name > return self.name > #End Class Record > > If I create an instance of the class like so - > joe = Record( "joe") > and then > print joe.name > or > pring joe.getName() > Instead of printing just the name, it prints > ( 'joe', ) > > I have been reading up on functions and classes, and haven't found any > information to explain this behavior. I > want the value to be a scalar string, and not a tuple. > > Any ideas? > > John A. Gooch > Systems Administrator > IT - Tools > EchoStar Satellite L.L.C. > 9601 S. Meridian Blvd. > Englewood, CO 80112 > Desk: 720-514-5708 > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From cyresse at gmail.com Wed Oct 27 01:32:12 2004 From: cyresse at gmail.com (Liam Clarke) Date: Wed Oct 27 01:32:14 2004 Subject: [Tutor] Would an OOP approach be simpler? In-Reply-To: References: Message-ID: Brilliant, thanks Danny, it's the structural stuff that I'm amiss on. On Sat, 23 Oct 2004 16:12:11 -0700 (PDT), Danny Yoo wrote: > > > On Sat, 23 Oct 2004, Liam Clarke wrote: > > > Well thanks to all for their help, my first module of my first project > > is completed. > > > > For anyone who's curious, the results are below - > > > > http://rafb.net/paste/results/qHyVC360.html > > > > Once again, thanks very much to all. > > > Hi Liam, > > Thanks for posting up your code! I took a look at it; looks pretty good. > Do you mind if I give a few suggestions? If you do mind, um... skip this > message. *grin* > > The only big target I can see so far is getReturns(): it's a bit long. > It might be useful to break it up a little, by using helper functions to > extract blocks of related statements. For example, there's a block here: > > if os.path.exists('./archives/wb%s' % weekstart): > done=file('./archives/wb%s/got.lst' %weekstart, 'rb') > donelist=done.readlines() > done.close() > list=donelist[0].split('/') > doesExist=1 > > I'm not too familiar with what this is doing, but let's describe this > block of code as something like checkIfDoesExist(). We can reform it as a > function: > > ### > def checkIfDoesExist(weekstart): > if os.path.exists('./archives/wb%s' % weekstart): > done=file('./archives/wb%s/got.lst' %weekstart, 'rb') > donelist=done.readlines() > done.close() > list=donelist[0].split('/') > return (list, 1) > else: > return (None, 0) > ### > > and then, back in getReturns(), we can use it like this: > > (list, doesExist) = checkIfDoesExist(weekstart) > > The reason this extraction ("refactoring") might be worthwhile is because > the code doesn't make clear what value the 'list' should have if the > directory doesn't exist. The refactored code tries to make sure that > 'list' does have some known value, regardless if 'doesExist' is true or > not. > > Another block in getReturns() that looks promising is the one that > connects to the mail server. This block here: > > success = 0 > session = imaplib.IMAP4(hostname) > while not success: > try: > session.login(user[account], pwd[account]) > except: > pass > else: > success = 1 > > looks like it is making darn sure that it connects and logs into the > server. We can call this something like connectToImap(): > > ### > def connectToImap(hostname, username, password): > success = 0 > session = imaplib.IMAP4(hostname) > while not success: > try: > session.login(username, password) > except: > pass > else: > success = 1 > return session > ### > > I made a few cosmetic changes here, mostly to reduce its direct ties to > the user and pwd collections. Back in getReturns(), we can replace the > block with: > > session = connectToImap(hostname, user[account], pwd[account]) > > Again, this refactoring helps readability because it's clear that the > block initializes a 'session' value. The other variable, the 'success' > variable, doesn't leak out into the rest of the getReturns() function. > > 'success' is a temporary variable that's used only to get that while loop > working. By refactoring the block out into a separate connectToImap() > function, we get to make its local role very clear to a reader of the > code. > > Are these kinds of structural changes useful? They don't add anything > technically new, but they do make the code easier to read. With those two > blocks extracted out, getReturns() now reads like: > > ### > def getReturns(hostname, user, pwd, searchstring, weekstart): > sender = [] > msgdata = [] > > (list, doesExist) = checkIfDoesExist(weekstart) > > for account in range(len(user)): > session = connectToImap(hostname, user[account], pwd[account]) > session.select() ... > ### > > So my main advice is to look out for places where "paragraph" blocks of > code tend to appear, and see if those blocks can be extracted out as real > functions. > > I hope this helps! > > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From kent_johnson at skillsoft.com Wed Oct 27 04:26:28 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Wed Oct 27 04:26:33 2004 Subject: [Tutor] Turning a "script" into an "application" In-Reply-To: References: Message-ID: <6.1.0.6.0.20041026220111.029072a0@mail4.skillsoft.com> Christian, If you want to be able to control your sniffer from a variety of front ends (command-line, GUI, web app) then you probably have to write it as a separate process with some kind of socket interface. If you can pick a single UI, and you are happy to have the UI running at the same time as the sniffer, you could make the sniffer a separate thread in the same application as the GUI. Putting the GUI and the sniffer in one application is simpler. You don't have to invent a socket communications protocol, you can use program variables to communicate between the two threads (GUI and sniffer). You could write the GUI in Tkinter or wxPython. If you decide to build a separate sniffer process, I suggest you build the communications protocol on top of an existing standard. That way you can use existing libraries to build the infrastructure. Inventing and implementing a socket protocol from scratch is probably not what you want to spend your time on. For example you could use XMLRPC to talk to the sniffer. Using xmlrpclib on the client side and SimpleXMLRPCServer on the sniffer side it is easy to set up. The client then makes procedure calls on the server through a proxy. The advantage of this method is it is easy to set up and it gives you a very pythonic interface on the client side. The disadvantage is that it is not easy to use the interface without writing a program. Another way to go is to use HTTP as your protocol. In this case you put request parameters in the URL. The server decodes the request and takes the appropriate action. An advantage of this method is you can test it with a browser client - by typing URLs or filling out a simple form you can control the sniffer. You could develop that into a rich web interface. I think you have to go outside the standard library to get good HTTP server support. There are many packages available; Snakelets is one that is intended to be easy to use: http://snakelets.sourceforge.net/ I suggest you start with the first version - GUI and sniffer in one application. It is a good first step even if the eventual goal is to have a separate sniffer process. Keep a strong separation between the two parts so if you decide later to split them it won't be too hard. Kent At 05:27 PM 10/26/2004 -0500, Christian Wyglendowski wrote: > > -----Original Message----- > > From: Bill Mill [mailto:bill.mill@gmail.com] > > Subject: Re: [Tutor] Turning a "script" into an "application" > > > > Christian, > > > > I'm not really sure what you're asking. Do you have more > > concrete questions? > >My main question boils down to: what programming/conceptual framework I >should use to turn my script into something resembling an application? > >I guess maybe I was a bit vague in my description. First off, the >program watches the network for virus-like patterns of behavior, and >alerts a user via email if it sees it during its capture window. > >Here is the basic flow I would like to see in the program: > >#RUNNING CONTROLLER >|--> user can change options (captureTime, warnThreshhold, >networkDevice, sleepTime, notifyAddress) >|--> user can start/stop sniffer >|--> user can save capture analysis >| >|_____ #RUNNING SNIFFER (basically a loop) > |--> sniffer runs for captureTime seconds > |--> sniffer analyzes captured data > |--> sniffer saves analysis to memory > |--> depending on analysis, sniffer sends alert via email or >does nothing > |--> sniffer sleeps for sleepTime, then loops > >Sorry for the bad ASCII diagram - but hopefully it makes some sense. > > > It seems to me that, instead of messing around with threads, > > you may want to write an entirely seperate script to control > > the network script. Pseudocode: > > > > ############## > > #network_script_controller > > ############# > > while 1: > > actions = {'1': send_foo_to_network_script, #this is a function >reference > > '2': send_bar_to_network_script #so is this > > #and whatever else menu options you want > > } > > print "Enter one to change foo, or two to change bar" > > msg = raw_input('>') > > actions[msg]() > > > > ############# > > #network_script > > ############ > > while 1: > > do_my_processing_loop() > > check_for_new_messages() > > > > And you could simply use sockets for communication between > > the two. Is that something like what you're looking for? > >Thanks for the idea. Despite not reall knowing what I was asking, you >answered my question pretty well! I had not considered a multi-process >approach but I can see that it could be quite flexible. > > > Peace > > Bill Mill > > bill.mill at gmail.com > > > >Thanks again. > >Christian >http://www.dowski.com > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From bill.mill at gmail.com Wed Oct 27 04:51:18 2004 From: bill.mill at gmail.com (Bill Mill) Date: Wed Oct 27 04:51:22 2004 Subject: [Tutor] Turning a "script" into an "application" In-Reply-To: <6.1.0.6.0.20041026220111.029072a0@mail4.skillsoft.com> References: <6.1.0.6.0.20041026220111.029072a0@mail4.skillsoft.com> Message-ID: <797fe3d4041026195164a7be97@mail.gmail.com> Kent, I hope you don't mind if I respectfully disagree. First off, the user explicitly stated that he would like to leave his interface options open, and this is more difficult to implement with threads. Secondly, he would have to learn about threads and thread synchronization. While this is not overly difficult, it is more difficult than learning sockets (IMNSHO, more on this) and tends to lead to very subtle and difficult to debug errors. I believe that sockets would be simpler for him to use, and that he doesn't need all of the protocol worry that you mentioned earlier, because he can simply pass a fixed-length message from the controller to the network script. Reading the socket is very simple; if there is data, read X bytes. If not, keep on chugging. Furthermore, once he's written the controller -> network script communication, he can experiment with his options *very* easily; text, GUI, web, whatever he wants. Peace Bill Mill bill.mill at gmail.com On Tue, 26 Oct 2004 22:26:28 -0400, Kent Johnson wrote: > Christian, > > If you want to be able to control your sniffer from a variety of front ends > (command-line, GUI, web app) then you probably have to write it as a > separate process with some kind of socket interface. If you can pick a > single UI, and you are happy to have the UI running at the same time as the > sniffer, you could make the sniffer a separate thread in the same > application as the GUI. > > Putting the GUI and the sniffer in one application is simpler. You don't > have to invent a socket communications protocol, you can use program > variables to communicate between the two threads (GUI and sniffer). You > could write the GUI in Tkinter or wxPython. > > If you decide to build a separate sniffer process, I suggest you build the > communications protocol on top of an existing standard. That way you can > use existing libraries to build the infrastructure. Inventing and > implementing a socket protocol from scratch is probably not what you want > to spend your time on. > > For example you could use XMLRPC to talk to the sniffer. Using xmlrpclib on > the client side and SimpleXMLRPCServer on the sniffer side it is easy to > set up. The client then makes procedure calls on the server through a > proxy. The advantage of this method is it is easy to set up and it gives > you a very pythonic interface on the client side. The disadvantage is that > it is not easy to use the interface without writing a program. > > Another way to go is to use HTTP as your protocol. In this case you put > request parameters in the URL. The server decodes the request and takes the > appropriate action. An advantage of this method is you can test it with a > browser client - by typing URLs or filling out a simple form you can > control the sniffer. You could develop that into a rich web interface. I > think you have to go outside the standard library to get good HTTP server > support. There are many packages available; Snakelets is one that is > intended to be easy to use: http://snakelets.sourceforge.net/ > > I suggest you start with the first version - GUI and sniffer in one > application. It is a good first step even if the eventual goal is to have a > separate sniffer process. Keep a strong separation between the two parts so > if you decide later to split them it won't be too hard. > > Kent > > > > At 05:27 PM 10/26/2004 -0500, Christian Wyglendowski wrote: > > > -----Original Message----- > > > From: Bill Mill [mailto:bill.mill@gmail.com] > > > Subject: Re: [Tutor] Turning a "script" into an "application" > > > > > > Christian, > > > > > > I'm not really sure what you're asking. Do you have more > > > concrete questions? > > > >My main question boils down to: what programming/conceptual framework I > >should use to turn my script into something resembling an application? > > > >I guess maybe I was a bit vague in my description. First off, the > >program watches the network for virus-like patterns of behavior, and > >alerts a user via email if it sees it during its capture window. > > > >Here is the basic flow I would like to see in the program: > > > >#RUNNING CONTROLLER > >|--> user can change options (captureTime, warnThreshhold, > >networkDevice, sleepTime, notifyAddress) > >|--> user can start/stop sniffer > >|--> user can save capture analysis > >| > >|_____ #RUNNING SNIFFER (basically a loop) > > |--> sniffer runs for captureTime seconds > > |--> sniffer analyzes captured data > > |--> sniffer saves analysis to memory > > |--> depending on analysis, sniffer sends alert via email or > >does nothing > > |--> sniffer sleeps for sleepTime, then loops > > > >Sorry for the bad ASCII diagram - but hopefully it makes some sense. > > > > > It seems to me that, instead of messing around with threads, > > > you may want to write an entirely seperate script to control > > > the network script. Pseudocode: > > > > > > ############## > > > #network_script_controller > > > ############# > > > while 1: > > > actions = {'1': send_foo_to_network_script, #this is a function > >reference > > > '2': send_bar_to_network_script #so is this > > > #and whatever else menu options you want > > > } > > > print "Enter one to change foo, or two to change bar" > > > msg = raw_input('>') > > > actions[msg]() > > > > > > ############# > > > #network_script > > > ############ > > > while 1: > > > do_my_processing_loop() > > > check_for_new_messages() > > > > > > And you could simply use sockets for communication between > > > the two. Is that something like what you're looking for? > > > >Thanks for the idea. Despite not reall knowing what I was asking, you > >answered my question pretty well! I had not considered a multi-process > >approach but I can see that it could be quite flexible. > > > > > Peace > > > Bill Mill > > > bill.mill at gmail.com > > > > > > >Thanks again. > > > >Christian > >http://www.dowski.com > > > >_______________________________________________ > >Tutor maillist - Tutor@python.org > >http://mail.python.org/mailman/listinfo/tutor > > _______________________________________________ > > > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From kent_johnson at skillsoft.com Wed Oct 27 05:14:26 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Wed Oct 27 05:14:33 2004 Subject: [Tutor] Turning a "script" into an "application" In-Reply-To: <797fe3d4041026195164a7be97@mail.gmail.com> References: <6.1.0.6.0.20041026220111.029072a0@mail4.skillsoft.com> <797fe3d4041026195164a7be97@mail.gmail.com> Message-ID: <6.1.0.6.0.20041026225558.029069a8@mail4.skillsoft.com> At 10:51 PM 10/26/2004 -0400, Bill Mill wrote: >Kent, > >I hope you don't mind if I respectfully disagree. Not at all! A little friendly disagreement is good for us all! >First off, the user >explicitly stated that he would like to leave his interface options >open, and this is more difficult to implement with threads. Yes, I agree that a threaded solution doesn't address this requirement. But he will have to implement some kind of front end. Combining that front end with the sniffer in a single app could be an easy way to get started. >Secondly, he would have to learn about threads and thread >synchronization. While this is not overly difficult, it is more >difficult than learning sockets (IMNSHO, more on this) and tends to >lead to very subtle and difficult to debug errors. I think there can be subtle errors either way. I don't think simple threaded applications are that hard but I've written a few already...you may have more experience with separate processes and socket interfaces. >I believe that sockets would be simpler for him to use, and that he >doesn't need all of the protocol worry that you mentioned earlier, >because he can simply pass a fixed-length message from the controller >to the network script. Reading the socket is very simple; if there is >data, read X bytes. If not, keep on chugging. I'm skeptical of this. But I admit I haven't written any applications this way. There will at least be buffering issues with the input - a complete command may not be available at once. It is possible that he will eventually want a threaded server anyway - one thread to listen for commands and another for the actual sniffer. In general I try to avoid inventing communications protocols from scratch. And Python xmlrpc is very easy to set up. >Furthermore, once he's written the controller -> network script >communication, he can experiment with his options *very* easily; text, >GUI, web, whatever he wants. Text and GUI would be simple; for a web interface he would then have to add a web server into the mix - running as yet another process? If a web interface is a real possibility I would start with a simple HTTP interface. Kent >Peace >Bill Mill >bill.mill at gmail.com > > >On Tue, 26 Oct 2004 22:26:28 -0400, Kent Johnson > wrote: > > Christian, > > > > If you want to be able to control your sniffer from a variety of front ends > > (command-line, GUI, web app) then you probably have to write it as a > > separate process with some kind of socket interface. If you can pick a > > single UI, and you are happy to have the UI running at the same time as the > > sniffer, you could make the sniffer a separate thread in the same > > application as the GUI. > > > > Putting the GUI and the sniffer in one application is simpler. You don't > > have to invent a socket communications protocol, you can use program > > variables to communicate between the two threads (GUI and sniffer). You > > could write the GUI in Tkinter or wxPython. > > > > If you decide to build a separate sniffer process, I suggest you build the > > communications protocol on top of an existing standard. That way you can > > use existing libraries to build the infrastructure. Inventing and > > implementing a socket protocol from scratch is probably not what you want > > to spend your time on. > > > > For example you could use XMLRPC to talk to the sniffer. Using xmlrpclib on > > the client side and SimpleXMLRPCServer on the sniffer side it is easy to > > set up. The client then makes procedure calls on the server through a > > proxy. The advantage of this method is it is easy to set up and it gives > > you a very pythonic interface on the client side. The disadvantage is that > > it is not easy to use the interface without writing a program. > > > > Another way to go is to use HTTP as your protocol. In this case you put > > request parameters in the URL. The server decodes the request and takes the > > appropriate action. An advantage of this method is you can test it with a > > browser client - by typing URLs or filling out a simple form you can > > control the sniffer. You could develop that into a rich web interface. I > > think you have to go outside the standard library to get good HTTP server > > support. There are many packages available; Snakelets is one that is > > intended to be easy to use: http://snakelets.sourceforge.net/ > > > > I suggest you start with the first version - GUI and sniffer in one > > application. It is a good first step even if the eventual goal is to have a > > separate sniffer process. Keep a strong separation between the two parts so > > if you decide later to split them it won't be too hard. > > > > Kent > > > > > > > > At 05:27 PM 10/26/2004 -0500, Christian Wyglendowski wrote: > > > > -----Original Message----- > > > > From: Bill Mill [mailto:bill.mill@gmail.com] > > > > Subject: Re: [Tutor] Turning a "script" into an "application" > > > > > > > > Christian, > > > > > > > > I'm not really sure what you're asking. Do you have more > > > > concrete questions? > > > > > >My main question boils down to: what programming/conceptual framework I > > >should use to turn my script into something resembling an application? > > > > > >I guess maybe I was a bit vague in my description. First off, the > > >program watches the network for virus-like patterns of behavior, and > > >alerts a user via email if it sees it during its capture window. > > > > > >Here is the basic flow I would like to see in the program: > > > > > >#RUNNING CONTROLLER > > >|--> user can change options (captureTime, warnThreshhold, > > >networkDevice, sleepTime, notifyAddress) > > >|--> user can start/stop sniffer > > >|--> user can save capture analysis > > >| > > >|_____ #RUNNING SNIFFER (basically a loop) > > > |--> sniffer runs for captureTime seconds > > > |--> sniffer analyzes captured data > > > |--> sniffer saves analysis to memory > > > |--> depending on analysis, sniffer sends alert via email or > > >does nothing > > > |--> sniffer sleeps for sleepTime, then loops > > > > > >Sorry for the bad ASCII diagram - but hopefully it makes some sense. > > > > > > > It seems to me that, instead of messing around with threads, > > > > you may want to write an entirely seperate script to control > > > > the network script. Pseudocode: > > > > > > > > ############## > > > > #network_script_controller > > > > ############# > > > > while 1: > > > > actions = {'1': send_foo_to_network_script, #this is a function > > >reference > > > > '2': send_bar_to_network_script #so is this > > > > #and whatever else menu options you want > > > > } > > > > print "Enter one to change foo, or two to change bar" > > > > msg = raw_input('>') > > > > actions[msg]() > > > > > > > > ############# > > > > #network_script > > > > ############ > > > > while 1: > > > > do_my_processing_loop() > > > > check_for_new_messages() > > > > > > > > And you could simply use sockets for communication between > > > > the two. Is that something like what you're looking for? > > > > > >Thanks for the idea. Despite not reall knowing what I was asking, you > > >answered my question pretty well! I had not considered a multi-process > > >approach but I can see that it could be quite flexible. > > > > > > > Peace > > > > Bill Mill > > > > bill.mill at gmail.com > > > > > > > > > >Thanks again. > > > > > >Christian > > >http://www.dowski.com > > > > > >_______________________________________________ > > >Tutor maillist - Tutor@python.org > > >http://mail.python.org/mailman/listinfo/tutor > > > > _______________________________________________ > > > > > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > From jeffpeery at yahoo.com Wed Oct 27 06:46:15 2004 From: jeffpeery at yahoo.com (Jeff Peery) Date: Wed Oct 27 06:46:18 2004 Subject: [Tutor] CGI and Quixote Message-ID: <20041027044615.24906.qmail@web60103.mail.yahoo.com> Hello, does anyone know where I can get a windows installer for quixote? I don't have a compiler and I would like to use quixote. thanks. Jeff -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20041026/6ad4d60e/attachment.html From dyoo at hkn.eecs.berkeley.edu Wed Oct 27 07:08:36 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Oct 27 07:08:40 2004 Subject: [Tutor] Classes Turn Strings Into Tuples for some reason In-Reply-To: Message-ID: On Wed, 27 Oct 2004, Liam Clarke wrote: > Hi John > > This part here... > self.name = name, > > The comma tells Python that self.name is a tuple, similar to > x=(4,5,6,7,) would. Yes, exactly. Python's syntax is a bit permissive when it comes to using tuples. For example, both: (x, y, z) = ('henry', 'richard', 'john') and: x, y, z = 'henny', 'richard', 'john' do the same thing: the two statements both do a "tuple assignment". And in the second case, Python can figure out that we are doing tuple assignment, even without the parentheses. As a variation of this, we can also do: kings = 'thengel', 'theoden', 'eomer' or: havens = 'lothlorien', 'rivendell' or even: one = 'ring', This is one of the few places where I think this particular permissive syntax --- optional parentheses for tuples --- might not have been such a good idea: I think that the mandatory parentheses would improve the readability of the language. But since it's in the language, we'd better be aware of it. From dyoo at hkn.eecs.berkeley.edu Wed Oct 27 07:20:41 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Oct 27 07:20:45 2004 Subject: [Tutor] CGI and Quixote In-Reply-To: <20041027044615.24906.qmail@web60103.mail.yahoo.com> Message-ID: On Tue, 26 Oct 2004, Jeff Peery wrote: > Hello, does anyone know where I can get a windows installer for quixote? > I don't have a compiler and I would like to use quixote. thanks. Hi Jeff, I'm not sure if many of us know about Quixote. Try the Quixote-users's mailing list: you should have better luck with them. Here's a link to their mailing list: http://mail.mems-exchange.org/mailman/listinfo/quixote-users According to the Quixote documentation, you might not even need a compiler. The installation might just be downloading it, starting up a command shell, and running 'python setup.py install'. http://www.mems-exchange.org/software/quixote/doc/INSTALL.html The installation of Quixote does include some optional stuff in C, but I don't think it's required: it looks like Quixote can run in a pure-Python mode, since their setup.py includes the following: ### (Some text cut out of setup.py) htmltext = Extension(name="quixote._c_htmltext", sources=["src/_c_htmltext.c"]) cimport = Extension(name="quixote.cimport", sources=["src/cimport.c"]) build_extensions = sys.platform != 'win32' if build_extensions: # The _c_htmltext module requires Python 2.2 features. if sys.hexversion >= 0x20200a1: kw['ext_modules'].append(htmltext) kw['ext_modules'].append(cimport) ### So it looks like the stuff that might need a C compiler, those extension modules, might not even need to be installed. The installation appears not to compile them on the Windows platform. Again, I'm not positively sure about this; you need to talk with people who have a clue of what they're talking about. *grin* Talk to the Quixote-users list; I'm sure they'll be happy to clarify your questions about their framework. Good luck to you! From joe at omc-international.com.au Wed Oct 27 07:28:06 2004 From: joe at omc-international.com.au (Joe Healy) Date: Wed Oct 27 07:28:08 2004 Subject: [Tutor] Turning a "script" into an "application" In-Reply-To: <797fe3d4041026195164a7be97@mail.gmail.com> References: <6.1.0.6.0.20041026220111.029072a0@mail4.skillsoft.com> <797fe3d4041026195164a7be97@mail.gmail.com> Message-ID: <417F31E6.7080800@omc-international.com.au> Bill Mill wrote: ... (cut) > Secondly, he would have to learn about threads and thread > synchronization. While this is not overly difficult, it is more > difficult than learning sockets (IMNSHO, more on this) and tends to > lead to very subtle and difficult to debug errors. > > This sounds interesting. Are you aware of any examples using sockets for basic rpc on the web somewhere? ... (rest cut) Thanks, Joe Healy From bill.mill at gmail.com Wed Oct 27 07:37:16 2004 From: bill.mill at gmail.com (Bill Mill) Date: Wed Oct 27 07:37:22 2004 Subject: [Tutor] Turning a "script" into an "application" In-Reply-To: <6.1.0.6.0.20041026225558.029069a8@mail4.skillsoft.com> References: <6.1.0.6.0.20041026220111.029072a0@mail4.skillsoft.com> <797fe3d4041026195164a7be97@mail.gmail.com> <6.1.0.6.0.20041026225558.029069a8@mail4.skillsoft.com> Message-ID: <797fe3d4041026223712c3ec8c@mail.gmail.com> > >I believe that sockets would be simpler for him to use, and that he > >doesn't need all of the protocol worry that you mentioned earlier, > >because he can simply pass a fixed-length message from the controller > >to the network script. Reading the socket is very simple; if there is > >data, read X bytes. If not, keep on chugging. > > I'm skeptical of this. But I admit I haven't written any applications this > way. There will at least be buffering issues with the input - a complete > command may not be available at once. It is possible that he will > eventually want a threaded server anyway - one thread to listen for > commands and another for the actual sniffer. In general I try to avoid > inventing communications protocols from scratch. And Python xmlrpc is very > easy to set up. > It may be that xmlrpc is easy to set up and easy to use; I've never used it. I'll look into it. As for my bias towards socket development, I will readily admit to that. I've spent a fair amount of time impelementing protocols, while I've never written anything other than toy threaded applications, so my view is certainly biased. I just feel that a simple socket protocol is very easy to implement, and avoids queues, locks, and other less familiar (for me) threading concepts. I'm not yet ready to concede my position, so I'll make one final arguments for my position, and it's a higher level one. Conceptually, the library and the GUI are different applications in this case. It is entirely possible that this network code he's written will be useful to others as a library. As such, it makes more sense conceptually to keep it separate from the front end. While a threaded approach doesn't necessarily preclude conceptual seperation of the front end from the back end (can I use more jargon than that?), it implies more similarity than they perhaps actually share. I question the necessity of shared memory, but if it's more comfortable for him, then by all means, he should go with it. Either way, he needs to be prepared to handle a separate set of issues. I'm glad we could have such civilized discourse on the topic; I'd like to point out here that this list has been excellent in the short time I've been reading it. I think it's good that we're exposing the pros and cons of each approach. Peace Bill Mill bill.mill at gmail.com From joe at omc-international.com.au Wed Oct 27 08:18:16 2004 From: joe at omc-international.com.au (Joe Healy) Date: Wed Oct 27 08:18:09 2004 Subject: [Tutor] Turning a "script" into an "application" In-Reply-To: <797fe3d4041026224741d8de35@mail.gmail.com> References: <6.1.0.6.0.20041026220111.029072a0@mail4.skillsoft.com> <797fe3d4041026195164a7be97@mail.gmail.com> <417F3196.2040208@omc-international.com.au> <797fe3d4041026224741d8de35@mail.gmail.com> Message-ID: <417F3DA8.1080504@omc-international.com.au> Bill Mill wrote: >Joe, > >Not sure what you mean. In python, sockets send and receive strings. >If a server has a socket listening on port X, and it associates some >string with some function call, all it has to do is call that >function. In pythonish pseudocode: > >####### ># Server >###### > >actions = {'func1': func1, #function reference > 'func2': myfunc2 #another > } >while 1: > socket.bind((host, port)) > socket.listen() > while data to read: > read data into variable buf > actions[buf]() > >####### ># Client >###### > >socket.connect((server, port)) >socket.send(func_to_perform) > >Is this at all what you mean? > > > Yes, I did not realise it was so simple. I gather that this will only handle one request at a time and not do anything in the mean time, but it looks like a good way of communicating between two processes. I have a number of programs collecting data from various places and this looks like the beginning of a way to keep an eye on them. Thanks, Joe Healy From bill.mill at gmail.com Wed Oct 27 08:48:11 2004 From: bill.mill at gmail.com (Bill Mill) Date: Wed Oct 27 08:48:16 2004 Subject: [Tutor] Turning a "script" into an "application" In-Reply-To: <417F3DA8.1080504@omc-international.com.au> References: <6.1.0.6.0.20041026220111.029072a0@mail4.skillsoft.com> <797fe3d4041026195164a7be97@mail.gmail.com> <417F3196.2040208@omc-international.com.au> <797fe3d4041026224741d8de35@mail.gmail.com> <417F3DA8.1080504@omc-international.com.au> Message-ID: <797fe3d404102623482cf0494@mail.gmail.com> Joe, Yes, this will only handle one connection at a time. If you want to write a server to handle a lot of connections concurrently, there are two main approaches. They are nicely illustrated by two different webservers. Medusa (http://www.amk.ca/python/code/medusa.html) uses a pool of sockets and iterates through them using something called polling. To learn more about this, study up on the asynchat module. Apache (http://httpd.apache.org/) versions 2.0 and above use a threaded model, where each request to the server creates a new thread in the backgrounds to handle the request, then goes back to listening. Study the threading module to learn more about this. As the python docs will tell you, threading is simpler and more popular, but for a network server, polling is often more efficient. Peace Bill Mill bill.mill at gmail.com On Wed, 27 Oct 2004 16:18:16 +1000, Joe Healy wrote: > Bill Mill wrote: > > >Joe, > > > >Not sure what you mean. In python, sockets send and receive strings. > >If a server has a socket listening on port X, and it associates some > >string with some function call, all it has to do is call that > >function. In pythonish pseudocode: > > > >####### > ># Server > >###### > > > >actions = {'func1': func1, #function reference > > 'func2': myfunc2 #another > > } > >while 1: > > socket.bind((host, port)) > > socket.listen() > > while data to read: > > read data into variable buf > > actions[buf]() > > > >####### > ># Client > >###### > > > >socket.connect((server, port)) > >socket.send(func_to_perform) > > > >Is this at all what you mean? > > > > > > > Yes, I did not realise it was so simple. I gather that this will only > handle one request at a time and not do anything in the mean time, but > it looks like a good way of communicating between two processes. I have > a number of programs collecting data from various places and this looks > like the beginning of a way to keep an eye on them. > > Thanks, > > Joe Healy > > From kent_johnson at skillsoft.com Wed Oct 27 13:54:21 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Wed Oct 27 13:54:25 2004 Subject: [Tutor] Turning a "script" into an "application" In-Reply-To: <797fe3d4041026223712c3ec8c@mail.gmail.com> References: <6.1.0.6.0.20041026220111.029072a0@mail4.skillsoft.com> <797fe3d4041026195164a7be97@mail.gmail.com> <6.1.0.6.0.20041026225558.029069a8@mail4.skillsoft.com> <797fe3d4041026223712c3ec8c@mail.gmail.com> Message-ID: <6.1.0.6.0.20041027074615.0290e7c8@mail4.skillsoft.com> At 01:37 AM 10/27/2004 -0400, Bill Mill wrote: >As for my bias towards socket development, I will readily admit to >that. I've spent a fair amount of time impelementing protocols, while >I've never written anything other than toy threaded applications, so >my view is certainly biased. I just feel that a simple socket protocol >is very easy to implement, and avoids queues, locks, and other less >familiar (for me) threading concepts. I think we each are biased towards what we are familiar with. No surprise there! >I'm not yet ready to concede my position, so I'll make one final >arguments for my position, and it's a higher level one. Conceptually, >the library and the GUI are different applications in this case. It is >entirely possible that this network code he's written will be useful >to others as a library. As such, it makes more sense conceptually to >keep it separate from the front end. I agree that he should think of the sniffer as a distinct, reusable module. To me, this implies a procedural interface (yet another front end) to the library which in my mind gets back to threads and XMLRPC. Though I suppose the procedural interface could talk to a separate process using the socket interface... Anyway, I think it's fair to say that both approaches will work, and both will present challenges to a beginner. The OP should choose based on his own preferences, biases and experience. Kent From Christian.Wyglendowski at greenville.edu Wed Oct 27 16:15:03 2004 From: Christian.Wyglendowski at greenville.edu (Christian Wyglendowski) Date: Wed Oct 27 16:15:20 2004 Subject: [Tutor] Turning a "script" into an "application" Message-ID: > -----Original Message----- > From: tutor-bounces@python.org > Subject: RE: [Tutor] Turning a "script" into an "application" > > Christian, > > If you want to be able to control your sniffer from a variety > of front ends (command-line, GUI, web app) then you probably > have to write it as a separate process with some kind of > socket interface. If you can pick a single UI, and you are > happy to have the UI running at the same time as the sniffer, > you could make the sniffer a separate thread in the same > application as the GUI. So I guess it is breaking down like this: o Threads for an all-in-one approach o Sockets for a more modular approach > If you decide to build a separate sniffer process, I suggest > you build the communications protocol on top of an existing > standard. . . (snipped) . > For example you could use XMLRPC to talk to the sniffer. > Using xmlrpclib on the client side and SimpleXMLRPCServer on > the sniffer side it is easy to set up. The client then makes > procedure calls on the server through a proxy. The advantage > of this method is it is easy to set up and it gives you a > very pythonic interface on the client side. The disadvantage > is that it is not easy to use the interface without writing a program. This sounds promising. I spent some time with the Python Cookbook last night and happened to look over some of the XMLRPC recipes. Considering that I want to keep things pretty loose as far as the interface<-->backend ties go, a socket based approach using XMLRPC looks pretty good right now. . . (more snipping) . > I suggest you start with the first version - GUI and sniffer > in one application. It is a good first step even if the > eventual goal is to have a separate sniffer process. Keep a > strong separation between the two parts so if you decide > later to split them it won't be too hard. I might wind up doing this eventually for a lightweight, easy to distribute application. Plus, I think I eventually need to get my hands dirty when it comes to threads. For now I think I am going to start digging into XMLRPC and using multiple processes. Thanks a lot for the insight and information. Christian http://www.dowski.com From mhansen at cso.atmel.com Wed Oct 27 16:27:42 2004 From: mhansen at cso.atmel.com (Mike Hansen) Date: Wed Oct 27 16:27:38 2004 Subject: [Tutor] Sets are cool Message-ID: <417FB05E.1@cso.atmel.com> A while ago, I had to send an e-mail message to the users of two different applications. I didn't want duplicate e-mail addresses since I wasn't sure the mail server would send multiple messages. I found other ways to get the combined list, but it got me thinking on how would I do it using Python. Well, sets to the rescue! >>> from sets import Set sets are new to version 2.3. I thought I had read that they might be built_in in 2.4. Anyone know? >>> mail_list = ["billyjoejeffbob@hick.com", "rakanishu@diabloii.com", "frodo@bagend.com", "averagejoe@ordinary.com", "rakanishu@diabloii.com"] This first mail list above has rakanishu twice. >>> mail_list2 = ["averagejoe@ordinary.com", "wolverine@xmen.org", "id10t@clueless.net"] mail_list2 has averagejoe in it. averagejoe is also in mail_list. >>> mail_list_set = Set(mail_list) Convert mail_list to a set. >>> mail_list_set Set(['billyjoejeffbob@hick.com', 'rakanishu@diabloii.com', 'frodo@bagend.com', 'averagejoe@ordinary.com']) Note: The double entry of rakanishu is now gone. Cool. >>> mail_list_set2 = Set(mail_list2) Convert mail_list2 to a set. >>> combined_mail_list = mail_list_set.union(mail_list_set2) union combines the two sets >>> combined_mail_list Set(['billyjoejeffbob@hick.com', 'frodo@bagend.com', 'averagejoe@ordinary.com', 'id10t@clueless.net', 'rakanishu@diabloii.com', 'wolverine@xmen.org']) Note: There is only one entry for averagejoe yet he was in both lists. Cool. Mission accomplished. I hadn't explored using sets in Python, and it's very handy. It looks like anytime you need to combine, find the differences, or find the common items in lists(or tuples), sets can make life easier. There are ways of doing this without using sets, but IMHO, using sets might be easier to read than looping through lists and comparing items. Thought I'd share another reason why I really love Python. Mike From Christian.Wyglendowski at greenville.edu Wed Oct 27 16:32:19 2004 From: Christian.Wyglendowski at greenville.edu (Christian Wyglendowski) Date: Wed Oct 27 16:32:25 2004 Subject: [Tutor] Turning a "script" into an "application" Message-ID: Bill, Kent, Joe, Thanks a lot for openly discussing the different approaches to my problem. With your help, I have gained some insight into the problem area that I am tackling, and that's what I was looking for. The multiprocess socket/XMLRPC option is very exciting in that I could create a generic "sniffer server" that can talk with whatever client(s) I decide to create. The all-in-one threaded option is tempting for a couple reasons: 1. I would like to get some experience with threads. 2. Overall, the architecture sounds less complex. For the sake of flexibility, I am leaning towards the multiprocess option using XMLRPC. Thanks again for the ideas/counter-ideas! Christian http://www.dowski.com From kent_johnson at skillsoft.com Wed Oct 27 16:48:28 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Wed Oct 27 16:49:17 2004 Subject: [Tutor] Sets are cool In-Reply-To: <417FB05E.1@cso.atmel.com> References: <417FB05E.1@cso.atmel.com> Message-ID: <6.1.0.6.0.20041027104356.02abd118@mail4.skillsoft.com> At 08:27 AM 10/27/2004 -0600, Mike Hansen wrote: > >>> from sets import Set > >sets are new to version 2.3. I thought I had read that they might be >built_in in 2.4. Anyone know? Yes, sets are cool, and yes, they are a built in type in Python 2.4. See here for details: http://www.python.org/dev/doc/devel/whatsnew/node2.html Actually Python 2.4 supports both the older 'sets.Set' and the 'set' built-in, which should be faster since it is implemented in C. If you want to write code that works under both you could use something like this: try: set except NameError: from sets import Set as set Then you can use set from either version of Python. Kent From RenX99 at gmail.com Wed Oct 27 17:13:28 2004 From: RenX99 at gmail.com (Rene Lopez) Date: Wed Oct 27 17:13:31 2004 Subject: [Tutor] recommended IDE for windows? Message-ID: <555128ce04102708132cd0cf98@mail.gmail.com> anyone have any recommendations for a good IDE for python on windows? Preferably free if possible :) So far I've been using idle, which works but seems pretty basic, would be nice to have some sort of IDE with tabs instead of multiple windows....helps keep the desktop clean ;-) -- Rene From kent_johnson at skillsoft.com Wed Oct 27 17:34:56 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Wed Oct 27 17:35:48 2004 Subject: [Tutor] recommended IDE for windows? In-Reply-To: <555128ce04102708132cd0cf98@mail.gmail.com> References: <555128ce04102708132cd0cf98@mail.gmail.com> Message-ID: <6.1.0.6.0.20041027113408.02909708@mail4.skillsoft.com> You can find a long list here: http://www.python.org/moin/IntegratedDevelopmentEnvironments Personally I use TextPad and Eclipse + pydev Kent At 11:13 AM 10/27/2004 -0400, Rene Lopez wrote: >anyone have any recommendations for a good IDE for python on windows? >Preferably free if possible :) So far I've been using idle, which >works but seems pretty basic, would be nice to have some sort of IDE >with tabs instead of multiple windows....helps keep the desktop clean >;-) >-- > >Rene >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From Christian.Wyglendowski at greenville.edu Wed Oct 27 17:43:05 2004 From: Christian.Wyglendowski at greenville.edu (Christian Wyglendowski) Date: Wed Oct 27 17:43:13 2004 Subject: [Tutor] recommended IDE for windows? Message-ID: > -----Original Message----- > [mailto:tutor-bounces@python.org] On Behalf Of Rene Lopez > Subject: [Tutor] recommended IDE for windows? > > anyone have any recommendations for a good IDE for python on windows? > Preferably free if possible :) So far I've been using idle, > which works but seems pretty basic, would be nice to have > some sort of IDE with tabs instead of multiple > windows....helps keep the desktop clean I use Pythonwin that comes with the pywin32 package (http://sourceforge.net/projects/pywin32/). It doesn't have tabs but it does have code completion, which I am very spoiled by. It also has some nice features for working with COM in Windows. I think that SPE (http://spe.pycs.net/) offers tabbed editing _and_ code completion. It requires wxPython and has some special features for working with the Blender3d application. It is a pre 1.0 though and has some quirks but also looks very promising. Christian http://www.dowski.com From mhansen at cso.atmel.com Wed Oct 27 17:50:45 2004 From: mhansen at cso.atmel.com (Mike Hansen) Date: Wed Oct 27 17:50:41 2004 Subject: [Tutor] recommended IDE for windows? In-Reply-To: <555128ce04102708132cd0cf98@mail.gmail.com> References: <555128ce04102708132cd0cf98@mail.gmail.com> Message-ID: <417FC3D5.60504@cso.atmel.com> A lot of people like Scite. I fired it up, but haven't played with it much. I have used Activestate's Komodo. It's not free. The personal edition is something like $30. The professional edition is around $250-$300. There are some really neat features like background syntax checking and code folding. Another editor/IDE I want to look into is Eclipse. Pydev is a plug-in for it. I'm kind of in the wait and see mode on this one. I've said this before..., you might take a look at emacs or vim. They have a steep learning curve, but they run on multiple platforms, so you don't have to learn a new editor when you are on Solaris or Linux. The point of emacs and vim is to keep your hands on the keyboard which supposedly makes you more productive. I'm digging into vim more and more. I tried emacs three times, and it didn't click with me. YMMV. Although vim doesn't have tabs, it has buffers, and you can display a buffer list. There are plenty of ways to configure emacs and vim do work mostly the way you want. I sometimes use JEdit for working on HTML since it does a great job of auto-completing tags for you. It think it also does syntax highlighting for Python. There's a list of editors at the Python web site.(http://www.python.org/moin/PythonEditors) You can also search this list for earlier discussions on editors/IDEs. Mike Rene Lopez wrote: >anyone have any recommendations for a good IDE for python on windows? >Preferably free if possible :) So far I've been using idle, which >works but seems pretty basic, would be nice to have some sort of IDE >with tabs instead of multiple windows....helps keep the desktop clean >;-) > > From bill.mill at gmail.com Wed Oct 27 18:05:46 2004 From: bill.mill at gmail.com (Bill Mill) Date: Wed Oct 27 18:05:56 2004 Subject: [Tutor] recommended IDE for windows? In-Reply-To: <417FC3D5.60504@cso.atmel.com> References: <555128ce04102708132cd0cf98@mail.gmail.com> <417FC3D5.60504@cso.atmel.com> Message-ID: <797fe3d4041027090567c6734f@mail.gmail.com> Hey, I'm gonna be the stodgy old man and second Mike's suggestion of Vim/Emacs. I prefer Vim personally (It is the editor to rule all editors!) but many prefer Emacs. Both editors are cross-platform to *everything*, so you almost never have to leave your editor behind. Furthermore, both have plugins for *everything* under the sun - syntax coloring, CVS uploading, etc etc. There are a lot of advantages to being good at a particular text editor; I find it comes in handy all the time. It sucks to learn, but boy is it useful once you get over the hump. Peace Bill Mill On Wed, 27 Oct 2004 09:50:45 -0600, Mike Hansen wrote: > A lot of people like Scite. I fired it up, but haven't played with it much. > > I have used Activestate's Komodo. It's not free. The personal edition is > something like $30. The professional edition is around $250-$300. There > are some really neat features like background syntax checking and code > folding. > > Another editor/IDE I want to look into is Eclipse. Pydev is a plug-in > for it. I'm kind of in the wait and see mode on this one. > > I've said this before..., you might take a look at emacs or vim. They > have a steep learning curve, but they run on multiple platforms, so you > don't have to learn a new editor when you are on Solaris or Linux. The > point of emacs and vim is to keep your hands on the keyboard which > supposedly makes you more productive. I'm digging into vim more and > more. I tried emacs three times, and it didn't click with me. YMMV. > Although vim doesn't have tabs, it has buffers, and you can display a > buffer list. There are plenty of ways to configure emacs and vim do work > mostly the way you want. > > I sometimes use JEdit for working on HTML since it does a great job of > auto-completing tags for you. It think it also does syntax highlighting > for Python. > > There's a list of editors at the Python web > site.(http://www.python.org/moin/PythonEditors) > You can also search this list for earlier discussions on editors/IDEs. > > Mike > > > > > Rene Lopez wrote: > > >anyone have any recommendations for a good IDE for python on windows? > >Preferably free if possible :) So far I've been using idle, which > >works but seems pretty basic, would be nice to have some sort of IDE > >with tabs instead of multiple windows....helps keep the desktop clean > >;-) > > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From RenX99 at gmail.com Wed Oct 27 18:06:30 2004 From: RenX99 at gmail.com (Rene Lopez) Date: Wed Oct 27 18:06:33 2004 Subject: [Tutor] Re: recommended IDE for windows? In-Reply-To: <555128ce04102708132cd0cf98@mail.gmail.com> References: <555128ce04102708132cd0cf98@mail.gmail.com> Message-ID: <555128ce04102709064c292234@mail.gmail.com> thanks for all the quick feedback. I think i found what i was looking for, at least for now ;-) -- Rene From RenX99 at gmail.com Wed Oct 27 18:09:29 2004 From: RenX99 at gmail.com (Rene Lopez) Date: Wed Oct 27 18:09:33 2004 Subject: [Tutor] recommended IDE for windows? In-Reply-To: <797fe3d4041027090567c6734f@mail.gmail.com> References: <555128ce04102708132cd0cf98@mail.gmail.com> <417FC3D5.60504@cso.atmel.com> <797fe3d4041027090567c6734f@mail.gmail.com> Message-ID: <555128ce04102709093beb2f83@mail.gmail.com> I actually use Vim to do most of my config file editing and such... never tried it for writing more than simple scripts, as it doesn't seem to be configured at the moment for fancy things like syntax highlighting and such. I suppose I should get around to learning it a bit better... so i can at least do more than just simple editing of files. On Wed, 27 Oct 2004 12:05:46 -0400, Bill Mill wrote: > Hey, > > I'm gonna be the stodgy old man and second Mike's suggestion of > Vim/Emacs. I prefer Vim personally (It is the editor to rule all > editors!) but many prefer Emacs. Both editors are cross-platform to > *everything*, so you almost never have to leave your editor behind. > Furthermore, both have plugins for *everything* under the sun - syntax > coloring, CVS uploading, etc etc. > > There are a lot of advantages to being good at a particular text > editor; I find it comes in handy all the time. It sucks to learn, but > boy is it useful once you get over the hump. > > Peace > Bill Mill > > > > > On Wed, 27 Oct 2004 09:50:45 -0600, Mike Hansen wrote: > > A lot of people like Scite. I fired it up, but haven't played with it much. > > > > I have used Activestate's Komodo. It's not free. The personal edition is > > something like $30. The professional edition is around $250-$300. There > > are some really neat features like background syntax checking and code > > folding. > > > > Another editor/IDE I want to look into is Eclipse. Pydev is a plug-in > > for it. I'm kind of in the wait and see mode on this one. > > > > I've said this before..., you might take a look at emacs or vim. They > > have a steep learning curve, but they run on multiple platforms, so you > > don't have to learn a new editor when you are on Solaris or Linux. The > > point of emacs and vim is to keep your hands on the keyboard which > > supposedly makes you more productive. I'm digging into vim more and > > more. I tried emacs three times, and it didn't click with me. YMMV. > > Although vim doesn't have tabs, it has buffers, and you can display a > > buffer list. There are plenty of ways to configure emacs and vim do work > > mostly the way you want. > > > > I sometimes use JEdit for working on HTML since it does a great job of > > auto-completing tags for you. It think it also does syntax highlighting > > for Python. > > > > There's a list of editors at the Python web > > site.(http://www.python.org/moin/PythonEditors) > > You can also search this list for earlier discussions on editors/IDEs. > > > > Mike > > > > > > > > > > Rene Lopez wrote: > > > > >anyone have any recommendations for a good IDE for python on windows? > > >Preferably free if possible :) So far I've been using idle, which > > >works but seems pretty basic, would be nice to have some sort of IDE > > >with tabs instead of multiple windows....helps keep the desktop clean > > >;-) > > > > > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- Rene From bill.mill at gmail.com Wed Oct 27 18:53:29 2004 From: bill.mill at gmail.com (Bill Mill) Date: Wed Oct 27 18:53:41 2004 Subject: [Tutor] recommended IDE for windows? In-Reply-To: <555128ce04102709093beb2f83@mail.gmail.com> References: <555128ce04102708132cd0cf98@mail.gmail.com> <417FC3D5.60504@cso.atmel.com> <797fe3d4041027090567c6734f@mail.gmail.com> <555128ce04102709093beb2f83@mail.gmail.com> Message-ID: <797fe3d4041027095354d085ec@mail.gmail.com> Rene, To get syntax highlighting (even in most of your config files! it highlights damn near anything recognizable) just type "syntax on" at the command prompt. Check out the FAQ - http://vimdoc.sourceforge.net/vimfaq.html . Peace Bill Mill bill.mill at gmail.com On Wed, 27 Oct 2004 12:09:29 -0400, Rene Lopez wrote: > I actually use Vim to do most of my config file editing and such... > never tried it for writing more than simple scripts, as it doesn't > seem to be configured at the moment for fancy things like syntax > highlighting and such. I suppose I should get around to learning it a > bit better... so i can at least do more than just simple editing of > files. > > > > > On Wed, 27 Oct 2004 12:05:46 -0400, Bill Mill wrote: > > Hey, > > > > I'm gonna be the stodgy old man and second Mike's suggestion of > > Vim/Emacs. I prefer Vim personally (It is the editor to rule all > > editors!) but many prefer Emacs. Both editors are cross-platform to > > *everything*, so you almost never have to leave your editor behind. > > Furthermore, both have plugins for *everything* under the sun - syntax > > coloring, CVS uploading, etc etc. > > > > There are a lot of advantages to being good at a particular text > > editor; I find it comes in handy all the time. It sucks to learn, but > > boy is it useful once you get over the hump. > > > > Peace > > Bill Mill > > > > > > > > > > On Wed, 27 Oct 2004 09:50:45 -0600, Mike Hansen wrote: > > > A lot of people like Scite. I fired it up, but haven't played with it much. > > > > > > I have used Activestate's Komodo. It's not free. The personal edition is > > > something like $30. The professional edition is around $250-$300. There > > > are some really neat features like background syntax checking and code > > > folding. > > > > > > Another editor/IDE I want to look into is Eclipse. Pydev is a plug-in > > > for it. I'm kind of in the wait and see mode on this one. > > > > > > I've said this before..., you might take a look at emacs or vim. They > > > have a steep learning curve, but they run on multiple platforms, so you > > > don't have to learn a new editor when you are on Solaris or Linux. The > > > point of emacs and vim is to keep your hands on the keyboard which > > > supposedly makes you more productive. I'm digging into vim more and > > > more. I tried emacs three times, and it didn't click with me. YMMV. > > > Although vim doesn't have tabs, it has buffers, and you can display a > > > buffer list. There are plenty of ways to configure emacs and vim do work > > > mostly the way you want. > > > > > > I sometimes use JEdit for working on HTML since it does a great job of > > > auto-completing tags for you. It think it also does syntax highlighting > > > for Python. > > > > > > There's a list of editors at the Python web > > > site.(http://www.python.org/moin/PythonEditors) > > > You can also search this list for earlier discussions on editors/IDEs. > > > > > > Mike > > > > > > > > > > > > > > > Rene Lopez wrote: > > > > > > >anyone have any recommendations for a good IDE for python on windows? > > > >Preferably free if possible :) So far I've been using idle, which > > > >works but seems pretty basic, would be nice to have some sort of IDE > > > >with tabs instead of multiple windows....helps keep the desktop clean > > > >;-) > > > > > > > > > > > _______________________________________________ > > > Tutor maillist - Tutor@python.org > > > http://mail.python.org/mailman/listinfo/tutor > > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > -- > > Rene > From bgailer at alum.rpi.edu Wed Oct 27 19:08:08 2004 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Wed Oct 27 19:07:50 2004 Subject: [Tutor] recommended IDE for windows? In-Reply-To: References: Message-ID: <6.1.2.0.0.20041027110716.03b21b30@mail.mric.net> At 09:43 AM 10/27/2004, Christian Wyglendowski wrote: > > -----Original Message----- > > [mailto:tutor-bounces@python.org] On Behalf Of Rene Lopez > > Subject: [Tutor] recommended IDE for windows? > > > > anyone have any recommendations for a good IDE for python on windows? > > Preferably free if possible :) So far I've been using idle, > > which works but seems pretty basic, would be nice to have > > some sort of IDE with tabs instead of multiple > > windows....helps keep the desktop clean > >I use Pythonwin that comes with the pywin32 package >(http://sourceforge.net/projects/pywin32/). It doesn't have tabs but it >does have code completion, which I am very spoiled by. It also has some >nice features for working with COM in Windows. > >I think that SPE (http://spe.pycs.net/) offers tabbed editing _and_ code >completion. It requires wxPython and has some special features for >working with the Blender3d application. It is a pre 1.0 though and has >some quirks but also looks very promising. I tried that page. The links on that page all take me to a photo of women golfing??? Bob Gailer bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell From gubbs at fudo.org Wed Oct 27 19:50:27 2004 From: gubbs at fudo.org (gubbs) Date: Wed Oct 27 19:50:30 2004 Subject: [Tutor] recommended IDE for windows? In-Reply-To: <6.1.2.0.0.20041027110716.03b21b30@mail.mric.net> References: <6.1.2.0.0.20041027110716.03b21b30@mail.mric.net> Message-ID: <42186.195.92.168.169.1098899427.squirrel@webmail.fudo.org> > At 09:43 AM 10/27/2004, Christian Wyglendowski wrote: >> > -----Original Message----- >> > [mailto:tutor-bounces@python.org] On Behalf Of Rene Lopez >> > Subject: [Tutor] recommended IDE for windows? >> > >> > anyone have any recommendations for a good IDE for python on windows? >> > Preferably free if possible :) So far I've been using idle, >> > which works but seems pretty basic, would be nice to have >> > some sort of IDE with tabs instead of multiple >> > windows....helps keep the desktop clean IDLE is pants for windows work imho. I have recently been using the thoroughly excellent (tabbed and code highlighting) pyPE written by Mr. Josiah Carlson. http://pype.sourceforge.net/ C. From RenX99 at gmail.com Wed Oct 27 19:53:55 2004 From: RenX99 at gmail.com (Rene Lopez) Date: Wed Oct 27 19:53:58 2004 Subject: [Tutor] Re: recommended IDE for windows? In-Reply-To: <555128ce04102708132cd0cf98@mail.gmail.com> References: <555128ce04102708132cd0cf98@mail.gmail.com> Message-ID: <555128ce04102710531d98c299@mail.gmail.com> I have noticed with jumping around checking out these other IDEs that sometimes my formatting gets thrown off for some reason. DrPython asks me if I want to convert my scripts to use UNIX style line breaks instead of windows style line breaks. I jump back and forth from windows and Linux... windows at work, and Linux at home so I'm not sure which to use. I don't seem to have this issue when I'm using idle at home or at work. Which should I choose? which is safer, it's a pain to have to figure out why my code won't work in an IDE cause the spacing got all fudged up. -- Rene From pythonTutor at venix.com Wed Oct 27 20:58:58 2004 From: pythonTutor at venix.com (Lloyd Kvam) Date: Wed Oct 27 20:59:56 2004 Subject: [Tutor] Re: recommended IDE for windows? In-Reply-To: <555128ce04102710531d98c299@mail.gmail.com> References: <555128ce04102708132cd0cf98@mail.gmail.com> <555128ce04102710531d98c299@mail.gmail.com> Message-ID: <1098903538.3337.43.camel@laptop.venix.com> The most likely cause of format issues relates to tab characters. The general Python recommendation is to indent four spaces for blocks. If you use tabs, the tab expansion should be set for eight spaces. Python will then handle mixtures of tabs and spaces correctly. Some editors will achieve the four space indent by using a tab expansion of four. This WILL foul up your code when viewed with an eight space expansion or when run by Python UNLESS ALL indents are done with tabs. If you can configure your editor(s) to save files with tabs expanded to spaces, then the code should be easy to move around. With regard to line breaks, I use UNIX style on Windows. All of the normal Python programs will work correctly. Notepad will not be available to edit your code, but that should not be much of a hardship. On Wed, 2004-10-27 at 13:53, Rene Lopez wrote: > I have noticed with jumping around checking out these other IDEs that > sometimes my formatting gets thrown off for some reason. DrPython > asks me if I want to convert my scripts to use UNIX style line breaks > instead of windows style line breaks. I jump back and forth from > windows and Linux... windows at work, and Linux at home so I'm not > sure which to use. I don't seem to have this issue when I'm using > idle at home or at work. Which should I choose? which is safer, it's > a pain to have to figure out why my code won't work in an IDE cause > the spacing got all fudged up. -- Lloyd Kvam Venix Corp From davholla2002 at yahoo.co.uk Wed Oct 27 21:12:01 2004 From: davholla2002 at yahoo.co.uk (David Holland) Date: Wed Oct 27 21:22:43 2004 Subject: [Tutor] Creating a pop up problem In-Reply-To: <20041027160555.F07F91E400F@bag.python.org> Message-ID: <20041027191201.18035.qmail@web25402.mail.ukl.yahoo.com> I wrote this little program to create a GUI which when you click on it creates 10 pop ups :- #!/usr/bin/env python import sys from Tkinter import * makemodal = (len(sys.argv) > 1) class Yoli(Frame): def __init__(self, master): Frame.__init__(self, master) self.grid() self.createwidgets() def loveyoli(self): win = Toplevel() Label(win, text='I love you Yoli').pack() if makemodal: win.focus_set() win.grab_set() win.wait_window() #print 'dialog exit' def callloveyoli(self): i = 0 j = 10 while i 1) class Yoli(Frame): def __init__(self, master): Frame.__init__(self, master) self.grid() self.createwidgets() def loveyoli(self): win = Toplevel() Label(win, text='I love you Yoli').pack() if makemodal: win.focus_set() win.grab_set() win.wait_window() #print 'dialog exit' def callloveyoli(self): i = 0 try: j = self.numb_ent.get() j = int(j) except: j = 3 while i I am attempting to read information from a remote registry using Python, but cannot find any examples of it in the Python/Activestate mailing list archives nor plain old Google.com. Can someone point out what I am doing wrong? The below code is what I am using, and it errors on the 'successful=' line, telling me I am giving it invalid parameters. The parameters I am unsure of are the first and last ones, as , once again, I can find no documentation as to what they should be in Python. ------------------------------ Microsoft documentation says this->http://msdn.microsoft.com/library/default.asp?url=/library/en-us/wmisd k/wmi/getstringvalue_method_in_class_stdregprov.asp uint32 GetStringValue( uint32 hDefKey, string sSubKeyName, string sValueName, string sValue ); ------------------------------- My Code ---------------------- wmiRegObj = win32com.client.GetObject( r'winmgmts://somesystem/root/default:StdRegProv') if wmiRegObj: print "Successfully connected to registry" successful = wmiRegObj.GetStringValue( 'HKEY_LOCAL_MACHINE', 'SOFTWARE\Microsoft\Windows NT\CurrentVersion\WinLogon\' , 'DefaultUserName', username ) John A. Gooch Systems Administrator IT - Tools EchoStar Satellite L.L.C. 9601 S. Meridian Blvd. Englewood, CO 80112 Desk: 720-514-5708 -----Original Message----- From: Christian Wyglendowski [mailto:Christian.Wyglendowski@greenville.edu] Sent: Wednesday, October 27, 2004 8:32 AM To: Kent Johnson; Bill Mill Cc: tutor@python.org Subject: RE: [Tutor] Turning a "script" into an "application" Bill, Kent, Joe, Thanks a lot for openly discussing the different approaches to my problem. With your help, I have gained some insight into the problem area that I am tackling, and that's what I was looking for. The multiprocess socket/XMLRPC option is very exciting in that I could create a generic "sniffer server" that can talk with whatever client(s) I decide to create. The all-in-one threaded option is tempting for a couple reasons: 1. I would like to get some experience with threads. 2. Overall, the architecture sounds less complex. For the sake of flexibility, I am leaning towards the multiprocess option using XMLRPC. Thanks again for the ideas/counter-ideas! Christian http://www.dowski.com _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From flaxeater at yahoo.com Wed Oct 27 22:20:32 2004 From: flaxeater at yahoo.com (Chad Crabtree) Date: Wed Oct 27 22:20:35 2004 Subject: [Tutor] Turning a "script" into an "application" Message-ID: <20041027202032.43505.qmail@web54306.mail.yahoo.com> Christian Wyglendowski wrote: >Bill, Kent, Joe, > >Thanks a lot for openly discussing the different approaches to my >problem. With your help, I have gained some insight into the problem >area that I am tackling, and that's what I was looking for. > >The multiprocess socket/XMLRPC option is very exciting in that I could >create a generic "sniffer server" that can talk with whatever client(s) >I decide to create. > >The all-in-one threaded option is tempting for a couple reasons: > 1. I would like to get some experience with threads. > 2. Overall, the architecture sounds less complex. > >For the sake of flexibility, I am leaning towards the multiprocess >option using XMLRPC. > >Thanks again for the ideas/counter-ideas! > Well I have read through this thread and I feel there is a simpler solution that has not been discussed. That is why not do the sniffing logic inside the OnIdle event in the GUI, it would be easy to do and maintain state between calls and to start and stop, you could use your current script like a library and just do state management inside a class, then do the appropriate calls from OnIdle and update the GUI from the class. I have not done threading or Socket programing but this was my first idea, this way you could use the mainloop of the GUI to do the asynch stuff ( I Think) for you. __________________________________ Do you Yahoo!? Yahoo! Mail Address AutoComplete - You start. We finish. http://promotions.yahoo.com/new_mail From pythonTutor at venix.com Wed Oct 27 23:29:40 2004 From: pythonTutor at venix.com (Lloyd Kvam) Date: Wed Oct 27 23:29:47 2004 Subject: [Tutor] Window Registry Access In-Reply-To: <15A1FDA26DAD524DA7A7AF77313EBA8F07BC00CD@riv-excha5.echostar.com> References: <15A1FDA26DAD524DA7A7AF77313EBA8F07BC00CD@riv-excha5.echostar.com> Message-ID: <1098912580.3337.56.camel@laptop.venix.com> On Wed, 2004-10-27 at 16:19, Gooch, John wrote: > I am attempting to read information from a remote registry using Python, but > cannot find any examples of it in the Python/Activestate mailing list > archives nor plain old Google.com. Can someone point out what I am doing > wrong? You have backslash (\) characters in the string. These are used in Python (and many other languages) to handle special characters that are otherwise hard to type directly. For example \r is the carriage return (enter) key. To enter a literal backslash, you use a pair of them (\\). The simpler alternative is to use a raw string. By placing r before the quote you can disable the special backslash processing. r'SOFTWARE\Microsoft\Windows NT\CurrentVersion\WinLogon'+'\\' == 'SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\WinLogon\\' NOTE that a raw string MUST NOT end with a backslash character! > The below code is what I am using, and it errors on the 'successful=' > line, telling me I am giving it invalid parameters. The parameters I am > unsure of are the first and last ones, as , once again, I can find no > documentation as to what they should be in Python. Python is simply providing a means to use functions provided by Microsoft. You need to use the Microsoft documentation while making allowances for the fact that the expected language is probably C++. > ------------------------------ > Microsoft documentation says > this->http://msdn.microsoft.com/library/default.asp?url=/library/en-us/wmisd > k/wmi/getstringvalue_method_in_class_stdregprov.asp > uint32 GetStringValue( > uint32 hDefKey, > string sSubKeyName, > string sValueName, > string sValue > ); > > ------------------------------- > > > My Code > ---------------------- > wmiRegObj = win32com.client.GetObject( > r'winmgmts://somesystem/root/default:StdRegProv') > if wmiRegObj: > print "Successfully connected to registry" > successful = wmiRegObj.GetStringValue( 'HKEY_LOCAL_MACHINE', > 'SOFTWARE\Microsoft\Windows NT\CurrentVersion\WinLogon\' , > 'DefaultUserName', username ) > > > John A. Gooch > Systems Administrator > IT - Tools > EchoStar Satellite L.L.C. > 9601 S. Meridian Blvd. > Englewood, CO 80112 > Desk: 720-514-5708 > > > -----Original Message----- > From: Christian Wyglendowski [mailto:Christian.Wyglendowski@greenville.edu] > Sent: Wednesday, October 27, 2004 8:32 AM > To: Kent Johnson; Bill Mill > Cc: tutor@python.org > Subject: RE: [Tutor] Turning a "script" into an "application" > > > Bill, Kent, Joe, > > Thanks a lot for openly discussing the different approaches to my problem. > With your help, I have gained some insight into the problem area that I am > tackling, and that's what I was looking for. > > The multiprocess socket/XMLRPC option is very exciting in that I could > create a generic "sniffer server" that can talk with whatever client(s) I > decide to create. > > The all-in-one threaded option is tempting for a couple reasons: > 1. I would like to get some experience with threads. > 2. Overall, the architecture sounds less complex. > > For the sake of flexibility, I am leaning towards the multiprocess option > using XMLRPC. > > Thanks again for the ideas/counter-ideas! > > Christian > http://www.dowski.com > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp From STEVEN.M.FAULCONER at saic.com Wed Oct 27 23:33:55 2004 From: STEVEN.M.FAULCONER at saic.com (Faulconer, Steven M.) Date: Wed Oct 27 23:33:47 2004 Subject: [Tutor] Mount size Message-ID: <207DA77D2384D411A48B0008C7095D810152B8D7@us-melbourne.mail.saic.com> Hello everyone, We are having some issues getting reliable information for available disk space within Python programs. We are using os.statvfs to get the blocks free, but the numbers are not consistent between local and NFS mounted drives. For instance, system A returns a given size for the f_bavail while system B returns exactly twice that number. The drive in question is local on system A and NFS v3 mounted on System B. On system A, f_bavail actually returns the exact kilobyte value for the available size for the drive in question. System B gets exactly double. On another system, I can't seem to correlate the value of f_bavail to the actual amount of storage available. Given that f_bavail is the number of blocks available (non-superuser) I would assume that we could multiply that by f_bsize and then divide by 1 million (for megabytes) or 1 billion (gigabytes). However, on none of the test systems does that return anything close to what it should be. All systems in question are running Solaris (8 or 9) and Python 2.3.2. I imagine I missed a detail or something, so please let me know if you need more information. If you have a recommended method for finding disk usage/available that works for local and NFS mounted systems, I'd love to see it. Thanks. Steven From keridee at jayco.net Thu Oct 28 00:07:53 2004 From: keridee at jayco.net (Jacob S.) Date: Thu Oct 28 00:12:58 2004 Subject: [Tutor] Questions come and questions go, but I will email forever Message-ID: <000701c4bc72$3e549240$dd5428cf@JSLAPTOP> import sys sys.stdout = tutor@python.org ## This email message ## Am I bored or what? print "Hi everyone!" print print '''\tI need help. The bottom line is, I am having extreme difficulties with messy code.\r\n My program has problems. There are two different scenes I want to implement using VPython,\r\n but I originally combined both of their codes together. Now, I want to put them into seperate\r\n functions so that I can call them. As it is, the two functions would have to reference each other.\r\n Really, I want to find if there is a way to make all future variables in a module global. Is there\r\n any sort of really simple function like sys.makeallglobals() that declares all variables that point\r\n forward as global? I would really like to know.''' print "Thanks\n"*60 print "Jacob Schmidt" '''P.S. I'm not joking by putting my email into a python format. I'm just getting extra practice ;-)''' From dyoo at hkn.eecs.berkeley.edu Thu Oct 28 00:20:03 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Oct 28 00:20:07 2004 Subject: [Tutor] Mount size In-Reply-To: <207DA77D2384D411A48B0008C7095D810152B8D7@us-melbourne.mail.saic.com> Message-ID: On Wed, 27 Oct 2004, Faulconer, Steven M. wrote: > We are having some issues getting reliable information for available disk > space within Python programs. We are using os.statvfs to get the blocks > free, but the numbers are not consistent between local and NFS mounted > drives. [some text cut] > Given that f_bavail is the number of blocks available (non-superuser) I > would assume that we could multiply that by f_bsize and then divide by 1 > million (for megabytes) or 1 billion (gigabytes). Hi Steven, You may want to use f_frsize, not f_bsize. The underlying man page for statvfs says the following about the tuple that we get back: """ u_long f_bsize; /* preferred file system block size */ u_long f_frsize; /* fundamental filesystem block (size if supported) */ fsblkcnt_t f_blocks; /* total # of blocks on file system in units of f_frsize */ fsblkcnt_t f_bfree; /* total # of free blocks */ fsblkcnt_t f_bavail; /* # of free blocks avail to non-super-user */ fsfilcnt_t f_files; /* total # of file nodes (inodes) */ fsfilcnt_t f_ffree; /* total # of free file nodes */ fsfilcnt_t f_favail; /* # of inodes avail to non-super-user*/ u_long f_fsid; /* file system id (dev for now) */ char f_basetype[FSTYPSZ]; /* target fs type name, null-terminated */ u_long f_flag; /* bit mask of flags */ u_long f_namemax; /* maximum file name length */ char f_fstr[32]; /* file system specific string */ u_long f_filler[16]; /* reserved for future expansion */ """ (Taken from Solaris 8 man page on statvfs) The way that the docs make a distinction between the "preferred" and "fundamental" block sizes is significant. Use 'f_frsize' instead, and you should get better results. There's also a section in the BUGS that says: """ BUGS The values returned for f_files, f_ffree, and f_favail may not be valid for NFS mounted file systems. """ So be careful not to depends on those particular values on NFS-mounted drives. I hope this helps! From alan.gauld at freenet.co.uk Thu Oct 28 00:27:30 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu Oct 28 00:27:16 2004 Subject: [Tutor] Turning a "script" into an "application" References: Message-ID: <006801c4bc74$25d327c0$af468651@xp> > Rather than use Windows to control my script's behavior, > I would like to add some larger control method to it so > it can have persistent (in memory) data, the ability to > control scan parameters from within the application, > the ability to stop and start scans from within the > application, save captured data to file, etc. None of this is difficult, just write a wrapper application around what you have, leave it running and get it to invoke the current app at a timed interval. The only need for threads would be if the current app takes a long time to run in which case it should run in the background to prevent the control app from "locking up" while the scan runs. > I would like to leave interface options open > (text, GUI, web, etc). Always a good idea to separate presentation from logic, but you might want to consider multiple applets for each presentation, each calling the same underlying set of components/modules. Alan G. From alan.gauld at freenet.co.uk Thu Oct 28 00:32:21 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu Oct 28 00:34:02 2004 Subject: [Tutor] jython vs CPython... what are the differences? References: <555128ce04102611206a77ad66@mail.gmail.com> Message-ID: <006d01c4bc74$d3add6b0$af468651@xp> > I know that speed is often a difference between the two... but what > else is different? Some modules aren't ported because Jython can use Java equivalents which the Jython team deem to be 'better'... Some modules are just not ported because nobody got round to it yet! Most pure python modules will work, but if they rely on a native C module which hasn't been ported then you are stuck. >From my experience about 75-80% of my code works fine, another 10% can be made to work with minor tweaks. But I am very much a vanilla Python user, YMMV... The really insanely great thing about Jython is its ability to mix n match Java objects with Python objects, and even to prototype new Java classes in Python before converting them to the much more verbose and demanding Java. Also, for testing new Java classes at the >>> prompt - fantastic! Alan g. From alan.gauld at freenet.co.uk Thu Oct 28 00:34:36 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu Oct 28 00:35:21 2004 Subject: [Tutor] Classes Turn Strings Into Tuples for some reason References: <15A1FDA26DAD524DA7A7AF77313EBA8F07BC00CB@riv-excha5.echostar.com> Message-ID: <008301c4bc75$23aea4a0$af468651@xp> ----- Original Message ----- From: "Gooch, John" To: Sent: Wednesday, October 27, 2004 12:10 AM Subject: [Tutor] Classes Turn Strings Into Tuples for some reason > #Define Classes > class Record: > def __init__(self, name ): > self.name = name, The comma at the end says "make this a tuple of one string". Remove the comma and all will be well. Alan g. From alan.gauld at freenet.co.uk Thu Oct 28 00:39:18 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu Oct 28 00:39:25 2004 Subject: [Tutor] Turning a "script" into an "application" References: <6.1.0.6.0.20041026220111.029072a0@mail4.skillsoft.com><797fe3d4041026195164a7be97@mail.gmail.com> <417F31E6.7080800@omc-international.com.au> Message-ID: <00a001c4bc75$cbbdb6e0$af468651@xp> > > Secondly, he would have to learn about threads and thread > > synchronization. While this is not overly difficult, it is more > > difficult than learning sockets (IMNSHO, more on this) and tends to > > lead to very subtle and difficult to debug errors. > > > > > This sounds interesting. Are you aware of any examples using sockets for > basic rpc on the web somewhere? There are lots, its how nearly all Unix rpc was done between 1980-1990. And it is still an easy way to do things if the number of simultaneous executions is low and the protocol is simple. The Dietel & Dietel Python book gives an example of a client server OXO game built using sockets, if that helps... Alan G. From alan.gauld at freenet.co.uk Thu Oct 28 00:43:07 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu Oct 28 00:42:54 2004 Subject: [Tutor] Turning a "script" into an "application" References: <6.1.0.6.0.20041026220111.029072a0@mail4.skillsoft.com><797fe3d4041026195164a7be97@mail.gmail.com><6.1.0.6.0.20041026225558.029069a8@mail4.skillsoft.com> <797fe3d4041026223712c3ec8c@mail.gmail.com> Message-ID: <00a501c4bc76$54719830$af468651@xp> > my view is certainly biased. I just feel that a simple socket protocol > is very easy to implement, and avoids queues, locks, and other less > familiar (for me) threading concepts. I would back this up. A lot of FUD has been created around the mysteries of using sockets - how hard "marshalling" is etc by the vendors of more modern rpc tools. But in fact for a simple command based protocol sockets are as easy as using pipes (which would be another even easier option!). You just read and write strings and parse the strings, which for a known, fixed protocol is easy. > I'm glad we could have such civilized discourse on the topic; I'd like > to point out here that this list has been excellent in the short time > I've been reading it. I think it's good that we're exposing the pros > and cons of each approach. This is one of the wonderfuil things about tutor - its invariably polite and it encompasses a huge range of experience both over time and technology. Alan G. From alan.gauld at freenet.co.uk Thu Oct 28 00:45:16 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu Oct 28 00:45:30 2004 Subject: [Tutor] Turning a "script" into an "application" References: <6.1.0.6.0.20041026220111.029072a0@mail4.skillsoft.com><797fe3d4041026195164a7be97@mail.gmail.com><417F3196.2040208@omc-international.com.au><797fe3d4041026224741d8de35@mail.gmail.com><417F3DA8.1080504@omc-international.com.au> <797fe3d404102623482cf0494@mail.gmail.com> Message-ID: <00ac01c4bc76$a1872d10$af468651@xp> > Yes, this will only handle one connection at a time. If you want to > write a server to handle a lot of connections concurrently, there are > two main approaches. They are nicely illustrated by two different > webservers. To be honest if you only need one request at a time - ie you only use one UI option at once - then pipes are even easier than sockets. The advantage of sockets is that you could have all three UI options running at once communicating with the same back end scanning server. Alan G. From alan.gauld at freenet.co.uk Thu Oct 28 00:49:03 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu Oct 28 00:49:03 2004 Subject: [Tutor] recommended IDE for windows? References: Message-ID: <00cf01c4bc77$28c36280$af468651@xp> > I use Pythonwin that comes with the pywin32 package > (http://sourceforge.net/projects/pywin32/). > It doesn't have tabs but It does however use an MDI interface as opposed to IDLEs SDI so the window clutter is reduced somewhat. Alan g. From dyoo at hkn.eecs.berkeley.edu Thu Oct 28 01:39:57 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Oct 28 01:40:03 2004 Subject: [Tutor] Questions come and questions go, but I will email forever In-Reply-To: <000701c4bc72$3e549240$dd5428cf@JSLAPTOP> Message-ID: On Wed, 27 Oct 2004, Jacob S. wrote: > print '''\tI need help. The bottom line is, I am having extreme difficulties > with messy code.\r\n > My program has problems. There are two different scenes I want to implement > using VPython,\r\n Hi Jacob, Quick note: if you use the triple-quoted strings, you don't have to put explicit '\r\n' characters at the end of each line: they're included as part of the string. For example: ### >>> message = """hello ... world ... this ... is ... a ... test""" >>> message 'hello\nworld\nthis\nis\na\ntest' >>> ### You're writing an email: it doesn't have to be double spaced. *grin* > but I originally combined both of their codes together. Now, I want to put > them into seperate\r\n > functions so that I can call them. As it is, the two functions would have to > reference each other.\r\n Hmmm. I'm still slightly confused about this. Can you show us what those two functions look like? There might be a way of disentangling them so that they don't reference each other. And if not, at least we'll be able to see why. Global variables are almost always a Very Bad Idea. Can you show us an example where it would be useful? Best of wishes to you! From keridee at jayco.net Thu Oct 28 03:08:03 2004 From: keridee at jayco.net (Jacob S.) Date: Thu Oct 28 03:07:19 2004 Subject: [Tutor] Controlling a process and then killing it References: <417A9838.3090401@h-lab.net> Message-ID: <003f01c4bc8a$9a8961e0$bb5428cf@JSLAPTOP> Hello. You might try the os module. If you look in the python documentation for os (standard module), you can see that os has functions like getpid() -- return the current process id -- etc. HTH, Jacob Schmidt From keridee at jayco.net Thu Oct 28 03:17:33 2004 From: keridee at jayco.net (Jacob S.) Date: Thu Oct 28 03:16:43 2004 Subject: [Tutor] Creating a pop up problem References: <20041027191201.18035.qmail@web25402.mail.ukl.yahoo.com> Message-ID: <004201c4bc8b$eb07a7c0$bb5428cf@JSLAPTOP> Hi. WARNING: This will not help you with your problem. I suggest, however, that you not use idle when running programs that contain tkinter. It has been said in many places--including this mailing list--that idle is written with tkinter, and the mainloops don't interact very well. If I were you, I would run the program from the interpreter or, if you're running windows--that's all I'm familiar with--you can double-click the py file if you have the file associations set up right. I hope that this helps, Jacob Schmidt From bill.mill at gmail.com Thu Oct 28 04:19:33 2004 From: bill.mill at gmail.com (Bill Mill) Date: Thu Oct 28 04:19:38 2004 Subject: [Tutor] Turning a "script" into an "application" In-Reply-To: <00ac01c4bc76$a1872d10$af468651@xp> References: <6.1.0.6.0.20041026220111.029072a0@mail4.skillsoft.com> <797fe3d4041026195164a7be97@mail.gmail.com> <417F3196.2040208@omc-international.com.au> <797fe3d4041026224741d8de35@mail.gmail.com> <417F3DA8.1080504@omc-international.com.au> <797fe3d404102623482cf0494@mail.gmail.com> <00ac01c4bc76$a1872d10$af468651@xp> Message-ID: <797fe3d40410271919185ede62@mail.gmail.com> On Wed, 27 Oct 2004 23:45:16 +0100, Alan Gauld wrote: > > Yes, this will only handle one connection at a time. If you want to > > write a server to handle a lot of connections concurrently, there > are > > two main approaches. They are nicely illustrated by two different > > webservers. > > To be honest if you only need one request at a time - ie you only use > one UI option at once - then pipes are even easier than sockets. > The advantage of sockets is that you could have all three UI options > running at once communicating with the same back end scanning server. > I agree that only one is necessary for the original poster's purposes. I was speaking hypothetically, since Joe was asking about network servers in general. Furthermore, pipes can't work over the network, which is a requirement of the original poster. Peace Bill Mill bill.mill at gmail.com > Alan G. > > From ewijaya at singnet.com.sg Wed Oct 27 20:27:03 2004 From: ewijaya at singnet.com.sg (Edward WIJAYA) Date: Thu Oct 28 04:27:11 2004 Subject: [Tutor] Python Command Line Args (input) equivalent to Perl Message-ID: Dear Tutor, I am new to Python, and I like to learn more about it. Since I am used to Perl before, I would like to know what is Python equivalent of Perl code below: $filename = $ARGV[0]; open (FILE,"$filename") || die "Can't Open $filename: $!\n"; while{ #dealing with it per-lines #process something here } Please also kindly suggest any pointer/website link, where I can find Perl-Python concordance, especially to facilitate Perl conversion to Python. Thanks so much for your time. Hope to hear from you again. -- Regards, Edward WIJAYA SINGAPORE From tktucker at gmail.com Thu Oct 28 04:35:25 2004 From: tktucker at gmail.com (Tom Tucker) Date: Thu Oct 28 04:35:28 2004 Subject: [Tutor] Line matching without a for statement? Message-ID: <2a278ffe041027193511eb0a3@mail.gmail.com> Tutors, Good evening. Is it possible to search/query a variable without doing a for statement (ie. for line in ouptut). Hopefully my terminology is correct. The below example script might make more sense. Thoughts? Thanks, Tom SCRIPT (Example) ###################### #!/usr/bin/python import os, re output = os.popen('/sbin/ifconfig -a').readlines() interface = re.compile(r'^eth\d') if interface.search(output): print "found an interface" ERROR OUTPUT ########################### Traceback (most recent call last): File "./test.py", line 9, in ? if interface.search(output): TypeError: expected string or buffer From keridee at jayco.net Thu Oct 28 04:41:51 2004 From: keridee at jayco.net (Jacob S.) Date: Thu Oct 28 04:41:34 2004 Subject: [Tutor] Questions come and questions go, but I will email forever References: Message-ID: <00b501c4bc97$b1bec690$bb5428cf@JSLAPTOP> Okay, Danny Yoo said... > You're writing an email: it doesn't have to be double spaced. *grin* I thought that "\r\n" is the escape sequence for a hard return. Maybe that's only true for Windows? > Hmmm. I'm still slightly confused about this. Can you show us what those > two functions look like? There might be a way of disentangling them so > that they don't reference each other. And if not, at least we'll be able > to see why. This is a killer, but I went gung ho into attacking the code and I don't have an original copy of the code. However, I can give you a non-working example. ## Beginning of non-working code from visual import * from time import localtime from __future__ import division import math import string import TimeConversion import winsound from visual.text import * import sys import os day = time.strftime("%A, %B %d, %Y") ## Displays the date that you see first print day global scenegoon global scene2goon scenegoon = 0 scene2goon = 0 dirlist = os.listdir("c:\\") if 'Jacob Laptop' in dirlist: variable = 594 elif 'Home Computer' in dirlist: variable = 370 elif 'Sissy Computer' in dirlist: variable = 365 elif 'Michael Laptop' in dirlist: variable = 594 elif 'Office Computer' in dirlist: variable = 365 elif 'School Auction Laptop' in dirlist: variable = 594 else: print 'Hey you need to put a folder in this computer!. ' print '''Folders include: Jacob Laptop Home Computer Sissy Computer Michael Laptop Office Computer School Auction Laptop ''' folder = raw_input('Which computer is this? ') folder = "C:\\"+folder os.mkdir(folder) ask = input('[365,594] Please give me one.') variable = ask alarm = raw_input('What should the alarm be set to? ') if alarm != '': alarm = TimeConversion.standtomil(alarm) alarm = string.split(alarm, ":") alarmhour = int(alarm[0]) alarmmin = int(alarm[1]) else: alarmhour = '' alarmmin = '' def makeanalog(): scenegoon = 1 ## Default values ## scene = display() scene.title = 'Analog Clock by Jacob\'s Clockworks, Inc.' scene.userspin = 1 scene.userzoom = 1 r = 5 # Radius of the clock handsradius = 0.05 clockfacecolor = color.white clockframecolor = color.blue hhandcolor = color.black mhandcolor = color.black shandcolor = color.red fourthscolor = color.purple hourcolor = color.orange mincolor = color.green ############################ scene.x = variable scene.exit=0 scene.range=(r+2, r+2, r+2) scene.visible = 1 clockface = cylinder(pos=(0,0,0), color=clockfacecolor, radius=r, axis=(0,0,0.1)) clockframe = ring(pos=(0,0,0),axis=clockface.axis, radius=r, color=clockframecolor, thickness=0.3) noonmark = ring(pos=(0,r-0.15,0),axis=(1,0,0),radius=0.3,thickness=0.3,color=fourthscol or) threequartermark = ring(pos=(-r+0.15,0,0),axis=(0,1,0),radius=0.3,thickness=0.3,color=fourthsco lor) onequartermark = ring(pos=(r-0.15,0,0),axis=(0,1,0),radius=0.3,thickness=0.3,color=fourthscol or) halfmark = ring(pos=(0,-r+0.15,0),axis=(1,0,0),radius=0.3,thickness=0.3,color=fourthsco lor) list=[1,2,4,5,7,8,10,11] for n in list: mark = sphere(pos=(r*sin(math.pi*n/6),r*cos(math.pi*n/6),0.3),color=hourcolor,radiu s=0.25) list=range(60) for n in list: if n % 5 == 0: list.pop(list.index(n)) for n in list: mark = sphere(pos=(r*sin(math.pi*n/30),r*cos(math.pi*n/30),0.3),color=mincolor,radi us=0.125) x='' y='' hhand='' mhand='' shand='' def makedigital(): scene2goon == 1 ## Default values ## scene2 = display() scene2.select() scene2.title = 'Digital Clock by Jacob\'s Clockworks, Inc.' scene2.userspin = 1 scene2.userzoom = 1 clockbgcolor = color.lcd clockframecolor = color.blue digitcolor = color.black ############################ clocklength = 10 clockheight = 3 scene2.x = variable scene2.y=430 scene2.height = 200 scene2.autoscale = 0 scene2.exit=0 scene2.range = [clocklength/2+1,clocklength/2+1,clocklength/2+1] scene2.visible = 1 clockbg = box(pos=(0,0,0),width=0.1,height=clockheight,length=clocklength,color=clockb gcolor) clockframe = box(pos=(0,0,-0.1),width=0.1,height=clockheight+0.25,length=clocklength+0.25 ,color=clockframecolor) scenegoon = 1 scene2goon = 1 def analogcode(): t = time.localtime() hour = t[3] min = t[4] sec = t[5] if hour == alarmhour: if min == alarmmin: if sec < 15 and sec >= 0: winsound.Beep(1000,250) if hour > 12: hour = hour-12 if hour == 0: hour = 12 if scene.kb.keys != 0: key = scene.kb.getkey() if key == 'f12': scenegoon = 0 if key == 'f11': clockface.color = input('Give me a tuple of the new face color. ') if key == 'q': scenegoon = 0 scene2goon = 0 try: del x del y hhand.visible=0 del hhand mhand.visible=0 del mhand shand.visible=0 del shand except: pass scene.select() newmin = min+(sec/60) newhour = hour+(newmin/60)+(sec/3600) y = 0.5*r*sin((math.pi*newhour)/6) x = 0.5*r*cos((math.pi*newhour)/6) hhand = curve(color=hhandcolor,radius=handsradius) hhand.append(pos=(0,0,0.3)) hhand.append(pos=(y,x,0.3)) y = 0.75*r*sin((math.pi*newmin)/30) x = 0.75*r*cos((math.pi*newmin)/30) mhand = curve(color=mhandcolor,radius=handsradius) mhand.append(pos=(0,0,0.3)) mhand.append(pos=(y,x,0.3)) y = 0.75*r*sin((math.pi*sec)/30) x = 0.75*r*cos((math.pi*sec)/30) shand = curve(color=shandcolor,radius=handsradius) shand.append(pos=(0,0,0.3)) shand.append(pos=(y,x,0.3)) def digitalcode(): scene2.select() if scene2.kb.keys != 0: key = scene2.kb.getkey() if key == 'f12': scene2goon = 0 if key == 'f11': clockbg.color = input('Give tuple for background color. ') if key == 'q': scenegoon = 0 scene2goon = 0 try: text.makeinvisible(hrmin) text.makeinvisible(secdigit) del hrdigit del mindigit del secdigit except: pass hour = str(hour) min = str(min) sec = str(sec) min = string.zfill(min,2) sec = string.zfill(sec,2) hrmin = string.join([hour,min],":") hrmin = text(pos=(-0.9,-1,0.11),color=digitcolor,string=hrmin,justify='center',heigh t=2,display=scene2) secdigit = text(pos=(3.35,-1,0.11),color=digitcolor,string=sec,justify='center',height= 1,display=scene2) while 1: rate(1) if scenegoon: analogcode() if scene2goon: digitalcode() if not scenegoon: try: scene.visible = 0 del scene except: pass if not scene2goon: try: scene2.visible = 0 del scene2 except: pass sys.exit() if __name__ == "__main__": makeanalog() ## End of code I guess I had better go into more detail. If you read the code closely enough, you will notice that this program displays (or displayed) two clocks, analog on top, digital on bottom. (It's pretty impressive for me) Before I messed with the code, the while loop contained both updates for the analog and the digital. I told myself that I didn't like the digital clock as much, and didn't want it displayed when __name__ == "__main__": So, in order to split the code apart, I wanted to put the two clocks into seperate functions. So, say, the variables for analog clock would be in makeanalog():, whereas the variables for the digital clock would be in makedigital(). Obviously, this would mean that: a) I would have to redefine the shared variables b) I would have to put each shared variable in the call of the function ex. makeanalog(clockfacecolor, handcolor, *args) or whatever *args means -- it means etc. in my book. OR c) I define all of the future variables global at the beginning of the script. Now, having said that, I am lazy, and though I like to look through and edit the code some of the time, this looked like a huge overhauling. I chose c. because it seems the easiest way to make all of the variables available to all of the functions. Since I have started working on it, I believe that I might try using classes instead. Even so, I am not stable and secure using classes, so any sort of generic help that would explain the basics of classes, but thoroughly and to the point. It would include things like the fact that classes have a root class and whatever they do to help the class that you define. Anyway, I would appreciate any help that you can give. I'm sorry if the explaination is long, but I have seen alot of posts to the tutor that you whizzes replied to with: > Hmmm. I'm still slightly confused about this. or "Can you give us anymore information?" HYCH & HTH, Jacob Schmidt From tktucker at gmail.com Thu Oct 28 04:56:22 2004 From: tktucker at gmail.com (Tom Tucker) Date: Thu Oct 28 04:56:26 2004 Subject: [Tutor] Python Command Line Args (input) equivalent to Perl In-Reply-To: References: Message-ID: <2a278ffe04102719565b4c5c2f@mail.gmail.com> Ed, Here is a small python script that does everything you requested except for the die exception. I am still learning myself. Concordance? What are you looking for exactly? Did you check http://www.python.org/doc/2.3.4/ ? SCRIPT ######### #!/usr/bin/python import sys filename = sys.argv[1] myfile = open(filename,'r') for line in myfile.readlines(): print line, myfile.close CLI ########## # ./example.py testfile this is a testfile cat testfile ########### this is a testfile On Thu, 28 Oct 2004 02:27:03 +0800, Edward WIJAYA wrote: > Dear Tutor, > > I am new to Python, and I like to > learn more about it. Since I am > used to Perl before, I would like > to know what is Python equivalent > of Perl code below: > > $filename = $ARGV[0]; > open (FILE,"$filename") || die "Can't Open $filename: $!\n"; > while{ #dealing with it per-lines > #process something here > } > > Please also kindly suggest any pointer/website > link, where I can find Perl-Python concordance, > especially to facilitate Perl conversion to Python. > > Thanks so much for your time. > Hope to hear from you again. > > -- > Regards, > Edward WIJAYA > SINGAPORE > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From bvande at po-box.mcgill.ca Thu Oct 28 04:58:53 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Thu Oct 28 04:58:42 2004 Subject: [Tutor] Python Command Line Args (input) equivalent to Perl In-Reply-To: References: Message-ID: <4180606D.8080202@po-box.mcgill.ca> Edward WIJAYA said unto the world upon 2004-10-27 14:27: > Dear Tutor, > Please also kindly suggest any pointer/website > link, where I can find Perl-Python concordance, > especially to facilitate Perl conversion to Python. > > Thanks so much for your time. > Hope to hear from you again. > Hi, I don't know Perl, so cannot speak from experience, but perhaps this might help: Best, Brian vdB From keridee at jayco.net Thu Oct 28 05:15:25 2004 From: keridee at jayco.net (Jacob S.) Date: Thu Oct 28 05:14:55 2004 Subject: [Tutor] What is a cricket match? References: <010e01c4b7d4$d5547bd0$ec5328cf@JSLAPTOP> <01b101c4b80d$0b687fe0$6aa98651@xp> <1098441138.4178e1b2789f3@www-mail.usyd.edu.au> Message-ID: <00ca01c4bc9c$6a587a80$bb5428cf@JSLAPTOP> I have a simple question. > its a leather ball, wooden wouldn't bounce (and these balls do) Depending on the type of wood, the wooden balls could very well bouce. Density plays a key factor in an objects ability to bounce. Take, for example, a foam ball and a super ball. The foam ball is far less dense (and I know that density is not the only thing involved.) than the super ball because the super ball is a very dense rubber. Foam balls loose a lot of energy when they impact because their low density causes a very low amount of elasticity. High amounts of elasticity will, as you remember, cause the objects to return to their normal state more vigorously. Anyway, wouldn't such a proposition indicate that exactly the opposite be true? Jacob Schmidt From keridee at jayco.net Thu Oct 28 05:18:22 2004 From: keridee at jayco.net (Jacob S.) Date: Thu Oct 28 05:18:19 2004 Subject: [Tutor] What is a cricket match? References: <010e01c4b7d4$d5547bd0$ec5328cf@JSLAPTOP> <5.1.0.14.2.20041022222948.04d9d2a8@mail.30below.com> Message-ID: <00d101c4bc9c$d84b9a90$bb5428cf@JSLAPTOP> Yeah, We're definitely nutters here, uh... I mean netters. Jacob From keridee at jayco.net Thu Oct 28 05:29:38 2004 From: keridee at jayco.net (Jacob S.) Date: Thu Oct 28 05:28:44 2004 Subject: [Tutor] Thanks for the Cricket Info Message-ID: <00e101c4bc9e$5cad6a60$bb5428cf@JSLAPTOP> Hi everyone! Thank you all for your information on cricket! You may not remember that I posted the first question about it by now, but I appreciate all (My email is not set up for html tags) of your raw_input. "Thank you"*3 (Once again, it's noted that I'm lazy to not write out all three thank you's, however it's ironic that I give 10 times that length in explanation.) Sorry, it's getting late for me, and I'm behind on sleep due to school, homework, worry, etc. That's why I seem a little stranger than I usually do. !?! Thank you again, you all have been very helpful. Jacob Schmidt From kent_johnson at skillsoft.com Thu Oct 28 05:53:20 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Thu Oct 28 05:53:24 2004 Subject: [Tutor] Line matching without a for statement? In-Reply-To: <2a278ffe041027193511eb0a3@mail.gmail.com> References: <2a278ffe041027193511eb0a3@mail.gmail.com> Message-ID: <6.1.0.6.0.20041027234900.02ab3800@mail4.skillsoft.com> If you use output = os.popen(...).read() I think you will get the entire output in one string. Then compile your re with interface = re.compile(r'^eth\d', re.MULTILINE) so the ^ will match the beginning of any line in the string. Then I think the search() will do what you want. Alternatively just use a or loop, it's not such a big deal! Be happy you aren't writing it in Java :-) for line in output: if interface.search(line): print "found" break # if you only want to print "found" once Kent At 10:35 PM 10/27/2004 -0400, Tom Tucker wrote: >Tutors, > >Good evening. Is it possible to search/query a variable without doing >a for statement (ie. for line in ouptut). Hopefully my terminology is >correct. The below example script might make more sense. Thoughts? > >Thanks, >Tom > >SCRIPT (Example) >###################### >#!/usr/bin/python >import os, re > >output = os.popen('/sbin/ifconfig -a').readlines() >interface = re.compile(r'^eth\d') > >if interface.search(output): > print "found an interface" > > >ERROR OUTPUT >########################### >Traceback (most recent call last): >File "./test.py", line 9, in ? >if interface.search(output): >TypeError: expected string or buffer >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From cyresse at gmail.com Thu Oct 28 06:24:36 2004 From: cyresse at gmail.com (Liam Clarke) Date: Thu Oct 28 06:24:39 2004 Subject: [Tutor] recommended IDE for windows? In-Reply-To: <42186.195.92.168.169.1098899427.squirrel@webmail.fudo.org> References: <6.1.2.0.0.20041027110716.03b21b30@mail.mric.net> <42186.195.92.168.169.1098899427.squirrel@webmail.fudo.org> Message-ID: Gubbs said - > I have recently been using the thoroughly excellent (tabbed and code > highlighting) pyPE written by Mr. Josiah Carlson. > > http://pype.sourceforge.net/ > I wholeheartedly agree with the above. It has a function tree, so you can collapse functions that you're not working on, it makes the spaces quite large (Unlike IDLE you're not peering at the screeen thinking 'is that a space'?), and the code highlighting works as you type. But I do like Pythonwin's autocomplete thingy. -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From alan.gauld at freenet.co.uk Thu Oct 28 09:32:23 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu Oct 28 09:33:35 2004 Subject: [Tutor] Turning a "script" into an "application" References: <6.1.0.6.0.20041026220111.029072a0@mail4.skillsoft.com><797fe3d4041026195164a7be97@mail.gmail.com><417F3196.2040208@omc-international.com.au><797fe3d4041026224741d8de35@mail.gmail.com><417F3DA8.1080504@omc-international.com.au><797fe3d404102623482cf0494@mail.gmail.com><00ac01c4bc76$a1872d10$af468651@xp> <797fe3d40410271919185ede62@mail.gmail.com> Message-ID: <011e01c4bcc0$44884320$af468651@xp> > Furthermore, pipes can't work over the network, which is a requirement > of the original poster. Ah, I missed that bit. No pipes then, except maybe for the web interface :-) Alan G From alan.gauld at freenet.co.uk Thu Oct 28 09:35:56 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu Oct 28 09:35:37 2004 Subject: [Tutor] Python Command Line Args (input) equivalent to Perl References: Message-ID: <012301c4bcc0$c376ebf0$af468651@xp> > $filename = $ARGV[0]; > open (FILE,"$filename") || die "Can't Open $filename: $!\n"; > while{ #dealing with it per-lines > #process something here > } filename = sys.argv[1] try: FILE = open(filename) except: print "Can't open ", filename,"!"; sys.exit(1) for line in FILE: # process line here > Please also kindly suggest any pointer/website > link, where I can find Perl-Python concordance, > especially to facilitate Perl conversion to Python. Try the archives of the list, someone was askling about this very recently. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld/tutor2/ From alan.gauld at freenet.co.uk Thu Oct 28 09:37:37 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu Oct 28 09:37:29 2004 Subject: [Tutor] Line matching without a for statement? References: <2a278ffe041027193511eb0a3@mail.gmail.com> Message-ID: <012801c4bcc0$ffd74fe0$af468651@xp> > output = os.popen('/sbin/ifconfig -a').readlines() > > if interface.search(output): > print "found an interface" > if interface.search(output): > TypeError: expected string or buffer readlines() returns a list of strings, read() returns a single long string. You can search the output of read() Alan G From alan.gauld at freenet.co.uk Thu Oct 28 09:54:32 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu Oct 28 09:54:59 2004 Subject: [Tutor] Window Registry Access References: <15A1FDA26DAD524DA7A7AF77313EBA8F07BC00CD@riv-excha5.echostar.com> Message-ID: <013e01c4bcc3$5c616d70$af468651@xp> > I am attempting to read information from a remote registry using Python, I'd recommend using WSH for this. You can access the WSH objects using the Python win extensions as usual. Here is some VBSCript sample code, converting to Python should be easy ...but I'm in a hurry :-( Dim wshSHell Set wshShell = CreateObject("WScript.Shell") ' Find the Windows OS version MsgBox wshShell.RegRead("HKLM\Software\Microsoft\Windows\CurrentVersion") ' CReate a new context menu item for Notepad wshShell.RegWrite("HKCR\*\Shell\Notepad", "View with Notepad", "REG_SZ") wshShell.RegWrite("HKCR\*\Shell\Notepad\Command","%WINDIR%\notepad.exe %","REG_EXPAND_SZ") Its possible to do edits over the network too by giving a network path... There are also networking objects within WSH... Alan G. From olli.s.rajala at tut.fi Thu Oct 28 12:18:53 2004 From: olli.s.rajala at tut.fi (Olli Rajala) Date: Thu Oct 28 12:18:55 2004 Subject: [Tutor] Installing PIL Message-ID: <20041028101853.GA5680@students.cc.tut.fi> Hi again... Thanks for some suggestions about PIL, it seems to be enough for my needs. Well, it would probably be, if I just could install it... I'm building my site in the linux-machine at school, so I have only normal account and so on, but it shouldn't matter, should it? I don't know what info to give you, but I give everything I think is relevant. If something is missing, please forgive me, I'll try to dig it up then. So, here's the problem. ************************************************** [mozart] ~/python > tar zcvf Imaging-1.1.4.tar.gz [mozart] ~/python > cd Imaging-1.1.4/libImaging/ [mozart] ~/python/Imaging-1.1.4/libImaging > ./configure creating cache ./config.cache checking for --without-gcc... no checking for gcc... gcc checking whether the C compiler (gcc ) works... yes checking whether the C compiler (gcc ) is a cross-compiler... no checking whether we are using GNU C... yes checking whether gcc accepts -g... yes checking for ranlib... ranlib checking for ar... ar checking MACHDEP... linux2 checking for jpeg_destroy_compress in -ljpeg... yes checking for deflate in -lz... yes checking how to run the C preprocessor... gcc -E checking for ANSI C header files... yes checking for inline... inline checking whether byte ordering is bigendian... no checking size of char... 1 checking size of short... 2 checking size of int... 4 checking size of long... 4 checking size of float... 4 checking size of double... 8 checking for working const... yes checking for prototypes... yes checking for unistd.h... yes checking for getpagesize... yes checking for working mmap... yes updating cache ./config.cache creating ./config.status creating Makefile creating ImConfig.h [mozart] ~/python/Imaging-1.1.4/libImaging > make < no errors or anything like that> [mozart] ~/python/Imaging-1.1.4/libImaging > cd .. [mozart] ~/python/Imaging-1.1.4 > python setup.py build Traceback (most recent call last): File "setup.py", line 287, in ? extra_compile_args=EXTRA_COMPILE_ARGS, NameError: name 'EXTRA_COMPILE_ARGS' is not defined [mozart] ~/python/Imaging-1.1.4 > python setup.py install Traceback (most recent call last): File "setup.py", line 287, in ? extra_compile_args=EXTRA_COMPILE_ARGS, NameError: name 'EXTRA_COMPILE_ARGS' is not defined [mozart] ~/python/Imaging-1.1.4 > python Python 2.2.2 (#1, Feb 24 2003, 19:13:11) [GCC 3.2.2 20030222 (Red Hat Linux 3.2.2-4)] on linux2 >>> ************************************************** So, what should I do, any ideas? TIA, -- <>< "Quite normal guy" Olli Rajala From kent_johnson at skillsoft.com Thu Oct 28 13:53:03 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Thu Oct 28 13:53:26 2004 Subject: [Tutor] Installing PIL In-Reply-To: <20041028101853.GA5680@students.cc.tut.fi> References: <20041028101853.GA5680@students.cc.tut.fi> Message-ID: <6.1.0.6.0.20041028074925.02900140@mail4.skillsoft.com> After a quick look at setup.py I think this is a bug. EXTRA_COMPILE_ARGS is only defined if Tkinter is present but it is used outside the test for Tkinter. To get it to work, I would try either - install Tkinter - edit setup.py, at line 121 insert a new line reading EXTRA_COMPILE_ARGS = None I also suggest you ask for help on the image-sig mailing list - see the PIL readme or web site for details. Kent At 01:18 PM 10/28/2004 +0300, Olli Rajala wrote: >Hi again... > >Thanks for some suggestions about PIL, it seems to be enough for my >needs. Well, it would probably be, if I just could install it... I'm >building my site in the linux-machine at school, so I have only normal >account and so on, but it shouldn't matter, should it? I don't know >what info to give you, but I give everything I think is relevant. If >something is missing, please forgive me, I'll try to dig it up then. > >So, here's the problem. > >************************************************** >[mozart] ~/python > tar zcvf Imaging-1.1.4.tar.gz > >[mozart] ~/python > cd Imaging-1.1.4/libImaging/ >[mozart] ~/python/Imaging-1.1.4/libImaging > ./configure >creating cache ./config.cache >checking for --without-gcc... no >checking for gcc... gcc >checking whether the C compiler (gcc ) works... yes >checking whether the C compiler (gcc ) is a cross-compiler... no >checking whether we are using GNU C... yes >checking whether gcc accepts -g... yes >checking for ranlib... ranlib >checking for ar... ar >checking MACHDEP... linux2 >checking for jpeg_destroy_compress in -ljpeg... yes >checking for deflate in -lz... yes >checking how to run the C preprocessor... gcc -E >checking for ANSI C header files... yes >checking for inline... inline >checking whether byte ordering is bigendian... no >checking size of char... 1 >checking size of short... 2 >checking size of int... 4 >checking size of long... 4 >checking size of float... 4 >checking size of double... 8 >checking for working const... yes >checking for prototypes... yes >checking for unistd.h... yes >checking for getpagesize... yes >checking for working mmap... yes >updating cache ./config.cache >creating ./config.status >creating Makefile >creating ImConfig.h >[mozart] ~/python/Imaging-1.1.4/libImaging > make > >< no errors or anything like that> > >[mozart] ~/python/Imaging-1.1.4/libImaging > cd .. >[mozart] ~/python/Imaging-1.1.4 > python setup.py build >Traceback (most recent call last): > File "setup.py", line 287, in ? > extra_compile_args=EXTRA_COMPILE_ARGS, >NameError: name 'EXTRA_COMPILE_ARGS' is not defined >[mozart] ~/python/Imaging-1.1.4 > python setup.py install >Traceback (most recent call last): > File "setup.py", line 287, in ? > extra_compile_args=EXTRA_COMPILE_ARGS, >NameError: name 'EXTRA_COMPILE_ARGS' is not defined > >[mozart] ~/python/Imaging-1.1.4 > python >Python 2.2.2 (#1, Feb 24 2003, 19:13:11) >[GCC 3.2.2 20030222 (Red Hat Linux 3.2.2-4)] on linux2 > >>> > >************************************************** >So, what should I do, any ideas? > >TIA, >-- ><>< >"Quite normal guy" >Olli Rajala >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From mlist-python at dideas.com Thu Oct 28 14:34:37 2004 From: mlist-python at dideas.com (Chris Barnhart) Date: Thu Oct 28 14:35:23 2004 Subject: [Tutor] HTMLParser problem unable to find all the IMG tags.... Message-ID: <6.1.2.0.0.20041028080847.03c35ca0@10.2.0.8> I'm trying to write a program that will locate the front page image at CNN.com. [If this already exist, I want to do this anyway as its a good learning exercise.] The problem is that using the HTMLParser I'm not getting all the IMG tags. I know this as I have another program that just uses string processing that gets 2.5 times more IMG SRC tag. I also know this because HTMLParser starttag is never called with the IMG that I'm after! There is also an exception related to the close method and EOF. Possibly my problem is in how I feed the data? Or related to nested tags? Any ideas? Thanks, Chris iimport urllib2 import HTMLParser from HTMLParser import HTMLParser class MyParser(HTMLParser): def __init__( self ) : HTMLParser.__init__(self) self.cnt = 0 def handle_starttag(self, tag, attr): # print "Encountered the beginning of a %s tag" % tag if (tag in "IMG" or tag in "img") : self.cnt = self.cnt + 1 print tag, def close(self) : print print "HTMLParse Found : ", self.cnt HTMLParser.close(self) mp = MyParser() for line in urllib2.urlopen('http://www.cnn.com') : mp.feed(line) mp.close() print "Finished" From STEVEN.M.FAULCONER at saic.com Thu Oct 28 15:37:18 2004 From: STEVEN.M.FAULCONER at saic.com (Faulconer, Steven M.) Date: Thu Oct 28 15:37:04 2004 Subject: [Tutor] Mount size Message-ID: <207DA77D2384D411A48B0008C7095D810152B8D8@us-melbourne.mail.saic.com> Danny, Thanks for the response. Since the calls are not reliable for NFS mounts, is there a pure python way of getting that information? We originally had a system call that ran a df with some awk's and sed's to get what we need, but we felt that had to be a way within python to do this. We can go back to that method, but I'd really like a pure python way of reliably getting available space on local and NFS mounted volumes. If you or anyone else has any ideas, I'd love to hear them. Thanks. -----Original Message----- From: Danny Yoo [mailto:dyoo@hkn.eecs.berkeley.edu] Sent: Wednesday, October 27, 2004 6:20 PM To: Faulconer, Steven M. Cc: tutor@python.org Subject: Re: [Tutor] Mount size On Wed, 27 Oct 2004, Faulconer, Steven M. wrote: > We are having some issues getting reliable information for available > disk space within Python programs. We are using os.statvfs to get the > blocks free, but the numbers are not consistent between local and NFS > mounted drives. [some text cut] > Given that f_bavail is the number of blocks available (non-superuser) > I would assume that we could multiply that by f_bsize and then divide > by 1 million (for megabytes) or 1 billion (gigabytes). Hi Steven, You may want to use f_frsize, not f_bsize. The underlying man page for statvfs says the following about the tuple that we get back: """ u_long f_bsize; /* preferred file system block size */ u_long f_frsize; /* fundamental filesystem block (size if supported) */ fsblkcnt_t f_blocks; /* total # of blocks on file system in units of f_frsize */ fsblkcnt_t f_bfree; /* total # of free blocks */ fsblkcnt_t f_bavail; /* # of free blocks avail to non-super-user */ fsfilcnt_t f_files; /* total # of file nodes (inodes) */ fsfilcnt_t f_ffree; /* total # of free file nodes */ fsfilcnt_t f_favail; /* # of inodes avail to non-super-user*/ u_long f_fsid; /* file system id (dev for now) */ char f_basetype[FSTYPSZ]; /* target fs type name, null-terminated */ u_long f_flag; /* bit mask of flags */ u_long f_namemax; /* maximum file name length */ char f_fstr[32]; /* file system specific string */ u_long f_filler[16]; /* reserved for future expansion */ """ (Taken from Solaris 8 man page on statvfs) The way that the docs make a distinction between the "preferred" and "fundamental" block sizes is significant. Use 'f_frsize' instead, and you should get better results. There's also a section in the BUGS that says: """ BUGS The values returned for f_files, f_ffree, and f_favail may not be valid for NFS mounted file systems. """ So be careful not to depends on those particular values on NFS-mounted drives. I hope this helps! From gubbs at fudo.org Thu Oct 28 15:52:34 2004 From: gubbs at fudo.org (gubbs) Date: Thu Oct 28 15:52:41 2004 Subject: [Tutor] recommended IDE for windows? In-Reply-To: References: <6.1.2.0.0.20041027110716.03b21b30@mail.mric.net><42186.195.92.168.169.1098899427.squirrel@webmail.fudo.org> Message-ID: <60742.195.92.168.170.1098971554.squirrel@webmail.fudo.org> > Gubbs said - >> I have recently been using the thoroughly excellent (tabbed and code >> highlighting) pyPE written by Mr. Josiah Carlson. >> >> http://pype.sourceforge.net/ >> > > I wholeheartedly agree with the above. It has a function tree, so you > can collapse functions that you're not working on, it makes the spaces > quite large (Unlike IDLE you're not peering at the screeen thinking > 'is that a space'?), and the code highlighting works as you type. > > But I do like Pythonwin's autocomplete thingy. I recently emailed the developer about adding some new features here's his (abridged)reply: > Thanks for this great app! You are welcome. > I dunno if this is really rude but I'd like to detach/tabbify the area > that shows all the function definitions on the right hand side since > it gets annoying having to resize the pane every time I open a new > file. Unfortunately you are going to have to wait for PyPE 2.x for a change in that behavior. 2.x will include major changes, among which will save you from having to continually resize that pane. Expect PyPE 2.x before January 1, 2005. - Josiah From bgailer at alum.rpi.edu Thu Oct 28 03:56:26 2004 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Thu Oct 28 17:14:01 2004 Subject: [Tutor] recommended IDE for windows? In-Reply-To: References: Message-ID: <6.1.2.0.0.20041027195458.03b3d410@mail.mric.net> At 09:43 AM 10/27/2004, Christian Wyglendowski wrote: >I think that SPE (http://spe.pycs.net/) offers tabbed editing _and_ code >completion. I finally found a link that gets me the download of SPE 0.5.1.E, downloaded and ran the Windows Installer. Now what do I do to run SPE? Bob Gailer bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell From John.Gooch at echostar.com Thu Oct 28 17:00:22 2004 From: John.Gooch at echostar.com (Gooch, John) Date: Thu Oct 28 17:26:05 2004 Subject: [Tutor] Window Registry Access Message-ID: <15A1FDA26DAD524DA7A7AF77313EBA8F07BC00CE@riv-excha5.echostar.com> Here is what I wound up doing: hHandle = win32api.RegConnectRegistry( "\\\\"+currentRec.name[0], win32con.HKEY_LOCAL_MACHINE) hHandle = win32api.RegOpenKeyEx( win32con.HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\WinLogon",0,win32con.KEY_ALL_ACCESS) hNoOfKeys = win32api.RegQueryInfoKey(hHandle)[1] hCounter = 0 while hCounter < hNoOfKeys: hData = win32api.RegEnumValue(hHandle,hCounter) if hData[0]== "DefaultUserName": username = hData[1] hCounter = hCounter + 1 if username: if debug: print "Last Logged in User is "+username+"\n" currentRec.lastlogon = username If works great, but I noticed that on many of the functions in this API, the return value is 'undefined', so it is very hard to avoid raising exceptions, so I have put try/except blocks around all of the i/o parts of my script. In Perl, the return type was always defined so I would catch an exception similarly ( different syntax, of course ) to this: if ( hHandle = win32api.RegConnectRegistry( "\\\\"+currentRec.name[0], win32con.HKEY_LOCAL_MACHINE) ) { use the connection } else { log fact that connection failed and continue on to next code block } John A. Gooch Systems Administrator IT - Tools EchoStar Satellite L.L.C. 9601 S. Meridian Blvd. Englewood, CO 80112 Desk: 720-514-5708 -----Original Message----- From: Alan Gauld [mailto:alan.gauld@freenet.co.uk] Sent: Thursday, October 28, 2004 1:55 AM To: Gooch, John; tutor@python.org Subject: Re: [Tutor] Window Registry Access > I am attempting to read information from a remote registry using Python, I'd recommend using WSH for this. You can access the WSH objects using the Python win extensions as usual. Here is some VBSCript sample code, converting to Python should be easy ...but I'm in a hurry :-( Dim wshSHell Set wshShell = CreateObject("WScript.Shell") ' Find the Windows OS version MsgBox wshShell.RegRead("HKLM\Software\Microsoft\Windows\CurrentVersion") ' CReate a new context menu item for Notepad wshShell.RegWrite("HKCR\*\Shell\Notepad", "View with Notepad", "REG_SZ") wshShell.RegWrite("HKCR\*\Shell\Notepad\Command","%WINDIR%\notepad.exe %","REG_EXPAND_SZ") Its possible to do edits over the network too by giving a network path... There are also networking objects within WSH... Alan G. From Mark.Kels at gmail.com Thu Oct 28 17:42:51 2004 From: Mark.Kels at gmail.com (Mark Kels) Date: Thu Oct 28 17:43:12 2004 Subject: [Tutor] running CGI without a server Message-ID: Hi all, I want to learn CGI programming with Python (I already know the basics of Python). The problem is that I dont have a server to run the CGI scripts on. Is there a way to run Python CGI scripts from the PC ( without uploading it to a server) ? P.S If you know a good python-cgi tutorial I'll be glad if you will send me a link :-) . Thanks !! From ewijaya at singnet.com.sg Thu Oct 28 10:07:53 2004 From: ewijaya at singnet.com.sg (Edward WIJAYA) Date: Thu Oct 28 18:07:54 2004 Subject: [Tutor] Data::Dumper for Python Message-ID: Hi, Is there any equivalent modules of it in Python. Brian van den Broek suggestion on Python-Perl phrasebook: is very useful, and cover mostly on types and data-structure. Any idea if there is any similar stuff for Perl-Python Modules comparison? -- Regards, Edward WIJAYA SINGAPORE From melnyk at gmail.com Thu Oct 28 18:23:45 2004 From: melnyk at gmail.com (Scott Melnyk) Date: Thu Oct 28 18:23:52 2004 Subject: [Tutor] searching for data in one file from another Message-ID: Hello! First, thanks to Rich for the great help last time I wrote in to the list. I have a file with exon ids, one per line and another large file with exon, gene and transcript info. I would like to remove each entry in the second (ID information and subsequent sequence data) which matches from the first, but I keep running into problems just getting the matching to work. # format of file to remove exons from is: >ENSE00001387275.1|ENSG00000187908.1|ENST00000339871.1 assembly=NCBI34|chr=10_NT_078087|strand=forward|bases 72877 to 72981|exons plus upstream and downstream regions for exon GAGATGGCAGGTGTCAGGGCCGAGTGGAGATCCTATACCGAGGCTCCTGGGGCACCGTGTGTGATGACAGCTGGGACACCAATGATGCCAACGTGGTCTGTAGGC in the above there is a newline after "regions for exon" then blank line the data after that is all one long line followed by blank space Here is the basics of my script so far: ################################################ import re, sys, string info=re.compile('^>(ENSE\d+\.\d).+') info2=re.compile('(ENSE\d+\.\d)') RFILE=open(sys.argv[1], 'r') #list of redundant exons R2FILE=open(sys.argv[2], 'r') #full list of genes,transcripts and exons #WFILE=open(sys.argv[3], 'w') #write above file minus redundant exons not ready for this yet m=0 Rexons=0 for line in RFILE: #cycle over the list of exons Rexons=Rexons+1 #counter for number of exons Matched1= info2.match(line) #test line matches format -each line should Ecount=0 #counter for how many occurances of this exon there are in big file if Matched1: RiD=Matched1.group(1) #assign the exon to RiD (Redundant iD) print "\n",RiD, "this is the ",Rexons," exon to check against" #just to watch while testing line2Count=0 #line counter for big file for line2 in R2FILE: #iterate through the big file line2Count=line2Count+1 Matched= info.match(line2) if Matched: ID=Matched.group(1) #ID is now the grouping from above-should be the exon id #print ID, if ID==RiD: Ecount=Ecount+1 m=m+1 print ID, "from line", line2Count print" checked total of ", line2Count," lines." print "There were ",Ecount," hits for this exon." print Rexons, "redundant exons in list" print m, "exons removed from large file" ################################################ when I run this I get Z:\datasets>C:\scomel\python2.3.4\python.exe ..\scripts\r 3pm.txt altsplice1.fasta ENSE00000677348.1 this is the 1 exon to check against ENSE00000677348.1 from line 188560 ENSE00000677348.1 from line 188656 checked total of 1156852 lines. There were 2 hits for this exon. ENSE00000677356.1 this is the 2 exon to check against checked total of 0 lines. There were 0 hits for this exon. ENSE00000677362.1 this is the 3 exon to check against checked total of 0 lines. There were 0 hits for this exon. ENSE00000677344.1 this is the 4 exon to check against checked total of 0 lines. There were 0 hits for this exon. Obviously I have made one or more errors in my iterations as it prints the line checked total of 0 lines after going through the first loop of first file. Each of the exons in the list RFILE is only there because it occurs in each version of the genes in the second list so there should be hits for each. When it starts to run there is a pause of 7-10 seconds after printing ENSE00000677348.1 this is the 1 exon to check against Then the everything cycles past as fast as can be written to screen, and finds no matches. I am stumped. Thanks in advance for all help, Scott -- Scott Melnyk melnyk@gmail.com From bill.mill at gmail.com Thu Oct 28 18:40:23 2004 From: bill.mill at gmail.com (Bill Mill) Date: Thu Oct 28 18:40:31 2004 Subject: [Tutor] Data::Dumper for Python In-Reply-To: References: Message-ID: <797fe3d4041028094049e95854@mail.gmail.com> Edward, Perhaps if you would explain for us what the data::dumper module does, we could tell you how to do it in python, or if there's a module existing to do it. Peace Bill Mill bill.mill at gmail.com On Thu, 28 Oct 2004 16:07:53 +0800, Edward WIJAYA wrote: > Hi, > > Is there any equivalent modules of it > in Python. > > Brian van den Broek suggestion on Python-Perl > phrasebook: > > is very useful, and cover mostly > on types and data-structure. > > Any idea if there is any > similar stuff for Perl-Python Modules > comparison? > > -- > Regards, > Edward WIJAYA > SINGAPORE > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From inkedmn at gmail.com Thu Oct 28 18:43:50 2004 From: inkedmn at gmail.com (Brett Kelly) Date: Thu Oct 28 18:44:00 2004 Subject: [Tutor] running CGI without a server In-Reply-To: References: Message-ID: Apache will install/run on any decent desktop machine, that'd be the easiest way to get a testing environment going... http://httpd.apache.org Brett On Thu, 28 Oct 2004 17:42:51 +0200, Mark Kels wrote: > Hi all, > > I want to learn CGI programming with Python (I already know the basics > of Python). > The problem is that I dont have a server to run the CGI scripts on. > Is there a way to run Python CGI scripts from the PC ( without > uploading it to a server) ? > > P.S > If you know a good python-cgi tutorial I'll be glad if you will send > me a link :-) . > > Thanks !! > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- Brett Kelly http://inkedmn.com:8000 From rdm at rcblue.com Thu Oct 28 18:44:09 2004 From: rdm at rcblue.com (Dick Moores) Date: Thu Oct 28 18:44:14 2004 Subject: [Tutor] How to calculate pi with this formula? Message-ID: <6.1.2.0.2.20041028093827.06b2ac00@rcblue.com> Is it possible to calculate almost-pi/2 using the (24) formula on without using (23)? If it's possible, how about a hint? Recursion? Thanks, tutors. Dick Moores rdm@rcblue.com From barry at angleinc.com Thu Oct 28 18:53:13 2004 From: barry at angleinc.com (Barry Sperling) Date: Thu Oct 28 18:53:22 2004 Subject: [Tutor] How to calculate pi with this formula? In-Reply-To: <6.1.2.0.2.20041028093827.06b2ac00@rcblue.com> References: <6.1.2.0.2.20041028093827.06b2ac00@rcblue.com> Message-ID: <418123F9.2020209@angleinc.com> As a quick thought: since you will not be interating forever, if you know how far you will go you can calculate that denominator and numerator by a formula, add 1, multiply that answer by the previous denominator and numerator, add 1, etc. until the denominator gets down to 1. It has a slightly different flavor that the previous ( formula 23 ). Barry Dick Moores wrote: > Is it possible to calculate almost-pi/2 using the (24) formula on > without using (23)? > > If it's possible, how about a hint? Recursion? > > Thanks, tutors. > > Dick Moores > rdm@rcblue.com > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From kent_johnson at skillsoft.com Thu Oct 28 19:06:54 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Thu Oct 28 19:08:27 2004 Subject: [Tutor] running CGI without a server In-Reply-To: References: Message-ID: <6.1.0.6.0.20041028130519.02ae23f0@mail4.skillsoft.com> You could also use CGIHTTPServer from the Python library to run a simple CGI server. The Python web site has links to quite a few CGI tutorials, though I can't say if they are any good: http://www.python.org/topics/web/ Kent At 09:43 AM 10/28/2004 -0700, Brett Kelly wrote: >Apache will install/run on any decent desktop machine, that'd be the >easiest way to get a testing environment going... > >http://httpd.apache.org > >Brett > >On Thu, 28 Oct 2004 17:42:51 +0200, Mark Kels wrote: > > Hi all, > > > > I want to learn CGI programming with Python (I already know the basics > > of Python). > > The problem is that I dont have a server to run the CGI scripts on. > > Is there a way to run Python CGI scripts from the PC ( without > > uploading it to a server) ? > > > > P.S > > If you know a good python-cgi tutorial I'll be glad if you will send > > me a link :-) . > > > > Thanks !! > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > >-- >Brett Kelly >http://inkedmn.com:8000 >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From BranimirP at cpas.com Thu Oct 28 19:19:03 2004 From: BranimirP at cpas.com (Branimir Petrovic) Date: Thu Oct 28 19:19:07 2004 Subject: [Tutor] "Clean screen" (where screen==stdout) functionality needed, but o n Windows Message-ID: <33678E78A2DD4D418396703A750048D40102504A@RIKER> I am looking for a way to occasionally clear whatever executing Python script have sent to stdout so far. "DOS-box" cls equivalent is preferred, although if all other fails I might just print N empty lines to scroll printed stuff out of the way... Preferably I'd like to be able to make (or fake) minimally functional command line interface environment for Python scripts on Windows. Should I be looking for something specific in Win32all? While it would be great if my Python script would be able to figure out how big is the "box" (DOS box that is) it uses for its stdout (in order to know how much "real estate" it has for its output), just the ability to clear it all up at will and start printing from the upper left corner would do for now. Googling uncovered this http://flangy.com/dev/python/curses/ but being in "Alpha 3" release from the beginning of this year and without any later updates... Any ideas and/or pointers on how to create usable command line interface for Python scripts on Windows platform is very welcome. Branimir From bill.mill at gmail.com Thu Oct 28 19:29:38 2004 From: bill.mill at gmail.com (Bill Mill) Date: Thu Oct 28 19:29:41 2004 Subject: [Tutor] How to calculate pi with this formula? In-Reply-To: <6.1.2.0.2.20041028093827.06b2ac00@rcblue.com> References: <6.1.2.0.2.20041028093827.06b2ac00@rcblue.com> Message-ID: <797fe3d40410281029294762a6@mail.gmail.com> Dick, Recursively: mpi(n, d, lim): if d >= lim: return 1 + (n/d) return 1 + (n/d) * mpi(n+1, d+2, lim) >>> 2 * mpi(1., 3., 1000) #note that 1 and/or 3 need to be floats 3.1415926535897931 Peace Bill Mill bill.mill at gmail.com On Thu, 28 Oct 2004 09:44:09 -0700, Dick Moores wrote: > Is it possible to calculate almost-pi/2 using the (24) formula on > without using (23)? > > If it's possible, how about a hint? Recursion? > > Thanks, tutors. > > Dick Moores > rdm@rcblue.com > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From tigershark at morganmeader.com Thu Oct 28 19:35:44 2004 From: tigershark at morganmeader.com (Morgan Meader) Date: Thu Oct 28 19:37:14 2004 Subject: [Tutor] Data::Dumper for Python In-Reply-To: References: Message-ID: <41812DF0.2020604@morganmeader.com> Edward, I asked the same exact question when I recently started learning Python(coming from Perl also). In Perl I use Data::Dumper mostly to review my data visually so I can see if I am accessing it correctly in a variety of ways. I also used it once for a data persistance operation that I have come to value the gnosis.xml.pickle module for in Python. So for debugging and general understanding and for looking at data visually, I have used the pprint module. import pprint pp = pprint.PrettyPrinter(indent=4) pp.pprint() All, Thanks for having such informative discussions! Prost, Morgan Edward WIJAYA wrote: > Hi, > > Is there any equivalent modules of it > in Python. > > Brian van den Broek suggestion on Python-Perl > phrasebook: > > is very useful, and cover mostly > on types and data-structure. > > Any idea if there is any > similar stuff for Perl-Python Modules > comparison? > From pythonTutor at venix.com Thu Oct 28 19:49:31 2004 From: pythonTutor at venix.com (Lloyd Kvam) Date: Thu Oct 28 19:50:18 2004 Subject: [Tutor] HTMLParser problem unable to find all the IMG tags.... In-Reply-To: <6.1.2.0.0.20041028080847.03c35ca0@10.2.0.8> References: <6.1.2.0.0.20041028080847.03c35ca0@10.2.0.8> Message-ID: <1098985771.4985.19.camel@laptop.venix.com> On Thu, 2004-10-28 at 08:34, Chris Barnhart wrote: > I'm trying to write a program that will locate the front page image at > CNN.com. [If this already exist, I want to do this anyway as its a good > learning exercise.] > > The problem is that using the HTMLParser I'm not getting all the IMG > tags. I know this as I have another program that just uses string > processing that gets 2.5 times more IMG SRC tag. I also know this because > HTMLParser starttag is never called with the IMG that I'm after! For debugging I would suggest saving the html locally from both methods and confirming that they are the same. Then run your HTMLParser against the saved file and print the img tags that you find. You can redirect the output to a file. Then compare to the original html to see what tags got missed. Debugging against the live site means that you have no control on the data being fed through and no easy way to validate your program. There's also a coding suggestion below. > > There is also an exception related to the close method and EOF. > Possibly my problem is in how I feed the data? Or related to nested tags? > Any ideas? > > Thanks, > Chris > > iimport urllib2 > import HTMLParser > > from HTMLParser import HTMLParser > > class MyParser(HTMLParser): > def __init__( self ) : > HTMLParser.__init__(self) > self.cnt = 0 > > def handle_starttag(self, tag, attr): > # print "Encountered the beginning of a %s tag" % tag > if (tag in "IMG" or tag in "img") : This if would miss Img and other mixed case variations. The "string in string" syntax (in recent pythons) is true when s1 is a substring of s2. I think your intent was really if tag in ("IMG","img"): I'd code: if tag.lower == "img": > self.cnt = self.cnt + 1 > print tag, > > def close(self) : > print > print "HTMLParse Found : ", self.cnt > HTMLParser.close(self) > > > > mp = MyParser() > for line in urllib2.urlopen('http://www.cnn.com') : > mp.feed(line) While I would not expect it to matter, I normally feed the data in one gulp. fp = urllib2.urlopen(.... mp.feed(fp.read()) > mp.close() > > print "Finished" > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp From STEVEN.M.FAULCONER at saic.com Thu Oct 28 20:33:23 2004 From: STEVEN.M.FAULCONER at saic.com (Faulconer, Steven M.) Date: Thu Oct 28 20:33:38 2004 Subject: [Tutor] Mount size Message-ID: <207DA77D2384D411A48B0008C7095D810152B8DE@us-melbourne.mail.saic.com> In further testing, I can't seem to get a reliable return for os.statvfs even on a locally mounted file system. The filesystem in question is on a fiber array, and is about 1.2TB in size (array is 3TB total). There are about 57GB free: (Formated output of 'df -k' ): Filesystem : /dev/dsk/c6t3005590899004201d1s0 Kbytes : 1191657968 Used : 1122893592 Avail : 56847800 Capacity : 96% Mounted On : /ndop2 Doing a 'df -g' [returns the raw statvfs structure] on the particular volume gives me (I changed formatting): /ndop2 (/dev/dsk/c6t3005590899004201d1s0): 8192 block size 8192 frag size 2383315936 total blocks 137039488 free blocks 113206336 available 1215872 total files 1139514 free files 30933024 filesys id ufs fstype 0x00000004 flag 255 filename length Now, in Python, doing a statvfs returns: F_BSIZE : 8192 F_FRSIZE : 8192 F_BLOCKS : 148957246L F_BFREE : 8515862L F_BAVAIL : 7026290L F_FILES : 1215872L F_FFREE : 1139502L F_FAVAIL : 1139502L F_FLAG : 4 F_NAMEMAX : 255 Now, the numbers should match for everything (or pretty close, I'd think), but they don't. F_FILES, F_FFREE seem to be about right, but the important (for me) parts, like F_BLOCKS and F_BFREE don't. What am I missing here? Is there some way to translate the return of os.statvfs() to a value close to the actual space on the drive? I imagine it is something silly that I'm overlooking. Thanks. Steven -----Original Message----- From: tutor-bounces@python.org [mailto:tutor-bounces@python.org] On Behalf Of Faulconer, Steven M. Sent: Thursday, October 28, 2004 9:37 AM To: 'Danny Yoo' Cc: tutor@python.org Subject: RE: [Tutor] Mount size Danny, Thanks for the response. Since the calls are not reliable for NFS mounts, is there a pure python way of getting that information? We originally had a system call that ran a df with some awk's and sed's to get what we need, but we felt that had to be a way within python to do this. We can go back to that method, but I'd really like a pure python way of reliably getting available space on local and NFS mounted volumes. If you or anyone else has any ideas, I'd love to hear them. Thanks. -----Original Message----- From: Danny Yoo [mailto:dyoo@hkn.eecs.berkeley.edu] Sent: Wednesday, October 27, 2004 6:20 PM To: Faulconer, Steven M. Cc: tutor@python.org Subject: Re: [Tutor] Mount size On Wed, 27 Oct 2004, Faulconer, Steven M. wrote: > We are having some issues getting reliable information for available > disk space within Python programs. We are using os.statvfs to get the > blocks free, but the numbers are not consistent between local and NFS > mounted drives. [some text cut] > Given that f_bavail is the number of blocks available (non-superuser) > I would assume that we could multiply that by f_bsize and then divide > by 1 million (for megabytes) or 1 billion (gigabytes). Hi Steven, You may want to use f_frsize, not f_bsize. The underlying man page for statvfs says the following about the tuple that we get back: """ u_long f_bsize; /* preferred file system block size */ u_long f_frsize; /* fundamental filesystem block (size if supported) */ fsblkcnt_t f_blocks; /* total # of blocks on file system in units of f_frsize */ fsblkcnt_t f_bfree; /* total # of free blocks */ fsblkcnt_t f_bavail; /* # of free blocks avail to non-super-user */ fsfilcnt_t f_files; /* total # of file nodes (inodes) */ fsfilcnt_t f_ffree; /* total # of free file nodes */ fsfilcnt_t f_favail; /* # of inodes avail to non-super-user*/ u_long f_fsid; /* file system id (dev for now) */ char f_basetype[FSTYPSZ]; /* target fs type name, null-terminated */ u_long f_flag; /* bit mask of flags */ u_long f_namemax; /* maximum file name length */ char f_fstr[32]; /* file system specific string */ u_long f_filler[16]; /* reserved for future expansion */ """ (Taken from Solaris 8 man page on statvfs) The way that the docs make a distinction between the "preferred" and "fundamental" block sizes is significant. Use 'f_frsize' instead, and you should get better results. There's also a section in the BUGS that says: """ BUGS The values returned for f_files, f_ffree, and f_favail may not be valid for NFS mounted file systems. """ So be careful not to depends on those particular values on NFS-mounted drives. I hope this helps! _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From dyoo at hkn.eecs.berkeley.edu Thu Oct 28 20:52:40 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Oct 28 20:52:49 2004 Subject: [Tutor] Mount size In-Reply-To: <207DA77D2384D411A48B0008C7095D810152B8D8@us-melbourne.mail.saic.com> Message-ID: On Thu, 28 Oct 2004, Faulconer, Steven M. wrote: > Thanks for the response. Since the calls are not reliable for NFS > mounts, Hi Steven, I'd better clarify this. That is not what I wrote. I quoted from the man page that: > BUGS > The values returned for f_files, f_ffree, and f_favail may > not be valid for NFS mounted file systems. What this is saying is that certain portions of the statvfs() return value might be buggy. But it does not say that the whole thing is broken. *grin* I assume that the rest of it --- including f_frsize and f_bavail --- is ok. If we look at the C source code for GNU df, we can see that it does use statvfs, f_frsize, f_bsize, and b_avail. /*** a fragment in coreutils-5.0/lib/fsutils.c ***/ struct statvfs fsd; if (statvfs (path, &fsd) < 0) return -1; /* f_frsize isn't guaranteed to be supported. */ fsp->fsu_blocksize = (fsd.f_frsize ? PROPAGATE_ALL_ONES (fsd.f_frsize) : PROPAGATE_ALL_ONES (fsd.f_bsize)); /******/ According to this code, GNU df prefers to use f_frsize if it's there. If f_frsize isn't there, then GNU df will fall back on f_bsize. But its first choice is to use f_frsize, which is the second component of the statvfs() return value. So you just have to be careful to discriminate which portions of os.statvfs() to use. I'm getting good results with: ### import os def getFreeBytes(mountpoint): """Returns the number of free bytes available off a mount point.""" data = os.statvfs(mountpoint) frsize = data[1] bavail = data[4] return frsize * bavail ### For example, let's say that we're on a Solaris 8 system with a NFS mount: ### -bash-2.05b$ /usr/pubsw/bin/df -H /sybase-log Filesystem Size Used Avail Use% Mounted on tair5:/export/sybase-log 5.3G 441M 4.8G 9% /sybase-log ### I'm getting very good agreement with that getFreeBytes() function: ### >>> getFreeBytes("/sybase-log") 4797079552L ### Anyway, I hope this helps! From rdm at rcblue.com Thu Oct 28 21:17:05 2004 From: rdm at rcblue.com (Dick Moores) Date: Thu Oct 28 21:17:53 2004 Subject: [Tutor] How to calculate pi with this formula? In-Reply-To: <797fe3d40410281029294762a6@mail.gmail.com> References: <6.1.2.0.2.20041028093827.06b2ac00@rcblue.com> <797fe3d40410281029294762a6@mail.gmail.com> Message-ID: <6.1.2.0.2.20041028121407.06c30af0@rcblue.com> Bill, Nice! Wish I could have thought of that. I noticed that a lim of 100 is large enough to get a pi of 3.1415926535897931 . BTW why the "mpi" function name? Thanks a lot! Dick At 10:29 10/28/2004, Bill Mill wrote: >Dick, > >Recursively: > >mpi(n, d, lim): > if d >= lim: return 1 + (n/d) > return 1 + (n/d) * mpi(n+1, d+2, lim) > > >>> 2 * mpi(1., 3., 1000) #note that 1 and/or 3 need to be floats >3.1415926535897931 > >Peace >Bill Mill >bill.mill at gmail.com > >On Thu, 28 Oct 2004 09:44:09 -0700, Dick Moores wrote: > > Is it possible to calculate almost-pi/2 using the (24) formula on > > without using (23)? > > > > If it's possible, how about a hint? Recursion? > > > > Thanks, tutors. > > > > Dick Moores > > rdm@rcblue.com From rdm at rcblue.com Thu Oct 28 21:20:05 2004 From: rdm at rcblue.com (Dick Moores) Date: Thu Oct 28 21:20:34 2004 Subject: [Tutor] How to calculate pi with this formula? In-Reply-To: <418123F9.2020209@angleinc.com> References: <6.1.2.0.2.20041028093827.06b2ac00@rcblue.com> <418123F9.2020209@angleinc.com> Message-ID: <6.1.2.0.2.20041028121910.030e1230@rcblue.com> Interesting! Thanks. Dick At 09:53 10/28/2004, Barry Sperling wrote: >As a quick thought: since you will not be interating forever, if you >know how far you will go you can calculate that denominator and >numerator by a formula, add 1, multiply that answer by the previous >denominator and numerator, add 1, etc. until the denominator gets down >to 1. It has a slightly different flavor that the previous ( formula 23 ). >Barry > >Dick Moores wrote: > >>Is it possible to calculate almost-pi/2 using the (24) formula on >> without using (23)? >>If it's possible, how about a hint? Recursion? >>Thanks, tutors. >>Dick Moores >>rdm@rcblue.com From mlist-python at dideas.com Thu Oct 28 21:36:03 2004 From: mlist-python at dideas.com (Chris Barnhart) Date: Thu Oct 28 21:36:49 2004 Subject: [Tutor] HTMLParser problem unable to find all the IMG tags.... In-Reply-To: <1098985771.4985.19.camel@laptop.venix.com> References: <6.1.2.0.0.20041028080847.03c35ca0@10.2.0.8> <1098985771.4985.19.camel@laptop.venix.com> Message-ID: <6.1.2.0.0.20041028152745.03c70ca0@qmail.dideas.com> At 01:49 PM 10/28/2004, Lloyd Kvam wrote: >On Thu, 2004-10-28 at 08:34, Chris Barnhart wrote: > > > > The problem is that using the HTMLParser I'm not getting all the IMG > > tags. I know this as I have another program that just uses string > > processing that gets 2.5 times more IMG SRC tag. I also know this because > > HTMLParser starttag is never called with the IMG that I'm after! > >For debugging I would suggest saving the html locally from both methods >and confirming that they are the same. Then run your HTMLParser against >the saved file and print the img tags that you find. You can redirect >the output to a file. Then compare to the original html to see what >tags got missed. > >Debugging against the live site means that you have no control on the >data being fed through and no easy way to validate your program. Thanks Lloyd, Yeah - I agree. I've saved the webpage to a file and am working through it. It's nothing to do with capitalization.... The webpage is in a string now, and I've found that if I cut off the start of the string, I can get "new" tags to appear. I'm trying to work though and fix exactly which tags are missing and why. Its kind of tedious! One possible problem is that HTMLParse is HTML 2.0 complied, but CNN's output is 4.01. f = open("cnn_py.html","r") html_full = f.read() f.close() html = html_full[20000:] h = MyParser() h.feed(html) h.close() When I figure this out, I'll make a new post. Chris From zmerch at 30below.com Thu Oct 28 21:38:19 2004 From: zmerch at 30below.com (Roger Merchberger) Date: Thu Oct 28 21:38:02 2004 Subject: [Tutor] getImageInfo() ? In-Reply-To: <20041026180429.GA11945@students.cc.tut.fi> Message-ID: <5.1.0.14.2.20041028153159.04c6ad50@mail.30below.com> Rumor has it that Olli Rajala may have mentioned these words: >Hi! >This is my first post to this list, so I thought to say hi. :) > >I'm doing my own imagegallery using python and thought if there were >some good/easy way to find the info of the pic, I mean the >width&height, so I could put them on the page in the -tag. Pics >are jpegs if that matters. You'll need to install the PIL (Python Image Library), then try this code snippet: import Image jpgfilename = 'c:/mypicture.jpg' # for winders... # jpgfilename = '/home/myhome/mypicture.jpg' # uncomment for *nix pix = Image.open(jpgfilename) (xsize, ysize) = pix.size # =-=-=-=-=-=-=-=-=-=-=-=-=-= There are many functions in the PIL, including resizing the image and I believe even converting it from one format to another. I have an application that changes my Winders background every 5 minutes, and I use the code above (with the Image.getpixel command) to extract a background pixel from each to re-set the background color of the desktop, so I don't have to stretch the image out of proportion... (It also changes my Eudora .sig file, and my new mail alert .wav ;-) ) HTH, Roger "Merch" Merchberger -- Roger "Merch" Merchberger | "Profile, don't speculate." SysAdmin, Iceberg Computers | Daniel J. Bernstein zmerch@30below.com | From bill.mill at gmail.com Thu Oct 28 21:41:19 2004 From: bill.mill at gmail.com (Bill Mill) Date: Thu Oct 28 21:41:33 2004 Subject: [Tutor] How to calculate pi with this formula? In-Reply-To: <6.1.2.0.2.20041028121407.06c30af0@rcblue.com> References: <6.1.2.0.2.20041028093827.06b2ac00@rcblue.com> <797fe3d40410281029294762a6@mail.gmail.com> <6.1.2.0.2.20041028121407.06c30af0@rcblue.com> Message-ID: <797fe3d40410281241351458e4@mail.gmail.com> Dick, mpi = abbrev(make pi) #at least in my head Peace Bill Mill bill.mill at gmail.com On Thu, 28 Oct 2004 12:17:05 -0700, Dick Moores wrote: > Bill, > > Nice! Wish I could have thought of that. > > I noticed that a lim of 100 is large enough to get a pi of > 3.1415926535897931 . > > BTW why the "mpi" function name? > > Thanks a lot! > > Dick > > > > At 10:29 10/28/2004, Bill Mill wrote: > >Dick, > > > >Recursively: > > > >mpi(n, d, lim): > > if d >= lim: return 1 + (n/d) > > return 1 + (n/d) * mpi(n+1, d+2, lim) > > > > >>> 2 * mpi(1., 3., 1000) #note that 1 and/or 3 need to be floats > >3.1415926535897931 > > > >Peace > >Bill Mill > >bill.mill at gmail.com > > > >On Thu, 28 Oct 2004 09:44:09 -0700, Dick Moores wrote: > > > Is it possible to calculate almost-pi/2 using the (24) formula on > > > without using (23)? > > > > > > If it's possible, how about a hint? Recursion? > > > > > > Thanks, tutors. > > > > > > Dick Moores > > > rdm@rcblue.com > > From RenX99 at gmail.com Thu Oct 28 21:45:39 2004 From: RenX99 at gmail.com (Rene Lopez) Date: Thu Oct 28 21:45:42 2004 Subject: [Tutor] recommended IDE for windows? In-Reply-To: <797fe3d4041027095354d085ec@mail.gmail.com> References: <555128ce04102708132cd0cf98@mail.gmail.com> <417FC3D5.60504@cso.atmel.com> <797fe3d4041027090567c6734f@mail.gmail.com> <555128ce04102709093beb2f83@mail.gmail.com> <797fe3d4041027095354d085ec@mail.gmail.com> Message-ID: <555128ce04102812452574d45b@mail.gmail.com> syntax on doesn't seem to make any difference in my vim screen, at least not while i'm connected via ssh.... i'll have to see if it makes a difference when i'm at home. On Wed, 27 Oct 2004 12:53:29 -0400, Bill Mill wrote: > Rene, > > To get syntax highlighting (even in most of your config files! it > highlights damn near anything recognizable) just type "syntax on" at > the command prompt. Check out the FAQ - > http://vimdoc.sourceforge.net/vimfaq.html . > > Peace > Bill Mill > bill.mill at gmail.com > > > > > On Wed, 27 Oct 2004 12:09:29 -0400, Rene Lopez wrote: > > I actually use Vim to do most of my config file editing and such... > > never tried it for writing more than simple scripts, as it doesn't > > seem to be configured at the moment for fancy things like syntax > > highlighting and such. I suppose I should get around to learning it a > > bit better... so i can at least do more than just simple editing of > > files. > > > > > > > > > > On Wed, 27 Oct 2004 12:05:46 -0400, Bill Mill wrote: > > > Hey, > > > > > > I'm gonna be the stodgy old man and second Mike's suggestion of > > > Vim/Emacs. I prefer Vim personally (It is the editor to rule all > > > editors!) but many prefer Emacs. Both editors are cross-platform to > > > *everything*, so you almost never have to leave your editor behind. > > > Furthermore, both have plugins for *everything* under the sun - syntax > > > coloring, CVS uploading, etc etc. > > > > > > There are a lot of advantages to being good at a particular text > > > editor; I find it comes in handy all the time. It sucks to learn, but > > > boy is it useful once you get over the hump. > > > > > > Peace > > > Bill Mill > > > > > > > > > > > > > > > On Wed, 27 Oct 2004 09:50:45 -0600, Mike Hansen wrote: > > > > A lot of people like Scite. I fired it up, but haven't played with it much. > > > > > > > > I have used Activestate's Komodo. It's not free. The personal edition is > > > > something like $30. The professional edition is around $250-$300. There > > > > are some really neat features like background syntax checking and code > > > > folding. > > > > > > > > Another editor/IDE I want to look into is Eclipse. Pydev is a plug-in > > > > for it. I'm kind of in the wait and see mode on this one. > > > > > > > > I've said this before..., you might take a look at emacs or vim. They > > > > have a steep learning curve, but they run on multiple platforms, so you > > > > don't have to learn a new editor when you are on Solaris or Linux. The > > > > point of emacs and vim is to keep your hands on the keyboard which > > > > supposedly makes you more productive. I'm digging into vim more and > > > > more. I tried emacs three times, and it didn't click with me. YMMV. > > > > Although vim doesn't have tabs, it has buffers, and you can display a > > > > buffer list. There are plenty of ways to configure emacs and vim do work > > > > mostly the way you want. > > > > > > > > I sometimes use JEdit for working on HTML since it does a great job of > > > > auto-completing tags for you. It think it also does syntax highlighting > > > > for Python. > > > > > > > > There's a list of editors at the Python web > > > > site.(http://www.python.org/moin/PythonEditors) > > > > You can also search this list for earlier discussions on editors/IDEs. > > > > > > > > Mike > > > > > > > > > > > > > > > > > > > > Rene Lopez wrote: > > > > > > > > >anyone have any recommendations for a good IDE for python on windows? > > > > >Preferably free if possible :) So far I've been using idle, which > > > > >works but seems pretty basic, would be nice to have some sort of IDE > > > > >with tabs instead of multiple windows....helps keep the desktop clean > > > > >;-) > > > > > > > > > > > > > > _______________________________________________ > > > > Tutor maillist - Tutor@python.org > > > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > _______________________________________________ > > > Tutor maillist - Tutor@python.org > > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > > > -- > > > > Rene > > > -- Rene From dyoo at hkn.eecs.berkeley.edu Thu Oct 28 22:01:06 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Oct 28 22:01:10 2004 Subject: [Tutor] Mount size In-Reply-To: <207DA77D2384D411A48B0008C7095D810152B8DE@us-melbourne.mail.saic.com> Message-ID: On Thu, 28 Oct 2004, Faulconer, Steven M. wrote: > In further testing, I can't seem to get a reliable return for os.statvfs > even on a locally mounted file system. The filesystem in question is on > a fiber array, and is about 1.2TB in size (array is 3TB total). [text cut] Hi Steven, Yikes. It sounds like the statvfs() function that Python uses isn't the same one that 'df' uses on your system, and that seems bizarre to me. In that case, I'm way in over my head then. *grin* I don't think I can effectively help to debug this problem. If no one else here has a clue about what's going on, then can you send your question (and a brief summary of how far we got here) off to the comp.lang.python newsgroup? There should be others there that can help figure out what's going on. Good luck to you! From kent_johnson at skillsoft.com Thu Oct 28 22:01:44 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Thu Oct 28 22:03:25 2004 Subject: [Tutor] HTMLParser problem unable to find all the IMG tags.... In-Reply-To: <6.1.2.0.0.20041028152745.03c70ca0@qmail.dideas.com> References: <6.1.2.0.0.20041028080847.03c35ca0@10.2.0.8> <1098985771.4985.19.camel@laptop.venix.com> <6.1.2.0.0.20041028152745.03c70ca0@qmail.dideas.com> Message-ID: <6.1.0.6.0.20041028160059.02ac62b8@mail4.skillsoft.com> You might want to take a look at BeautifulSoup, it is designed to pull data from (possibly) badly-formed web pages. http://www.crummy.com/software/BeautifulSoup/ Kent At 03:36 PM 10/28/2004 -0400, Chris Barnhart wrote: >At 01:49 PM 10/28/2004, Lloyd Kvam wrote: >>On Thu, 2004-10-28 at 08:34, Chris Barnhart wrote: >> > >> > The problem is that using the HTMLParser I'm not getting all the IMG >> > tags. I know this as I have another program that just uses string >> > processing that gets 2.5 times more IMG SRC tag. I also know this because >> > HTMLParser starttag is never called with the IMG that I'm after! >> >>For debugging I would suggest saving the html locally from both methods >>and confirming that they are the same. Then run your HTMLParser against >>the saved file and print the img tags that you find. You can redirect >>the output to a file. Then compare to the original html to see what >>tags got missed. >> >>Debugging against the live site means that you have no control on the >>data being fed through and no easy way to validate your program. > > >Thanks Lloyd, > >Yeah - I agree. I've saved the webpage to a file and am working through >it. It's nothing to do with capitalization.... > >The webpage is in a string now, and I've found that if I cut off the start >of the string, I can get "new" tags to appear. I'm trying to work though >and fix exactly which tags are missing and why. Its kind of tedious! > >One possible problem is that HTMLParse is HTML 2.0 complied, but CNN's >output is 4.01. > >f = open("cnn_py.html","r") >html_full = f.read() >f.close() >html = html_full[20000:] >h = MyParser() >h.feed(html) >h.close() > >When I figure this out, I'll make a new post. > >Chris >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From dyoo at hkn.eecs.berkeley.edu Thu Oct 28 22:11:35 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Oct 28 22:11:40 2004 Subject: [Tutor] Python Command Line Args (input) equivalent to Perl In-Reply-To: Message-ID: On Thu, 28 Oct 2004, Edward WIJAYA wrote: > I am new to Python, and I like to learn more about it. Since I am used > to Perl before, I would like to know what is Python equivalent of Perl > code below: > > > $filename = $ARGV[0]; > open (FILE,"$filename") || die "Can't Open $filename: $!\n"; > while{ #dealing with it per-lines > #process something here > } Hi Edward, Several variables that Perl makes globally available have equivalents in Python. Python tries to keep fewer global variables at toplevel: they equivalents will often live in separate modules. Perl's '@ARGV', for example, has an equivalent in Python's 'sys.argv' list. Perl's '%ENV' corresponds with Python's 'os.environ' dictionary. For example, from the interactive interpreter, we can type: ### >>> import os >>> os.environ['HOME'] '/home/dyoo' ### If you have more questions, please feel free to ask! From mhansen at cso.atmel.com Thu Oct 28 22:15:01 2004 From: mhansen at cso.atmel.com (Mike Hansen) Date: Thu Oct 28 22:14:56 2004 Subject: [Tutor] Re: recommended IDE for windows? In-Reply-To: <20041028194546.AB49F1E4007@bag.python.org> References: <20041028194546.AB49F1E4007@bag.python.org> Message-ID: <41815345.2070306@cso.atmel.com> Hmmm... I have syntax enable in my vimrc file. You might try that. There's a book on VIM... the link below is to the PDF version. http://www.truth.sk/vim/vimbook-OPL.pdf Also, the main VIM site is http://www.vim.org I'd check out that site as well as the comp.editors newsgroup. Mike > > Subject: > Re: [Tutor] recommended IDE for windows? > From: > Rene Lopez > Date: > Thu, 28 Oct 2004 15:45:39 -0400 > To: > Bill Mill > > To: > Bill Mill > CC: > tutor@python.org > > >syntax on doesn't seem to make any difference in my vim screen, at >least not while i'm connected via ssh.... i'll have to see if it makes >a difference when i'm at home. > > > > >On Wed, 27 Oct 2004 12:53:29 -0400, Bill Mill wrote: > > >>Rene, >> >>To get syntax highlighting (even in most of your config files! it >>highlights damn near anything recognizable) just type "syntax on" at >>the command prompt. Check out the FAQ - >>http://vimdoc.sourceforge.net/vimfaq.html . >> >>Peace >>Bill Mill >>bill.mill at gmail.com >> >> >> >> >>On Wed, 27 Oct 2004 12:09:29 -0400, Rene Lopez wrote: >> >> >>>I actually use Vim to do most of my config file editing and such... >>>never tried it for writing more than simple scripts, as it doesn't >>>seem to be configured at the moment for fancy things like syntax >>>highlighting and such. I suppose I should get around to learning it a >>>bit better... so i can at least do more than just simple editing of >>>files. >>> >>> >>> >>> >>>On Wed, 27 Oct 2004 12:05:46 -0400, Bill Mill wrote: >>> >>> >>>>Hey, >>>> >>>>I'm gonna be the stodgy old man and second Mike's suggestion of >>>>Vim/Emacs. I prefer Vim personally (It is the editor to rule all >>>>editors!) but many prefer Emacs. Both editors are cross-platform to >>>>*everything*, so you almost never have to leave your editor behind. >>>>Furthermore, both have plugins for *everything* under the sun - syntax >>>>coloring, CVS uploading, etc etc. >>>> >>>>There are a lot of advantages to being good at a particular text >>>>editor; I find it comes in handy all the time. It sucks to learn, but >>>>boy is it useful once you get over the hump. >>>> >>>>Peace >>>>Bill Mill >>>> >>>> >>>> >>>> >>>>On Wed, 27 Oct 2004 09:50:45 -0600, Mike Hansen wrote: >>>> >>>> >>>>>A lot of people like Scite. I fired it up, but haven't played with it much. >>>>> >>>>>I have used Activestate's Komodo. It's not free. The personal edition is >>>>>something like $30. The professional edition is around $250-$300. There >>>>>are some really neat features like background syntax checking and code >>>>>folding. >>>>> >>>>>Another editor/IDE I want to look into is Eclipse. Pydev is a plug-in >>>>>for it. I'm kind of in the wait and see mode on this one. >>>>> >>>>>I've said this before..., you might take a look at emacs or vim. They >>>>>have a steep learning curve, but they run on multiple platforms, so you >>>>>don't have to learn a new editor when you are on Solaris or Linux. The >>>>>point of emacs and vim is to keep your hands on the keyboard which >>>>>supposedly makes you more productive. I'm digging into vim more and >>>>>more. I tried emacs three times, and it didn't click with me. YMMV. >>>>>Although vim doesn't have tabs, it has buffers, and you can display a >>>>>buffer list. There are plenty of ways to configure emacs and vim do work >>>>>mostly the way you want. >>>>> >>>>>I sometimes use JEdit for working on HTML since it does a great job of >>>>>auto-completing tags for you. It think it also does syntax highlighting >>>>>for Python. >>>>> >>>>>There's a list of editors at the Python web >>>>>site.(http://www.python.org/moin/PythonEditors) >>>>>You can also search this list for earlier discussions on editors/IDEs. >>>>> >>>>>Mike >>>>> >>>>> >>>>> >>>>> >>>>>Rene Lopez wrote: >>>>> >>>>> >>>>> >>>>>>anyone have any recommendations for a good IDE for python on windows? >>>>>>Preferably free if possible :) So far I've been using idle, which >>>>>>works but seems pretty basic, would be nice to have some sort of IDE >>>>>>with tabs instead of multiple windows....helps keep the desktop clean >>>>>>;-) >>>>>> >>>>>> >>>>>> >>>>>> >>>>>_______________________________________________ >>>>>Tutor maillist - Tutor@python.org >>>>>http://mail.python.org/mailman/listinfo/tutor >>>>> >>>>> >>>>> >>>>_______________________________________________ >>>>Tutor maillist - Tutor@python.org >>>>http://mail.python.org/mailman/listinfo/tutor >>>> >>>> >>>> >>>-- >>> >>>Rene >>> >>> >>> > > > > >------------------------------------------------------------------------ > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > From dyoo at hkn.eecs.berkeley.edu Thu Oct 28 22:20:27 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Oct 28 22:20:31 2004 Subject: [Tutor] How to calculate pi with this formula? In-Reply-To: <6.1.2.0.2.20041028121910.030e1230@rcblue.com> Message-ID: On Thu, 28 Oct 2004, Dick Moores wrote: > Interesting! Thanks. Hi Dick, Hmmm... This seems very close to a problem exercise from the classic textbook Structure and Interpretation of Computer Programs (SICP): http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-24.html#%_idx_3976 The approach that the SICP folks use is called "stream processing": I wonder how difficult it would be to translate this from Scheme into Python... From mlist-python at dideas.com Thu Oct 28 22:22:33 2004 From: mlist-python at dideas.com (Chris Barnhart) Date: Thu Oct 28 22:23:20 2004 Subject: [Tutor] HTMLParser problem unable to find all the IMG tags.... Message-ID: <6.1.2.0.0.20041028155831.03aa8150@qmail.dideas.com> At 01:49 PM 10/28/2004, Lloyd Kvam wrote: >On Thu, 2004-10-28 at 08:34, Chris Barnhart wrote: > > > > The problem is that using the HTMLParser I'm not getting all the IMG > > tags. I know this as I have another program that just uses string > > processing that gets 2.5 times more IMG SRC tag. I also know this because > > HTMLParser starttag is never called with the IMG that I'm after! The problem with my getting all the IMG tags from CNN is the lack of a space separating a close quote and start of an attribute in at least one their IMG SRC statements. So its a problem with CNN. But this causes HTMLParser to fail permanently until the end. For example this statement breaks HTMLParser: Following is a demo program and the output. It run parse two strings each with 3 img src tags. The 2nd string has the lack of space in the 2nd statement. I guess at this point I'm supposed to fix the Parser since CNN can't be fixed? import urllib2 from HTMLParser import HTMLParser class MyParser(HTMLParser): def __init__( self ) : HTMLParser.__init__(self) self.cnt = 0 def handle_starttag(self, tag, attr): print tag, attr def close(self) : HTMLParser.close(self) s_bug = '"' s_ok = '"' print "Working output" html = s_ok h = MyParser() h.feed(html) h.close() print "\nBroken output" html = s_bug h = MyParser() h.feed(html) h.close() print "Finished" >>> Working output img [('src', 'http://abc.com'), ('width', '10')] img [('src', 'http://abc.com'), ('width', '10')] img [('src', 'http://abc.com'), ('width', '10')] Broken output img [('src', 'http://abc.com'), ('width', '10')] Traceback (most recent call last): File "C:\Python23\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", line 310, in RunScript exec codeObject in __main__.__dict__ File "C:\src\python\url_bug.py", line 35, in ? h.close() File "C:\src\python\url_bug.py", line 15, in close HTMLParser.close(self) File "C:\Python23\lib\HTMLParser.py", line 112, in close self.goahead(1) File "C:\Python23\lib\HTMLParser.py", line 164, in goahead self.error("EOF in middle of construct") File "C:\Python23\lib\HTMLParser.py", line 115, in error raise HTMLParseError(message, self.getpos()) HTMLParseError: EOF in middle of construct, at line 1, column 38 >>> From kent_johnson at skillsoft.com Thu Oct 28 22:48:13 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Thu Oct 28 22:49:55 2004 Subject: [Tutor] How to calculate pi with this formula? In-Reply-To: References: <6.1.2.0.2.20041028121910.030e1230@rcblue.com> Message-ID: <6.1.0.6.0.20041028164658.02921540@mail4.skillsoft.com> Hans Nowak has played around with that a bit. Look here: http://zephyrfalcon.org/weblog/arch_d7_2003_10_04.html#e362 and here: http://zephyrfalcon.org/weblog2/arch_e10_00630.html#e633 Kent At 01:20 PM 10/28/2004 -0700, Danny Yoo wrote: >On Thu, 28 Oct 2004, Dick Moores wrote: > > > Interesting! Thanks. > >Hi Dick, > > >Hmmm... This seems very close to a problem exercise from the classic >textbook Structure and Interpretation of Computer Programs (SICP): > >http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-24.html#%_idx_3976 > >The approach that the SICP folks use is called "stream processing": I >wonder how difficult it would be to translate this from Scheme into >Python... > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From alan.gauld at freenet.co.uk Thu Oct 28 23:02:46 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu Oct 28 23:03:49 2004 Subject: [Tutor] recommended IDE for windows? References: <555128ce04102708132cd0cf98@mail.gmail.com><417FC3D5.60504@cso.atmel.com><797fe3d4041027090567c6734f@mail.gmail.com><555128ce04102709093beb2f83@mail.gmail.com><797fe3d4041027095354d085ec@mail.gmail.com> <555128ce04102812452574d45b@mail.gmail.com> Message-ID: <01b601c4bd31$7a01ec10$af468651@xp> > syntax on doesn't seem to make any difference in my vim screen, at > least not while i'm connected via ssh.... i'll have to see if it makes > a difference when i'm at home. It will depend on what your terminal settings are. If the server thinks you are a vt200 or similar then it will be very limited in what it can do... Syntax highlighting works in a colour xterm, but is much better in the gui - gvim. Alan G. From alan.gauld at freenet.co.uk Thu Oct 28 23:00:44 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu Oct 28 23:04:50 2004 Subject: [Tutor] "Clean screen" (where screen==stdout) functionality needed, but o n Windows References: <33678E78A2DD4D418396703A750048D40102504A@RIKER> Message-ID: <01a301c4bd31$31b8fa70$af468651@xp> > I am looking for a way to occasionally clear whatever executing Python > script have sent to stdout so far. THis comes up a lot but unfortunately it is platform specific so there is no nice neat answer. > "DOS-box" cls equivalent is preferred, although if all other fails I > might just print N empty lines to scroll printed stuff out of the way... os.system('CLS') may be your best bet... > While it would be great if my Python script would be able to figure out > how big is the "box" (DOS box that is) CLS will do all of that for you. > Googling uncovered this http://flangy.com/dev/python/curses/ but being > in "Alpha 3" release from the beginning of this year and without any > later updates... curses is overkill for clearing the screen, you'd be as well with print '\n'*100 But if you know you are on DOS why not let the OS do it... Alan G. From dyoo at hkn.eecs.berkeley.edu Thu Oct 28 23:05:59 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Oct 28 23:06:10 2004 Subject: [Tutor] HTMLParser problem unable to find all the IMG tags.... In-Reply-To: <6.1.2.0.0.20041028155831.03aa8150@qmail.dideas.com> Message-ID: On Thu, 28 Oct 2004, Chris Barnhart wrote: > At 01:49 PM 10/28/2004, Lloyd Kvam wrote: > >On Thu, 2004-10-28 at 08:34, Chris Barnhart wrote: > > > > > > The problem is that using the HTMLParser I'm not getting all the IMG > > > tags. I know this as I have another program that just uses string > > > processing that gets 2.5 times more IMG SRC tag. I also know this because > > > HTMLParser starttag is never called with the IMG that I'm after! > > > The problem with my getting all the IMG tags from CNN is the lack of a > space separating a close quote and start of an attribute in at least one > their IMG SRC statements. Hi Chris, Ah, that makes sense. Can you send a feature request or bug report to the Python developers? They keep a bug list on Sourceforge: http://sourceforge.net/tracker/?group_id=5470 I did some diving through the code. The bug appears to be that the internal function HTMLParser.check_for_whole_start_tag() doesn't recognize that: is a whole start tag element. I think it might have to do with HTMLParser.locatestarttagend, because the regular expression there says: ### locatestarttagend = re.compile(r""" <[a-zA-Z][-.a-zA-Z0-9:_]* # tag name (?:\s+ # whitespace before attribute name (?:[a-zA-Z_][-.:a-zA-Z0-9_]* # attribute name (?:\s*=\s* # value indicator (?:'[^']*' # LITA-enclosed value |\"[^\"]*\" # LIT-enclosed value |[^'\">\s]+ # bare value ) )? ) )* \s* # trailing whitespace """, re.VERBOSE) ### that there's a required whitespace before every attribute value. CNN's HTML obviously doesn't have this. I wonder what happens if we relax the regular expression slightly, so that the whitespace is optional. ### >>> import HTMLParser >>> import re >>> HTMLParser.locatestarttagend = re.compile(r""" ... <[a-zA-Z][-.a-zA-Z0-9:_]* # tag name ... (?:\s* # optional whitespace before ... # attribute name ... (?:[a-zA-Z_][-.:a-zA-Z0-9_]* # attribute name ... (?:\s*=\s* # value indicator ... (?:'[^']*' # LITA-enclosed value ... |\"[^\"]*\" # LIT-enclosed value ... |[^'\">\s]+ # bare value ... ) ... )? ... ) ... )* ... \s* # trailing whitespace ... """, re.VERBOSE) >>> class Parser(HTMLParser.HTMLParser): ... def handle_starttag(self, tag, attrs): ... print "START", tag, attrs ... >>> p = Parser() >>> p.feed(' ') START img [('src', 'abc.jpg'), ('width', '5')] ### Ok, that makes the parser a little more permissive, so that it'll accept the screwed up HTML that CNN is providing us. *grin* Chris, would this work for you? Maybe we can pass this off to the Python developers and get it into the next release. Do you want to send the bug report to them? Good luck to you! From kent_johnson at skillsoft.com Thu Oct 28 23:13:25 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Thu Oct 28 23:15:03 2004 Subject: [Tutor] "Clean screen" (where screen==stdout) functionality needed, but o n Windows In-Reply-To: <33678E78A2DD4D418396703A750048D40102504A@RIKER> References: <33678E78A2DD4D418396703A750048D40102504A@RIKER> Message-ID: <6.1.0.6.0.20041028171301.02aac4c8@mail4.skillsoft.com> You might want to take a look at wconio: http://newcenturycomputers.net/projects/wconio.html Kent At 01:19 PM 10/28/2004 -0400, Branimir Petrovic wrote: >I am looking for a way to occasionally clear whatever executing Python >script have sent to stdout so far. > >"DOS-box" cls equivalent is preferred, although if all other fails I >might just print N empty lines to scroll printed stuff out of the way... > >Preferably I'd like to be able to make (or fake) minimally functional >command line interface environment for Python scripts on Windows. >Should I be looking for something specific in Win32all? > >While it would be great if my Python script would be able to figure out >how big is the "box" (DOS box that is) it uses for its stdout (in order >to know how much "real estate" it has for its output), just the ability >to clear it all up at will and start printing from the upper left corner >would do for now. > >Googling uncovered this http://flangy.com/dev/python/curses/ but being >in "Alpha 3" release from the beginning of this year and without any >later updates... > >Any ideas and/or pointers on how to create usable command line >interface for Python scripts on Windows platform is very welcome. > >Branimir >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From RenX99 at gmail.com Fri Oct 29 00:08:25 2004 From: RenX99 at gmail.com (Rene Lopez) Date: Fri Oct 29 00:08:31 2004 Subject: [Tutor] Re: recommended IDE for windows? In-Reply-To: <41815345.2070306@cso.atmel.com> References: <20041028194546.AB49F1E4007@bag.python.org> <41815345.2070306@cso.atmel.com> Message-ID: <555128ce04102815086d0d1c37@mail.gmail.com> thanks for the help, i got it working now. :) On Thu, 28 Oct 2004 14:15:01 -0600, Mike Hansen wrote: > Hmmm... > > I have syntax enable in my vimrc file. You might try that. > > There's a book on VIM... the link below is to the PDF version. > > http://www.truth.sk/vim/vimbook-OPL.pdf > > Also, the main VIM site is > > http://www.vim.org > > I'd check out that site as well as the comp.editors newsgroup. > > Mike > > > > > Subject: > > Re: [Tutor] recommended IDE for windows? > > From: > > Rene Lopez > > Date: > > Thu, 28 Oct 2004 15:45:39 -0400 > > To: > > Bill Mill > > > > To: > > Bill Mill > > CC: > > tutor@python.org > > > > > > > >syntax on doesn't seem to make any difference in my vim screen, at > >least not while i'm connected via ssh.... i'll have to see if it makes > >a difference when i'm at home. > > > > > > > > > >On Wed, 27 Oct 2004 12:53:29 -0400, Bill Mill wrote: > > > > > >>Rene, > >> > >>To get syntax highlighting (even in most of your config files! it > >>highlights damn near anything recognizable) just type "syntax on" at > >>the command prompt. Check out the FAQ - > >>http://vimdoc.sourceforge.net/vimfaq.html . > >> > >>Peace > >>Bill Mill > >>bill.mill at gmail.com > >> > >> > >> > >> > >>On Wed, 27 Oct 2004 12:09:29 -0400, Rene Lopez wrote: > >> > >> > >>>I actually use Vim to do most of my config file editing and such... > >>>never tried it for writing more than simple scripts, as it doesn't > >>>seem to be configured at the moment for fancy things like syntax > >>>highlighting and such. I suppose I should get around to learning it a > >>>bit better... so i can at least do more than just simple editing of > >>>files. > >>> > >>> > >>> > >>> > >>>On Wed, 27 Oct 2004 12:05:46 -0400, Bill Mill wrote: > >>> > >>> > >>>>Hey, > >>>> > >>>>I'm gonna be the stodgy old man and second Mike's suggestion of > >>>>Vim/Emacs. I prefer Vim personally (It is the editor to rule all > >>>>editors!) but many prefer Emacs. Both editors are cross-platform to > >>>>*everything*, so you almost never have to leave your editor behind. > >>>>Furthermore, both have plugins for *everything* under the sun - syntax > >>>>coloring, CVS uploading, etc etc. > >>>> > >>>>There are a lot of advantages to being good at a particular text > >>>>editor; I find it comes in handy all the time. It sucks to learn, but > >>>>boy is it useful once you get over the hump. > >>>> > >>>>Peace > >>>>Bill Mill > >>>> > >>>> > >>>> > >>>> > >>>>On Wed, 27 Oct 2004 09:50:45 -0600, Mike Hansen wrote: > >>>> > >>>> > >>>>>A lot of people like Scite. I fired it up, but haven't played with it much. > >>>>> > >>>>>I have used Activestate's Komodo. It's not free. The personal edition is > >>>>>something like $30. The professional edition is around $250-$300. There > >>>>>are some really neat features like background syntax checking and code > >>>>>folding. > >>>>> > >>>>>Another editor/IDE I want to look into is Eclipse. Pydev is a plug-in > >>>>>for it. I'm kind of in the wait and see mode on this one. > >>>>> > >>>>>I've said this before..., you might take a look at emacs or vim. They > >>>>>have a steep learning curve, but they run on multiple platforms, so you > >>>>>don't have to learn a new editor when you are on Solaris or Linux. The > >>>>>point of emacs and vim is to keep your hands on the keyboard which > >>>>>supposedly makes you more productive. I'm digging into vim more and > >>>>>more. I tried emacs three times, and it didn't click with me. YMMV. > >>>>>Although vim doesn't have tabs, it has buffers, and you can display a > >>>>>buffer list. There are plenty of ways to configure emacs and vim do work > >>>>>mostly the way you want. > >>>>> > >>>>>I sometimes use JEdit for working on HTML since it does a great job of > >>>>>auto-completing tags for you. It think it also does syntax highlighting > >>>>>for Python. > >>>>> > >>>>>There's a list of editors at the Python web > >>>>>site.(http://www.python.org/moin/PythonEditors) > >>>>>You can also search this list for earlier discussions on editors/IDEs. > >>>>> > >>>>>Mike > >>>>> > >>>>> > >>>>> > >>>>> > >>>>>Rene Lopez wrote: > >>>>> > >>>>> > >>>>> > >>>>>>anyone have any recommendations for a good IDE for python on windows? > >>>>>>Preferably free if possible :) So far I've been using idle, which > >>>>>>works but seems pretty basic, would be nice to have some sort of IDE > >>>>>>with tabs instead of multiple windows....helps keep the desktop clean > >>>>>>;-) > >>>>>> > >>>>>> > >>>>>> > >>>>>> > >>>>>_______________________________________________ > >>>>>Tutor maillist - Tutor@python.org > >>>>>http://mail.python.org/mailman/listinfo/tutor > >>>>> > >>>>> > >>>>> > >>>>_______________________________________________ > >>>>Tutor maillist - Tutor@python.org > >>>>http://mail.python.org/mailman/listinfo/tutor > >>>> > >>>> > >>>> > >>>-- > >>> > >>>Rene > >>> > >>> > >>> > > > > > > > > > >------------------------------------------------------------------------ > > > >_______________________________________________ > > > >Tutor maillist - Tutor@python.org > >http://mail.python.org/mailman/listinfo/tutor > > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- Rene From BranimirP at cpas.com Fri Oct 29 00:09:03 2004 From: BranimirP at cpas.com (Branimir Petrovic) Date: Fri Oct 29 00:09:08 2004 Subject: [Tutor] "Clean screen" (where screen==stdout) functionality n eeded,but o n Windows Message-ID: <33678E78A2DD4D418396703A750048D40102504D@RIKER> > -----Original Message----- > From: Alan Gauld > > I am looking for a way to occasionally clear whatever executing > Python > > script have sent to stdout so far. > > THis comes up a lot but unfortunately it is platform specific so > there is no nice neat answer. > Pity there isn't something of the sort. I'd love to be able to build Python apps that visually look and feel like good ole Norton Commander (MC nowadays) so it would look the same, be easy to navigate via keyboard only and work the same regardless of the platform it runs on (built of "standard parts" too if possible). > > "DOS-box" cls equivalent is preferred, although if all other fails I > > might just print N empty lines to scroll printed stuff out of the > way... > > os.system('CLS') > > may be your best bet... > Ah that's it exactly! I remembered seeing something to run OS commands, but in moment of need - couldn't remember what it was. Search on exec/execute theme proved futile, and context sensitive (by what you want to do) search does not exist. Python's standard library definitely needs better documentation... So for now os.system('cls') will do, and if I really care about keyboard navigatable NC look-alike, paradoxically - it will have to be done/emulated via GUI toolkit. > -----Original Message----- > From: Kent Johnson > You might want to take a look at wconio: > http://newcenturycomputers.net/projects/wconio.html > Looks like I'll be able to add some bells (if not whistles too) to my "half-a-pony-show" (os.system('cls')) after all;) Thanks for the pointer! Branimir From rmkrauter at yahoo.com Fri Oct 29 02:42:34 2004 From: rmkrauter at yahoo.com (Rich Krauter) Date: Fri Oct 29 02:42:42 2004 Subject: [Tutor] searching for data in one file from another In-Reply-To: References: Message-ID: <418191FA.7070304@yahoo.com> Scott Melnyk wrote: > Hello! > I have a file with exon ids, one per line and another large file with > exon, gene and transcript info. > > I would like to remove each entry in the second (ID information and > subsequent sequence data) which matches from the first, but I keep > running into problems just getting the matching to work. > # format of file to remove exons from is: > > >ENSE00001387275.1|ENSG00000187908.1|ENST00000339871.1 > assembly=NCBI34|chr=10_NT_078087|strand=forward|bases 72877 to > 72981|exons plus upstream and downstream regions for exon > > GAGATGGCAGGTGTCAGGGCCGAGTGGAGATCCTATACCGAGGCTCCTGGGGCACCGTGTGTG > [code and text cut] Hi Scott, You might be making things a little too hard on yourself. Here is a function to take a filename and a list of exons to delete from it; it prints to stdout the exons not in the exons_to_delete list: def deleteExons(fname,exons_to_delete): f = open(fname) exon = None for line in f: if line.startswith('>'): exon = line[1:].split('|')[0] if exon in exons_to_delete: continue yield line if __name__ == '__main__': for line in deleteExons('D:/exondata.txt',['ENSE00001387276.1']): print line, I'll leave the code for populating the exons_to_delete list up to you. Note, this might be slow if the exons_to_delete list has lots of entries; if so, you could use a dict or a set instead of list to contain exons_to_delete. I ran above function on a file that looks like this: ############ >ENSE00001387275.1|ENSG00000187908.1|ENST00000339871.1 assembly=NCBI34|chr=10_NT_078087|strand=forward|bases 72877 to 72981|exons plus upstream and downstream regions for exon GAGATGGCAGGTGTCAGGGCCGAGTGGAGATCCTATACCGAGGCTCCTGGGGCACCGTGTGTG >ENSE00001387276.1|ENSG00000187908.1|ENST00000339871.1 assembly=NCBI34|chr=10_NT_078087|strand=forward|bases 72877 to 72981|exons plus upstream and downstream regions for exon GAGATGGCAGGTGTCAGGGCCGAGTGGAGATCCTATACCGAGGCTCCTGGGGCACCGTGTGTG >ENSE00001387277.1|ENSG00000187908.1|ENST00000339871.1 assembly=NCBI34|chr=10_NT_078087|strand=forward|bases 72877 to 72981|exons plus upstream and downstream regions for exon GAGATGGCAGGTGTCAGGGCCGAGTGGAGATCCTATACCGAGGCTCCTGGGGCACCGTGTGTGA ############ and got output that looks like this: ############## >ENSE00001387275.1|ENSG00000187908.1|ENST00000339871.1 assembly=NCBI34|chr=10_NT_078087|strand=forward|bases 72877 to 72981|exons plus upstream and downstream regions for exon GAGATGGCAGGTGTCAGGGCCGAGTGGAGATCCTATACCGAGGCTCCTGGGGCACCGTGTGTGA >ENSE00001387277.1|ENSG00000187908.1|ENST00000339871.1 assembly=NCBI34|chr=10_NT_078087|strand=forward|bases 72877 to 72981|exons plus upstream and downstream regions for exon GAGATGGCAGGTGTCAGGGCCGAGTGGAGATCCTATACCGAGGCTCCTGGGGCACCGTGTGTGA ############# Hope that helps. Rich From cyresse at gmail.com Fri Oct 29 03:41:38 2004 From: cyresse at gmail.com (Liam Clarke) Date: Fri Oct 29 03:41:46 2004 Subject: [Tutor] "Clean screen" (where screen==stdout) functionality n eeded, but o n Windows In-Reply-To: <33678E78A2DD4D418396703A750048D40102504D@RIKER> References: <33678E78A2DD4D418396703A750048D40102504D@RIKER> Message-ID: I just use something I saw in one of Alan's tutorials - for i in range(26): print Of course, it only works on a 25 line monitor. On Thu, 28 Oct 2004 18:09:03 -0400, Branimir Petrovic wrote: > > > -----Original Message----- > > From: Alan Gauld > > > > I am looking for a way to occasionally clear whatever executing > > Python > > > script have sent to stdout so far. > > > > THis comes up a lot but unfortunately it is platform specific so > > there is no nice neat answer. > > > > Pity there isn't something of the sort. I'd love to be able to > build Python apps that visually look and feel like good ole Norton > Commander (MC nowadays) so it would look the same, be easy to > navigate via keyboard only and work the same regardless of the > platform it runs on (built of "standard parts" too if possible). > > > > "DOS-box" cls equivalent is preferred, although if all other fails I > > > might just print N empty lines to scroll printed stuff out of the > > way... > > > > os.system('CLS') > > > > may be your best bet... > > > > Ah that's it exactly! I remembered seeing something to run OS > commands, but in moment of need - couldn't remember what it was. > Search on exec/execute theme proved futile, and context sensitive > (by what you want to do) search does not exist. Python's standard > library definitely needs better documentation... > > So for now os.system('cls') will do, and if I really care about > keyboard navigatable NC look-alike, paradoxically - it will have > to be done/emulated via GUI toolkit. > > > -----Original Message----- > > From: Kent Johnson > > > You might want to take a look at wconio: > > http://newcenturycomputers.net/projects/wconio.html > > > > Looks like I'll be able to add some bells (if not whistles too) > to my "half-a-pony-show" (os.system('cls')) after all;) Thanks > for the pointer! > > Branimir > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From cepl at surfbest.net Fri Oct 29 00:55:59 2004 From: cepl at surfbest.net (Matej Cepl) Date: Fri Oct 29 17:03:34 2004 Subject: [Tutor] Too many open files -- how to copy a folder? Message-ID: <1286346.t315YGR7Yt@blahoslav.ceplovi.cz> Hi, I've tried this: blahoslav:matej$ python Python 2.3.4 (#2, Sep 24 2004, 08:39:09) [GCC 3.3.4 (Debian 1:3.3.4-12)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import mailbox >>> box = mailbox.Maildir("/home/matej/WP/trash/") >>> another = [x for x in box] Traceback (most recent call last): File "", line 1, in ? File "/usr/lib/python2.3/mailbox.py", line 246, in next IOError: [Errno 24] Too many open files: '/home/matej/WP/trash/cur/1098844013.6284.XKuCF:2,S' Can be done something about that? Of course, that I will use some filter in the mapping, but still even when I try >>> import email,email.Utils >>> import mailbox >>> box = mailbox.Maildir("/home/matej/WP/trash/") >>> date = email.Utils.parsedate_tz >>> import time >>> dlist = list(time.localtime()) >>> dlist[1] -= 3 >>> archdate = tuple(dlist) >>> alist = [x for x in box if date(x['date'])", line 1, in ? File "/usr/lib/python2.3/mailbox.py", line 246, in next IOError: [Errno 24] Too many open files: '/home/matej/WP/trash/cur/1098844013.6284.XKuCF:2,S' >>> I don't get too far (and the folder is not that extreme -- 1333 messages). Any thoughts? Matej -- Matej Cepl, http://www.ceplovi.cz/matej GPG Finger: 89EF 4BC6 288A BF43 1BAB 25C3 E09F EF25 D964 84AC 138 Highland Ave. #10, Somerville, Ma 02143, (617) 623-1488 I have never killed a man, but I have read many obituaries with great pleasure. -- Clarence Darrow From mlist-python at dideas.com Fri Oct 29 17:16:28 2004 From: mlist-python at dideas.com (Chris Barnhart) Date: Fri Oct 29 17:22:22 2004 Subject: [Tutor] HTMLParser problem unable to find all the IMG tags.... In-Reply-To: References: <6.1.2.0.0.20041028155831.03aa8150@qmail.dideas.com> Message-ID: <6.1.2.0.0.20041029105051.040d63a0@qmail.dideas.com> Danny, Thank you much for looking into this. I'll make your change to my copy of HTMLParser.py and see how it works. As for a bug report, you've traced the issue deeper and into territory that is beyond me [I started pyton 1 week ago, and don't know perl in part due to the RE stuff!] so I'd recommend that submit it. I'd just be sending them your insights if I did it myself. It would also be valuable to document that HTMLParser is sensitive to minor spec flaws. When I get the CNN grabber working I'll post it to this thread.... Thanks, Chris At 05:05 PM 10/28/2004, you wrote: >On Thu, 28 Oct 2004, Chris Barnhart wrote: > > > At 01:49 PM 10/28/2004, Lloyd Kvam wrote: > > >On Thu, 2004-10-28 at 08:34, Chris Barnhart wrote: > > > > > > > > The problem is that using the HTMLParser I'm not getting all the IMG > > > > tags. I know this as I have another program that just uses string > > > > processing that gets 2.5 times more IMG SRC tag. I also know this > because > > > > HTMLParser starttag is never called with the IMG that I'm after! > > > > > > The problem with my getting all the IMG tags from CNN is the lack of a > > space separating a close quote and start of an attribute in at least one > > their IMG SRC statements. > > > >Hi Chris, > > >Ah, that makes sense. Can you send a feature request or bug report to the >Python developers? They keep a bug list on Sourceforge: > > http://sourceforge.net/tracker/?group_id=5470 > > >I did some diving through the code. The bug appears to be that the >internal function HTMLParser.check_for_whole_start_tag() doesn't recognize >that: > > > >is a whole start tag element. > > > >I think it might have to do with HTMLParser.locatestarttagend, because the >regular expression there says: > > >### >locatestarttagend = re.compile(r""" > <[a-zA-Z][-.a-zA-Z0-9:_]* # tag name > (?:\s+ # whitespace before attribute name > (?:[a-zA-Z_][-.:a-zA-Z0-9_]* # attribute name > (?:\s*=\s* # value indicator > (?:'[^']*' # LITA-enclosed value > |\"[^\"]*\" # LIT-enclosed value > |[^'\">\s]+ # bare value > ) > )? > ) > )* > \s* # trailing whitespace >""", re.VERBOSE) >### > > >that there's a required whitespace before every attribute value. CNN's >HTML obviously doesn't have this. > > > >I wonder what happens if we relax the regular expression slightly, so that >the whitespace is optional. > >### > >>> import HTMLParser > >>> import re > >>> HTMLParser.locatestarttagend = re.compile(r""" >... <[a-zA-Z][-.a-zA-Z0-9:_]* # tag name >... (?:\s* # optional whitespace before >... # attribute name >... (?:[a-zA-Z_][-.:a-zA-Z0-9_]* # attribute name >... (?:\s*=\s* # value indicator >... (?:'[^']*' # LITA-enclosed value >... |\"[^\"]*\" # LIT-enclosed value >... |[^'\">\s]+ # bare value >... ) >... )? >... ) >... )* >... \s* # trailing whitespace >... """, re.VERBOSE) > >>> class Parser(HTMLParser.HTMLParser): >... def handle_starttag(self, tag, attrs): >... print "START", tag, attrs >... > >>> p = Parser() > >>> p.feed(' ') >START img [('src', 'abc.jpg'), ('width', '5')] >### > > >Ok, that makes the parser a little more permissive, so that it'll accept >the screwed up HTML that CNN is providing us. *grin* > > >Chris, would this work for you? Maybe we can pass this off to the Python >developers and get it into the next release. Do you want to send the bug >report to them? > > >Good luck to you! From mlist-python at dideas.com Fri Oct 29 17:21:07 2004 From: mlist-python at dideas.com (Chris Barnhart) Date: Fri Oct 29 17:22:25 2004 Subject: [Tutor] HTMLParser problem unable to find all the IMG tags.... In-Reply-To: <6.1.0.6.0.20041028160059.02ac62b8@mail4.skillsoft.com> References: <6.1.2.0.0.20041028080847.03c35ca0@10.2.0.8> <1098985771.4985.19.camel@laptop.venix.com> <6.1.2.0.0.20041028152745.03c70ca0@qmail.dideas.com> <6.1.0.6.0.20041028160059.02ac62b8@mail4.skillsoft.com> Message-ID: <6.1.2.0.0.20041029111651.040d6110@qmail.dideas.com> Kent, Another great idea - thank you. I'm going to modify my copy HTMLParser.py to use Danny Yoo's RE adjustment and see how that works. But I'll certainly keep BeautifulSoup handy too. There's a lot of broken HTML out there - so I'm sure it'll come in handy. Chris At 04:01 PM 10/28/2004, you wrote: >You might want to take a look at BeautifulSoup, it is designed to pull >data from (possibly) badly-formed web pages. >http://www.crummy.com/software/BeautifulSoup/ > >Kent From John.Gooch at echostar.com Fri Oct 29 17:39:46 2004 From: John.Gooch at echostar.com (Gooch, John) Date: Fri Oct 29 17:40:03 2004 Subject: [Tutor] Multithreading and COM Objects Message-ID: <15A1FDA26DAD524DA7A7AF77313EBA8F07BC00D2@riv-excha5.echostar.com> Here is some info and a question. First the information: What I discovered recently discovered was that to access MS Windows COM objects from within threads, I had to import the pythoncom module, and then called 'pythoncom.CoInitialize()' at the beginning of each thread. It works like a charm, whereas before each thread would spit out cryptic errors that basically said "Connection failed" when doing a 'GetObject' call to get a COM object. Now the question: I am always concerned with performance and resources. I see I am getting a reference to a COM object now, and I am wondering if I need to do an resource cleanup in each thread after it is done with the COM object(s). The two situations that apply to my current project are the 'GetObject' reference, and the 'win32api.RegConnectRegistry' reference. John A. Gooch Systems Administrator IT - Tools EchoStar Satellite L.L.C. 9601 S. Meridian Blvd. Englewood, CO 80112 Desk: 720-514-5708 From RenX99 at gmail.com Fri Oct 29 17:58:52 2004 From: RenX99 at gmail.com (Rene Lopez) Date: Fri Oct 29 17:58:55 2004 Subject: [Tutor] python cgi question... Message-ID: <555128ce04102908582e752221@mail.gmail.com> I have a form that has two sets of radio buttons on it... and i want to certain radio buttons in the second set inactive, or not available depending on what the user selects from the first set... I suspect this is something that I could do with some sort of javascript, but i don't know any javascript.... anyone know how to do this or can you point me to a decent tutorial? I -- Rene From flaxeater at yahoo.com Fri Oct 29 18:14:01 2004 From: flaxeater at yahoo.com (Chad Crabtree) Date: Fri Oct 29 18:14:04 2004 Subject: [Tutor] Too many open files -- how to copy a folder? Message-ID: <20041029161402.41611.qmail@web54305.mail.yahoo.com> Matej Cepl wrote: >>>>import email,email.Utils >>>>import mailbox >>>>box = mailbox.Maildir("/home/matej/WP/trash/") >>>>date = email.Utils.parsedate_tz >>>>import time >>>>dlist = list(time.localtime()) >>>>dlist[1] -= 3 >>>>archdate = tuple(dlist) >>>>alist = [x for x in box if date(x['date'])>>> >>>> >Traceback (most recent call last): > File "", line 1, in ? > File "/usr/lib/python2.3/mailbox.py", line 246, in next >IOError: [Errno 24] Too many open files: >'/home/matej/WP/trash/cur/1098844013.6284.XKuCF:2,S' > > Perhaps instead of using a list comprehension you should use a generator, if you wnat a generator expression then you need to upgrade to 2.4 however let's try and get the jist of this def genBox(box): for x in box: if date(x['date']) I have a form that has two sets of radio buttons on it... and i want to certain radio buttons in the second set inactive, or not available depending on what the user selects from the first set... I suspect this is something that I could do with some sort of javascript, but i don't know any javascript.... anyone know how to do this or can you point me to a decent tutorial? -- Rene P.S. any one else seeing issues sending mail to the list? I got a message returned earlier. From bill at celestial.net Fri Oct 29 18:56:50 2004 From: bill at celestial.net (Bill Campbell) Date: Fri Oct 29 18:56:54 2004 Subject: [Tutor] Too many open files -- how to copy a folder? In-Reply-To: <1286346.t315YGR7Yt@blahoslav.ceplovi.cz> References: <1286346.t315YGR7Yt@blahoslav.ceplovi.cz> Message-ID: <20041029165650.GA58101@alexis.mi.celestial.com> On Thu, Oct 28, 2004, Matej Cepl wrote: >Hi, > >I've tried this: > >blahoslav:matej$ python >Python 2.3.4 (#2, Sep 24 2004, 08:39:09) >[GCC 3.3.4 (Debian 1:3.3.4-12)] on linux2 >Type "help", "copyright", "credits" or "license" for more information. >>>> import mailbox >>>> box = mailbox.Maildir("/home/matej/WP/trash/") >>>> another = [x for x in box] >Traceback (most recent call last): > File "", line 1, in ? > File "/usr/lib/python2.3/mailbox.py", line 246, in next >IOError: [Errno 24] Too many open files: >'/home/matej/WP/trash/cur/1098844013.6284.XKuCF:2,S' > >Can be done something about that? Of course, that I will use some filter in >the mapping, but still even when I try It would be far easier to look at the file names individually rather than trying to suck them in like this, particularly since maildir file names have the Unix date as the first part of the file name. I would probably do it something like this: import getdate # date parsing routines import os cutoffdate = getdate('10/1/2003') mdir = os.path.join(os.environ['HOME'], '/Maildir') fh = os.popen('find %s -type f') # let find do the work for you for file in fx.xreadlines(): file = file.[:-1] # strip newline ftime, seq, host = file.split('.') # split name into parts if ftime < cutoffdate: # do something for old files else: # do somehthing else on newer files Bill -- INTERNET: bill@Celestial.COM Bill Campbell; Celestial Software LLC UUCP: camco!bill PO Box 820; 6641 E. Mercer Way FAX: (206) 232-9186 Mercer Island, WA 98040-0820; (206) 236-1676 URL: http://www.celestial.com/ ``A human being should be able to change a diaper, plan an invasion, butcher a hog, conn a ship, design a building, write a sonnet, balance accounts, build a wall, set a bone, comfort the dying, take orders, give orders, cooperate, act alone, solve equations, analyze a new problem, pitch manure, program a computer, cook a tasty meal, fight efficiently, die gallantly. Specialization is for insects.'' Robert Heinlein From kent_johnson at skillsoft.com Fri Oct 29 18:56:19 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Fri Oct 29 18:58:30 2004 Subject: [Tutor] Too many open files -- how to copy a folder? In-Reply-To: <1286346.t315YGR7Yt@blahoslav.ceplovi.cz> References: <1286346.t315YGR7Yt@blahoslav.ceplovi.cz> Message-ID: <6.1.0.6.0.20041029125032.02927e60@mail4.skillsoft.com> another = [x for x in box] This creates a list of all the messages in box. Apparently each message wraps an open file, that is why you are getting the IOError. My guess is that somewhere later in your program you say for msg in another: # do something with msg If I am right, you can rewrite your program to iterate directly over the mailbox, like this: for msg in box: # do something with msg This form avoids creating a list with all the messages in it. Only one message is active at a time and you will avoid the IOError. Kent At 06:55 PM 10/28/2004 -0400, Matej Cepl wrote: >Hi, > >I've tried this: > >blahoslav:matej$ python >Python 2.3.4 (#2, Sep 24 2004, 08:39:09) >[GCC 3.3.4 (Debian 1:3.3.4-12)] on linux2 >Type "help", "copyright", "credits" or "license" for more information. > >>> import mailbox > >>> box = mailbox.Maildir("/home/matej/WP/trash/") > >>> another = [x for x in box] >Traceback (most recent call last): > File "", line 1, in ? > File "/usr/lib/python2.3/mailbox.py", line 246, in next >IOError: [Errno 24] Too many open files: >'/home/matej/WP/trash/cur/1098844013.6284.XKuCF:2,S' > >Can be done something about that? Of course, that I will use some filter in >the mapping, but still even when I try > > >>> import email,email.Utils > >>> import mailbox > >>> box = mailbox.Maildir("/home/matej/WP/trash/") > >>> date = email.Utils.parsedate_tz > >>> import time > >>> dlist = list(time.localtime()) > >>> dlist[1] -= 3 > >>> archdate = tuple(dlist) > >>> alist = [x for x in box if date(x['date'])Traceback (most recent call last): > File "", line 1, in ? > File "/usr/lib/python2.3/mailbox.py", line 246, in next >IOError: [Errno 24] Too many open files: >'/home/matej/WP/trash/cur/1098844013.6284.XKuCF:2,S' > >>> > >I don't get too far (and the folder is not that extreme -- 1333 messages). >Any thoughts? > >Matej > > >-- >Matej Cepl, http://www.ceplovi.cz/matej >GPG Finger: 89EF 4BC6 288A BF43 1BAB 25C3 E09F EF25 D964 84AC >138 Highland Ave. #10, Somerville, Ma 02143, (617) 623-1488 > >I have never killed a man, but I have read many obituaries with >great pleasure. > -- Clarence Darrow > > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From cepl at surfbest.net Fri Oct 29 19:17:43 2004 From: cepl at surfbest.net (Matej Cepl) Date: Fri Oct 29 19:19:10 2004 Subject: [Tutor] Re: Too many open files -- how to copy a folder? References: <20041029161402.41611.qmail@web54305.mail.yahoo.com> Message-ID: <1331470.RN7079mQKC@blahoslav.ceplovi.cz> Chad Crabtree wrote: > def genBox(box): > for x in box: > if date(x['date']) yield x > > I have not tested this but I think this would call only one file at a > time. I gave up on doing it directly and rather load whole mailbox into memory, done all manipulation in lists, and then fixed the maildir directory (see attached example). It is not much tested, but I would really welcome any comments on it (obviously, I would rather not screw up my mails). Thanks for the suggestion though, Matej -- Matej Cepl, http://www.ceplovi.cz/matej GPG Finger: 89EF 4BC6 288A BF43 1BAB 25C3 E09F EF25 D964 84AC 138 Highland Ave. #10, Somerville, Ma 02143, (617) 623-1488 His mother should have thrown him away and kept the stork. -- Mae West -------------- next part -------------- A non-text attachment was scrubbed... Name: archive-folder.py Type: application/x-python Size: 2889 bytes Desc: Object for archiving Maildir folder into mbox archive Url : http://mail.python.org/pipermail/tutor/attachments/20041029/34732034/archive-folder.bin From glingl at aon.at Fri Oct 29 20:27:11 2004 From: glingl at aon.at (Gregor Lingl) Date: Fri Oct 29 20:26:54 2004 Subject: [Tutor] How to calculate pi with another formula? In-Reply-To: <6.1.2.0.2.20041028093827.06b2ac00@rcblue.com> References: <6.1.2.0.2.20041028093827.06b2ac00@rcblue.com> Message-ID: <41828B7F.1060608@aon.at> Hi Dick! Accidentally I just was tinkering around with the new decimal module of Python2.4. (By the way: it also works with Python 2.3 - just copy it into /Python23/Lib) The attached program uses a very elementary (and inefficient) formula to calculate pi, namely as the area of a 6*2**n-sided polygon (starting with n=0), inscribed into a circle of radius 1. (Going back to Archimedes, if I'm right ...) Nevertheless it calculates pi with a precision of (nearly) 100 digits, and the precision can be arbitrarily enlarged. In the output of this program only the last digit is not correct. import decimal decimal.getcontext().prec = 100 def calcpi(): s = decimal.Decimal(1) h = decimal.Decimal(3).sqrt()/2 n = 6 for i in range(170): A = n*h*s/2 # A ... area of polygon print i,":",A s2 = ((1-h)**2+s**2/4) s = s2.sqrt() h = (1-s2/4).sqrt() n = 2*n calcpi() Just for fun ... Gregor Dick Moores schrieb: > Is it possible to calculate almost-pi/2 using the (24) formula on > without using (23)? > > If it's possible, how about a hint? Recursion? > > Thanks, tutors. > > Dick Moores > rdm@rcblue.com > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From RenX99 at gmail.com Fri Oct 29 20:40:18 2004 From: RenX99 at gmail.com (Rene Lopez) Date: Fri Oct 29 20:40:38 2004 Subject: [Tutor] Jython clarification... Message-ID: <555128ce0410291140ccf61ce@mail.gmail.com> Does Jython allow you to create an applet that you can run in a browser? I'm kind of confused about this, or how to do this, or if it's even possible. -- Rene From kent_johnson at skillsoft.com Fri Oct 29 21:14:21 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Fri Oct 29 21:16:34 2004 Subject: [Tutor] Jython clarification... In-Reply-To: <555128ce0410291140ccf61ce@mail.gmail.com> References: <555128ce0410291140ccf61ce@mail.gmail.com> Message-ID: <6.1.0.6.0.20041029151113.02b09bb0@mail4.skillsoft.com> Yes, you can. See here for demos: http://www.jython.org/applets/index.html You have to compile your applet to a .class file using jythonc. Some more info here: http://www.jython.org/docs/jythonc.html If you have trouble with this you might do better on the jython-users list. (I have never done this myself so I won't be able to give much more help than this.) Kent At 02:40 PM 10/29/2004 -0400, Rene Lopez wrote: >Does Jython allow you to create an applet that you can run in a >browser? I'm kind of confused about this, or how to do this, or if >it's even possible. > >-- > >Rene >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From barry at angleinc.com Fri Oct 29 21:37:16 2004 From: barry at angleinc.com (Barry Sperling) Date: Fri Oct 29 21:37:35 2004 Subject: [Tutor] How to calculate pi with another formula? In-Reply-To: <41828B7F.1060608@aon.at> References: <6.1.2.0.2.20041028093827.06b2ac00@rcblue.com> <41828B7F.1060608@aon.at> Message-ID: <41829BEC.6000105@angleinc.com> Thanks, Gregor! As a newby I didn't know about such improvements, so I did what you suggested and added decimal.py to my lib directory in 2.3 and it worked. Below is the code for the iterative answer ( different from the recursive one that Bill Mill gave ) that I suggested to Dick, originally as a text hint, but now using the decimal module: import decimal decimal.getcontext().prec = 40 # ARBITRARY UPPER LIMIT TO PRECISION # ITERATIVE METHOD, USING THE NUMERATOR AS A COMPARISON numer = decimal.Decimal(100) # ARBITRARY UPPER LIMIT TO NUMERATOR subtotal = decimal.Decimal(1) # INITIALIZE Last_Numerator = decimal.Decimal(1) # COUNTING DOWN WE'LL STOP AT 1 Subtraction_Amount = decimal.Decimal(1) # COUNTING DOWN BY 1s Pi_Correction = decimal.Decimal(2) # SINCE THE PRIOR CALC GIVES PI/2 while numer >= Last_Numerator: denom = 2 * numer + 1 #THE FORMULA DERIVING EACH DENOM FROM EACH NUMER subtotal = 1 + numer / denom * subtotal numer -= Subtraction_Amount # WORKING FROM INSIDE-OUT print Pi_Correction * subtotal Barry Gregor Lingl wrote: > Hi Dick! > > Accidentally I just was tinkering around with the new > decimal module of Python2.4. (By the way: it also works > with Python 2.3 - just copy it into /Python23/Lib) > Dick Moores schrieb: > >> Is it possible to calculate almost-pi/2 using the (24) formula on >> without using (23)? >> >> Dick Moores >> rdm@rcblue.com From ps_python at yahoo.com Fri Oct 29 22:14:09 2004 From: ps_python at yahoo.com (kumar s) Date: Fri Oct 29 22:14:13 2004 Subject: [Tutor] GXL in Python Message-ID: <20041029201409.35070.qmail@web53704.mail.yahoo.com> Dear group, I have set of XML documents and I want to convert them into GXL format (Graph eXchange Language). Is there any module for GXL. Thanks kumar. __________________________________ Do you Yahoo!? Yahoo! Mail Address AutoComplete - You start. We finish. http://promotions.yahoo.com/new_mail From isrgish at fastem.com Fri Oct 29 22:54:01 2004 From: isrgish at fastem.com (Isr Gish) Date: Fri Oct 29 22:54:20 2004 Subject: [Tutor] How to calculate pi with another formula? Message-ID: <20041029205417.F1E931E4003@bag.python.org> How can I get the Decimal module without downloading the whole install for Python 2.4 All the best, Isr -----Original Message----- >From: "Gregor Lingl" >Sent: 10/29/04 2:27:11 PM >To: "Dick Moores" >Cc: "tutor@python.org" >Subject: Re: [Tutor] How to calculate pi with another formula? >Hi Dick! > >Accidentally I just was tinkering around with the new >decimal module of Python2.4. (By the way: it also works >with Python 2.3 - just copy it into /Python23/Lib) > >The attached program uses a very elementary (and inefficient) >formula to calculate pi, namely as the area of a 6*2**n-sided >polygon (starting with n=0), inscribed into a circle of radius 1. >(Going back to Archimedes, if I'm right ...) > >Nevertheless it calculates pi with a precision of (nearly) >100 digits, and the precision can be arbitrarily enlarged. >In the output of this program only the last digit is not correct. > >import decimal > >decimal.getcontext().prec = 100 > >def calcpi(): > s = decimal.Decimal(1) > h = decimal.Decimal(3).sqrt()/2 > n = 6 > for i in range(170): > A = n*h*s/2 # A ... area of polygon > print i,":",A > s2 = ((1-h)**2+s**2/4) > s = s2.sqrt() > h = (1-s2/4).sqrt() > n = 2*n > >calcpi() > >Just for fun ... > >Gregor > > >Dick Moores schrieb: > >> Is it possible to calculate almost-pi/2 using the (24) formula on >> without using (23)? >> >> If it's possible, how about a hint? Recursion? >> >> Thanks, tutors. >> >> Dick Moores >> rdm@rcblue.com >> >> _______________________________________________ >> Tutor maillist - Tutor@python.org >> http://mail.python.org/mailman/listinfo/tutor >> >> >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > From cajuntechie at gmail.com Sat Oct 30 00:35:21 2004 From: cajuntechie at gmail.com (Anthony P.) Date: Sat Oct 30 00:35:34 2004 Subject: [Tutor] Python on handhelds Message-ID: Hello Everyone, I've been asked to develop a simple application that will run on the Dell Axiom handheld computer. Does anyone know how to get Python to run on this little device? Thanks, Anthony From kent_johnson at skillsoft.com Sat Oct 30 03:04:12 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Sat Oct 30 03:04:20 2004 Subject: [Tutor] How to calculate pi with another formula? In-Reply-To: <20041029205417.F1E931E4003@bag.python.org> References: <20041029205417.F1E931E4003@bag.python.org> Message-ID: <6.1.0.6.0.20041029210115.02a77298@mail4.skillsoft.com> Download the reference implementation from the PEP: http://www.python.org/peps/pep-0327.html#reference-implementation PEPs are Python Enhancement Proposals. Any change to the Python language or the standard libraries is written up as a PEP. Library changes often have reference implementations so people can try them out. Kent At 04:54 PM 10/29/2004 -0400, Isr Gish wrote: >How can I get the Decimal module without downloading the whole install for >Python 2.4 > >All the best, >Isr > > >-----Original Message----- > >From: "Gregor Lingl" > >Sent: 10/29/04 2:27:11 PM > >To: "Dick Moores" > >Cc: "tutor@python.org" > >Subject: Re: [Tutor] How to calculate pi with another formula? > >Hi Dick! > > > >Accidentally I just was tinkering around with the new > >decimal module of Python2.4. (By the way: it also works > >with Python 2.3 - just copy it into /Python23/Lib) > > > >The attached program uses a very elementary (and inefficient) > >formula to calculate pi, namely as the area of a 6*2**n-sided > >polygon (starting with n=0), inscribed into a circle of radius 1. > >(Going back to Archimedes, if I'm right ...) > > > >Nevertheless it calculates pi with a precision of (nearly) > >100 digits, and the precision can be arbitrarily enlarged. > >In the output of this program only the last digit is not correct. > > > >import decimal > > > >decimal.getcontext().prec = 100 > > > >def calcpi(): > > s = decimal.Decimal(1) > > h = decimal.Decimal(3).sqrt()/2 > > n = 6 > > for i in range(170): > > A = n*h*s/2 # A ... area of polygon > > print i,":",A > > s2 = ((1-h)**2+s**2/4) > > s = s2.sqrt() > > h = (1-s2/4).sqrt() > > n = 2*n > > > >calcpi() > > > >Just for fun ... > > > >Gregor > > > > > >Dick Moores schrieb: > > > >> Is it possible to calculate almost-pi/2 using the (24) formula on > >> without using (23)? > >> > >> If it's possible, how about a hint? Recursion? > >> > >> Thanks, tutors. > >> > >> Dick Moores > >> rdm@rcblue.com > >> > >> _______________________________________________ > >> Tutor maillist - Tutor@python.org > >> http://mail.python.org/mailman/listinfo/tutor > >> > >> > >_______________________________________________ > >Tutor maillist - Tutor@python.org > >http://mail.python.org/mailman/listinfo/tutor > > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From lysdexia at crackrabbit.com Sat Oct 30 04:45:27 2004 From: lysdexia at crackrabbit.com (Douglas N. Shawhan) Date: Sat Oct 30 04:46:47 2004 Subject: [Tutor] Splitting at a capital letter in a string In-Reply-To: <6.1.0.6.0.20041027104356.02abd118@mail4.skillsoft.com> References: <417FB05E.1@cso.atmel.com> <6.1.0.6.0.20041027104356.02abd118@mail4.skillsoft.com> Message-ID: <41830047.10005@crackrabbit.com> Is there a way to use the string module to split a string at a capital, so that: HiImAStringWithCaps is rendered Hi Im A String With Caps I looked at the re module, and it looks as if it could be used for such shenannigans... From bill at celestial.net Sat Oct 30 05:14:35 2004 From: bill at celestial.net (Bill Campbell) Date: Sat Oct 30 05:14:39 2004 Subject: [Tutor] Splitting at a capital letter in a string In-Reply-To: <41830047.10005@crackrabbit.com> References: <417FB05E.1@cso.atmel.com> <6.1.0.6.0.20041027104356.02abd118@mail4.skillsoft.com> <41830047.10005@crackrabbit.com> Message-ID: <20041030031435.GA91513@alexis.mi.celestial.com> On Fri, Oct 29, 2004, Douglas N. Shawhan wrote: >Is there a way to use the string module to split a string at a capital, >so that: > >HiImAStringWithCaps > >is rendered > >Hi Im A String With Caps > >I looked at the re module, and it looks as if it could be used for such >shenannigans... One way to do this would be: import re pat = re.compile('([A-Z])') s = pat.sub(r' \1', 'HiImAStringWithCaps').strip() The strip call gets rid of the first blank inserted. Bill -- INTERNET: bill@Celestial.COM Bill Campbell; Celestial Systems, Inc. UUCP: camco!bill PO Box 820; 6641 E. Mercer Way FAX: (206) 232-9186 Mercer Island, WA 98040-0820; (206) 236-1676 URL: http://www.celestial.com/ Democracy must be sometihng more than two wolves and a sheep voting on what to have for dinner -- James Bovard From lysdexia at crackrabbit.com Sat Oct 30 05:26:06 2004 From: lysdexia at crackrabbit.com (Douglas N. Shawhan) Date: Sat Oct 30 05:27:25 2004 Subject: [Tutor] Splitting at a capital letter in a string In-Reply-To: <20041030031435.GA91513@alexis.mi.celestial.com> References: <417FB05E.1@cso.atmel.com> <6.1.0.6.0.20041027104356.02abd118@mail4.skillsoft.com> <41830047.10005@crackrabbit.com> <20041030031435.GA91513@alexis.mi.celestial.com> Message-ID: <418309CE.90003@crackrabbit.com> Yep. re looks like the only way. I was just wondering if I was missing something in String. Thanks! That's what I'll work with! Bill Campbell wrote: >On Fri, Oct 29, 2004, Douglas N. Shawhan wrote: > > >>Is there a way to use the string module to split a string at a capital, >>so that: >> >>HiImAStringWithCaps >> >>is rendered >> >>Hi Im A String With Caps >> >>I looked at the re module, and it looks as if it could be used for such >>shenannigans... >> >> > >One way to do this would be: > >import re >pat = re.compile('([A-Z])') >s = pat.sub(r' \1', 'HiImAStringWithCaps').strip() > >The strip call gets rid of the first blank inserted. > >Bill >-- >INTERNET: bill@Celestial.COM Bill Campbell; Celestial Systems, Inc. >UUCP: camco!bill PO Box 820; 6641 E. Mercer Way >FAX: (206) 232-9186 Mercer Island, WA 98040-0820; (206) 236-1676 >URL: http://www.celestial.com/ > >Democracy must be sometihng more than two wolves and a sheep voting on what >to have for dinner -- James Bovard >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > From rex at biz-experts.net Sat Oct 30 05:38:04 2004 From: rex at biz-experts.net (Rex) Date: Sat Oct 30 05:38:15 2004 Subject: [Tutor] python cgi question... In-Reply-To: <555128ce04102908582e752221@mail.gmail.com> Message-ID: Rene, Try Thau's JavaScript Tutorial on webmonkey.com. It was my first try at javascript and it really helped me get started. Has nice on-line working examples. Lesson 5 has what you're looking for. http://webmonkey.wired.com/webmonkey/programming/javascript/tutorials/tutori al1.html and the advanced one on: http://webmonkey.wired.com/webmonkey/programming/javascript/tutorials/tutori al2.html Good luck Rex -----Original Message----- From: tutor-bounces@python.org [mailto:tutor-bounces@python.org]On Behalf Of Rene Lopez Sent: Friday, October 29, 2004 10:59 AM To: Python Tutor Subject: [Tutor] python cgi question... I have a form that has two sets of radio buttons on it... and i want to certain radio buttons in the second set inactive, or not available depending on what the user selects from the first set... I suspect this is something that I could do with some sort of javascript, but i don't know any javascript.... anyone know how to do this or can you point me to a decent tutorial? I -- Rene _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From bill at celestial.net Sat Oct 30 07:36:32 2004 From: bill at celestial.net (Bill Campbell) Date: Sat Oct 30 07:36:36 2004 Subject: [Tutor] Splitting at a capital letter in a string In-Reply-To: <418309CE.90003@crackrabbit.com> References: <417FB05E.1@cso.atmel.com> <6.1.0.6.0.20041027104356.02abd118@mail4.skillsoft.com> <41830047.10005@crackrabbit.com> <20041030031435.GA91513@alexis.mi.celestial.com> <418309CE.90003@crackrabbit.com> Message-ID: <20041030053632.GA98402@alexis.mi.celestial.com> On Fri, Oct 29, 2004, Douglas N. Shawhan wrote: >Yep. re looks like the only way. I was just wondering if I was missing >something in String. > >Thanks! That's what I'll work with! Glad to help. I'm very much a python newbie after doing perl for over 15 years. Having python doing perl-style regular expressions is very helpful to me. >Bill Campbell wrote: > >>On Fri, Oct 29, 2004, Douglas N. Shawhan wrote: >> >> >>>Is there a way to use the string module to split a string at a capital, >>>so that: >>> >>>HiImAStringWithCaps >>> >>>is rendered >>> >>>Hi Im A String With Caps >>> >>>I looked at the re module, and it looks as if it could be used for such >>>shenannigans... >>> >>> >> >>One way to do this would be: >> >>import re >>pat = re.compile('([A-Z])') >>s = pat.sub(r' \1', 'HiImAStringWithCaps').strip() >> >>The strip call gets rid of the first blank inserted. >> >>Bill >>-- >>INTERNET: bill@Celestial.COM Bill Campbell; Celestial Systems, Inc. >>UUCP: camco!bill PO Box 820; 6641 E. Mercer Way >>FAX: (206) 232-9186 Mercer Island, WA 98040-0820; (206) >>236-1676 >>URL: http://www.celestial.com/ >> >>Democracy must be sometihng more than two wolves and a sheep voting on what >>to have for dinner -- James Bovard >>_______________________________________________ >>Tutor maillist - Tutor@python.org >>http://mail.python.org/mailman/listinfo/tutor >> >> >> > -- Bill -- INTERNET: bill@Celestial.COM Bill Campbell; Celestial Software LLC UUCP: camco!bill PO Box 820; 6641 E. Mercer Way FAX: (206) 232-9186 Mercer Island, WA 98040-0820; (206) 236-1676 URL: http://www.celestial.com/ ``Nobody wants to be called common people, especially common people.'' Will Rogers From bob at nc.rr.com Sat Oct 30 14:25:41 2004 From: bob at nc.rr.com (bob@nc.rr.com) Date: Sat Oct 30 14:25:47 2004 Subject: [Tutor] Interactive only syntaxerror? Message-ID: Given the following file - test.py: ---------------------------------- if 1: print "True" print "Done" ---------------------------------- Invoking python at the command prompt works, as expected: ---------------------------------- C:\Python>python test.py True Done C:\Python>python python Python 2.3.4 (#53, May 25 2004, 21:17:02) [MSC v.1200 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> if 1: ... print "True" ... print "Done" File "", line 3 print "Done" ^ SyntaxError: invalid syntax >>> ---------------------------------- Thanks Bob From bgailer at alum.rpi.edu Sat Oct 30 15:09:47 2004 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Sat Oct 30 15:10:19 2004 Subject: [Tutor] Interactive only syntaxerror? In-Reply-To: References: Message-ID: <6.1.2.0.0.20041030070636.027e1b48@mail.mric.net> At 06:25 AM 10/30/2004, bob@nc.rr.com wrote: >Given the following file - test.py: >---------------------------------- >if 1: > print "True" >print "Done" >---------------------------------- >Invoking python at the command prompt works, as expected: >---------------------------------- >C:\Python>python test.py >True >Done > >C:\Python>python True >Done >---------------------------------- >Why does this fail with a SyntaxError? >---------------------------------- >C:\Python>python >Python 2.3.4 (#53, May 25 2004, 21:17:02) [MSC v.1200 32 bit (Intel)] on win32 >Type "help", "copyright", "credits" or "license" for more information. > >>> if 1: >... print "True" >... print "Done" > File "", line 3 > print "Done" > ^ >SyntaxError: invalid syntax The ... prompt is asking for an indented line of code as part of the if block Hit enter at the 2nd ... to end the if block (which will then execute) and enter print "Done" at the following >>> Should look like: >>> if 1: ... print "True" ... True >>> print "Done" Done Bob Gailer bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell From orbitz at ezabel.com Sat Oct 30 16:43:49 2004 From: orbitz at ezabel.com (orbitz) Date: Sat Oct 30 16:43:58 2004 Subject: [Tutor] Interactive only syntaxerror? In-Reply-To: References: Message-ID: <4183A8A5.2070208@ezabel.com> you have to hit enter again to let the interactive interpreter know you are done with that scope, that is why there are ... You want >>> bob@nc.rr.com wrote: >Given the following file - test.py: >---------------------------------- >if 1: > print "True" >print "Done" >---------------------------------- >Invoking python at the command prompt works, as expected: >---------------------------------- >C:\Python>python test.py >True >Done > >C:\Python>python True >Done >---------------------------------- >Why does this fail with a SyntaxError? >---------------------------------- >C:\Python>python >Python 2.3.4 (#53, May 25 2004, 21:17:02) [MSC v.1200 32 bit (Intel)] on win32 >Type "help", "copyright", "credits" or "license" for more information. > > >>>>if 1: >>>> >>>> >... print "True" >... print "Done" > File "", line 3 > print "Done" > ^ >SyntaxError: invalid syntax > > >---------------------------------- >Thanks >Bob > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > From RenX99 at gmail.com Sat Oct 30 18:05:36 2004 From: RenX99 at gmail.com (Rene Lopez) Date: Sat Oct 30 18:05:51 2004 Subject: [Tutor] Cookie not reading first time through... Message-ID: <555128ce04103009057466ef3c@mail.gmail.com> I'm trying to learn how to use python for cgi scripts... I created a form that submits some info that I put in a cookie. Then the script calls itself and reads the cookie, and displays a different form to get more information. The problem I'm running into is the script is setting the cookie... but it doesn't read it the first time through for some reason, if I immediately try it again it works fine. So for some reason it's not picking up the cookie the first time. Would it be a better idea to break the script into two different scripts to accomplish this? Any advise would be appreciated, please be gentle, I'm still a newbie ;-) here is the script: #!/usr/bin/python import cgi,os,Cookie import cgitb; cgitb.enable() def name_race(): print "Content-Type: text/html\n\n" print "" print "" print "" print "
      " print "" print "" print "
      Name:
      " print "

      " print "" print "" print "" print "" print "" print "" print "" print "
      Race:
      Human
      Elf
      " print "

      " print "" print "" def pick_class(): mycookie = Cookie.SmartCookie(os.environ.get("HTTP_COOKIE", "")) race = mycookie["race"].value name = mycookie["name"].value print "Content-Type: text/html\n\n" print "" print "" print name print race print "\n" def print_sheet(): pass def main(): form = cgi.FieldStorage() mycookie = Cookie.SmartCookie() if form.has_key("name") and form.has_key("race"): if (form["action"].value == "getclass"): mycookie["name"] = form["name"].value mycookie["name"]["max-age"] = 60 mycookie["race"] = form["race"].value mycookie["race"]["max-age"] = 60 print mycookie pick_class() else: name_race() main() -- Rene From RenX99 at gmail.com Sat Oct 30 18:13:22 2004 From: RenX99 at gmail.com (Rene Lopez) Date: Sat Oct 30 18:13:28 2004 Subject: [Tutor] Python on handhelds In-Reply-To: References: Message-ID: <555128ce041030091377852178@mail.gmail.com> I believe that the Axiom is a pocket pc PDA.... if so you might want to take a look at: http://www.murkworks.com/Research/Python/PocketPCPython/Overview that's a port of python for the pocket pc supporting python 2.2 I haven't personally tried it, so YMMV. Rene On Fri, 29 Oct 2004 17:35:21 -0500, Anthony P. wrote: > Hello Everyone, > > I've been asked to develop a simple application that will run on the > Dell Axiom handheld computer. Does anyone know how to get Python to > run on this little device? > > Thanks, > Anthony > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- Rene From kent_johnson at skillsoft.com Sat Oct 30 18:14:32 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Sat Oct 30 18:14:38 2004 Subject: [Tutor] Splitting at a capital letter in a string In-Reply-To: <20041030031435.GA91513@alexis.mi.celestial.com> References: <417FB05E.1@cso.atmel.com> <6.1.0.6.0.20041027104356.02abd118@mail4.skillsoft.com> <41830047.10005@crackrabbit.com> <20041030031435.GA91513@alexis.mi.celestial.com> Message-ID: <6.1.0.6.0.20041030121138.02923898@mail4.skillsoft.com> You can use a "positive lookbehind assertion" to avoid matching the first letter of the string. This says, match any capital letter that is preceded by any character: >>> import re >>> s='HiImAStringWithCaps' >>> re.sub(r'(?<=.)([A-Z])', r' \1', s) 'Hi Im A String With Caps' If you really want to split the string, use re.findall: >>> re.findall('[A-Z][^A-Z]*', s) ['Hi', 'Im', 'A', 'String', 'With', 'Caps'] Kent At 08:14 PM 10/29/2004 -0700, Bill Campbell wrote: >On Fri, Oct 29, 2004, Douglas N. Shawhan wrote: > >Is there a way to use the string module to split a string at a capital, > >so that: > > > >HiImAStringWithCaps > > > >is rendered > > > >Hi Im A String With Caps > > > >I looked at the re module, and it looks as if it could be used for such > >shenannigans... > >One way to do this would be: > >import re >pat = re.compile('([A-Z])') >s = pat.sub(r' \1', 'HiImAStringWithCaps').strip() > >The strip call gets rid of the first blank inserted. > >Bill >-- >INTERNET: bill@Celestial.COM Bill Campbell; Celestial Systems, Inc. >UUCP: camco!bill PO Box 820; 6641 E. Mercer Way >FAX: (206) 232-9186 Mercer Island, WA 98040-0820; (206) 236-1676 >URL: http://www.celestial.com/ > >Democracy must be sometihng more than two wolves and a sheep voting on what >to have for dinner -- James Bovard >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From RenX99 at gmail.com Sat Oct 30 18:21:09 2004 From: RenX99 at gmail.com (Rene Lopez) Date: Sat Oct 30 18:21:17 2004 Subject: [Tutor] programming theology questions Message-ID: <555128ce04103009214f4a0993@mail.gmail.com> How many programming languages can safely fit in your head before you get confused, or think it's not worth it? :-) Is there any programming language blasphemy? Like learning C++ and then VB? Is that a sin or a exercise in insanity? Just curious as to what languages you keep in your mental toolboxes :) -- Rene From bgailer at alum.rpi.edu Sat Oct 30 18:52:28 2004 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Sat Oct 30 19:14:32 2004 Subject: [Tutor] programming theology questions In-Reply-To: <555128ce04103009214f4a0993@mail.gmail.com> References: <555128ce04103009214f4a0993@mail.gmail.com> Message-ID: <6.1.2.0.0.20041030103843.04976cd8@mail.mric.net> At 10:21 AM 10/30/2004, Rene Lopez wrote: >How many programming languages can safely fit in your head before you >get confused, or think it's not worth it? :-) My history: machine language (IBM 650, 370) assembler (650, GE415, Singer10, IBM370) APL, APL2, Basic, Focal, Fortran, Pascal, PLAS, PLX, PL/I, C and C++, dBase-VisualFoxPro, Python, CMS Exec & Exec2, REXX, Advanced Revelation R-Basic, Clarion, all versions of MS Word and Excel macro languages, Access. I started learning J but got lost.... I've studied but not used ADA, Modula II, Snobol, Cobol, Algol. Rarely have I been confused. It may take a bit to return to one I haven't used for a while. I have also developed my own languages and tools for manipulating languages. >Is there any programming language blasphemy? Like learning C++ and >then VB? Is that a sin or a exercise in insanity? Ease in writing and reading is high on my list. Hence I have most enjoyed APL and Python. I'm still wishing for ways to incorporate some of APL into Python. As my buddy says "what is the constraint on you project that keeps you from using Python?" Bob Gailer bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell From pythonTutor at venix.com Sat Oct 30 21:00:27 2004 From: pythonTutor at venix.com (Lloyd Kvam) Date: Sat Oct 30 21:00:49 2004 Subject: [Tutor] programming theology questions In-Reply-To: <6.1.2.0.0.20041030103843.04976cd8@mail.mric.net> References: <555128ce04103009214f4a0993@mail.gmail.com> <6.1.2.0.0.20041030103843.04976cd8@mail.mric.net> Message-ID: <1099162827.7237.18.camel@laptop.venix.com> On Sat, 2004-10-30 at 12:52, Bob Gailer wrote: > At 10:21 AM 10/30/2004, Rene Lopez wrote: > >How many programming languages can safely fit in your head before you > >get confused, or think it's not worth it? :-) > > My history: machine language (IBM 650, 370) assembler (650, GE415, > Singer10, IBM370) APL, APL2, Basic, Focal, Fortran, Pascal, PLAS, PLX, > PL/I, C and C++, dBase-VisualFoxPro, Python, CMS Exec & Exec2, REXX, > Advanced Revelation R-Basic, Clarion, all versions of MS Word and Excel > macro languages, Access. I started learning J but got lost.... I've studied > but not used ADA, Modula II, Snobol, Cobol, Algol. How did you avoid Java and Perl?? > > Rarely have I been confused. It may take a bit to return to one I haven't > used for a while. In general, the ideas are related so moving between programming languages is not that hard. However, it is much easier to get burned by language pitfalls when you are just using a language occasionally. (e.g. == is Perl's numeric comparison. eq is the string comparison. so "abc" == "def" evaluates as true since both convert to the number zero) > > I have also developed my own languages and tools for manipulating languages. > > >Is there any programming language blasphemy? Like learning C++ and > >then VB? Is that a sin or a exercise in insanity? > > Ease in writing and reading is high on my list. Hence I have most enjoyed > APL and Python. I'm still wishing for ways to incorporate some of APL into > Python. As my buddy says "what is the constraint on you project that keeps > you from using Python?" > Bob Gailer > bgailer@alum.rpi.edu > 303 442 2625 home > 720 938 2625 cell > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp From bgailer at alum.rpi.edu Sat Oct 30 21:16:13 2004 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Sat Oct 30 21:15:40 2004 Subject: [Tutor] programming theology questions In-Reply-To: <1099162827.7237.18.camel@laptop.venix.com> References: <555128ce04103009214f4a0993@mail.gmail.com> <6.1.2.0.0.20041030103843.04976cd8@mail.mric.net> <1099162827.7237.18.camel@laptop.venix.com> Message-ID: <6.1.2.0.0.20041030131319.049a2600@mail.mric.net> At 01:00 PM 10/30/2004, Lloyd Kvam wrote: >On Sat, 2004-10-30 at 12:52, Bob Gailer wrote: > > At 10:21 AM 10/30/2004, Rene Lopez wrote: > > >How many programming languages can safely fit in your head before you > > >get confused, or think it's not worth it? :-) > > > > My history: machine language (IBM 650, 370) assembler (650, GE415, > > Singer10, IBM370) APL, APL2, Basic, Focal, Fortran, Pascal, PLAS, PLX, > > PL/I, C and C++, dBase-VisualFoxPro, Python, CMS Exec & Exec2, REXX, > > Advanced Revelation R-Basic, Clarion, all versions of MS Word and Excel > > macro languages, Access. I started learning J but got lost.... I've > studied > > but not used ADA, Modula II, Snobol, Cobol, Algol. > >How did you avoid Java and Perl?? I picked up a Java book cuz I wanted to learn socket programming. After reading the relevant chapter and code examples I guessed it would take a couple of hours of typing and debugging to run the examples. I then went to the Python site, found the socket module w/examples and in 5 minutes had it running. That was the end of my interest in Java. Just never had an opportunity to use Perl. Bob Gailer bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell From acasad at weber.ucsd.edu Tue Oct 19 07:17:54 2004 From: acasad at weber.ucsd.edu (Andrew Casad) Date: Sun Oct 31 01:05:57 2004 Subject: [Tutor] Parsing HTML file Message-ID: <3B143CD3-218E-11D9-B458-000A95C46B16@weber.ucsd.edu> I am trying to do some parsing of HTML similar to that asked about in a post on Thu Dec 11 2003. I would like to go through pages on my website, which have a huge number of: Caption. I would like to have the entire Caption (e.g., between the tags) inserted as a Description in the JPEG header of the image to which the hyperlink points. How do you suggest that I go about doing this? Cheers, Andrew Casad http://anthro.ucsd.edu/~acasad/ From apb_4 at hotmail.com Wed Oct 27 22:12:58 2004 From: apb_4 at hotmail.com (Adam Bark) Date: Sun Oct 31 01:07:03 2004 Subject: [Tutor] Compiling Message-ID: Do you think it would be possible to pass Python through an interpreter to create a C file then use a C compiler to create exe files? _________________________________________________________________ It's fast, it's easy and it's free. Get MSN Messenger today! http://www.msn.co.uk/messenger From cgjung at comcast.net Wed Oct 13 06:23:05 2004 From: cgjung at comcast.net (Comcast Mail) Date: Sun Oct 31 01:07:23 2004 Subject: [Tutor] Syntax Problem? Message-ID: <000d01c4b0dc$5aa62c70$f6aeda18@usertz7f6j789v> Skipped content of type multipart/alternative-------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: image/jpeg Size: 2743 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20041013/527122f0/attachment.jpe From ed18hg at bellsouth.net Sun Oct 24 16:20:07 2004 From: ed18hg at bellsouth.net (Ed Gaitan) Date: Sun Oct 31 01:08:47 2004 Subject: [Tutor] Letters vs. numbers Message-ID: <20041024142005.YTYK22603.imf24aec.mail.bellsouth.net@winxp40gb> Hello, I am creating MD5 hashes from a range of numbers. This works fine: for i in xrange(10): import md5 m = md5.new() m.update("%i" % i) print "i=",i,"md5(i)=",m.hexdigest() But now I want to output a 5 character combination of lower case letters and 0-9 digits. Is there a function that combines both and then I put the variable into the md5() function? Any bit of help would be appreciated. Thanks. Ed -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20041024/880cb265/attachment.html From fusco_john at yahoo.com Fri Oct 22 04:03:40 2004 From: fusco_john at yahoo.com (John Fusco) Date: Sun Oct 31 01:09:07 2004 Subject: [Tutor] Japanese Font question - Windows vs. Linux Message-ID: <41786A7C.1040702@yahoo.com> I have a simple script that runs fine on Windows, but does not select the right fonts on Linux (Fedora core 2). I have Japanese fonts on my Linux machine, but for some reason Tkinter doesn't seem to understand how to encode them. Even if I select a Japanese capable font liike "Mincho", I get the right font, but not the right characters. Does anyone know what I am missing? Do I have to coerce Tkinter to map the fonts correctly? Why don't I have to do this on Windows? Here's a simple example. from Tkinter import *; def Hiragana(sound): return eval( r"u'\N{HIRAGANA LETTER " + sound + "}'" ) win = Tk(); for x in "AIUEO": b = Button(win,text=Hiragana(x)) b.pack() win.mainloop(); Thanks, John From hugonz at h-lab.net Thu Oct 14 22:27:12 2004 From: hugonz at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Sun Oct 31 01:09:39 2004 Subject: [Tutor] How to save password ? In-Reply-To: <20041014200357.45923.qmail@web52601.mail.yahoo.com> References: <20041014200357.45923.qmail@web52601.mail.yahoo.com> Message-ID: <416EE11D.1040500@h-lab.net> It's basically the same case as the password file in UNIX /etc/passwd or /etc/shadow. The trick is not allowing a user to modify the hashes, but that is done only through file permissions... > I don't think you can do this, you can just try to hide it or perhaps > > you can encrypt the password file, but if someone is determined > enough > then it will be broken in addition they can just open up the script > and > modify out the password authentication. > From hugonz at h-lab.net Sun Oct 17 08:13:46 2004 From: hugonz at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Sun Oct 31 01:09:44 2004 Subject: [Tutor] Simple Question... In-Reply-To: <47856308316.20041016165216@columbus.rr.com> References: <20041016174645.31391.qmail@web61009.mail.yahoo.com> <8464C062-1F9E-11D9-8BDA-000393CBC88E@yahoo.fr> <47856308316.20041016165216@columbus.rr.com> Message-ID: <41720D9A.5040807@h-lab.net> I know it's a bit pedantic, but doesn't this favor longer lines in the "random" selection? Not to say that it's not very good for the majority of applications.... > Wouldn't it be much quicker to do something like this? > > import os.path > import random > > size = os.path.getsize('test.txt') > print size > > randline = random.randint(1, size) > print randline > > testfile = open('test.txt', 'r') > testfile.seek(randline) > print testfile.readline() #read what is likely half a line > print testfile.readline() #read the next whole line > testfile.close() > > You'd just need to add some exception handling in the event you tried > to read off the end of the file. > > Alan > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From hugonz at h-lab.net Tue Oct 19 19:56:15 2004 From: hugonz at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Sun Oct 31 01:09:48 2004 Subject: [Tutor] modified readline()??? In-Reply-To: <1ff2dfbf0410190448305e9ac@mail.gmail.com> References: <4174AB77.4030302@h-lab.net> <1ff2dfbf0410190448305e9ac@mail.gmail.com> Message-ID: <4175553F.3020804@h-lab.net> Thanks, I think I'll do that. As I come from a Perl background, I thought I could redefine the separator in a similar way as it is done with Perl's $/ variable... but I guess that cannot be done.... Thanks again, Hugo Michael Janssen wrote: >> >>But the program just puts some kind of terminal control between status >>lines. Can I redefine the "CR" in readline() as to read up to that >>character??? I cannot simply use read() and block with some buffer size >>since that does not guarante I'm getting the whole "50%" string so that >>I can parse it.... I could be getting just 5 in one pass, and then 0% >>in the next.... > > > read one char at a time and stop reading when you found the stop > character. Meanwhile store the read chars somewhere. > > Michael > From mail at mjclift.freeserve.co.uk Mon Oct 25 18:16:00 2004 From: mail at mjclift.freeserve.co.uk (Malcolm Clift) Date: Sun Oct 31 01:10:19 2004 Subject: [Tutor] \ n in list\ string Message-ID: <001701c4baad$eb90a410$d6964c51@a> Hi All, This is partly a wx problem, but I'm not convinced the answer is related to wx hence my posting to this group. I have been experimenting with the DragImage demo in wx. I'm trying to have a simple word wrap based on the number of items in the l1 list. Someone suggested the 'for i in range' line, but this just alters the y value for the whole text. I think that something like this 'for i in range...' needs to go before the image is drawn. I have also tried putting \ n in the text, which would seem to be the easiest thing to do, but I couldn't get this to work. # Make a shape from some text l1 = ['a','b','c','d','a','b','c','d','a','b','c','d','a','b','c','d',] text = " "+"".join(l1) bg_colour = wx.Colour(57, 115, 57) # matches the bg image font = wx.Font(36, wx.MODERN, wx.NORMAL, wx.NORMAL, 0, "Arial") textExtent = self.GetFullTextExtent(text, font) # create a bitmap the same size as our text bmp = wx.EmptyBitmap(textExtent[0], textExtent[1]) # 'draw' the text onto the bitmap dc = wx.MemoryDC() dc.SelectObject(bmp) dc.SetBackground(wx.Brush(bg_colour, wx.SOLID)) dc.Clear() dc.SetTextForeground(wx.RED) dc.SetFont(font) dc.DrawText(text, 0, 0) dc.SelectObject(wx.NullBitmap) mask = wx.Mask(bmp, bg_colour) bmp.SetMask(mask) shape = DragShape(bmp) for i in range(len(text)): shape.pos = (145, 170 + (i//12)*100) shape.text = "Some dragging text" self.shapes.append(shape) Thanks for any help, M -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20041025/3a95960a/attachment.htm From morgan at insightmill.com Wed Oct 13 21:40:15 2004 From: morgan at insightmill.com (Morgan Meader) Date: Sun Oct 31 01:10:41 2004 Subject: [Tutor] redundant function ( or, I need advice about cleaning up my code ) Message-ID: <416D8491.7040101@insightmill.com> Hello all, I am very new to python. I have the basics down somewhat but really want to save myself maintainence problems down the road. Please permit me to ask for guidance. This is one function example of the 4000 lines or so that I have so far. It(the program) is working as expected but it is ugly... well... just look below at this example. Anyway... some pointers( not refs ;-) ) as to how some of you experts would handle this kind of duplicate code in a function. FYI... I don't quite understand OOP yet but I'm reading furiously. And unfortunately I come from the Shell scripting world so any advice re: unlearning bad habits would be welcome. [code] def addChannelFeatures(job,step,impData,coup): layerNames = [] layerTypes = [] layerPols = [] for i in xrange(len(job.matrix.info['gROWname'])): if job.matrix.info['gROWtype'][i] == 'power_ground' or \ job.matrix.info['gROWtype'][i] == 'mixed' or \ job.matrix.info['gROWtype'][i] == 'signal': layerNames.append(job.matrix.info['gROWname'][i]) layerTypes.append(job.matrix.info['gROWlayer_type'][i]) layerPols.append(job.matrix.info['gROWpolarity'][i]) layers.sort() # add the channels step.clearAll() for imp in impData: # positive planes for i in imp['ranges']: if layerTypes[i] != 'signal': if layerPols == 'positive': step.affect(layerNames[i]) if imp['impedence_type'] == 'stripline': channelSize = 1000*(imp['width'] + 2*imp['spacing']) addSChannel(imp,channelSize,coup,pol='negative') elif imp['impedence_type'] == 'broadside': channelSize = 1000*(imp['width'] + 2*imp['spacing']) addBChannel(imp,channelSize,coup,pol='negative') elif imp['impedence_type'] == 'differential': channelSize = 1000*(2*imp['width'] + 3*imp['spacing']) addDChannel(imp,channelSize,coup,pol='negative') step.clearAll() if DEBUG: step.PAUSE('are stripline the channels looking good?') # negative planes for i in imp['ranges']: if layerTypes[i] != 'signal': if layerPols == 'negative': step.affect(layerNames[i]) if imp['impedence_type'] == 'stripline': channelSize = 1000*(imp['width'] + 2*imp['spacing']) addSChannel(imp,channelSize,coup,pol='positive') elif imp['impedence_type'] == 'broadside': channelSize = 1000*(imp['width'] + 2*imp['spacing']) addBChannel(imp,channelSize,coup,pol='positive') elif imp['impedence_type'] == 'differential': channelSize = 1000*(2*imp['width'] + 3*imp['spacing']) addDChannel(imp,channelSize,coup,pol='positive') step.clearAll() if DEBUG: step.PAUSE('are stripline the channels looking good?') pass [/code] Thank you for any help, Morgan From Rafal.Kaniewski at capital-fx.co.uk Mon Oct 25 12:13:42 2004 From: Rafal.Kaniewski at capital-fx.co.uk (Rafal Kaniewski) Date: Sun Oct 31 01:11:03 2004 Subject: [Tutor] Windows file structure Message-ID: <29BB8902C842E04FB49B7F64BA1E65BB08623A@cfxserver1.capital-fx.co.uk> Hello world... Seeking to learn by creating a solution that makes empty folders according to a set of variables on a windows network. Would prefer the solution to also work in Unix and OSX file structures. i.e. I have a list of different languages and I need to create several sets of empty folders in different specified places on the network, folders are named in different sets acording to the languages. Please advise where to start...Thanks... Rafal Kaniewski (previous experience - some of the beginners tutorials on python.org; basic HTML / XML ; intermediate filemaker scripting) Scanned for viruses by MailDefender From SMITHB2 at WESTAT.com Thu Oct 14 22:57:46 2004 From: SMITHB2 at WESTAT.com (Barrett Smith) Date: Sun Oct 31 01:11:58 2004 Subject: [Tutor] Ftplib: using LIST command timing out Message-ID: <446DDE75CFC7E1438061462F85557B0F0373A259@remail2.westat.com> I'm connecting to my ftp server using the ftplib, and can make and destroy directories, upload files, and so forth just fine. When I try to use the retrlines() method with the LIST command the operation times out. The specific line is: Connection.retrlines('LIST') Anyone had this problem before or know how to fix it? Is it possible my host is somehow restricting the LIST command (though since I'm logging in to my ftp account via python I don't understand how it would work)? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20041014/eef89aaa/attachment.html From maxnoel_fr at yahoo.fr Sun Oct 31 01:58:56 2004 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Sun Oct 31 01:59:00 2004 Subject: Fwd: [Tutor] redundant function ( or, I need advice about cleaning up my code ) Message-ID: (argh, clicked "reply" again. I *will* get used to this one day, I swear) Begin forwarded message: > From: Max Noel > Date: October 31, 2004 00:49:56 BST > To: Morgan Meader > Subject: Re: [Tutor] redundant function ( or, I need advice about > cleaning up my code ) > > > On Oct 13, 2004, at 20:40, Morgan Meader wrote: > >> if job.matrix.info['gROWtype'][i] == 'power_ground' or \ >> job.matrix.info['gROWtype'][i] == 'mixed' or \ >> job.matrix.info['gROWtype'][i] == 'signal': > > This test can be shortened somewhat by using the in operator. > > if job.matrix.info['gRowType][i] in ('power_ground', 'mixed', > 'signal'): > # do stuff > >> layers.sort() > > Mmh... I don't see an initialization for this variable... Is it a > global variable? If so, it's a Bad Thing. > >> if layerTypes[i] != 'signal': >> if layerPols == 'positive': >> step.affect(layerNames[i]) > > You can do that with a single test. > > if layerTypes[i] != 'signal' and layerPols == 'positive': > step.affect(layerNames[i]) > > If the first part of the test evaluates to False, the second part > won't be evaluated, as there is no need to (we already know the > boolean expression is false). > > > > > Also, there are a few things that I think could be improved in your > general coding style: > - Use functions. Lots of them. This single function you submitted to > us is huge. It could probably be broken up into at least 5 parts. > - You're almost only using C-style for loops. It works, but you should > try to use more foreach-style for loops. Instead of doing: > for i in range(len(a)): > # do something with a[i] > You should use: > for element in a: > # do something with element > It's faster, more elegant and usually more efficient. Have a look at > list comprehensions, too, they're very useful. > - I'm not absolutely sure, but it seems that some of the functions > you're using are modifying their arguments instead of returning > values. That's not a good idea, especially since Python can return > arrays, dictionaries or tuples. > > HTH, > > -- Wild_Cat > maxnoel_fr at yahoo dot fr -- ICQ #85274019 > "Look at you hacker... A pathetic creature of meat and bone, panting > and sweating as you run through my corridors... How can you challenge > a perfect, immortal machine?" > > -- maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From cyresse at gmail.com Sun Oct 31 02:46:00 2004 From: cyresse at gmail.com (Liam Clarke) Date: Sun Oct 31 02:46:03 2004 Subject: [Tutor] Windows file structure In-Reply-To: <29BB8902C842E04FB49B7F64BA1E65BB08623A@cfxserver1.capital-fx.co.uk> References: <29BB8902C842E04FB49B7F64BA1E65BB08623A@cfxserver1.capital-fx.co.uk> Message-ID: Hi Rafal Have a look at the os module, os is designed for cross platform compatibility, and it's handy on any OS. As a beginner myself, here's what I learnt in dealing with Python and directories - Use forward slashes. Win32 uses back slashes itself, but use forward slashes and Python does the rest. The os module and os.path are your friends. For example, my code that checks for a directory, and if it isn't present, creates it is as follows- if not os.path.exists('./archives/wb%s' % weekstart): os.mkdir('./archives/wb%s' % weekstart) os.path.exists returns a 1 if the specified path exists, 0 if it doesn't. the "./archives/wb%s" % weekstart is probably what you need. Say you've got five folders to create, and three languages to do it in, you could probably set up a list of the folder names like folderlist=[["English", "data", "temporary", "main", "archive"], ["Espa?ol", "datos", "temporal", "principal", "archivo"], ["Italiano", "dati", "provvisorio", "principale", "archivio"]] And then a wee loop - for slot in range(len(folderlist)): os.mkdir("../%s" % folderlist[slot][0]) for secondslot in range(1,len(folderlist[slot])): os.mkdir("../%s/%s" % (folderlist[slot][0], folderlist[slot][secondslot])) So that will create three directories in your root directory, English, Espa?ol, and Italiano, and each folder would have the subfolders as above. I will add my standard disclaimer - This is a quick and dirty way to do it, there's probably a simpler, cleaner way to do it, but it works. For me. There's probably a couple of *nix pitfalls I'm forgetting, probably to do with privileges and what not. I don't know *nix from my foot, so yeah.... : / Hope it helps Liam Clarke On Mon, 25 Oct 2004 11:13:42 +0100, Rafal Kaniewski wrote: > Hello world... > > Seeking to learn by creating a solution that makes empty folders > according to a set of variables on a windows network. Would prefer the > solution to also work in Unix and OSX file structures. > > i.e. I have a list of different languages and I need to create several > sets of empty folders in different specified places on the network, > folders are named in different sets acording to the languages. > > Please advise where to start...Thanks... > > Rafal Kaniewski > > (previous experience - some of the beginners tutorials on python.org; > basic HTML / XML ; intermediate filemaker scripting) > > Scanned for viruses by MailDefender > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From cyresse at gmail.com Sun Oct 31 02:49:15 2004 From: cyresse at gmail.com (Liam Clarke) Date: Sun Oct 31 02:49:18 2004 Subject: [Tutor] programming theology questions In-Reply-To: <6.1.2.0.0.20041030131319.049a2600@mail.mric.net> References: <555128ce04103009214f4a0993@mail.gmail.com> <6.1.2.0.0.20041030103843.04976cd8@mail.mric.net> <1099162827.7237.18.camel@laptop.venix.com> <6.1.2.0.0.20041030131319.049a2600@mail.mric.net> Message-ID: As Bob just mentioned sockets, I thought I'd ask, what exactly are sockets? I thought that they were just for stuff like open ports, etc, but then people are talking about two programmes running concurrently communicating via sockets. Can anyone give a newbie a very brief rundown? Regards, Liam Clarke On Sat, 30 Oct 2004 13:16:13 -0600, Bob Gailer wrote: > At 01:00 PM 10/30/2004, Lloyd Kvam wrote: > >On Sat, 2004-10-30 at 12:52, Bob Gailer wrote: > > > At 10:21 AM 10/30/2004, Rene Lopez wrote: > > > >How many programming languages can safely fit in your head before you > > > >get confused, or think it's not worth it? :-) > > > > > > My history: machine language (IBM 650, 370) assembler (650, GE415, > > > Singer10, IBM370) APL, APL2, Basic, Focal, Fortran, Pascal, PLAS, PLX, > > > PL/I, C and C++, dBase-VisualFoxPro, Python, CMS Exec & Exec2, REXX, > > > Advanced Revelation R-Basic, Clarion, all versions of MS Word and Excel > > > macro languages, Access. I started learning J but got lost.... I've > > studied > > > but not used ADA, Modula II, Snobol, Cobol, Algol. > > > >How did you avoid Java and Perl?? > > I picked up a Java book cuz I wanted to learn socket programming. After > reading the relevant chapter and code examples I guessed it would take a > couple of hours of typing and debugging to run the examples. I then went to > the Python site, found the socket module w/examples and in 5 minutes had it > running. That was the end of my interest in Java. > > Just never had an opportunity to use Perl. > > > > Bob Gailer > bgailer@alum.rpi.edu > 303 442 2625 home > 720 938 2625 cell > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From cyresse at gmail.com Sun Oct 31 02:52:04 2004 From: cyresse at gmail.com (Liam Clarke) Date: Sun Oct 31 02:52:07 2004 Subject: [Tutor] redundant function ( or, I need advice about cleaning up my code ) In-Reply-To: References: Message-ID: Hi, >You're almost only using C-style for loops. It works, but you should > try to use more foreach-style for loops. Instead of doing: > for i in range(len(a)): > # do something with a[i] > You should use: > for element in a: > # do something with element Just saw this, so if I've got a ten item list, for element in a: will pull up a[element]? If so, that totally rocks, and I have to make my code look prettier. On Sun, 31 Oct 2004 00:58:56 +0100, Max Noel wrote: > (argh, clicked "reply" again. I *will* get used to this one day, I > swear) > > Begin forwarded message: > > > From: Max Noel > > Date: October 31, 2004 00:49:56 BST > > To: Morgan Meader > > Subject: Re: [Tutor] redundant function ( or, I need advice about > > cleaning up my code ) > > > > > > On Oct 13, 2004, at 20:40, Morgan Meader wrote: > > > >> if job.matrix.info['gROWtype'][i] == 'power_ground' or \ > >> job.matrix.info['gROWtype'][i] == 'mixed' or \ > >> job.matrix.info['gROWtype'][i] == 'signal': > > > > This test can be shortened somewhat by using the in operator. > > > > if job.matrix.info['gRowType][i] in ('power_ground', 'mixed', > > 'signal'): > > # do stuff > > > >> layers.sort() > > > > Mmh... I don't see an initialization for this variable... Is it a > > global variable? If so, it's a Bad Thing. > > > >> if layerTypes[i] != 'signal': > >> if layerPols == 'positive': > >> step.affect(layerNames[i]) > > > > You can do that with a single test. > > > > if layerTypes[i] != 'signal' and layerPols == 'positive': > > step.affect(layerNames[i]) > > > > If the first part of the test evaluates to False, the second part > > won't be evaluated, as there is no need to (we already know the > > boolean expression is false). > > > > > > > > > > Also, there are a few things that I think could be improved in your > > general coding style: > > - Use functions. Lots of them. This single function you submitted to > > us is huge. It could probably be broken up into at least 5 parts. > > - You're almost only using C-style for loops. It works, but you should > > try to use more foreach-style for loops. Instead of doing: > > for i in range(len(a)): > > # do something with a[i] > > You should use: > > for element in a: > > # do something with element > > It's faster, more elegant and usually more efficient. Have a look at > > list comprehensions, too, they're very useful. > > - I'm not absolutely sure, but it seems that some of the functions > > you're using are modifying their arguments instead of returning > > values. That's not a good idea, especially since Python can return > > arrays, dictionaries or tuples. > > > > HTH, > > > > -- Wild_Cat > > maxnoel_fr at yahoo dot fr -- ICQ #85274019 > > "Look at you hacker... A pathetic creature of meat and bone, panting > > and sweating as you run through my corridors... How can you challenge > > a perfect, immortal machine?" > > > > > -- > maxnoel_fr at yahoo dot fr -- ICQ #85274019 > "Look at you hacker... A pathetic creature of meat and bone, panting > and sweating as you run through my corridors... How can you challenge a > perfect, immortal machine?" > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From missive at hotmail.com Sun Oct 31 02:01:56 2004 From: missive at hotmail.com (Lee Harr) Date: Sun Oct 31 02:02:04 2004 Subject: [Tutor] Re: Letters vs. numbers Message-ID: >But now I want to output a 5 character combination of lower case letters >and >0-9 digits. Is there a function that combines both and then I put the >variable into the md5() function? Any bit of help would be appreciated. > import random import string variable = ''.join(random.sample(string.lowercase+string.digits, 5)) _________________________________________________________________ Express yourself instantly with MSN Messenger! Download today it's FREE! http://messenger.msn.com/ From cyresse at gmail.com Sun Oct 31 02:03:13 2004 From: cyresse at gmail.com (Liam Clarke) Date: Sun Oct 31 02:03:16 2004 Subject: [Tutor] Syntax Problem? In-Reply-To: <000d01c4b0dc$5aa62c70$f6aeda18@usertz7f6j789v> References: <000d01c4b0dc$5aa62c70$f6aeda18@usertz7f6j789v> Message-ID: G'day, So, you've done the following - >>>def NewLine(): (press enter) ... print (press enter) ... (press enter) >>> If you type NewLine(), you should just get this - >>>NewLine() >>> And as for Threelines... >>>def ThreeLines(): (press enter) ... NewLine() (press enter) ... NewLine() (press enter) ... NewLine() (press enter) ... (press enter) >>> And when you run threelines, you'd be expecting this - >>>ThreeLines() >>> Where I think you're going wrong is that in the interactive interpreter, when you define a code block (which is what the : on the end of def Newline(): does) , the interpreter automatically moves you down and one tab across, and that is what the ... prompt means. Each time you press enter after adding code, you'll get the ... prompt again, until you press enter at ... prompt, with nothing further added. This tells the interpreter that your code block has finished. So, using enter, you shouldn't have to touch Tab for those functions. HTH Liam Clarke On Wed, 13 Oct 2004 00:23:08 -0400, Comcast Mail wrote: > > > > Hello, > > > > I'm working through "How to think Like a Computer Scientist Learning with > Python." by Downery, Elkner & Meyers. I am in section Chap 3, Functions. > Specifically in section 3.7 "Definitions and use." This is driving me > crazy as the exercise seems simple but my version of Python 2.3.4 is not > acting right. When I input the following as per the book instructions > > > > >>>def newLine(): I then tab under to the next line and type "print" > However, I only end up with the editors three ellipses ? > > > > when I type > > > > >>>def threelines(): the book says I'm supposed to get > > > > newLine() > > newLine() > > newLine() > > > > but all I get again is ?three ellipses > > > > I also tried def newLine(): then "enter" then "print" then I get > "indentationerror" > > > > What the heck is going on? I had no problems with earlier exercises. Any > help would be greatly appreciated. Please respond both on the board and to > me at this email address if possible. > > > > > Sincerely, > M.J.DeYoung. > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From kent_johnson at skillsoft.com Sun Oct 31 02:44:47 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Sun Oct 31 02:44:52 2004 Subject: [Tutor] Windows file structure In-Reply-To: References: <29BB8902C842E04FB49B7F64BA1E65BB08623A@cfxserver1.capital-fx.co.uk> Message-ID: <6.1.0.6.0.20041030214022.02a79fd8@mail4.skillsoft.com> A few notes: - Instead of for slot in range(len(folderlist)): # do something with folderlist[slot] it is better to write for names in folderlist: # do something with names - os.makedirs() will make all the directories needed to reach a path, so you don't have to make the intermediate paths. - A more portable way to join paths is with os.path.join(); this will work on a wider variety of platforms that code that assumes that / is the separator. So you could write your loop as for names in folderlist: for secondslot in names[1:]: os.makedirs(os.path.join('..', names[0], secondslot)) Kent At 01:46 PM 10/31/2004 +1300, Liam Clarke wrote: >folderlist=[["English", "data", "temporary", "main", "archive"], > ["Espa?ol", "datos", "temporal", "principal", "archivo"], > ["Italiano", "dati", "provvisorio", "principale", "archivio"]] > >And then a wee loop - > >for slot in range(len(folderlist)): > os.mkdir("../%s" % folderlist[slot][0]) > for secondslot in range(1,len(folderlist[slot])): > os.mkdir("../%s/%s" % (folderlist[slot][0], >folderlist[slot][secondslot])) From kent_johnson at skillsoft.com Sun Oct 31 03:13:24 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Sun Oct 31 03:13:37 2004 Subject: [Tutor] redundant function ( or, I need advice about cleaning up my code ) In-Reply-To: <416D8491.7040101@insightmill.com> References: <416D8491.7040101@insightmill.com> Message-ID: <6.1.0.6.0.20041030215609.02a7c940@mail4.skillsoft.com> Morgan, A few suggestions: - Comments and white space are your friends! Breaking up a section of code with blank lines makes it much more readable. - When you have sections of code that are almost the same, you can often make a function containing the common pieces. Pass the varying parts as parameters to the function. So this chunk of code: for i in imp['ranges']: if layerTypes[i] != 'signal': if layerPols == 'positive': step.affect(layerNames[i]) if imp['impedence_type'] == 'stripline': channelSize = 1000*(imp['width'] + 2*imp['spacing']) addSChannel(imp,channelSize,coup,pol='negative') elif imp['impedence_type'] == 'broadside': channelSize = 1000*(imp['width'] + 2*imp['spacing']) addBChannel(imp,channelSize,coup,pol='negative') elif imp['impedence_type'] == 'differential': channelSize = 1000*(2*imp['width'] + 3*imp['spacing']) addDChannel(imp,channelSize,coup,pol='negative') could be a function with two arguments, layerPolType and polType: def addChannels(imp, layerPolType, polType): for i in imp['ranges']: if layerTypes[i] != 'signal': if layerPols == layerPolType: step.affect(layerNames[i]) if imp['impedence_type'] == 'stripline': channelSize = 1000*(imp['width'] + 2*imp['spacing']) addSChannel(imp,channelSize,coup,pol=polType) elif imp['impedence_type'] == 'broadside': channelSize = 1000*(imp['width'] + 2*imp['spacing']) addBChannel(imp,channelSize,coup,pol=polType) elif imp['impedence_type'] == 'differential': channelSize = 1000*(2*imp['width'] + 3*imp['spacing']) addDChannel(imp,channelSize,coup,pol=polType) Then you can call addChannels(imp, 'positive', 'negative') and addChannels(imp, 'negative', 'positive') instead of having two copies of the code. (I may have missed some differences, and I'm sure you can think of better names, but hopefully you get the idea.) - The dictionary object imp is crying out to be a class. ranges, impedence_type, width and spacing would all be member fields. At the least this would clean up the syntax a little; instead of imp['width'] you would write imp.width. But the big win comes when you start to move some functionality into the imp class: class Imp: def __init__(self, ranges, impedence_type, width, spacing): self.ranges = ranges self.impedence_type = impedence_type self.width = width self.spacing = spacing def getChannelSize(self): if self.impedence_type == 'stripline': return 1000*(imp['width'] + 2*imp['spacing']) if self.impedence_type == 'broadside': return 1000*(imp['width'] + 2*imp['spacing']) if self.impedence_type == 'differential': return 1000*(2*imp['width'] + 3*imp['spacing']) The code in the main program becomes if imp.impedence_type== 'stripline': addSChannel(imp,imp.getChannelSize(),coup,pol=polType) elif imp.impedence_type == 'broadside': addBChannel(imp,imp.getChannelSize(),coup,pol=polType) elif imp.impedence_type == 'differential': addDChannel(imp,imp.getChannelSize(),coup,pol=polType) Depending on what addSChannel, etc do, you might be able to move them into Imp methods also to avoid the double test of impedence_type. Kent At 12:40 PM 10/13/2004 -0700, Morgan Meader wrote: >Hello all, > >I am very new to python. I have the basics down somewhat but really want >to save myself maintainence problems down the road. Please permit me to >ask for guidance. > >This is one function example of the 4000 lines or so that I have so far. >It(the program) is working as expected but it is ugly... well... just look >below at this example. Anyway... some pointers( not refs ;-) ) as to how >some of you experts would handle this kind of duplicate code in a function. > >FYI... I don't quite understand OOP yet but I'm reading furiously. And >unfortunately I come from the Shell scripting world so any advice re: >unlearning bad habits would be welcome. > > >[code] > >def addChannelFeatures(job,step,impData,coup): > layerNames = [] > layerTypes = [] > layerPols = [] > for i in xrange(len(job.matrix.info['gROWname'])): > if job.matrix.info['gROWtype'][i] == 'power_ground' or \ > job.matrix.info['gROWtype'][i] == 'mixed' or \ > job.matrix.info['gROWtype'][i] == 'signal': > layerNames.append(job.matrix.info['gROWname'][i]) > layerTypes.append(job.matrix.info['gROWlayer_type'][i]) > layerPols.append(job.matrix.info['gROWpolarity'][i]) > layers.sort() > # add the channels > step.clearAll() > for imp in impData: > # positive planes > for i in imp['ranges']: > if layerTypes[i] != 'signal': > if layerPols == 'positive': > step.affect(layerNames[i]) > if imp['impedence_type'] == 'stripline': > channelSize = 1000*(imp['width'] + 2*imp['spacing']) > addSChannel(imp,channelSize,coup,pol='negative') > elif imp['impedence_type'] == 'broadside': > channelSize = 1000*(imp['width'] + 2*imp['spacing']) > addBChannel(imp,channelSize,coup,pol='negative') > elif imp['impedence_type'] == 'differential': > channelSize = 1000*(2*imp['width'] + 3*imp['spacing']) > addDChannel(imp,channelSize,coup,pol='negative') > > step.clearAll() > if DEBUG: > step.PAUSE('are stripline the channels looking good?') > # negative planes > for i in imp['ranges']: > if layerTypes[i] != 'signal': > if layerPols == 'negative': > step.affect(layerNames[i]) > if imp['impedence_type'] == 'stripline': > channelSize = 1000*(imp['width'] + 2*imp['spacing']) > addSChannel(imp,channelSize,coup,pol='positive') > elif imp['impedence_type'] == 'broadside': > channelSize = 1000*(imp['width'] + 2*imp['spacing']) > addBChannel(imp,channelSize,coup,pol='positive') > elif imp['impedence_type'] == 'differential': > channelSize = 1000*(2*imp['width'] + 3*imp['spacing']) > addDChannel(imp,channelSize,coup,pol='positive') > > step.clearAll() > if DEBUG: > step.PAUSE('are stripline the channels looking good?') > > pass > >[/code] > > > > >Thank you for any help, >Morgan > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From cyresse at gmail.com Sun Oct 31 03:26:00 2004 From: cyresse at gmail.com (Liam Clarke) Date: Sun Oct 31 03:26:05 2004 Subject: [Tutor] Windows file structure In-Reply-To: <6.1.0.6.0.20041030214022.02a79fd8@mail4.skillsoft.com> References: <29BB8902C842E04FB49B7F64BA1E65BB08623A@cfxserver1.capital-fx.co.uk> <6.1.0.6.0.20041030214022.02a79fd8@mail4.skillsoft.com> Message-ID: Heh, I'm going to update my standard disclaimer to - This is a quick and dirty way to do it, there's probably a simpler, cleaner way to do it, which will be posted shortly by someone more knowledgeable. For secondslot in names[1:] means secondslot is a slice of names, doesn't it? I get confused about slices sometimes. On Sat, 30 Oct 2004 21:44:47 -0400, Kent Johnson wrote: > A few notes: > > - Instead of > for slot in range(len(folderlist)): > # do something with folderlist[slot] > > it is better to write > for names in folderlist: > # do something with names > > - os.makedirs() will make all the directories needed to reach a path, so > you don't have to make the intermediate paths. > > - A more portable way to join paths is with os.path.join(); this will work > on a wider variety of platforms that code that assumes that / is the separator. > > So you could write your loop as > for names in folderlist: > for secondslot in names[1:]: > os.makedirs(os.path.join('..', names[0], secondslot)) > > Kent > > > > At 01:46 PM 10/31/2004 +1300, Liam Clarke wrote: > >folderlist=[["English", "data", "temporary", "main", "archive"], > > ["Espa?ol", "datos", "temporal", "principal", "archivo"], > > ["Italiano", "dati", "provvisorio", "principale", "archivio"]] > > > >And then a wee loop - > > > >for slot in range(len(folderlist)): > > os.mkdir("../%s" % folderlist[slot][0]) > > for secondslot in range(1,len(folderlist[slot])): > > os.mkdir("../%s/%s" % (folderlist[slot][0], > >folderlist[slot][secondslot])) > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From kent_johnson at skillsoft.com Sun Oct 31 03:47:11 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Sun Oct 31 03:47:18 2004 Subject: [Tutor] Windows file structure In-Reply-To: References: <29BB8902C842E04FB49B7F64BA1E65BB08623A@cfxserver1.capital-fx.co.uk> <6.1.0.6.0.20041030214022.02a79fd8@mail4.skillsoft.com> Message-ID: <6.1.0.6.0.20041030223701.02adc188@mail4.skillsoft.com> At 03:26 PM 10/31/2004 +1300, Liam Clarke wrote: >Heh, I'm going to update my standard disclaimer to - > >This is a quick and dirty way to do it, there's probably a simpler, >cleaner way to do it, which will be posted shortly by someone more >knowledgeable. Awww...don't get discouraged! It takes a while to learn how easy Python makes things for you :-) >For secondslot in names[1:] means secondslot is a slice of names, >doesn't it? I get confused about slices sometimes. Not quite. names[1:] is a slice of names (every element except element 0), so it is a list. for secondslot in names[1:]: iterates over the elements of names[1:], binding each element in turn to the name 'secondslot', and executing the loop body. >>> names = ["English", "data", "temporary", "main", "archive"] >>> names[1:] ['data', 'temporary', 'main', 'archive'] >>> for n in names[1:]: ... print 'n =', n ... n = data n = temporary n = main n = archive Kent From maxnoel_fr at yahoo.fr Sun Oct 31 03:47:38 2004 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Sun Oct 31 03:47:43 2004 Subject: [Tutor] redundant function ( or, I need advice about cleaning up my code ) In-Reply-To: <41844C87.4040303@insightmill.com> References: <416D8491.7040101@insightmill.com> <672E3FEE-2ACE-11D9-A933-000393CBC88E@yahoo.fr> <41844C87.4040303@insightmill.com> Message-ID: <3A5B61FA-2AE7-11D9-A933-000393CBC88E@yahoo.fr> On Oct 31, 2004, at 02:23, Morgan Meader wrote: > Anyway... I thank you and will look into the areas you suggested... > esp. List comprehension and foreach. > > Question: > I did it that way because I had more than one list I was looking at. > Is there another way to have the index so I can get values that match > up by index on multiple lists? Mmh... I don't think there's a built-in way to do that, but you can create a custom iterator that will do the job. (iterators are another great thing in Python, Ruby and Java) def multiList(what): """Iterates over multiple lists at the same time. what is a list of lists of thesame size, and the function yields a series of tuples, where the i-th tuple yielded contains the i-th element in each list in what.""" for i in range(len(what[0])): # This is exactly what I was warning you against. # There has to be a better way of doing this, # only I can't seem to be able to find it. D'oh! out = [element[i] for element in what] yield tuple(out) Then, you just use a for loop that looks like this: for (gROWname, gROWtype) in multiList((job.matrix.info['gROWname'], job.matrix.info['gROWtype'])): # do stuff Warning, my code here is quick & dirty, and untested. Use at your own risk. But anyway, you get the idea. ^^ -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From kent_johnson at skillsoft.com Sun Oct 31 04:03:50 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Sun Oct 31 04:04:03 2004 Subject: [Tutor] redundant function ( or, I need advice about cleaning up my code ) In-Reply-To: <3A5B61FA-2AE7-11D9-A933-000393CBC88E@yahoo.fr> References: <416D8491.7040101@insightmill.com> <672E3FEE-2ACE-11D9-A933-000393CBC88E@yahoo.fr> <41844C87.4040303@insightmill.com> <3A5B61FA-2AE7-11D9-A933-000393CBC88E@yahoo.fr> Message-ID: <6.1.0.6.0.20041030230021.02aed1c8@mail4.skillsoft.com> That's exactly what the builtin function zip() does - it makes a list containing matched elements from each of the lists passed as arguments: >>> l1 = [1,2,3,4] >>> l2 = ['a', 'b', 'c', 'd'] >>> zip(l1, l2) [(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd')] >>> for number, letter in zip(l1, l2): ... print number, letter ... 1 a 2 b 3 c 4 d If you want to iterate a single list, but you need the index for some reason, you can use enumerate(): >>> for i, item in enumerate(l2): ... print i, item ... 0 a 1 b 2 c 3 d enumerate() returns an iterator so if you want a list you have to ask for it explicitly: >>> list(enumerate(l2)) [(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')] Kent At 02:47 AM 10/31/2004 +0000, Max Noel wrote: >On Oct 31, 2004, at 02:23, Morgan Meader wrote: >>I did it that way because I had more than one list I was looking at. Is >>there another way to have the index so I can get values that match up by >>index on multiple lists? > > Mmh... I don't think there's a built-in way to do that, but you > can create a custom iterator that will do the job. (iterators are another > great thing in Python, Ruby and Java) From rdm at rcblue.com Sun Oct 31 11:05:09 2004 From: rdm at rcblue.com (Dick Moores) Date: Sun Oct 31 11:05:12 2004 Subject: [Tutor] How to calculate pi with another formula? In-Reply-To: <41828B7F.1060608@aon.at> References: <6.1.2.0.2.20041028093827.06b2ac00@rcblue.com> <41828B7F.1060608@aon.at> Message-ID: <6.1.2.0.2.20041031020144.04b03eb0@rcblue.com> Thanks, Gregor! I downloaded just the decimal module (thanks to Kent), and found the doc for decimal, . Exciting! Thanks, Dick At 10:27 10/29/2004, Gregor Lingl wrote: >Hi Dick! > >Accidentally I just was tinkering around with the new >decimal module of Python2.4. (By the way: it also works >with Python 2.3 - just copy it into /Python23/Lib) > >The attached program uses a very elementary (and inefficient) >formula to calculate pi, namely as the area of a 6*2**n-sided >polygon (starting with n=0), inscribed into a circle of radius 1. >(Going back to Archimedes, if I'm right ...) > >Nevertheless it calculates pi with a precision of (nearly) >100 digits, and the precision can be arbitrarily enlarged. >In the output of this program only the last digit is not correct. > >import decimal > >decimal.getcontext().prec = 100 > >def calcpi(): > s = decimal.Decimal(1) > h = decimal.Decimal(3).sqrt()/2 > n = 6 > for i in range(170): > A = n*h*s/2 # A ... area of polygon > print i,":",A > s2 = ((1-h)**2+s**2/4) > s = s2.sqrt() > h = (1-s2/4).sqrt() > n = 2*n > >calcpi() > >Just for fun ... > >Gregor > > >Dick Moores schrieb: > >>Is it possible to calculate almost-pi/2 using the (24) formula on >> without using (23)? >> >>If it's possible, how about a hint? Recursion? >> >>Thanks, tutors. >> >>Dick Moores >>rdm@rcblue.com From keridee at jayco.net Fri Oct 29 17:50:29 2004 From: keridee at jayco.net (Jacob S.) Date: Sun Oct 31 14:02:14 2004 Subject: [Tutor] Does anyone know if IDLE has a maximized setting? Message-ID: <000201c4bf49$c32d4be0$d05328cf@JSLAPTOP> Hello again. I am using IDLE for editing my scripts and I was wondering if there was a way to default the IDLE windows to come up maximized every time. As it is, I have to maximize the window every time I right click on a file and click edit with IDLE. This gets annoying very quickly. Does anyone know what file in the idlelib directory might contain the TK script for the editor and shell windows so that I might change that setting myself? Thanks for any help, Jacob Schmidt From dleigh0 at carolina.rr.com Sun Oct 31 18:31:34 2004 From: dleigh0 at carolina.rr.com (Diana Furr) Date: Sun Oct 31 18:24:46 2004 Subject: [Tutor] array Message-ID: <000601c4bf6f$78549260$121c8645@oemcomputer> I am taking a programming class that uses the book Programming Logic and Design and we program with python. We are starting on a chapter about arrays and I have a few questions. I understand from reading the chapter what an array is and why they are used, but I don't know how to make an array in python. I have read from different links on python.org but I still don't get it. This is the assignment: Write a Python code for a program that reads numbers entered from the keyboard into an array1, stores their doubles in a second array2, and prints out both arrays. For the purpose of this assignment assume that there will be no more than 10 numbers. Have the program prompt at the beginning of the program and ask how many numbers will be entered. The program should loop and ask if another set of numbers will be entered, program termination is dependent on user input. Suggested output is shown below: Array 1 Array2 10 20 11 22 15 30 33 66 I don't want someone to give me the answer, but maybe show me what an array that is dependant on user input looks like in Python. I understand if no one wants to help but please at least point me in the right direction. Thank you, Diana -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20041031/1d49040f/attachment.htm From maxnoel_fr at yahoo.fr Sun Oct 31 18:37:17 2004 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Sun Oct 31 18:37:29 2004 Subject: [Tutor] array In-Reply-To: <000601c4bf6f$78549260$121c8645@oemcomputer> References: <000601c4bf6f$78549260$121c8645@oemcomputer> Message-ID: <82ACFB49-2B63-11D9-BBAA-000393CBC88E@yahoo.fr> On Oct 31, 2004, at 17:31, Diana Furr wrote: > I don't want someone to give me the answer, but maybe show me what an > array that is dependant on user input looks like in Python. I > understand if no one wants to help but please at least point me in the > right direction. We can't be specific here (can't help you do your homework, sorry ;) ), but the basic idea is to create an empty array, then store the user's input in a variable and append it to the end of the array. -- Wild_Cat maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From tanja.pislar at gmail.com Sun Oct 31 19:31:06 2004 From: tanja.pislar at gmail.com (tanja pislar) Date: Sun Oct 31 19:31:09 2004 Subject: [Tutor] array In-Reply-To: <000601c4bf6f$78549260$121c8645@oemcomputer> References: <000601c4bf6f$78549260$121c8645@oemcomputer> Message-ID: maybe just a hint: try and read how to use lists in Python.. that will give you everything you'll need for your assignment some links: http://www.developer.com/lang/other/article.php/628971 http://diveintopython.org/native_data_types/lists.html On Sun, 31 Oct 2004 12:31:34 -0500, Diana Furr wrote: > > I am taking a programming class that uses the book Programming Logic and > Design and we program with python. We are starting on a chapter about arrays > and I have a few questions. I understand from reading the chapter what an > array is and why they are used, but I don't know how to make an array in > python. I have read from different links on python.org but I still don't get > it. > > This is the assignment: > > Write a Python code for a program that reads numbers entered from the > keyboard into an array1, stores their doubles in a second array2, and prints > out both arrays. For the purpose of this assignment assume that there will > be no more than 10 numbers. Have the program prompt at the beginning of the > program and ask how many numbers will be entered. The program should loop > and ask if another set of numbers will be entered, program termination is > dependent on user input. Suggested output is shown below: > > Array 1 Array2 > > 10 20 > > 11 22 > > 15 30 > > 33 66 > > I don't want someone to give me the answer, but maybe show me what an array > that is dependant on user input looks like in Python. I understand if no one > wants to help but please at least point me in the right direction. > > Thank you, > > Diana > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > > -- www.klaustrofobik.org From orbitz at ezabel.com Sun Oct 31 19:47:20 2004 From: orbitz at ezabel.com (orbitz) Date: Sun Oct 31 19:47:25 2004 Subject: [Tutor] Compiling In-Reply-To: References: Message-ID: <41853338.8050109@ezabel.com> Anything is possible, however is it worth your time to make a python to C compiler? if you need speed critical things, just drop to C and use it from python. Adam Bark wrote: > Do you think it would be possible to pass Python through an > interpreter to create a C file then use a C compiler to create exe files? > > _________________________________________________________________ > It's fast, it's easy and it's free. Get MSN Messenger today! > http://www.msn.co.uk/messenger > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From kent_johnson at skillsoft.com Sun Oct 31 20:44:15 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Sun Oct 31 20:44:21 2004 Subject: [Tutor] Compiling In-Reply-To: <41853338.8050109@ezabel.com> References: <41853338.8050109@ezabel.com> Message-ID: <6.1.0.6.0.20041031142824.02952b58@mail4.skillsoft.com> Are you thinking of taking this on as a project or are you wondering if someone has done it? If the latter, why do you want this? If your goal is to make an exe from a python program, you can do that with py2exe http://starship.python.net/crew/theller/py2exe/ and others. If your goal is to speed up critical sections of code, there are several ways to do this including psyco (http://psyco.sourceforge.net/index.html), pyrex (http://nz.cosc.canterbury.ac.nz/~greg/python/Pyrex/), and writing a C extension (http://docs.python.org/ext/ext.html). Kent Adam Bark wrote: >Do you think it would be possible to pass Python through an interpreter to >create a C file then use a C compiler to create exe files? From isrgish at fastem.com Sun Oct 31 21:26:31 2004 From: isrgish at fastem.com (Isr Gish) Date: Sun Oct 31 21:26:50 2004 Subject: [Tutor] Python on handhelds Message-ID: <20041031202648.954E31E4003@bag.python.org> >From: "Anthony P." >Sent: 10/29/04 5:35:21 PM >To: "Python Tutor List" >Subject: [Tutor] Python on handhelds > >Hello Everyone, > >I've been asked to develop a simple application that will run on the >Dell Axiom handheld computer. Does anyone know how to get Python to >run on this little device? > Hi Anthony, There is a 2.3 version availabe at sourceforge.net, search for pythonce. There is also a PythonCE mailing list at http://mail.python.org/mailman/listinfo/pythonce >Thanks, >Anthony >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From cyresse at gmail.com Sun Oct 31 22:48:16 2004 From: cyresse at gmail.com (Liam Clarke) Date: Sun Oct 31 22:48:20 2004 Subject: [Tutor] array In-Reply-To: References: <000601c4bf6f$78549260$121c8645@oemcomputer> Message-ID: Yeah, the terminology is confusing. 'Array' tends to be a hangover from the days of BASIC. An array in the days of BASIC could be 1 dimensional or two dimensional (Or 3 if you were really keen) A 1 dimensional array would be something along these lines: Index # 0 1 2 3 4 5 6 7 8 9... a = Value 'a' 'b' 'c' 'd' 55.... so a(0) would be 'a', a(4) would be 55. 2 dimensional arrays were like this - a ={ 0 1 2 3 4 5 6 7... 0 'a' 'b' c' 'd' 55 1 2 3 4 } and a(0,0) would be 'a', and a(0,4) would be 55. Python doesn't do two dimensional arrays out of the box, so forget about those. An 1 dimensional array in Python is called a list. A list is denoted by a group of values surrounded by [ ] brackets. a=['a','b','c','d',55] A list is accessed by index number, same as an array. a[0]='a', a[4]=55. (Sidenote, a list can also contain sublists, which isn't really relevant to your current problem, but keep it in mind, as it will come in useful for future Python work. A=['a',['b','c','d'],55] ... A[0]='a', A[1]=['b','c','d'] , A[2]=55. A[1][0]='b', A[1][2]='d') So to conclude, 4 basic hints for you - 1. An array in Python is a list. 2. Computers start counting at 0.... 3. ...which is why a 'for x in range(y)' statement counts up to, but not including y. I.E., if y was 10, it would count 0-9. It works like this for a reason, which you'll understand the more you work with list. 4. Lastly, and I can't stress how useful this site is, http://www.freenetpages.co.uk/hp/alan.gauld/tutor2/index.htm This is one of the best tutorials I found. I only started using Python 4 weeks ago, I worked through Alan Gauld's above tutorial, and yeah, I just finished creating my first GUI based programme. Good luck, Liam Clarke On Sun, 31 Oct 2004 19:31:06 +0100, tanja pislar wrote: > maybe just a hint: try and read how to use lists in Python.. that will > give you everything you'll need for your assignment > > some links: > http://www.developer.com/lang/other/article.php/628971 > http://diveintopython.org/native_data_types/lists.html > > > > > On Sun, 31 Oct 2004 12:31:34 -0500, Diana Furr wrote: > > > > I am taking a programming class that uses the book Programming Logic and > > Design and we program with python. We are starting on a chapter about arrays > > and I have a few questions. I understand from reading the chapter what an > > array is and why they are used, but I don't know how to make an array in > > python. I have read from different links on python.org but I still don't get > > it. > > > > This is the assignment: > > > > Write a Python code for a program that reads numbers entered from the > > keyboard into an array1, stores their doubles in a second array2, and prints > > out both arrays. For the purpose of this assignment assume that there will > > be no more than 10 numbers. Have the program prompt at the beginning of the > > program and ask how many numbers will be entered. The program should loop > > and ask if another set of numbers will be entered, program termination is > > dependent on user input. Suggested output is shown below: > > > > Array 1 Array2 > > > > 10 20 > > > > 11 22 > > > > 15 30 > > > > 33 66 > > > > I don't want someone to give me the answer, but maybe show me what an array > > that is dependant on user input looks like in Python. I understand if no one > > wants to help but please at least point me in the right direction. > > > > Thank you, > > > > Diana > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > > > -- > www.klaustrofobik.org > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From marilyn at deliberate.com Sun Oct 31 22:53:42 2004 From: marilyn at deliberate.com (Marilyn Davis) Date: Sun Oct 31 22:53:46 2004 Subject: [Tutor] escape-quoting strings Message-ID: Hi Python Tutors, I'm having a devil of a time quoting strings properly for MySql. The string is fed to me on the command line from my Mail Transfer Agent. In the worst case, it might feed me an argument like this: "\"Toys \\\"R\\\" Us \$250 Gift\" " Printing the argument: "Toys \"R\" Us $250 Gift" That's nice. That's how it actually looked in the email. My program has to feed that string into MySql. It should look the same as on the argument list, plus some %'s: "%\"Toys \\\"R\\\" Us $250 Gift\" %" And for the life of me, I can't get it to happen. Here's my little test script that tries 4 different approaches, none of which work: --- #! /usr/bin/env python import sys address = sys.argv[1] print address db_style = '''%%%s%%''' % address print '1', db_style ad2 = address.replace('"','\\"') db_style2 = '''%%%s%%''' % ad2 print "2:", db_style2 ad3 = address.replace('\"','\\\"') ad3 = ad3.replace('"','\\"') db_style3 = '''%%%s%%''' % ad3 print '3:', db_style3 ad44 = '' ad4 = address.replace('\"','\\\"') print ad4 mark = 0 for ch in ad4: print ch, if ch == '\\' and mark == 1: # two in a row ad44 += '\\\\' # make 3? mark = 1 elif ch == '\\': mark = 1 ad44 += ch elif ch == '"' and mark: ad44 += ch mark = 0 elif ch == '"': ad44 += '\\"' mark = 0 else: ad44 += ch print ad44 db_style4 = '''%%%s%%''' % ad4 print db_style4 --- ./arg_test.py "\"Toys \\\"R\\\" Us \$250 Gift\" " "Toys \"R\" Us $250 Gift" 1 %"Toys \"R\" Us $250 Gift" % 2: %\"Toys \\"R\\" Us $250 Gift\" % 3: %\\"Toys \\\"R\\\" Us $250 Gift\\" % \"Toys \\"R\\" Us $250 Gift\" \ \ " \" T \"T o \"To y \"Toy s \"Toys \"Toys \ \"Toys \ \ \"Toys \\\ " \"Toys \\\" R \"Toys \\\"R \ \"Toys \\\"R\ \ \"Toys \\\"R\\\ " \"Toys \\\"R\\\" \"Toys \\\"R\\\" U \"Toys \\\"R\\\" U s \"Toys \\\"R\\\" Us \"Toys \\\"R\\\" Us $ \"Toys \\\"R\\\" Us $ 2 \"Toys \\\"R\\\" Us $2 5 \"Toys \\\"R\\\" Us $25 0 \"Toys \\\"R\\\" Us $250 \"Toys \\\"R\\\" Us $250 G \"Toys \\\"R\\\" Us $250 G i \"Toys \\\"R\\\" Us $250 Gi f \"Toys \\\"R\\\" Us $250 Gif t \"Toys \\\"R\\\" Us $250 Gift \ \"Toys \\\"R\\\" Us $250 Gift\ " \"Toys \\\"R\\\" Us $250 Gift\" \"Toys \\\"R\\\" Us $250 Gift\" < \"Toys \\\"R\\\" Us $250 Gift\" < o \"Toys \\\"R\\\" Us $250 Gift\" \"Toys \\\"R\\\" Us $250 Gift\" %\"Toys \\"R\\" Us $250 Gift\" % [root@maildance scripts]# Help!!! Thank you. Marilyn Davis From rick at niof.net Sun Oct 31 23:05:22 2004 From: rick at niof.net (Rick Pasotto) Date: Sun Oct 31 23:05:28 2004 Subject: [Tutor] escape-quoting strings In-Reply-To: References: Message-ID: <20041031220522.GK31976@niof.net> On Sun, Oct 31, 2004 at 01:53:42PM -0800, Marilyn Davis wrote: > Hi Python Tutors, > > I'm having a devil of a time quoting strings properly for MySql. You example did not include any MySql statements. How are you sending the string to MySql? -- "I don't want to get to the end of my life and find that I lived just the length of it. I want to have lived the width of it as well." -- Diane Ackerman Rick Pasotto rick@niof.net http://www.niof.net