From rdm at rcblue.com Sat Mar 1 00:13:34 2008 From: rdm at rcblue.com (Dick Moores) Date: Fri, 29 Feb 2008 15:13:34 -0800 Subject: [Tutor] How to open IE7 to a certain URL? In-Reply-To: References: Message-ID: <20080229231340.C7E111E4022@bag.python.org> At 02:09 PM 2/29/2008, J?nos Juh?sz wrote: > > > I've got this so far: > > > > > > #!/usr/bin/env python > > > #coding=utf-8 > > > import time > > > b = '20:00:00' > > > while True: > > > a = time.strftime('%H:%M:%S') > > > time.sleep(0.5) > > > if a == b: > > > print "TIME!" > > > break > > > > >It needn't to make this comparison in every 0.5 seconds. >Calculate how long to sleep and ask that from the pc. > > >import time >b = '20:00:00' > >(bhour, bmin, bsec) = b.split(':') >bsec = int(bsec) + int(bmin)*60 + int(bhour)*360 > >while True: > act = time.localtime() > actsec = act.tm_sec + act.tm_min*60 + act.tm_hour*360 > wait = bsec - actsec > if wait < 0: > wait += 360*24 # it will be tomorrow > time.sleep(wait) > print 'I am doing!' > break Ah, very nice! (But all the '360's should be '3600', of course.) Thanks, Janos. Dick From alan.gauld at btinternet.com Sat Mar 1 00:29:02 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 29 Feb 2008 23:29:02 -0000 Subject: [Tutor] Need help with encoder & decryption keys References: <64017.68.191.136.241.1204324249.squirrel@webmail.opmstech.org> Message-ID: "Trey Keown" wrote > from being isolated, and messages being intercepted. So... is it > possible to decompile things within a .pyc file? Yes its definitely possible and in fact not even difficult - the tools come with Python. Do not do that if you want real security. Use a separate data file and put the encryption there. Alan G From kent37 at tds.net Sat Mar 1 00:54:42 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 29 Feb 2008 18:54:42 -0500 Subject: [Tutor] Need help with encoder & decryption keys In-Reply-To: <64017.68.191.136.241.1204324249.squirrel@webmail.opmstech.org> References: <64017.68.191.136.241.1204324249.squirrel@webmail.opmstech.org> Message-ID: <47C89B42.7000705@tds.net> Trey Keown wrote: > is it > possible to decompile things within a .pyc file? Yes, it is possible. There is a commercial service that will do this, for older versions of Python at least. To figure out a secret key kept in a .pyc file it might be enough to disassemble functions in the module; that can be done with the standard dis module. And of course if you stored the secrets as module globals all you have to do is import the module and print the value... Kent From rdm at rcblue.com Sat Mar 1 01:15:07 2008 From: rdm at rcblue.com (Dick Moores) Date: Fri, 29 Feb 2008 16:15:07 -0800 Subject: [Tutor] How to open IE7 to a certain URL? In-Reply-To: <20080229231340.C7E111E4022@bag.python.org> References: <20080229231340.C7E111E4022@bag.python.org> Message-ID: <20080301001512.BC7B71E4009@bag.python.org> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080229/45b14991/attachment.htm From keridee at jayco.net Sat Mar 1 01:25:40 2008 From: keridee at jayco.net (Tiger12506) Date: Fri, 29 Feb 2008 19:25:40 -0500 Subject: [Tutor] How to open IE7 to a certain URL? References: <20080229231340.C7E111E4022@bag.python.org> Message-ID: <003401c87b32$cb1fa890$a8fce004@jslaptop> time.sleep is not exactly accurate, so I would suggest that you use this method, short 5 minutes or so and then do a sleep(10) or so in a loop to get closer to the time. >>import time >>b = '20:00:00' >> >>(bhour, bmin, bsec) = b.split(':') >>bsec = int(bsec) + int(bmin)*60 + int(bhour)*360 >> >>while True: >> act = time.localtime() >> actsec = act.tm_sec + act.tm_min*60 + act.tm_hour*360 >> wait = bsec - actsec >> if wait < 0: >> wait += 360*24 # it will be tomorrow >> time.sleep(wait) >> print 'I am doing!' >> break > > Ah, very nice! (But all the '360's should be '3600', of course.) > > Thanks, Janos. > > Dick > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From cfuller084 at thinkingplanet.net Sat Mar 1 01:48:02 2008 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Fri, 29 Feb 2008 18:48:02 -0600 Subject: [Tutor] How to open IE7 to a certain URL? In-Reply-To: <003401c87b32$cb1fa890$a8fce004@jslaptop> References: <20080229231340.C7E111E4022@bag.python.org> <003401c87b32$cb1fa890$a8fce004@jslaptop> Message-ID: <200802291848.02261.cfuller084@thinkingplanet.net> On Friday 29 February 2008 18:25, Tiger12506 wrote: > time.sleep is not exactly accurate, so I would suggest that you use this > method, short 5 minutes or so and then do a sleep(10) or so in a loop to > get closer to the time. Another advantage to shorter sleeps is it reduces the latency of anything else your program needs to do, such as exit gracefully, reschedule the event, or whatever. Not too short, because that uses more CPU time. It also makes a difference if the clock gets reset :) Cheers From cfuller084 at thinkingplanet.net Sat Mar 1 01:33:22 2008 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Fri, 29 Feb 2008 18:33:22 -0600 Subject: [Tutor] How to open IE7 to a certain URL? In-Reply-To: <20080229182455.B37301E4003@bag.python.org> References: <20080229122924.14F8D1E4003@bag.python.org> <200802291040.10710.cfuller@thinkingplanet.net> <20080229182455.B37301E4003@bag.python.org> Message-ID: <200802291833.23009.cfuller084@thinkingplanet.net> I left out the daily increment. there should be a event_time += 86400 end of the inner loop. while True: while time() References: <20080229122924.14F8D1E4003@bag.python.org> <200802291040.10710.cfuller@thinkingplanet.net> <20080229182455.B37301E4003@bag.python.org> Message-ID: <200802291811.14209.cfuller@thinkingplanet.net> On Friday 29 February 2008 12:24, Dick Moores wrote: > http://www.kuow.org/real.ram . Try this to start, then turn into a service with FireDaemon, http://www.firedaemon.com/. You'll need to fill in the quit() function, and the particulars for your media player. from time import mktime, strftime, strptime, localtime, time, sleep # return true if the program should exit def quit(): pass import subprocess def launch(): args = ( 'c:\\pathto\\cmd', 'http://www.kuow.org/real.ram' ) subprocess.call(args) # get the seconds since epoch of midnight, add the desired time of day, # and convert back into seconds since epoch. We'll wake up just a bit # early, so we can use a coarser timer. event_time = mktime(strptime(strftime('%Y%m%d', localtime(time()))+'19:59:40','%Y%m%d%H:%M:%S')) while True: while time()file tranfer Message-ID: Hello, I have a modem connect to my Windows XP PC through a serial cable. I Want to transfer the file(e.g '.TXT' format) from XP PC to serial modem and also from Serial modem to winXP PC. Can anybody help me out how to do it in Python and provide some sample code or useful links so that I can proceed further in my project?? All help will be highly appreciated. Thanks & Regards, Govind -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080301/8631d5de/attachment.htm From kent37 at tds.net Sat Mar 1 14:01:14 2008 From: kent37 at tds.net (Kent Johnson) Date: Sat, 01 Mar 2008 08:01:14 -0500 Subject: [Tutor] serial -->file tranfer In-Reply-To: References: Message-ID: <47C9539A.3050207@tds.net> govind goyal wrote: > Hello, > > I have a modem connect to my Windows XP PC through a serial cable. > I Want to transfer the file(e.g '.TXT' format) from XP PC to serial > modem and also > from Serial modem to winXP PC. > > Can anybody help me out how to do it in Python and provide some sample > code or useful links > so that I can proceed further in my project?? http://pyserial.sourceforge.net/ The enhancedserial example looks pretty close to what you need: http://pyserial.cvs.sourceforge.net/pyserial/pyserial/examples/enhancedserial.py?revision=1.1&view=markup Kent From ricaraoz at gmail.com Sat Mar 1 17:15:23 2008 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Sat, 01 Mar 2008 13:15:23 -0300 Subject: [Tutor] comparison bug in python (or do I not get it?) In-Reply-To: References: <47C806C5.4060409@tds.net> Message-ID: <47C9811B.6090806@bigfoot.com> Hans Fangohr wrote: > Hi Kent, > >> Hans Fangohr wrote: >> >>> In [2]: 2 in [1,2,3] == True >>> Out[2]: False >>> >>> Why does [2] return False? Would people agree that this is a bug? >> No, not a bug. Don't be too quick to blame your tools! > > That's good news. I'd be worried if this wasn't the desired behaviour > -- I just hadn't understood the logic. > >> The equivalent expression is >> In [1]: (2 in [1,2,3]) and ([1,2,3]==False) >> Out[1]: False > > Ah -- that's the way to read it! > >> 'in' is considered a comparison operator and can be chained with other >> comparisons. For a clearer example, consider >> In [2]: 2 < 3 < 4 >> Out[2]: True >> >> which is not the same as >> In [3]: 2 < (3 < 4) >> Out[3]: False >> >> or >> In [4]: (2 < 3) < 4 >> Out[4]: True >> >> It is equivalent to >> In [5]: (2 < 3) and (3 < 4) >> Out[5]: True >> > > Well explained -- makes perfect sense now. > Just one further question : >>> 1 == True True >>> 5 == True False and yet >>> if 5 : print 'True' True I thought a non-zero or non-empty was evaluated as True. Now in the 5 == True line I'm not saying "5 is True", shouldn't it evaluate just like the "if" statement? From kent37 at tds.net Sat Mar 1 16:39:41 2008 From: kent37 at tds.net (Kent Johnson) Date: Sat, 01 Mar 2008 10:39:41 -0500 Subject: [Tutor] comparison bug in python (or do I not get it?) In-Reply-To: <47C9811B.6090806@bigfoot.com> References: <47C806C5.4060409@tds.net> <47C9811B.6090806@bigfoot.com> Message-ID: <47C978BD.3030908@tds.net> Ricardo Ar?oz wrote: > >>> 1 == True > True Yes, True is an integer with value 1. Actually True is a bool but bool is a subclass of int: In [3]: type(True) Out[3]: In [4]: isinstance(True, int) Out[4]: True In [5]: int(True) Out[5]: 1 > >>> 5 == True > False Right, because 5 != 1 > and yet > > >>> if 5 : print 'True' > True > > > I thought a non-zero or non-empty was evaluated as True. Yes, in a boolean context 5 is evaluated as True: In [7]: bool(5) Out[7]: True From the docs: In the context of Boolean operations, and also when expressions are used by control flow statements, the following values are interpreted as false: False, None, numeric zero of all types, and empty strings and containers (including strings, tuples, lists, dictionaries, sets and frozensets). All other values are interpreted as true. http://docs.python.org/ref/Booleans.html#Booleans Now in the 5 == > True line I'm not saying "5 is True", shouldn't it evaluate just like > the "if" statement? No. When you say if 5: you are implicitly converting 5 to a boolean and the 'non-zero evaluates to True' rule applies. When you say if 5 == True: you are explicitly comparing the two values and 5 is not converted to boolean. From the docs: The operators <, >, ==, >=, <=, and != compare the values of two objects. The objects need not have the same type. If both are numbers, they are converted to a common type. http://docs.python.org/ref/comparisons.html The first one is equivalent to if bool(5): while the second one is if 5 == int(True): Kent From kent37 at tds.net Sat Mar 1 16:41:29 2008 From: kent37 at tds.net (Kent Johnson) Date: Sat, 01 Mar 2008 10:41:29 -0500 Subject: [Tutor] Need help with encoder & decryption keys In-Reply-To: <60638.68.191.136.241.1204337336.squirrel@webmail.opmstech.org> References: <64017.68.191.136.241.1204324249.squirrel@webmail.opmstech.org> <47C89B42.7000705@tds.net> <60638.68.191.136.241.1204337336.squirrel@webmail.opmstech.org> Message-ID: <47C97929.3020704@tds.net> Trey Keown wrote: > mmm... So, what would be an effective way to hide the data's key? > I'm kind of new to the whole encryption scene, although I've had some > experience with it whilst working on homebrew software on gaming > platforms. I don't know, I'm not a crypto expert. I guess it depends partly on what you are trying to do. I do have a little experience with SSH, it stores keys in files in the filesystem and relies on the OS to protect them from unauthorized access. Kent PS Please use Reply All to reply to the list. From cfuller084 at thinkingplanet.net Sat Mar 1 18:13:08 2008 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Sat, 1 Mar 2008 11:13:08 -0600 Subject: [Tutor] Need help with encoder & decryption keys In-Reply-To: <64017.68.191.136.241.1204324249.squirrel@webmail.opmstech.org> References: <64017.68.191.136.241.1204324249.squirrel@webmail.opmstech.org> Message-ID: <200803011113.08775.cfuller084@thinkingplanet.net> On Friday 29 February 2008 16:30, Trey Keown wrote: > Hey all, > Been away for a while. So, I'm in the process of making a program for > encrypting and decrypting strings of text. And I was wondering how it > would be possible to perhaps keep keys in a .pyc file, and keep them > from being isolated, and messages being intercepted. So... is it > possible to decompile things within a .pyc file? > This isn't for any serius project, just me attempting to make something > to prove that I can do it. > > Thanks for any help. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor The best you can do is to make it tricky to reverse engineer. ?Same goes for compiled code or assembly, only those are admittedly closer to the "bare metal". ?Java and C# Care also "byte-compiled" languages, and I think Java has some security features, although I don't know what they are. Don't use a fixed constant. ?Compute the key, and spread the dependencies around. ?You could mix in a deterministic random number generator. Of course, this is all useless if your program can be inspected while its running. ?It's impossible, in principle, really, when the recipient of the secret message and the eavesdropper are the same entity. Still, unless you have determined adversaries, it won't be worth the trouble. ? Plenty good enough for casual use, but don't bet national security on it or anything. Cheers From bgailer at alum.rpi.edu Sat Mar 1 19:27:00 2008 From: bgailer at alum.rpi.edu (bob gailer) Date: Sat, 01 Mar 2008 13:27:00 -0500 Subject: [Tutor] comparison bug in python (or do I not get it?) In-Reply-To: <47C9811B.6090806@bigfoot.com> References: <47C806C5.4060409@tds.net> <47C9811B.6090806@bigfoot.com> Message-ID: <47C99FF4.3010804@alum.rpi.edu> Ricardo Ar?oz wrote: > Just one further question : > > >>> 1 == True > True > >>> 5 == True > False > > and yet > > >>> if 5 : print 'True' > True > > > I thought a non-zero or non-empty was evaluated as True. Now in the 5 == > True line I'm not saying "5 is True", shouldn't it evaluate just like > the "if" statement? Python Library Reference: 3.1 Truth Value Testing: Any object can be tested for truth value, for use in an if or while condition or as operand of the Boolean operations below. The following values are considered false: None False zero of any numeric type, for example, 0, 0L, 0.0, 0j. any empty sequence, for example, '', (), []. any empty mapping, for example, {}. instances of user-defined classes, if the class defines a __nonzero__() or __len__() method, when that method returns the integer zero or bool value False.3.1 All other values are considered true -- so objects of many types are always true. -- Bob Gailer 919-636-4239 Chapel Hill, NC From varsha.purohit at gmail.com Sun Mar 2 17:12:02 2008 From: varsha.purohit at gmail.com (Varsha Purohit) Date: Sun, 2 Mar 2008 08:12:02 -0800 Subject: [Tutor] [tutor] Finding image statistics Message-ID: Hello All, i have an application where i am comparing two images and highlighting the difference part in a separate image. I am using ImageChops subtract method. Here is the code: file1=Image.open("./pics/original.jpg") file2=Image.open(val) diff = ImageChops.subtract(file1,file2,0.3) diff.save("./pics/diff"+".jpg") I found ImageStat module of pil but i am not sure how to use the methods of this module in this application. I want to find other image statistics such as finding number of pixels which exist after taking difference between two images, getting sum of all pixels and area of pixels that are in that image etc. please guide me regarding this... thanks, -- Varsha Purohit, Graduate Student -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080302/93b28231/attachment.htm From kent37 at tds.net Sun Mar 2 18:02:26 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 02 Mar 2008 12:02:26 -0500 Subject: [Tutor] [tutor] Finding image statistics In-Reply-To: References: Message-ID: <47CADDA2.4070101@tds.net> Varsha Purohit wrote: > of this module in this application. > > I want to find other image statistics such as finding number of pixels > which exist after taking difference between two images, getting sum of > all pixels and area of pixels that are in that image etc. I don't think you can get all of that out of ImageStat, it is pretty basic. In [18]: import Image, ImageStat In [19]: i=Image.open('kent.jpg') In [21]: s=ImageStat.Stat(i) In [23]: s.extrema Out[23]: [(0, 255), (0, 255), (0, 251)] In [24]: s.count Out[24]: [43200, 43200, 43200] In [25]: s.mean Out[25]: [116.61453703703704, 103.23967592592592, 97.624606481481479] etc. Kent From varsha.purohit at gmail.com Sun Mar 2 18:48:24 2008 From: varsha.purohit at gmail.com (Varsha Purohit) Date: Sun, 2 Mar 2008 09:48:24 -0800 Subject: [Tutor] [tutor] Finding image statistics In-Reply-To: <47CADDA2.4070101@tds.net> References: <47CADDA2.4070101@tds.net> Message-ID: Yes i am getting this but i was confused why i am getting 3 values for count, extrema.. and dats y i couldn't figure out how to find area of those pixels...... On Sun, Mar 2, 2008 at 9:02 AM, Kent Johnson wrote: > Varsha Purohit wrote: > > of this module in this application. > > > > I want to find other image statistics such as finding number of pixels > > which exist after taking difference between two images, getting sum of > > all pixels and area of pixels that are in that image etc. > > I don't think you can get all of that out of ImageStat, it is pretty > basic. > > In [18]: import Image, ImageStat > In [19]: i=Image.open('kent.jpg') > In [21]: s=ImageStat.Stat(i) > In [23]: s.extrema > Out[23]: [(0, 255), (0, 255), (0, 251)] > In [24]: s.count > Out[24]: [43200, 43200, 43200] > In [25]: s.mean > Out[25]: [116.61453703703704, 103.23967592592592, 97.624606481481479] > > etc. > > Kent > -- Varsha Purohit, Graduate Student -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080302/9502ca66/attachment.htm From kent37 at tds.net Sun Mar 2 23:01:02 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 02 Mar 2008 17:01:02 -0500 Subject: [Tutor] [tutor] Finding image statistics In-Reply-To: References: <47CADDA2.4070101@tds.net> Message-ID: <47CB239E.8050509@tds.net> Varsha Purohit wrote: > Yes i am getting this but i was confused why i am getting 3 values for > count, extrema.. and dats y i couldn't figure out how to find area of > those pixels...... From the docs: "The following attributes contain a sequence with one element for each layer in the image. " So the three values are for the red, green and blue components (assuming you have an RGB image). What pixels do you want the area of? Wouldn't that just be the pixel count times the pixel size (which you would have to know independently from the geometry of the camera and scene)? Kent From varsha.purohit at gmail.com Mon Mar 3 01:09:15 2008 From: varsha.purohit at gmail.com (Varsha Purohit) Date: Sun, 2 Mar 2008 16:09:15 -0800 Subject: [Tutor] [tutor] Finding image statistics In-Reply-To: References: <47CADDA2.4070101@tds.net> Message-ID: I am getting this list as an output [268541.0, 264014.0, 324155.0] Actually in my code i am finding difference between two images and i need to count the number of pixels which appear as a difference of these two images. These values i m getting as output are little large. i m pasting my code again.... file1=Image.open("./pics/original.jpg") file2=Image.open(val) diff = ImageChops.subtract(file1,file2,0.3) stat1 = ImageStat.Stat(diff) count1=stat1.sum print count1 diff.save("./pics/diff"+".jpg") diff.show() AS you can see i am finding difference of two images which are nearly identical. But they have some pixels that are different and i can see that in the output image diff.jpg. So i am trying to put this difference image in the imagestat and trying to see if i can get to count the number of pixels ....... thanks, On Sun, Mar 2, 2008 at 9:48 AM, Varsha Purohit wrote: > Yes i am getting this but i was confused why i am getting 3 values for > count, extrema.. and dats y i couldn't figure out how to find area of those > pixels...... > > > On Sun, Mar 2, 2008 at 9:02 AM, Kent Johnson wrote: > > > Varsha Purohit wrote: > > > of this module in this application. > > > > > > I want to find other image statistics such as finding number of pixels > > > which exist after taking difference between two images, getting sum of > > > all pixels and area of pixels that are in that image etc. > > > > I don't think you can get all of that out of ImageStat, it is pretty > > basic. > > > > In [18]: import Image, ImageStat > > In [19]: i=Image.open('kent.jpg') > > In [21]: s=ImageStat.Stat(i) > > In [23]: s.extrema > > Out[23]: [(0, 255), (0, 255), (0, 251)] > > In [24]: s.count > > Out[24]: [43200, 43200, 43200] > > In [25]: s.mean > > Out[25]: [116.61453703703704, 103.23967592592592, 97.624606481481479] > > > > etc. > > > > Kent > > > > > > -- > Varsha Purohit, > Graduate Student -- Varsha Purohit, Graduate Student -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080302/8b1a2cac/attachment.htm From kent37 at tds.net Mon Mar 3 01:45:33 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 02 Mar 2008 19:45:33 -0500 Subject: [Tutor] [tutor] Finding image statistics In-Reply-To: References: <47CADDA2.4070101@tds.net> Message-ID: <47CB4A2D.1000109@tds.net> Varsha Purohit wrote: > I am getting this list as an output > > [268541.0, 264014.0, 324155.0] This is the sum of the values of the red pixels, etc. They are not counts, but sums. So if you have an image with the two pixels (1, 2, 3), (4, 5, 6) you would get a sum of (5, 7, 9). > > Actually in my code i am finding difference between two images and i > need to count the number of pixels which appear as a difference of these > two images. These values i m getting as output are little large. So you want a count of the number of pixels that differ between the two images? Maybe this: diff = ImageChops.difference(file1, file2) # Convert to grayscale so differences are counted just once per pixel diff = ImageOps.grayscale(diff) # Convert each difference to 0 or 1 so we can count them # Clipping function def clip(x): return 1 if x >= 1 else 0 # Apply the clipping function diff = Image.eval(diff, clip) print ImageStat.Stat(diff).sum Kent > > i m pasting my code again.... > > file1=Image.open("./pics/original.jpg") > file2=Image.open(val) > diff = ImageChops.subtract(file1,file2,0.3) > stat1 = ImageStat.Stat(diff) > > count1=stat1.sum > print count1 > diff.save("./pics/diff"+".jpg") > > diff.show() > > AS you can see i am finding difference of two images which are nearly > identical. But they have some pixels that are different and i can see > that in the output image diff.jpg. So i am trying to put this difference > image in the imagestat and trying to see if i can get to count the > number of pixels ....... From andreas at kostyrka.org Mon Mar 3 14:28:11 2008 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Mon, 03 Mar 2008 14:28:11 +0100 Subject: [Tutor] Need help with encoder & decryption keys In-Reply-To: <47C89B42.7000705@tds.net> References: <64017.68.191.136.241.1204324249.squirrel@webmail.opmstech.org> <47C89B42.7000705@tds.net> Message-ID: <47CBFCEB.1000106@kostyrka.org> And if it's a string constant, in many cases running strings (Unix program) on the pyc file will reveal it too. All this basically turns down to the problem, that it's hard to embed an encryption key in a program, so that it's not possible to extract it. Notice the the current crop of HDDVD/Blueray decrypters, that tend to derive their copy of the key by extracting it from legal software players. (Hint: it's a basically unsolvable problem, notice how the industry "solved" it by making that kind of analysis illegal, DMCA is the hint here.) If you want to have "typical" C program security for embedded key data, the only thing that you can do is to make a Pyrex module (Which gets compiled to C, and is loaded as an .so shared library). As pointed out above, this is not really safe, it just makes it slightly harder to extract the data. Some thoughts: 1.) the data cannot be made accessible to Python, or else you can read it out. That means decryption/encryption needs to be done in Pyrex/C. PLUS Pyrex should not use any Python functions/modules to achieve the goal. (import secretmodule ; print secretmodule.value. OR: import md5 ; md5.md5 = myLoggingMd5Replacement ) 2.) the stuff done in your C module cannot be to trivial, or an attacker that is determinated can easily remove references to the module. So to summarize: Your idea usually makes no sense. It clearly falls into the "know what you are doing and why" ** n category, with n > 1 ;) There might be technical or legal reasons to do that, BUT they are really, really seldom. And this category question is usually not really appropriate for a tutoring mailing list :) The only way to make sure something is not compromised is to avoid giving it out completely, and put it on your own servers. Again, the above thoughts apply. Plus consider that your program is running in an environment that you do not control: E.g. even if you communicate via SSL and check certificates, and embed the CA certificate into your app so that it cannot be easily replaced. Consider loading a small wrapper for SSL_read/SSL_write via LD_PRELOAD. Oops, the user just learned the complete clear text of your communication. Worse if it's to simple he can just replace the data, worst case by loading a wrapper around openssl that mimics the server. It's no fun, and the easiest way is to give your users the access (e.g. the source code). This stops the crowd that has to prove itself for the fun of breaking a security system. (And yes, there are people that do that). Then put your rules into the LICENSE. That lays out the rules what is allowed. And in some cases, add some lines that check "licenses", so a customer cannot claim that he ran your program unauthorized by mistake. Not much more you can do here, sorry. Making it hard to remove the license check means just that the fun crowd might get motivated into breaking it. Leaving out at least some checks means that users can claim that they ran a copy of your program by mistake. That might have legal ramifications, and worse, in many cases (if you are not a member of BSA), you wouldn't want to sue a customer anyway, right? (Nothing surer to piss off a customer than to sue him.) Andreas Kent Johnson wrote: > Trey Keown wrote: >> is it >> possible to decompile things within a .pyc file? > > Yes, it is possible. There is a commercial service that will do this, > for older versions of Python at least. > > To figure out a secret key kept in a .pyc file it might be enough to > disassemble functions in the module; that can be done with the standard > dis module. > > And of course if you stored the secrets as module globals all you have > to do is import the module and print the value... > > Kent > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From andreas at kostyrka.org Mon Mar 3 14:31:35 2008 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Mon, 03 Mar 2008 14:31:35 +0100 Subject: [Tutor] Need help with encoder & decryption keys In-Reply-To: <47C97929.3020704@tds.net> References: <64017.68.191.136.241.1204324249.squirrel@webmail.opmstech.org> <47C89B42.7000705@tds.net> <60638.68.191.136.241.1204337336.squirrel@webmail.opmstech.org> <47C97929.3020704@tds.net> Message-ID: <47CBFDB7.5020700@kostyrka.org> Well, actually, ssh can also protect private keys with a cryptographic pass phrase. But this is often not what is wanted as it implies that the user needs to provide the pass phrase every time it is used. (Well, that's not the complete truth, man ssh-agent, but that's completely different thing ;) ) Andreas Kent Johnson wrote: > Trey Keown wrote: > >> mmm... So, what would be an effective way to hide the data's key? >> I'm kind of new to the whole encryption scene, although I've had some >> experience with it whilst working on homebrew software on gaming >> platforms. > > I don't know, I'm not a crypto expert. I guess it depends partly on what > you are trying to do. > > I do have a little experience with SSH, it stores keys in files in the > filesystem and relies on the OS to protect them from unauthorized access. > > Kent > > PS Please use Reply All to reply to the list. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From eric at abrahamsen.com Mon Mar 3 15:19:42 2008 From: eric at abrahamsen.com (Eric Abrahamsen) Date: Mon, 3 Mar 2008 22:19:42 +0800 Subject: [Tutor] sorting objects on two attributes Message-ID: I have a grisly little sorting problem to which I've hacked together a solution, but I'm hoping someone here might have a better suggestion. I have a list of objects, each of which has two attributes, object_id and submit_date. What I want is to sort them by content_type, then by submit_date within content_type, and then sort each content_type block according to which block has the newest object by submit_date. (This sequence of sorting might not be optimal, I'm not sure). I'm actually creating a list of recent comments on blog entries for a python-based web framework, and want to arrange the comments according to blog entry (content_type), by submit_date within that entry, with the entries with the newest comments showing up on top. I don't believe a single cmp function fed to list.sort() can do this, because you can't know how two objects should be compared until you know all the values for all the objects. I'd be happy to be proven wrong here. After some false starts with dictionaries, here's what I've got. Queryset is the original list of comments (I'm doing this in django), and it returns a list of lists, though I might flatten it afterwards. It works, but it's ghastly unreadable and if there were a more graceful solution I'd feel better about life in general: def make_com_list(queryset): ids = set([com.object_id for com in queryset]) xlist = [[com for com in queryset if com.object_id == i] for i in ids] for ls in xlist: ls.sort(key=lambda x: x.submit_date) xlist.sort(key=lambda x: max([com.submit_date for com in x]), reverse=True) return xlist I'd appreciate any hints! Thanks, Eric From andreas at kostyrka.org Mon Mar 3 15:42:43 2008 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Mon, 03 Mar 2008 15:42:43 +0100 Subject: [Tutor] sorting objects on two attributes In-Reply-To: References: Message-ID: <1204555363.9927.13.camel@localhost> Well, this assumes that all named attributes do exist. If not, you need to replace x.attr with getattr(x, "attr", defaultvalue) ;) l.sort(key=lambda x: (x.content_type, x.submit_date)) Now, you can construct a sorted list "t": t = [] for key, item_iterator in itertools.groupby(l, key=lambda x: (x.content_type, x.submit_date)): sorted_part = sorted(item_iterator, key=lambda x: x.submit_date) t.append((sorted_part[-1].submit_date, key, sorted_part)) t.sort() t = sum([x[2] for x in t], []) Totally untested, as written in the MTA :) Andreas Am Montag, den 03.03.2008, 22:19 +0800 schrieb Eric Abrahamsen: > I have a grisly little sorting problem to which I've hacked together a > solution, but I'm hoping someone here might have a better suggestion. > > I have a list of objects, each of which has two attributes, object_id > and submit_date. What I want is to sort them by content_type, then by > submit_date within content_type, and then sort each content_type block > according to which block has the newest object by submit_date. (This > sequence of sorting might not be optimal, I'm not sure). I'm actually > creating a list of recent comments on blog entries for a python-based > web framework, and want to arrange the comments according to blog > entry (content_type), by submit_date within that entry, with the > entries with the newest comments showing up on top. > > I don't believe a single cmp function fed to list.sort() can do this, > because you can't know how two objects should be compared until you > know all the values for all the objects. I'd be happy to be proven > wrong here. > > After some false starts with dictionaries, here's what I've got. > Queryset is the original list of comments (I'm doing this in django), > and it returns a list of lists, though I might flatten it afterwards. > It works, but it's ghastly unreadable and if there were a more > graceful solution I'd feel better about life in general: > > > def make_com_list(queryset): > ids = set([com.object_id for com in queryset]) > xlist = [[com for com in queryset if com.object_id == i] for i in > ids] > for ls in xlist: > ls.sort(key=lambda x: x.submit_date) > xlist.sort(key=lambda x: max([com.submit_date for com in x]), > reverse=True) > return xlist > > I'd appreciate any hints! > > Thanks, > Eric > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Dies ist ein digital signierter Nachrichtenteil Url : http://mail.python.org/pipermail/tutor/attachments/20080303/7ca5901e/attachment.pgp From kent37 at tds.net Mon Mar 3 17:00:20 2008 From: kent37 at tds.net (Kent Johnson) Date: Mon, 03 Mar 2008 11:00:20 -0500 Subject: [Tutor] sorting objects on two attributes In-Reply-To: References: Message-ID: <47CC2094.70300@tds.net> Eric Abrahamsen wrote: > I have a list of objects, each of which has two attributes, object_id > and submit_date. What I want is to sort them by content_type, then by > submit_date within content_type, and then sort each content_type block > according to which block has the newest object by submit_date. (This > sequence of sorting might not be optimal, I'm not sure). I'm actually > creating a list of recent comments on blog entries for a python-based > web framework, and want to arrange the comments according to blog > entry (content_type), by submit_date within that entry, with the > entries with the newest comments showing up on top. This description doesn't match your code. There is no content_type in the code. I think what you want to do is group the comments by object_id, sort within each object_id group by submit_date, then sort the groups by most recent submit date. > I don't believe a single cmp function fed to list.sort() can do this, > because you can't know how two objects should be compared until you > know all the values for all the objects. I'd be happy to be proven > wrong here. Django's SortedDict might help. Perhaps this: from operator import attrgetter from django.utils.datastructures import SortedDict sd = SortedDict() for com in sorted(queryset, key=attrgetter.submit_date, reverse=True): sd.setdefault(com.object.id, []).append(com) Now sd.keys() is a list of object_ids in descending order by most recent comment, and sd[object_id] is a list of comments for object_id, also in descending order by submit_date. If you want the comments in increasing date order (which I think your code below does) then you have to reverse the lists of comments, e.g. for l in sd.values(): l.reverse() or just reverse at the point of use with the reversed() iterator. > def make_com_list(queryset): > ids = set([com.object_id for com in queryset]) > xlist = [[com for com in queryset if com.object_id == i] for i in > ids] > for ls in xlist: > ls.sort(key=lambda x: x.submit_date) > xlist.sort(key=lambda x: max([com.submit_date for com in x]), > reverse=True) No need for max() since the list is sorted; use key=lambda x: x[-1].submit_date Kent From kent37 at tds.net Mon Mar 3 17:06:08 2008 From: kent37 at tds.net (Kent Johnson) Date: Mon, 03 Mar 2008 11:06:08 -0500 Subject: [Tutor] sorting objects on two attributes In-Reply-To: <1204555363.9927.13.camel@localhost> References: <1204555363.9927.13.camel@localhost> Message-ID: <47CC21F0.5040209@tds.net> Andreas Kostyrka wrote: > l.sort(key=lambda x: (x.content_type, x.submit_date)) > > Now, you can construct a sorted list "t": > > t = [] > for key, item_iterator in itertools.groupby(l, key=lambda x: (x.content_type, x.submit_date)): > sorted_part = sorted(item_iterator, key=lambda x: x.submit_date) > t.append((sorted_part[-1].submit_date, key, sorted_part)) I think you mean for key, item_iterator in itertools.groupby(l, key=lambda x: (x.content_type)): # Group by content type only sorted_part = list(item_iterator) # No need to sort again t.append((sorted_part[-1].submit_date, key, sorted_part)) Kent From cfuller084 at thinkingplanet.net Mon Mar 3 17:11:12 2008 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Mon, 3 Mar 2008 10:11:12 -0600 Subject: [Tutor] sorting objects on two attributes In-Reply-To: <1204555363.9927.13.camel@localhost> References: <1204555363.9927.13.camel@localhost> Message-ID: <200803031011.12422.cfuller084@thinkingplanet.net> Almost. And better than my original idea. You could have a hierarchical sort function: def hiersort(a,b): if a.attr1 != b.attr1: return cmp(a.attr1, b.attr1) else: if a.attr2 != b.attr2: return cmp(a.attr2, b.attr2) else: return cmp(a.attr3, b.att3) l.sort(hiersort) You can keep nesting for more than three attributes, or you could make it arbitrary by setting it up recursively and setting the attribute hierarchy as a parameter somewhere. But that's probably unnecessarily fancy. Cheers On Monday 03 March 2008 08:42, Andreas Kostyrka wrote: > Well, this assumes that all named attributes do exist. If not, you need > to replace x.attr with getattr(x, "attr", defaultvalue) ;) > > > l.sort(key=lambda x: (x.content_type, x.submit_date)) > > Now, you can construct a sorted list "t": > > t = [] > for key, item_iterator in itertools.groupby(l, key=lambda x: > (x.content_type, x.submit_date)): sorted_part = sorted(item_iterator, > key=lambda x: x.submit_date) t.append((sorted_part[-1].submit_date, key, > sorted_part)) > > t.sort() > > t = sum([x[2] for x in t], []) > > Totally untested, as written in the MTA :) > > Andreas > > Am Montag, den 03.03.2008, 22:19 +0800 schrieb Eric Abrahamsen: > > I have a grisly little sorting problem to which I've hacked together a > > solution, but I'm hoping someone here might have a better suggestion. > > > > I have a list of objects, each of which has two attributes, object_id > > and submit_date. What I want is to sort them by content_type, then by > > submit_date within content_type, and then sort each content_type block > > according to which block has the newest object by submit_date. (This > > sequence of sorting might not be optimal, I'm not sure). I'm actually > > creating a list of recent comments on blog entries for a python-based > > web framework, and want to arrange the comments according to blog > > entry (content_type), by submit_date within that entry, with the > > entries with the newest comments showing up on top. > > > > I don't believe a single cmp function fed to list.sort() can do this, > > because you can't know how two objects should be compared until you > > know all the values for all the objects. I'd be happy to be proven > > wrong here. > > > > After some false starts with dictionaries, here's what I've got. > > Queryset is the original list of comments (I'm doing this in django), > > and it returns a list of lists, though I might flatten it afterwards. > > It works, but it's ghastly unreadable and if there were a more > > graceful solution I'd feel better about life in general: > > > > > > def make_com_list(queryset): > > ids = set([com.object_id for com in queryset]) > > xlist = [[com for com in queryset if com.object_id == i] for i in > > ids] > > for ls in xlist: > > ls.sort(key=lambda x: x.submit_date) > > xlist.sort(key=lambda x: max([com.submit_date for com in x]), > > reverse=True) > > return xlist > > > > I'd appreciate any hints! > > > > Thanks, > > Eric > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor From kent37 at tds.net Mon Mar 3 17:34:35 2008 From: kent37 at tds.net (Kent Johnson) Date: Mon, 03 Mar 2008 11:34:35 -0500 Subject: [Tutor] sorting objects on two attributes In-Reply-To: <200803031011.12422.cfuller084@thinkingplanet.net> References: <1204555363.9927.13.camel@localhost> <200803031011.12422.cfuller084@thinkingplanet.net> Message-ID: <47CC289B.7000004@tds.net> Chris Fuller wrote: > You could have a hierarchical sort > function: > > def hiersort(a,b): > if a.attr1 != b.attr1: > return cmp(a.attr1, b.attr1) > else: > if a.attr2 != b.attr2: > return cmp(a.attr2, b.attr2) > else: > return cmp(a.attr3, b.att3) > > > l.sort(hiersort) That is exactly what l.sort(key=lambda x: (x.attr1, x.attr2, x.attr3)) does, except the key= version is simpler and most likely faster. You can also use l.sort(key=operator.attrgetter('attr1', 'attr2', 'attr3')) > You can keep nesting for more than three attributes, or you could make it > arbitrary by setting it up recursively and setting the attribute hierarchy as > a parameter somewhere. But that's probably unnecessarily fancy. l.sort(key=operator.attrgetter(*list_of_attribute_names)) should work... Kent From goldwamh at slu.edu Mon Mar 3 17:56:54 2008 From: goldwamh at slu.edu (Michael H. Goldwasser) Date: Mon, 3 Mar 2008 10:56:54 -0600 Subject: [Tutor] sorting objects on two attributes In-Reply-To: References: Message-ID: <18380.11734.27255.896563@Michael-Goldwassers-Computer.local> Hello Eric, Your basic outlook is fine, but you can do it much more efficiently with a single sort. Here's the way I'd approach the task (untested): # -------------------------------------------------- # first compute the latest date for each id group; uses O(n) time newest = {} for q in queryset: id,date = q.object_id, q.submit_date if id not in newest or date > newest[id]: newest[id] = date # now sort based on the following decorator as a key data.sort(reverse=True, key=lambda x: (newest[x.object_id], x.object_id, x.submit_date)) # -------------------------------------------------- In essence, you compute the max date within each group, but your approach (i.e., building explicit sublists and then repeatedly calling max on those sublists) is far more time-consuming than the above dictionary based approach. Note well that using a tuple as a decorator key is more efficient than calling sort separately for each subgroup. The lexicographical order of the following (newest[x.object_id], x.object_id, x.submit_date) should produce the order that you desire. The reason for the middle entry is to ensure that items groups by object_id in the case that two different groups achieve the same maximum date. It wasn't clear to me whether you wanted elements within groups from oldest to newest or newest to oldest. I believe that the code I give produces the ordering that you intend, but you may adjust the sign of the decorate elements if necessary. With regard, Michael +----------------------------------------------- | Michael Goldwasser | Associate Professor | Dept. Mathematics and Computer Science | Saint Louis University | 220 North Grand Blvd. | St. Louis, MO 63103-2007 On Monday March 3, 2008, Eric Abrahamsen wrote: > I have a grisly little sorting problem to which I've hacked together a > solution, but I'm hoping someone here might have a better suggestion. > > I have a list of objects, each of which has two attributes, object_id > and submit_date. What I want is to sort them by content_type, then by > submit_date within content_type, and then sort each content_type block > according to which block has the newest object by submit_date. (This > sequence of sorting might not be optimal, I'm not sure). I'm actually > creating a list of recent comments on blog entries for a python-based > web framework, and want to arrange the comments according to blog > entry (content_type), by submit_date within that entry, with the > entries with the newest comments showing up on top. > > I don't believe a single cmp function fed to list.sort() can do this, > because you can't know how two objects should be compared until you > know all the values for all the objects. I'd be happy to be proven > wrong here. > > After some false starts with dictionaries, here's what I've got. > Queryset is the original list of comments (I'm doing this in django), > and it returns a list of lists, though I might flatten it afterwards. > It works, but it's ghastly unreadable and if there were a more > graceful solution I'd feel better about life in general: > > > def make_com_list(queryset): > ids = set([com.object_id for com in queryset]) > xlist = [[com for com in queryset if com.object_id == i] for i in > ids] > for ls in xlist: > ls.sort(key=lambda x: x.submit_date) > xlist.sort(key=lambda x: max([com.submit_date for com in x]), > reverse=True) > return xlist > > I'd appreciate any hints! > > Thanks, > Eric > From varsha.purohit at gmail.com Mon Mar 3 18:46:48 2008 From: varsha.purohit at gmail.com (Varsha Purohit) Date: Mon, 3 Mar 2008 09:46:48 -0800 Subject: [Tutor] [tutor] Finding image statistics In-Reply-To: <47CB4A2D.1000109@tds.net> References: <47CADDA2.4070101@tds.net> <47CB4A2D.1000109@tds.net> Message-ID: Yeahh so by doing this i am counting only the difference part since we have grayscaled the image and assuming it will count only the pixels that evolve as difference.... if i use sum2 instead of sum i think it will give squared sum which is area... and if i just use count it would count the number of pixels developed like that... sounds interesting .. thanks for throwing light for me in right direction.... On Sun, Mar 2, 2008 at 4:45 PM, Kent Johnson wrote: > Varsha Purohit wrote: > > I am getting this list as an output > > > > [268541.0, 264014.0, 324155.0] > > This is the sum of the values of the red pixels, etc. They are not > counts, but sums. So if you have an image with the two pixels > (1, 2, 3), (4, 5, 6) you would get a sum of (5, 7, 9). > > > > Actually in my code i am finding difference between two images and i > > need to count the number of pixels which appear as a difference of these > > two images. These values i m getting as output are little large. > > So you want a count of the number of pixels that differ between the two > images? Maybe this: > > diff = ImageChops.difference(file1, file2) > > # Convert to grayscale so differences are counted just once per pixel > diff = ImageOps.grayscale(diff) > > # Convert each difference to 0 or 1 so we can count them > # Clipping function > def clip(x): > return 1 if x >= 1 else 0 > > # Apply the clipping function > diff = Image.eval(diff, clip) > > print ImageStat.Stat(diff).sum > > Kent > > > > > i m pasting my code again.... > > > > file1=Image.open("./pics/original.jpg") > > file2=Image.open(val) > > diff = ImageChops.subtract(file1,file2,0.3) > > stat1 = ImageStat.Stat(diff) > > > > count1=stat1.sum > > print count1 > > diff.save("./pics/diff"+".jpg") > > > > diff.show() > > > > AS you can see i am finding difference of two images which are nearly > > identical. But they have some pixels that are different and i can see > > that in the output image diff.jpg. So i am trying to put this difference > > image in the imagestat and trying to see if i can get to count the > > number of pixels ....... > > -- Varsha Purohit, Graduate Student -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080303/17bd7b3f/attachment.htm From kent37 at tds.net Mon Mar 3 20:55:58 2008 From: kent37 at tds.net (Kent Johnson) Date: Mon, 03 Mar 2008 14:55:58 -0500 Subject: [Tutor] [tutor] Finding image statistics In-Reply-To: References: <47CADDA2.4070101@tds.net> <47CB4A2D.1000109@tds.net> Message-ID: <47CC57CE.8060202@tds.net> Varsha Purohit wrote: > Yeahh so by doing this i am counting only the difference part since we > have grayscaled the image and assuming it will count only the pixels > that evolve as difference.... Yes > if i use sum2 instead of sum i think it > will give squared sum which is area... and if i just use count it would > count the number of pixels developed like that... sounds interesting .. > thanks for throwing light for me in right direction.... No. First, pixels are already a measure of area. Second, if each pixel value is 0 or 1, squaring the values won't make any difference. Kent From marshall.jiang at gmail.com Tue Mar 4 03:07:35 2008 From: marshall.jiang at gmail.com (Shuai Jiang (Runiteking1)) Date: Mon, 3 Mar 2008 21:07:35 -0500 Subject: [Tutor] Python and displaying mathematical equations? Message-ID: Hello, I'm trying to create an application that retrieves and displays (probably in HTML or PDF format) math problems from a database. The problem is that I need some sort of mechanism to display mathematical equations. I'm trying to not use Latex as it would cause the users to install Latex (and most likely dvipng) on their own computers. Is there a lighter version of Latex for Python or do I have to just use Latex? Thanks! Marshall Jiang -- Visit my blog at runiteking1.blogspot.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080303/25fb3905/attachment.htm From john at fouhy.net Tue Mar 4 03:15:32 2008 From: john at fouhy.net (John Fouhy) Date: Tue, 4 Mar 2008 15:15:32 +1300 Subject: [Tutor] Python and displaying mathematical equations? In-Reply-To: References: Message-ID: <5e58f2e40803031815t736e6807y60cef965ed6ef830@mail.gmail.com> On 04/03/2008, Shuai Jiang (Runiteking1) wrote: > Hello, I'm trying to create an application that retrieves and displays > (probably in HTML or PDF format) math problems from a database. > The problem is that I need some sort of mechanism to display mathematical > equations. If you can describe your equations in MathML then there may be options for you -- a quick google for "python mathml" turned up a few hits -- e.g. http://sourceforge.net/projects/pymathml/ or http://www.grigoriev.ru/svgmath/ (if you accept SVG as an output). -- John. From eric at abrahamsen.com Tue Mar 4 03:50:25 2008 From: eric at abrahamsen.com (Eric Abrahamsen) Date: Tue, 4 Mar 2008 10:50:25 +0800 Subject: [Tutor] sorting objects on two attributes In-Reply-To: <18380.11734.27255.896563@Michael-Goldwassers-Computer.local> References: <18380.11734.27255.896563@Michael-Goldwassers-Computer.local> Message-ID: <51DFD99C-0B28-45DA-8D37-A6654D1AD266@abrahamsen.com> Well I expected to learn a thing or two, but I didn't expect not to understand the suggestions at all! :) Thanks to everyone who responded, and sorry for the typo (it was meant to be object_id throughout, not content_type). So far Michael's solution works and is most comprehensible to me ? ie I stand a fighting chance of figuring it out. I didn't realize you could make direct use of SortedDicts in django, so that's worth a try, too. Itertools.groupby is totally impenetrable to me, but works as well! Is there any consensus about which might go faster? I will go right now and google until my brain is full. Thanks again, Eric On Mar 4, 2008, at 12:56 AM, Michael H. Goldwasser wrote: > > > Hello Eric, > > Your basic outlook is fine, but you can do it much more efficiently > with a single sort. Here's the way I'd approach the task > (untested): > > # -------------------------------------------------- > # first compute the latest date for each id group; uses O(n) time > newest = {} > for q in queryset: > id,date = q.object_id, q.submit_date > if id not in newest or date > newest[id]: > newest[id] = date > > # now sort based on the following decorator as a key > data.sort(reverse=True, key=lambda x: (newest[x.object_id], > x.object_id, x.submit_date)) > # -------------------------------------------------- > > In essence, you compute the max date within each group, but your > approach (i.e., building explicit sublists and then repeatedly > calling max on those sublists) is far more time-consuming than the > above dictionary based approach. > > Note well that using a tuple as a decorator key is more efficient > than calling sort separately for each subgroup. The > lexicographical order of the following > > (newest[x.object_id], x.object_id, x.submit_date) > > should produce the order that you desire. The reason for the middle > entry is to ensure that items groups by object_id in the case that > two different groups achieve the same maximum date. It wasn't clear > to me whether you wanted elements within groups from oldest to > newest or newest to oldest. I believe that the code I give produces > the ordering that you intend, but you may adjust the sign of the > decorate elements if necessary. > > With regard, > Michael > > +----------------------------------------------- > | Michael Goldwasser > | Associate Professor > | Dept. Mathematics and Computer Science > | Saint Louis University > | 220 North Grand Blvd. > | St. Louis, MO 63103-2007 > > > On Monday March 3, 2008, Eric Abrahamsen wrote: > >> I have a grisly little sorting problem to which I've hacked >> together a >> solution, but I'm hoping someone here might have a better >> suggestion. >> >> I have a list of objects, each of which has two attributes, >> object_id >> and submit_date. What I want is to sort them by content_type, >> then by >> submit_date within content_type, and then sort each content_type >> block >> according to which block has the newest object by submit_date. >> (This >> sequence of sorting might not be optimal, I'm not sure). I'm >> actually >> creating a list of recent comments on blog entries for a python- >> based >> web framework, and want to arrange the comments according to blog >> entry (content_type), by submit_date within that entry, with the >> entries with the newest comments showing up on top. >> >> I don't believe a single cmp function fed to list.sort() can do >> this, >> because you can't know how two objects should be compared until you >> know all the values for all the objects. I'd be happy to be proven >> wrong here. >> >> After some false starts with dictionaries, here's what I've got. >> Queryset is the original list of comments (I'm doing this in >> django), >> and it returns a list of lists, though I might flatten it >> afterwards. >> It works, but it's ghastly unreadable and if there were a more >> graceful solution I'd feel better about life in general: >> >> >> def make_com_list(queryset): >> ids = set([com.object_id for com in queryset]) >> xlist = [[com for com in queryset if com.object_id == i] for >> i in >> ids] >> for ls in xlist: >> ls.sort(key=lambda x: x.submit_date) >> xlist.sort(key=lambda x: max([com.submit_date for com in x]), >> reverse=True) >> return xlist >> >> I'd appreciate any hints! >> >> Thanks, >> Eric >> > From kent37 at tds.net Tue Mar 4 04:04:32 2008 From: kent37 at tds.net (Kent Johnson) Date: Mon, 03 Mar 2008 22:04:32 -0500 Subject: [Tutor] sorting objects on two attributes In-Reply-To: <51DFD99C-0B28-45DA-8D37-A6654D1AD266@abrahamsen.com> References: <18380.11734.27255.896563@Michael-Goldwassers-Computer.local> <51DFD99C-0B28-45DA-8D37-A6654D1AD266@abrahamsen.com> Message-ID: <47CCBC40.1010907@tds.net> Eric Abrahamsen wrote: > Itertools.groupby is totally impenetrable to me Maybe this will help: http://personalpages.tds.net/~kent37/blog/arch_m1_2005_12.html#e69 Kent From eric at abrahamsen.com Tue Mar 4 04:44:32 2008 From: eric at abrahamsen.com (Eric Abrahamsen) Date: Tue, 4 Mar 2008 11:44:32 +0800 Subject: [Tutor] sorting objects on two attributes In-Reply-To: <47CCBC40.1010907@tds.net> References: <18380.11734.27255.896563@Michael-Goldwassers-Computer.local> <51DFD99C-0B28-45DA-8D37-A6654D1AD266@abrahamsen.com> <47CCBC40.1010907@tds.net> Message-ID: On Mar 4, 2008, at 11:04 AM, Kent Johnson wrote: > Eric Abrahamsen wrote: >> Itertools.groupby is totally impenetrable to me > > Maybe this will help: > http://personalpages.tds.net/~kent37/blog/arch_m1_2005_12.html#e69 > > Kent > It did! Thanks very much. I think I understand now what's going on in the groupby line. And then this line: t.append((sorted_part[-1].submit_date, key, sorted_part)) is basically a Decorate-Sort-Undecorate operation, sorting on sorted_part[-1].submit_date because that's guaranteed to be the latest date in each group? It's starting to come clear... From kent37 at tds.net Tue Mar 4 13:27:26 2008 From: kent37 at tds.net (Kent Johnson) Date: Tue, 04 Mar 2008 07:27:26 -0500 Subject: [Tutor] sorting objects on two attributes In-Reply-To: <47CC21F0.5040209@tds.net> References: <1204555363.9927.13.camel@localhost> <47CC21F0.5040209@tds.net> Message-ID: <47CD402E.5090007@tds.net> Here is a version based on Andreas' solution using groupby() that avoids the decorate-undecorate by using the key= parameter for the second sort: l.sort(key=lambda x: (x.content_type, x.submit_date)) t = [ list(items) for key, items in itertools.groupby(l, key=lambda x: (x.content_type)) ] t.sort(key=lambda x: x[-1].submit_date, x[-1].object_id) Kent From rdm at rcblue.com Tue Mar 4 14:05:48 2008 From: rdm at rcblue.com (Dick Moores) Date: Tue, 04 Mar 2008 05:05:48 -0800 Subject: [Tutor] Translate this VB.NET code into Python for me? Message-ID: <20080304130635.D16391E400E@bag.python.org> I thought I'd dip into .NET by downloading the free Microsoft Visual Basic 2005 Express Edition, and start working through _Beginning Visual Basic 2005 Express Edition_, by Peter Wright (Apress). By the second chapter I've begun to suspect that GUIs aside, Python is a lot simpler to write. Could someone prove that to me by translating the code I've pasted at (from pp. 51-54 of the book), which prints Butch barks Mac yips Butch snarls at you in a menacing fashion. Mac licks you all over, then drools on you. in the console? I'd sure appreciate it, and it might be another bit of good PR for Python. Please use classes in your translation. Thanks, Dick Moores From malaclypse2 at gmail.com Tue Mar 4 16:10:50 2008 From: malaclypse2 at gmail.com (Jerry Hill) Date: Tue, 4 Mar 2008 10:10:50 -0500 Subject: [Tutor] Translate this VB.NET code into Python for me? In-Reply-To: <20080304130635.D16391E400E@bag.python.org> References: <20080304130635.D16391E400E@bag.python.org> Message-ID: <16651e80803040710t750f16bfieee635b5553f910c@mail.gmail.com> On Tue, Mar 4, 2008 at 8:05 AM, Dick Moores wrote: > By the second chapter I've begun to suspect that GUIs aside, Python > is a lot simpler to write. Could someone prove that to me by > translating the code I've pasted at > (from pp. 51-54 of the > book), which prints This code is pretty straightforward to translate into python. It's pretty short so, I've pasted it inline: import sys class Dog(object): def __init__(self, name, sound="barks"): self.name = name self.sound = sound def bark(self): print "%s %s" % (self.name, self.sound) def do_your_thing(self): raise NotImplementedError class Rottweiler(Dog): def do_your_thing(self): print "%s snarls at you in a menacing fashion." % self.name class Spaniel(Dog): def do_your_thing(self): print "%s licks you all over, then drools on you." % self.name if __name__ == "__main__": butch = Rottweiler("Butch") mac = Spaniel("Mac", "yips") butch.bark() mac.bark() butch.do_your_thing() mac.do_your_thing() sys.stdin.readline() It's probably more pythonic to not define the Dog.do_your_thing() method at all than to raise the NotImplementedError, but I think that this way mirrors the VB code a bit better. I don't think there's a good way to mark the entire Dog class as abstract in python, which I think is what the VB code does with the "MustInherit Class Dog" line. -- Jerry From alan.gauld at btinternet.com Tue Mar 4 19:05:08 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 4 Mar 2008 18:05:08 -0000 Subject: [Tutor] Translate this VB.NET code into Python for me? References: <20080304130635.D16391E400E@bag.python.org> Message-ID: "Dick Moores" wrote in message news:20080304130635.D16391E400E at bag.python.org... >I thought I'd dip into .NET by downloading the free Microsoft Visual > Basic 2005 Express Edition, and start working through _Beginning > Visual Basic 2005 Express Edition_, by Peter Wright (Apress). > > By the second chapter I've begun to suspect that GUIs aside, Python > is a lot simpler to write. It depends, there are other areas where VB is at least comparable to Python, especially in manipulating the Windows OS and using COM features etc. > Could someone prove that to me by translating the code I've pasted Jerry has done a fine job of that but it doesn't really prove much since as he says VB has a few features that Python doesn't directly support (and vice versa). But also console level apps are exactly where Python is strong and VB weak so this kind of example proves that Python is better for simple OOP code using a CLI. You could do a GUI example and use IronPython to show how it copes with GUI code. Since IP can access the same GUI library as VB.NET they should be very similar in code structure. I would expect VB.NET to always be at least a bit more verbose than Python because of its heritage, but in basic concepts, as your example shows, it can do pretty much the same kinds of things as Python (but with a much smaller standard library!). HTH, -- Alan Gauld Author of the Learn to Program web site Temorarily at: http://uk.geocities.com/alan.gauld at btinternet.com/ Normally: http://www.freenetpages.co.uk/hp/alan.gauld From washakie at gmail.com Tue Mar 4 23:03:18 2008 From: washakie at gmail.com (washakie) Date: Tue, 4 Mar 2008 14:03:18 -0800 (PST) Subject: [Tutor] help with slice Message-ID: <15837808.post@talk.nabble.com> Could someone please explain 'slices' also for dictionaries? basically, I'd like to know how you would call every 3rd element in a list of lists... My logic says: ThirdElems=List[:][2] Which to me reads, for every item in List (which are lists), return the third item. but this doesn't work. Thanks! -- View this message in context: http://www.nabble.com/help-with-slice-tp15837808p15837808.html Sent from the Python - tutor mailing list archive at Nabble.com. From allen.fowler at yahoo.com Tue Mar 4 23:10:57 2008 From: allen.fowler at yahoo.com (Allen Fowler) Date: Tue, 4 Mar 2008 14:10:57 -0800 (PST) Subject: [Tutor] Video file metadata? (MP4/WMV) Message-ID: <130286.49653.qm@web45610.mail.sp1.yahoo.com> Hello, I have several hundred WMV video files with bad embedded author/title/date information. However, the correct information is correctly encoded in the file name.. i.e. "title-author-date.wmv" Seems like the a great job for Python. :) Also, I am about to convert these fiiles to MP4 for use on an iPod. The video software I am using will, I think, transfer the metadata from the WMV to the new MP4 files. So, two questions: 1) Does these exist a python module I can use to programatically edit the metadata in MP4 files? 2) Failing that, is there a python module I can use to edit the metadata in the WMV files? (hopeing the data makes it through the conversion..) -- Thank you ____________________________________________________________________________________ Be a better friend, newshound, and know-it-all with Yahoo! Mobile. Try it now. http://mobile.yahoo.com/;_ylt=Ahu06i62sR8HDtDypao8Wcj9tAcJ From andreas at kostyrka.org Tue Mar 4 23:26:56 2008 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Tue, 04 Mar 2008 23:26:56 +0100 Subject: [Tutor] Video file metadata? (MP4/WMV) In-Reply-To: <130286.49653.qm@web45610.mail.sp1.yahoo.com> References: <130286.49653.qm@web45610.mail.sp1.yahoo.com> Message-ID: <1204669616.14387.5.camel@localhost> Don't think so. Do you have any cmdline tool to update the meta data? Alternativly you can naturally embed Win32 components and control them with Python, but I'm not a Windows guy. Andreas Am Dienstag, den 04.03.2008, 14:10 -0800 schrieb Allen Fowler: > Hello, > > I have several hundred WMV video files with bad embedded author/title/date information. > > However, the correct information is correctly encoded in the file name.. i.e. "title-author-date.wmv" > > Seems like the a great job for Python. :) > > Also, I am about to convert these fiiles to MP4 for use on an iPod. The video software I am using will, I think, transfer the metadata from the WMV to the new MP4 files. > > So, two questions: > > 1) Does these exist a python module I can use to programatically edit the metadata in MP4 > files? > > 2) Failing that, is there a python module I can use to edit the > metadata in the WMV files? (hopeing the data makes it through the > conversion..) > > -- Thank you > > > > > > ____________________________________________________________________________________ > Be a better friend, newshound, and > know-it-all with Yahoo! Mobile. Try it now. http://mobile.yahoo.com/;_ylt=Ahu06i62sR8HDtDypao8Wcj9tAcJ > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Dies ist ein digital signierter Nachrichtenteil Url : http://mail.python.org/pipermail/tutor/attachments/20080304/3aa3031c/attachment.pgp From andreas at kostyrka.org Tue Mar 4 23:28:53 2008 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Tue, 04 Mar 2008 23:28:53 +0100 Subject: [Tutor] help with slice In-Reply-To: <15837808.post@talk.nabble.com> References: <15837808.post@talk.nabble.com> Message-ID: <1204669733.14387.8.camel@localhost> What you probably want is: [elem_list[2] for elem_list in List] If you are not sure that the list have at least three elements, you can use something like this: [(elem_list + [None, None, None])[2] for elem_list in List] Which will use None as a default value. Andreas Am Dienstag, den 04.03.2008, 14:03 -0800 schrieb washakie: > Could someone please explain 'slices' also for dictionaries? > > basically, I'd like to know how you would call every 3rd element in a list > of lists... > > My logic says: ThirdElems=List[:][2] > > Which to me reads, for every item in List (which are lists), return the > third item. > but this doesn't work. > > Thanks! -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Dies ist ein digital signierter Nachrichtenteil Url : http://mail.python.org/pipermail/tutor/attachments/20080304/79d467ce/attachment.pgp From tjampman at gmail.com Wed Mar 5 00:24:12 2008 From: tjampman at gmail.com (Ole Henning Jensen) Date: Wed, 05 Mar 2008 00:24:12 +0100 Subject: [Tutor] help with slice In-Reply-To: <1204669733.14387.8.camel@localhost> References: <15837808.post@talk.nabble.com> <1204669733.14387.8.camel@localhost> Message-ID: <47CDDA1C.9020402@gmail.com> > Could someone please explain 'slices' also for dictionaries? > > basically, I'd like to know how you would call every 3rd element in a list > of lists... > > My logic says: ThirdElems=List[:][2] > What this does is, just assign the 3 value of List to the variable. look at this way, step by step. >>> lst = range(10) # Generate a list >>> print lst[:] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> lst == lst[:] True ## So lst[:] is really (sort of) just the same list >>> lst[:][2] 2 # So lst[:][ is basically the same as lst[2] > Which to me reads, for every item in List (which are lists), return the > third item. > but this doesn't work. What you need to do is loop all the way through your list and then only do something to every third element in the list This is an example of a for loop, that prints out every 3 element: >>> lst = ["hello", "sweet", "world", "goodbye", "sweet", "world"] >>> for index in lst: if index % 3 == 0: print lst[index] hello goodbye Best Regards Ole H. Jensen From bgailer at alum.rpi.edu Wed Mar 5 01:13:44 2008 From: bgailer at alum.rpi.edu (bob gailer) Date: Tue, 04 Mar 2008 19:13:44 -0500 Subject: [Tutor] help with slice In-Reply-To: <15837808.post@talk.nabble.com> References: <15837808.post@talk.nabble.com> Message-ID: <47CDE5B8.3080407@alum.rpi.edu> washakie wrote: > Could someone please explain 'slices' also for dictionaries? > > basically, I'd like to know how you would call every 3rd element in a list > of lists... > > My logic says: ThirdElems=List[:][2] > > Which to me reads, for every item in List (which are lists), return the > third item. > That is wishful reading. No basis in reality. List[:] gives you a shallow copy of List. [2] then refers to the 3rd element of that copy. Try: [sublist[2] for sublist in List] -- Bob Gailer 919-636-4239 Chapel Hill, NC From bgailer at alum.rpi.edu Wed Mar 5 01:20:31 2008 From: bgailer at alum.rpi.edu (bob gailer) Date: Tue, 04 Mar 2008 19:20:31 -0500 Subject: [Tutor] help with slice In-Reply-To: <47CDE5B8.3080407@alum.rpi.edu> References: <15837808.post@talk.nabble.com> <47CDE5B8.3080407@alum.rpi.edu> Message-ID: <47CDE74F.3000108@alum.rpi.edu> bob gailer wrote: > washakie wrote: > >> Could someone please explain 'slices' also for dictionaries? >> >> basically, I'd like to know how you would call every 3rd element in a list >> of lists... >> Call? Do you mean that these elements are callable objects (e.g. functions) which you want to "call", or are you just trying to get a list of the elements? My answer below addresses the 2nd meaning. >> My logic says: ThirdElems=List[:][2] >> >> Which to me reads, for every item in List (which are lists), return the >> third item. >> >> > That is wishful reading. No basis in reality. List[:] gives you a > shallow copy of List. [2] then refers to the 3rd element of that copy. > > Try: [sublist[2] for sublist in List] > > -- Bob Gailer 919-636-4239 Chapel Hill, NC From alan.gauld at btinternet.com Wed Mar 5 01:24:45 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 5 Mar 2008 00:24:45 -0000 Subject: [Tutor] help with slice References: <15837808.post@talk.nabble.com> Message-ID: "washakie" wrote > Could someone please explain 'slices' also for dictionaries? So far as I know slices don;t work for dictionaries directly - dictionaries don't have the concept of order. However you could get a list of keys and apply a slice to that, although I'm not sure how it would ever be useful. > basically, I'd like to know how you would call every 3rd element in > a list > of lists... > > My logic says: ThirdElems=List[:][2] > Which to me reads, for every item in List (which are lists), return > the > third item.but this doesn't work. This actually says take a copy of the list and give me the 3rd element of that copy. You need to use a list comprehension: thirds = [sublist[2] for sublist in myList] HTH, -- Alan Gauld Author of the Learn to Program web site Temorarily at: http://uk.geocities.com/alan.gauld at btinternet.com/ Normally: http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Wed Mar 5 01:29:31 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 5 Mar 2008 00:29:31 -0000 Subject: [Tutor] help with slice References: <15837808.post@talk.nabble.com><1204669733.14387.8.camel@localhost> <47CDDA1C.9020402@gmail.com> Message-ID: "Ole Henning Jensen" wrote > What you need to do is loop all the way through your list and then > only > do something to every third element in the list That's not quite what the OP asked for, he wanted the third element from every sublist in the master list > This is an example of a for loop, that prints out every 3 element: You can do this using slicing, no need for a for loop L = range(10) print L{2::3] the 2 is the start position - the 3rd element, then the final 3 is the step size, giving every third element up to the end of the list. Interesting maybe, but not what the OP asked for. -- Alan Gauld Author of the Learn to Program web site Temorarily at: http://uk.geocities.com/alan.gauld at btinternet.com/ Normally: http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Wed Mar 5 01:32:01 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 5 Mar 2008 00:32:01 -0000 Subject: [Tutor] Video file metadata? (MP4/WMV) References: <130286.49653.qm@web45610.mail.sp1.yahoo.com> Message-ID: "Allen Fowler" wrote in > 1) Does these exist a python module I can use to > programatically edit the metadata in MP4 > files? I don;t know of one but if you can find the spec it might be easy enough to just edit the files using normal (binary) file handling methods. I've certainly done that for MIDI files. -- Alan Gauld Author of the Learn to Program web site Temorarily at: http://uk.geocities.com/alan.gauld at btinternet.com/ Normally: http://www.freenetpages.co.uk/hp/alan.gauld From rdm at rcblue.com Wed Mar 5 02:23:27 2008 From: rdm at rcblue.com (Dick Moores) Date: Tue, 04 Mar 2008 17:23:27 -0800 Subject: [Tutor] Translate this VB.NET code into Python for me? In-Reply-To: <16651e80803040710t750f16bfieee635b5553f910c@mail.gmail.com > References: <20080304130635.D16391E400E@bag.python.org> <16651e80803040710t750f16bfieee635b5553f910c@mail.gmail.com> Message-ID: <20080305012335.4A3151E4007@bag.python.org> At 07:10 AM 3/4/2008, Jerry Hill wrote: >On Tue, Mar 4, 2008 at 8:05 AM, Dick Moores wrote: > > By the second chapter I've begun to suspect that GUIs aside, Python > > is a lot simpler to write. Could someone prove that to me by > > translating the code I've pasted at > > (from pp. 51-54 of the > > book), which prints > >This code is pretty straightforward to translate into python. It's >pretty short so, I've pasted it inline: > >import sys > >class Dog(object): > def __init__(self, name, sound="barks"): > self.name = name > self.sound = sound > def bark(self): > print "%s %s" % (self.name, self.sound) > def do_your_thing(self): > raise NotImplementedError > >class Rottweiler(Dog): > def do_your_thing(self): > print "%s snarls at you in a menacing fashion." % self.name > >class Spaniel(Dog): > def do_your_thing(self): > print "%s licks you all over, then drools on you." % self.name > >if __name__ == "__main__": > butch = Rottweiler("Butch") > mac = Spaniel("Mac", "yips") > > butch.bark() > mac.bark() > > butch.do_your_thing() > mac.do_your_thing() > sys.stdin.readline() > >It's probably more pythonic to not define the Dog.do_your_thing() >method at all than to raise the NotImplementedError, but I think that >this way mirrors the VB code a bit better. I don't think there's a >good way to mark the entire Dog class as abstract in python, which I >think is what the VB code does with the "MustInherit Class Dog" line. Thanks VERY much, Jerry Dick From rdm at rcblue.com Wed Mar 5 02:58:20 2008 From: rdm at rcblue.com (Dick Moores) Date: Tue, 04 Mar 2008 17:58:20 -0800 Subject: [Tutor] Translate this VB.NET code into Python for me? In-Reply-To: References: <20080304130635.D16391E400E@bag.python.org> Message-ID: <20080305015832.727D71E4007@bag.python.org> At 10:05 AM 3/4/2008, Alan Gauld wrote: >"Dick Moores" wrote in message >news:20080304130635.D16391E400E at bag.python.org... > >I thought I'd dip into .NET by downloading the free Microsoft Visual > > Basic 2005 Express Edition, and start working through _Beginning > > Visual Basic 2005 Express Edition_, by Peter Wright (Apress). > > > > By the second chapter I've begun to suspect that GUIs aside, Python > > is a lot simpler to write. > >It depends, there are other areas where VB is at least comparable >to Python, especially in manipulating the Windows OS and using >COM features etc. > > > Could someone prove that to me by translating the code I've pasted > >Jerry has done a fine job of that but it doesn't really prove much >since >as he says VB has a few features that Python doesn't directly >support (and vice versa). But also console level apps are exactly >where Python is strong and VB weak so this kind of example >proves that Python is better for simple OOP code using a CLI. > >You could do a GUI example and use IronPython to show how >it copes with GUI code. You surely don't mean that I could. :-) But could someone on the Tutor list, the IPython-user list, or the python-win32 list? Good idea. I'll give it a try after a bit. >Since IP can access the same GUI >library as VB.NET they should be very similar in code structure. I dug up this paragraph from the new book on IPython due out in Sept. '08: "IronPython uses .NET classes natively and seamlessly, and there are a lot of them. Two of the gems in the collection are Windows Forms and the Windows Presentation Foundation, which are excellent libraries for building attractive and native looking user interfaces. As a Python programmer, you may be surprised by how straightforward the programmers interface to these libraries feels. Whatever programming task you are approaching, it is likely that there is some .NET assembly available to tackle it. This includes third party libraries for sophisticated GUI components, like data grids, where there is nothing comparable available for CPython. Table 1.1 shows a small selection of the libraries available to you in the .NET framework." (The last paragraph on p.12 of the the free chapter 1 in PDF form: ) >I would expect VB.NET to always be at least a bit more >verbose than Python because of its heritage, but in basic >concepts, as your example shows, it can do pretty much the >same kinds of things as Python (but with a much smaller >standard library!). > >HTH, Sure does! Thanks, Alan. Dick From marshall.jiang at gmail.com Wed Mar 5 02:59:18 2008 From: marshall.jiang at gmail.com (Shuai Jiang (Runiteking1)) Date: Tue, 4 Mar 2008 20:59:18 -0500 Subject: [Tutor] Python and displaying mathematical equations? In-Reply-To: <5e58f2e40803031815t736e6807y60cef965ed6ef830@mail.gmail.com> References: <5e58f2e40803031815t736e6807y60cef965ed6ef830@mail.gmail.com> Message-ID: Never even knew about MathML... stupid me. My Firefox browser can't handle the MathML test page quite well, can't show the root sign. Thank you very much! On Mon, Mar 3, 2008 at 9:15 PM, John Fouhy wrote: > On 04/03/2008, Shuai Jiang (Runiteking1) wrote: > > Hello, I'm trying to create an application that retrieves and displays > > (probably in HTML or PDF format) math problems from a database. > > The problem is that I need some sort of mechanism to display > mathematical > > equations. > > If you can describe your equations in MathML then there may be options > for you -- a quick google for "python mathml" turned up a few hits -- > e.g. http://sourceforge.net/projects/pymathml/ or > http://www.grigoriev.ru/svgmath/ (if you accept SVG as an output). > > -- > John. > -- Visit my blog at runiteking1.blogspot.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080304/543f5b1b/attachment.htm From allen.fowler at yahoo.com Wed Mar 5 04:04:13 2008 From: allen.fowler at yahoo.com (Allen Fowler) Date: Tue, 4 Mar 2008 19:04:13 -0800 (PST) Subject: [Tutor] Video file metadata? (MP4/WMV) Message-ID: <165921.42026.qm@web45615.mail.sp1.yahoo.com> I can't seem to find a simple description of the MP4 sepc... it might be because there is not one. :) That being said, what is the correct way to parse binary files in Python? ----- Original Message ---- > From: Alan Gauld > To: tutor at python.org > Sent: Tuesday, March 4, 2008 7:32:01 PM > Subject: Re: [Tutor] Video file metadata? (MP4/WMV) > > > "Allen Fowler" wrote in > > > 1) Does these exist a python module I can use to > > programatically edit the metadata in MP4 > > files? > > I don;t know of one but if you can find the spec it might > be easy enough to just edit the files using normal (binary) > file handling methods. I've certainly done that for MIDI files. > > > -- > Alan Gauld > Author of the Learn to Program web site > Temorarily at: > http://uk.geocities.com/alan.gauld at btinternet.com/ > Normally: > http://www.freenetpages.co.uk/hp/alan.gauld > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > ____________________________________________________________________________________ Be a better friend, newshound, and know-it-all with Yahoo! Mobile. Try it now. http://mobile.yahoo.com/;_ylt=Ahu06i62sR8HDtDypao8Wcj9tAcJ From alan.gauld at btinternet.com Wed Mar 5 09:48:02 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 5 Mar 2008 08:48:02 -0000 Subject: [Tutor] Video file metadata? (MP4/WMV) References: <165921.42026.qm@web45615.mail.sp1.yahoo.com> Message-ID: "Allen Fowler" wrote > That being said, what is the correct way to parse binary files in > Python? The safest way is to open in binary mode and use read() to get the data then use the struct module to decode the data into python objects. There is a very basic intro to this at the end of my file handling topic in my tutorial. -- Alan Gauld Author of the Learn to Program web site Temorarily at: http://uk.geocities.com/alan.gauld at btinternet.com/ Normally: http://www.freenetpages.co.uk/hp/alan.gauld From ian at showmedo.com Wed Mar 5 10:15:08 2008 From: ian at showmedo.com (Ian Ozsvald) Date: Wed, 05 Mar 2008 09:15:08 +0000 Subject: [Tutor] Video file metadata? (MP4/WMV) In-Reply-To: <130286.49653.qm@web45610.mail.sp1.yahoo.com> References: <130286.49653.qm@web45610.mail.sp1.yahoo.com> Message-ID: <47CE649C.4060309@showmedo.com> Hi Allen. I don't know of a Python module but I believe that ffmpeg will do what you want. Inside ShowMeDo I start it using os.spawnv and I use Python to do some processing on ffmpeg's output. We use it to transcode incoming AVI/MOVs to .FLV files. This would be more involved than just using a module. I've never looked at ffmpeg's handling of metadata but looking at the help I see: ian at ian-desktop:~$ ffmpeg ... -title string set the title -timestamp time set the timestamp -author string set the author -copyright string set the copyright -comment string set the comment -album string set the album ... which might be what you're after? You should also be able to use ffmpeg for automated conversion to MP4. The only drawback is that ffmpeg might not understand the most recent WMV formats (WMV9 if memory serves) as Microsoft won't open the spec. HTH, Ian. Allen Fowler wrote: > Hello, > > I have several hundred WMV video files with bad embedded author/title/date information. > > However, the correct information is correctly encoded in the file name.. i.e. "title-author-date.wmv" > > Seems like the a great job for Python. :) > > Also, I am about to convert these fiiles to MP4 for use on an iPod. The video software I am using will, I think, transfer the metadata from the WMV to the new MP4 files. > > So, two questions: > > 1) Does these exist a python module I can use to programatically edit the metadata in MP4 > files? > > 2) Failing that, is there a python module I can use to edit the > metadata in the WMV files? (hopeing the data makes it through the > conversion..) > > -- Thank you > > > > > > ____________________________________________________________________________________ > Be a better friend, newshound, and > know-it-all with Yahoo! Mobile. Try it now. http://mobile.yahoo.com/;_ylt=Ahu06i62sR8HDtDypao8Wcj9tAcJ > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- http://Services.ShowMeDo.com http://ShowMeDo.com Ian at ShowMeDo.com From kent37 at tds.net Wed Mar 5 19:11:28 2008 From: kent37 at tds.net (Kent Johnson) Date: Wed, 05 Mar 2008 13:11:28 -0500 Subject: [Tutor] Video file metadata? (MP4/WMV) In-Reply-To: <165921.42026.qm@web45615.mail.sp1.yahoo.com> References: <165921.42026.qm@web45615.mail.sp1.yahoo.com> Message-ID: <47CEE250.5080207@tds.net> Allen Fowler wrote: > what is the correct way to parse binary files in Python? http://docs.python.org/lib/module-struct.html and perhaps http://construct.wikispaces.com/ Kent From kent37 at tds.net Wed Mar 5 19:22:53 2008 From: kent37 at tds.net (Kent Johnson) Date: Wed, 05 Mar 2008 13:22:53 -0500 Subject: [Tutor] Translate this VB.NET code into Python for me? In-Reply-To: References: <20080304130635.D16391E400E@bag.python.org> Message-ID: <47CEE4FD.9070401@tds.net> Alan Gauld wrote: You could do a GUI example and use IronPython to show how > it copes with GUI code. Since IP can access the same GUI > library as VB.NET they should be very similar in code structure. Here is a blog post I came across recently that shows a number of ways to construct a GUI in Python on Windows. One of the examples is IronPython with .NET. http://www.ginstrom.com/scribbles/2008/02/26/python-gui-programming-platforms-for-windows/ Kent From carroll at tjc.com Wed Mar 5 21:28:12 2008 From: carroll at tjc.com (Terry Carroll) Date: Wed, 5 Mar 2008 12:28:12 -0800 (PST) Subject: [Tutor] Video file metadata? (MP4/WMV) In-Reply-To: <165921.42026.qm@web45615.mail.sp1.yahoo.com> Message-ID: On Tue, 4 Mar 2008, Allen Fowler wrote: > I can't seem to find a simple description of the MP4 sepc... it might be > because there is not one. :) Does this help? http://www.digitalpreservation.gov/formats/fdd/fdd000155.shtml I think, though, that using Python to drive an already-written utility that understands the file format (like ffmpeg, as siggested by Ian) will probably be your best bet. I was going to suggest looking into Pymedia, http://pymedia.org/ , but don't see anything suggesting MP4 support on http://pymedia.org/features.html I don't know if it's being developed any longer either. Its last release was in 2005. http://sourceforge.net/projects/pymedia/ From cmarlett at luc.edu Wed Mar 5 23:15:46 2008 From: cmarlett at luc.edu (Christopher Marlett) Date: Wed, 05 Mar 2008 16:15:46 -0600 Subject: [Tutor] hello can you help me solve this problem Message-ID: <47CEC732020000290007049E@gwial1.it.luc.edu> This may be a very broad question but whatever help you could give me would be great. Exercise 2.4.5.1. * Make a program scene.py creating a scene with the graphics methods. You are likely to need to adjust the positions of objects by trial and error until you get the positions you want. Make sure you have graphics.py in the same directory as your program. Exercise 2.4.5.2. * Elaborate your scene program so it becomes changeScene.py, and changes one or more times when you click the mouse (and use win.getMouse()). You may use the position of the mouse click to affect the result, or it may just indicate you are ready to go on to the next view. Also, I don't quite understand how this works. Do you e mail me with your response or is there a website I need to visit to see my question and your response posted? From bgailer at alum.rpi.edu Thu Mar 6 00:12:29 2008 From: bgailer at alum.rpi.edu (bob gailer) Date: Wed, 05 Mar 2008 18:12:29 -0500 Subject: [Tutor] hello can you help me solve this problem In-Reply-To: <47CEC732020000290007049E@gwial1.it.luc.edu> References: <47CEC732020000290007049E@gwial1.it.luc.edu> Message-ID: <47CF28DD.6060006@alum.rpi.edu> Christopher Marlett wrote: > This may be a very broad question but whatever help you could give me would be great. > > Exercise 2.4.5.1. * Make a program scene.py creating a scene with the graphics methods. You are likely to need to adjust the positions of objects by trial and error until you get the positions you want. Make sure you have graphics.py in the same directory as your program. > > Exercise 2.4.5.2. * Elaborate your scene program so it becomes changeScene.py, and changes one or more times when you click the mouse (and use win.getMouse()). You may use the position of the mouse click to affect the result, or it may just indicate you are ready to go on to the next view. > We don't offer solutions to homework for many reasons. I assume this is homework. However if you show us a program (or even a program design) you've written and tell us where you are stuck we are glad to help. > Also, I don't quite understand how this works. Do you e mail me with your response or is there a website I need to visit to see my question and your response posted? > We email you and the tutor list. Please reply to the list not just to the author. -- Bob Gailer 919-636-4239 Chapel Hill, NC From katcipis at inf.ufsc.br Thu Mar 6 01:07:49 2008 From: katcipis at inf.ufsc.br (Tiago Katcipis) Date: Wed, 05 Mar 2008 21:07:49 -0300 Subject: [Tutor] Const on Python Message-ID: <47CF35D5.2050208@inf.ufsc.br> Its a simple question but i have found some trouble to find a good answer to it, maybe i just dont searched enough but it wont cost anything to ask here, and it will not cost to much to answer :-). I have started do develop on python and i really liked it, but im still learning. Im used to develop on c++ and java and i wanted to know if there is any way to create a final or const member, a member that after assigned cant be reassigned. Thanks to anyone who tries to help me and sorry to bother with a so silly question. i hope someday i can be able to help :-) best regards katcipis From alan.gauld at btinternet.com Thu Mar 6 01:13:06 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 6 Mar 2008 00:13:06 -0000 Subject: [Tutor] hello can you help me solve this problem References: <47CEC732020000290007049E@gwial1.it.luc.edu> Message-ID: "Christopher Marlett" wrote > Exercise 2.4.5.1. * Make a program scene.py creating a scene > with the graphics methods. You are likely to need to adjust the > positions of objects by trial and error until you get the positions > you want. Make sure you have graphics.py in the same directory > as your program. Is this by any chance from the LiveWires tutorial? If so they tend to use a lot of mod8ules that are specific to their course so only folks with LiveWires experience are likely to be able to help. You need to give us some context as to where these come from and where the graphics.py mentioned is found. Its not part of the standard Python library. Also it woyuld be good to tell us what part of the problem you don't understand! The more specific the question the greater the chance of an effective answer. > Also, I don't quite understand how this works. Do you > email me with your response or is there a website > I need to visit to see my question and your response posted? You mail themailing list and the server forwards it to everyone on the list. We "Reply All" and the list server will forward the reply to you and the list. There are at least 3 web sites where you can read the messages too, but a mail client is usually more powerful and faster. Finally gmane do a news (nntp) feed that you can subscribe to and receivecon your favoured news reader. In my view the best of both worlds! :-) HTH, -- Alan Gauld Author of the Learn to Program web site Temorarily at: http://uk.geocities.com/alan.gauld at btinternet.com/ Normally: http://www.freenetpages.co.uk/hp/alan.gauld From john at fouhy.net Thu Mar 6 01:30:23 2008 From: john at fouhy.net (John Fouhy) Date: Thu, 6 Mar 2008 13:30:23 +1300 Subject: [Tutor] Const on Python In-Reply-To: <47CF35D5.2050208@inf.ufsc.br> References: <47CF35D5.2050208@inf.ufsc.br> Message-ID: <5e58f2e40803051630q4a1639b4y95ac8ddb608cd02b@mail.gmail.com> On 06/03/2008, Tiago Katcipis wrote: > learning. Im used to develop on c++ and java and i wanted to know if > there is any way to create a final or const member, a member that after > assigned cant be reassigned. Thanks to anyone who tries to help me and > sorry to bother with a so silly question. i hope someday i can be able > to help :-) The short answer is: "Not really". Actually, with recent versions of python, you could do something with properties. e.g.: >>> class MyClass(object): ... def fget_FOO(self): ... return 'foo' ... FOO = property(fget=fget_FOO) ... >>> x = MyClass() >>> x.FOO 'foo' >>> x.FOO = 'bar' Traceback (most recent call last): File "", line 1, in AttributeError: can't set attribute property() takes up to three arguments: get, set, and docstring. In this case, I omitted the setter. Thus python doesn't allow me to set that attribute. You could also mess around with getattr() to achieve a similar effect. Generally, though, python takes the attitude that programmers are adults capable of thinking for themselves, and if you're silly enough to reassign a constant, you deserve whatever you get. Best just to make your variable names ALL_CAPS and write documentation saying they're constant :-) See also this recipe: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65207 for another take on the issue. -- John. From katcipis at inf.ufsc.br Thu Mar 6 01:54:59 2008 From: katcipis at inf.ufsc.br (Tiago Katcipis) Date: Wed, 05 Mar 2008 21:54:59 -0300 Subject: [Tutor] Const on Python In-Reply-To: <5e58f2e40803051630q4a1639b4y95ac8ddb608cd02b@mail.gmail.com> References: <47CF35D5.2050208@inf.ufsc.br> <5e58f2e40803051630q4a1639b4y95ac8ddb608cd02b@mail.gmail.com> Message-ID: <47CF40E3.6090808@inf.ufsc.br> Thanks for the help John. I agree with you that the programmer is already a grow person and should know when he can modify a attribute :-). Instead when other people will be able to continue to develop on the code i writed the const would give confidence that someone would not mess with my constants... i dont think its really necessary the const, but if it exists i would use...if dont exists....ok. Looking forward to go on developing on python and have more questions, hope that they will be better than this one :-). Again thanks for the help best regards katcipis John Fouhy escreveu: > On 06/03/2008, Tiago Katcipis wrote: > >> learning. Im used to develop on c++ and java and i wanted to know if >> there is any way to create a final or const member, a member that after >> assigned cant be reassigned. Thanks to anyone who tries to help me and >> sorry to bother with a so silly question. i hope someday i can be able >> to help :-) >> > > The short answer is: "Not really". > > Actually, with recent versions of python, you could do something with > properties. e.g.: > > >>>> class MyClass(object): >>>> > ... def fget_FOO(self): > ... return 'foo' > ... FOO = property(fget=fget_FOO) > ... > >>>> x = MyClass() >>>> x.FOO >>>> > 'foo' > >>>> x.FOO = 'bar' >>>> > Traceback (most recent call last): > File "", line 1, in > AttributeError: can't set attribute > > > property() takes up to three arguments: get, set, and docstring. In > this case, I omitted the setter. Thus python doesn't allow me to set > that attribute. You could also mess around with getattr() to achieve > a similar effect. > > Generally, though, python takes the attitude that programmers are > adults capable of thinking for themselves, and if you're silly enough > to reassign a constant, you deserve whatever you get. Best just to > make your variable names ALL_CAPS and write documentation saying > they're constant :-) > > See also this recipe: > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65207 > for another take on the issue. > > From bgailer at alum.rpi.edu Thu Mar 6 04:34:45 2008 From: bgailer at alum.rpi.edu (bob gailer) Date: Wed, 05 Mar 2008 22:34:45 -0500 Subject: [Tutor] Const on Python In-Reply-To: <47CF35D5.2050208@inf.ufsc.br> References: <47CF35D5.2050208@inf.ufsc.br> Message-ID: <47CF6655.5080108@alum.rpi.edu> Tiago Katcipis wrote: > Its a simple question but i have found some trouble to find a good > answer to it, maybe i just dont searched enough but it wont cost > anything to ask here, and it will not cost to much to answer :-). Well there is a cost (at least to me) to read all the extra words that have nothing to do with the question. I'd rather see: "Is there a way to create a constant member, one that after assignment can't be reassigned? Thanks katcipis" > I have > started do develop on python and i really liked it, but im still > learning. Im used to develop on c++ and java and i wanted to know if > there is any way to create a final or const member, a member that after > assigned cant be reassigned. Thanks to anyone who tries to help me and > sorry to bother with a so silly question. i hope someday i can be able > to help :-) > > best regards > > katcipis > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Bob Gailer 919-636-4239 Chapel Hill, NC From rdm at rcblue.com Thu Mar 6 07:29:33 2008 From: rdm at rcblue.com (Dick Moores) Date: Wed, 05 Mar 2008 22:29:33 -0800 Subject: [Tutor] Translate this VB.NET code into Python for me? In-Reply-To: <47CEE4FD.9070401@tds.net> References: <20080304130635.D16391E400E@bag.python.org> <47CEE4FD.9070401@tds.net> Message-ID: <20080306062946.9B6571E4003@bag.python.org> At 10:22 AM 3/5/2008, Kent Johnson wrote: >Alan Gauld wrote: > You could do a GUI example and use IronPython to show how > > it copes with GUI code. Since IP can access the same GUI > > library as VB.NET they should be very similar in code structure. > >Here is a blog post I came across recently that shows a number of ways >to construct a GUI in Python on Windows. One of the examples is >IronPython with .NET. >http://www.ginstrom.com/scribbles/2008/02/26/python-gui-programming-platforms-for-windows/ Thanks, Kent! Dick Moores From andreas at kostyrka.org Thu Mar 6 10:39:58 2008 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Thu, 06 Mar 2008 10:39:58 +0100 Subject: [Tutor] Const on Python In-Reply-To: <47CF35D5.2050208@inf.ufsc.br> References: <47CF35D5.2050208@inf.ufsc.br> Message-ID: <1204796398.13045.10.camel@localhost> The answer is slightly more complex. 1.) objects are either mutable or immutable. E.g. tuples and strings are per definition immutable and "constant". Lists and dictionaries are an example of the mutable kind. 2.) "variables", "instance members" are all only references to objects. Examples: # lists are mutable a = [1, 2] b = a b.append(3) assert a == [1, 2, 3] Now coming back to your question, that you want a non-changeable name, well, one can create such a beast, e.g.: def constant(value): def _get(*_dummy): return value return property(_get) class Test(object): const_a = constant(123) This creates a member that can only be fetched, but not set or deleted. But in practice, I personally never have seen a need for something like this. You can always overcome the above constant. Btw, you can do that in C++ privates too, worst case by casting around and ending up with a pointer that points to the private element ;) Andreas Am Mittwoch, den 05.03.2008, 21:07 -0300 schrieb Tiago Katcipis: > Its a simple question but i have found some trouble to find a good > answer to it, maybe i just dont searched enough but it wont cost > anything to ask here, and it will not cost to much to answer :-). I have > started do develop on python and i really liked it, but im still > learning. Im used to develop on c++ and java and i wanted to know if > there is any way to create a final or const member, a member that after > assigned cant be reassigned. Thanks to anyone who tries to help me and > sorry to bother with a so silly question. i hope someday i can be able > to help :-) > > best regards > > katcipis > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Dies ist ein digital signierter Nachrichtenteil Url : http://mail.python.org/pipermail/tutor/attachments/20080306/e56f0d67/attachment.pgp From katcipis at inf.ufsc.br Thu Mar 6 14:08:27 2008 From: katcipis at inf.ufsc.br (Tiago Katcipis) Date: Thu, 6 Mar 2008 10:08:27 -0300 Subject: [Tutor] Const on Python In-Reply-To: <1204796398.13045.10.camel@localhost> References: <47CF35D5.2050208@inf.ufsc.br> <1204796398.13045.10.camel@localhost> Message-ID: <60a9403b0803060508r47548cfcnfa339f5d872eeca6@mail.gmail.com> thanks for the help Andreas, i dont really need that much a const so i wont do anything like that to have a const like data. I am very used to java and c++, thats why i always used acess modifier, but i think i can live without it now i know that it dont exist in python :P. On Thu, Mar 6, 2008 at 6:39 AM, Andreas Kostyrka wrote: > The answer is slightly more complex. > > 1.) objects are either mutable or immutable. E.g. tuples and strings are > per definition immutable and "constant". Lists and dictionaries are an > example of the mutable kind. > > 2.) "variables", "instance members" are all only references to objects. > > Examples: > > # lists are mutable > a = [1, 2] > b = a > b.append(3) > assert a == [1, 2, 3] > > Now coming back to your question, that you want a non-changeable name, > well, one can create such a beast, e.g.: > > def constant(value): > def _get(*_dummy): > return value > return property(_get) > > class Test(object): > const_a = constant(123) > > This creates a member that can only be fetched, but not set or deleted. > > But in practice, I personally never have seen a need for something like > this. You can always overcome the above constant. Btw, you can do that > in C++ privates too, worst case by casting around and ending up with a > pointer that points to the private element ;) > > Andreas > > > Am Mittwoch, den 05.03.2008, 21:07 -0300 schrieb Tiago Katcipis: > > Its a simple question but i have found some trouble to find a good > > answer to it, maybe i just dont searched enough but it wont cost > > anything to ask here, and it will not cost to much to answer :-). I have > > started do develop on python and i really liked it, but im still > > learning. Im used to develop on c++ and java and i wanted to know if > > there is any way to create a final or const member, a member that after > > assigned cant be reassigned. Thanks to anyone who tries to help me and > > sorry to bother with a so silly question. i hope someday i can be able > > to help :-) > > > > best regards > > > > katcipis > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080306/3893ae74/attachment.htm From kent37 at tds.net Thu Mar 6 14:35:51 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 06 Mar 2008 08:35:51 -0500 Subject: [Tutor] Const on Python In-Reply-To: <60a9403b0803060508r47548cfcnfa339f5d872eeca6@mail.gmail.com> References: <47CF35D5.2050208@inf.ufsc.br> <1204796398.13045.10.camel@localhost> <60a9403b0803060508r47548cfcnfa339f5d872eeca6@mail.gmail.com> Message-ID: <47CFF337.6050600@tds.net> Tiago Katcipis wrote: > thanks for the help Andreas, i dont really need that much a const so i > wont do anything like that to have a const like data. I am very used to > java and c++, thats why i always used acess modifier, but i think i can > live without it now i know that it dont exist in python :P. My experience, moving from C++ to Java to Python as the language I use every day at work: C++ is extremely complex. The good side of this is it gives you tremendous control - final, const, pass by reference or value, memory allocation, etc, etc. The bad side is that it is a lot to think about - should this parameter be const? who is going to deallocate this object? and there is a lot of room for error, whole books have been written on the topic (e.g. Effective C++ which even has a sequel). Java is less complex and flexible than C++. At first I missed the control of C++, then I realized that it wasn't really buying me much and that the cost was too high - coding Java is much less work than coding C++. Then Python. Python takes away even more low-level control. And I don't miss it at all. My Python programs work just fine without static typing, constants, etc. Python is simple and flexible and just does what I want with no fuss. Java is a heavy straightjacket. C++ is inconceivably complex. So relax and enjoy it, the only risk is that you will never want to touch Java and C++ again. :-) Kent From andreas at kostyrka.org Thu Mar 6 14:47:38 2008 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Thu, 06 Mar 2008 14:47:38 +0100 Subject: [Tutor] Const on Python In-Reply-To: <60a9403b0803060508r47548cfcnfa339f5d872eeca6@mail.gmail.com> References: <47CF35D5.2050208@inf.ufsc.br> <1204796398.13045.10.camel@localhost> <60a9403b0803060508r47548cfcnfa339f5d872eeca6@mail.gmail.com> Message-ID: <1204811258.13045.23.camel@localhost> Well, as a philosophical argument, the public/private classification is broken by design. Why? Assuming that one considers the "protection" part as useful (which experience with dynamic languages like Python suggest is not axiomatic), because it forces you to map all roles of a given class to a fixed number of roles (public, protected, private in C++). Consider for example a buffered data stream. Now I can envision the following usage cases: 1.) just a simple "I want to write something" customer. 2.) "I need more control about the buffering" customer. 3.) "I want to implement the lowlevel IO" subclass. 4.) "I want to change/implement the buffering" subclass. Now a good language (in the static language world) should allow me specify this in a way, so that I can see for example what user classes need updates if I change say the buffering implementation. As an example for such an implementation, see the Modula 3 language. ;) But that was only a visit into the reasoning that "static language" advocates might find relevant. OTOH, the dynamic camp usually don't care much for that kinds of access restrictions. (Well, Smalltalk does disallow member variable access from outside of an object, BUT that's just to force people to use methods. There is again no access control system for methods.) Andreas Am Donnerstag, den 06.03.2008, 10:08 -0300 schrieb Tiago Katcipis: > thanks for the help Andreas, i dont really need that much a const so i > wont do anything like that to have a const like data. I am very used > to java and c++, thats why i always used acess modifier, but i think i > can live without it now i know that it dont exist in python :P. > > > > On Thu, Mar 6, 2008 at 6:39 AM, Andreas Kostyrka > wrote: > The answer is slightly more complex. > > 1.) objects are either mutable or immutable. E.g. tuples and > strings are > per definition immutable and "constant". Lists and > dictionaries are an > example of the mutable kind. > > 2.) "variables", "instance members" are all only references to > objects. > > Examples: > > # lists are mutable > a = [1, 2] > b = a > b.append(3) > assert a == [1, 2, 3] > > Now coming back to your question, that you want a > non-changeable name, > well, one can create such a beast, e.g.: > > def constant(value): > def _get(*_dummy): > return value > return property(_get) > > class Test(object): > const_a = constant(123) > > This creates a member that can only be fetched, but not set or > deleted. > > But in practice, I personally never have seen a need for > something like > this. You can always overcome the above constant. Btw, you can > do that > in C++ privates too, worst case by casting around and ending > up with a > pointer that points to the private element ;) > > Andreas > > > Am Mittwoch, den 05.03.2008, 21:07 -0300 schrieb Tiago > Katcipis: > > Its a simple question but i have found some trouble to find > a good > > answer to it, maybe i just dont searched enough but it wont > cost > > anything to ask here, and it will not cost to much to > answer :-). I have > > started do develop on python and i really liked it, but im > still > > learning. Im used to develop on c++ and java and i wanted to > know if > > there is any way to create a final or const member, a member > that after > > assigned cant be reassigned. Thanks to anyone who tries to > help me and > > sorry to bother with a so silly question. i hope someday i > can be able > > to help :-) > > > > best regards > > > > katcipis > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Dies ist ein digital signierter Nachrichtenteil Url : http://mail.python.org/pipermail/tutor/attachments/20080306/da4665f8/attachment.pgp From andreas at kostyrka.org Thu Mar 6 15:18:11 2008 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Thu, 06 Mar 2008 15:18:11 +0100 Subject: [Tutor] Const on Python In-Reply-To: <47CFF337.6050600@tds.net> References: <47CF35D5.2050208@inf.ufsc.br> <1204796398.13045.10.camel@localhost> <60a9403b0803060508r47548cfcnfa339f5d872eeca6@mail.gmail.com> <47CFF337.6050600@tds.net> Message-ID: <1204813091.13045.54.camel@localhost> Am Donnerstag, den 06.03.2008, 08:35 -0500 schrieb Kent Johnson: > C++ is extremely complex. The good side of this is it gives you > tremendous control - final, const, pass by reference or value, memory > allocation, etc, etc. The bad side is that it is a lot to think about - > should this parameter be const? who is going to deallocate this object? > and there is a lot of room for error, whole books have been written on > the topic (e.g. Effective C++ which even has a sequel). Concur. What is worse, it's to complicated for the average "commercial" developer. And the claim that you can program C++ effectively without knowing the whole language does not work in practice. (Hint: Yes, you can program without understanding the whole language. And no, you have no chance of debugging your program if you don't understand what that complicated library is doing. So in practice you end with senior developers doing the debugging, while the newbies try to understand what you are doing.) As a saving grace to C++ I must note that there are a number of "features" in Python that can produce something comparativly newbie-unfriendly as C++. But you will notice that most Python developers shrink away from using these features, so in effect this is not a burning issue. Somehow these "advanced" topics don't deter newbies from writing and debugging Python programs. (E.g. you can program for years Python without learning the fact that it's not the class that does the self bounding, instead it's function.__get__ that does it ;) ) > > Java is less complex and flexible than C++. At first I missed the > control of C++, then I realized that it wasn't really buying me much and > that the cost was too high - coding Java is much less work than coding C++. Java has automatic memory management, is safe (meaning that typically the worst thing that happens is traceback), and has an object model that nearer to a dynamic language like Python or Smalltalk than to C++. Basically, while it looks much like C++ on a first glance, the underpinnings come from more dynamic/runtime oriented languages. And because it does all these irrelevant details for the developer automatically, the IT industry can get enough souls to program it. ;) > > Then Python. Python takes away even more low-level control. And I don't > miss it at all. My Python programs work just fine without static typing, > constants, etc. Worse, something that one likes to forget. Practically in any software system the amount of code that is heavily exercised, the "inner loop" is tiny. Meaning that after having written your Python code (usually in a fraction of the time planned for the C++ implementation), you can improve the algorithms and speed up these critical sections. (By redoing them in Python, Pyrex, C/C++.) That's the underlying truth to "Python faster than C++" message. Not because Python is faster than C++ (in execution speed). Of the primitive operations around 98-98% are slower in Python than in C/C++. But it allows you to implement your application faster than in C++. The initial implementation will be slower than a C++ implementation. But it might be already "fast enough". But the point is, that in most cases, your friendly C++ coder in the next room is still implementing his initial implementation while the Python coder is already benchmarking/tuning his app. Or spends time thinking about the algorithms. So the following stands, usually, and you can usually even replace the languages with Perl, Ruby, PHP, Smalltalk, Lisp, Java, ...: C++ is faster than Python (if the resources in money and time are unlimited: that's why many C++ gurus in academy have a strong different feeling). Python is faster than C++ (in time to market, if resources are limited) Python is faster than C++ (in execution time, if resources are limited enough so that the C++ version is an unoptimized first try, while the Python version is usually a 2nd or 3rd generation implementation). In commercial practice sometimes "political" considerations make for crazy decisions, e.g. witnessed by me: 1.) a new web service needs to be developed. 2.) the policy of the company is that all developers need to know C ++/Java. 3.) the project lead calls in the next free developer to his office, and as it happens it's one of the local C++ gurus. 4.) The C++ guru, being slightly bored, tells the project lead that in his own estimation, it would be faster to do the service in Python, even with him learning Python first. It would make even more sense technically to do the webservice in Erlang, as it has to interface with an Erlang server. He'd be happy to learn more Erlang too ;) 5.) The project lead makes him to do it in C++ anyway. Would make the scheduling of the group way to complicated if you could not assign any developer to every ticket coming in. That's the moment where you start scratching your head. > Python is simple and flexible and just does what I want with no fuss. > Java is a heavy straightjacket. C++ is inconceivably complex. Concur. It's just that most people in the IT industry don't grasp it. Or the fact that especially C++ comes like an iceberg with the worst under the waterline: Debugging that stuff. (Even with the nicest coolest debugging tools, debugging C++ still takes an experienced developer with intuition.) > So relax and enjoy it, the only risk is that you will never want to > touch Java and C++ again. Well, at least not without getting an premium for all the pain ;) Andreas -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Dies ist ein digital signierter Nachrichtenteil Url : http://mail.python.org/pipermail/tutor/attachments/20080306/462f0fd3/attachment.pgp From katcipis at inf.ufsc.br Thu Mar 6 16:51:56 2008 From: katcipis at inf.ufsc.br (Tiago Katcipis) Date: Thu, 6 Mar 2008 12:51:56 -0300 Subject: [Tutor] Const on Python In-Reply-To: <1204813091.13045.54.camel@localhost> References: <47CF35D5.2050208@inf.ufsc.br> <1204796398.13045.10.camel@localhost> <60a9403b0803060508r47548cfcnfa339f5d872eeca6@mail.gmail.com> <47CFF337.6050600@tds.net> <1204813091.13045.54.camel@localhost> Message-ID: <60a9403b0803060751j318e70d0q8ec7c2b91550426@mail.gmail.com> so far im starting to feel all what you have said. Im using python to implement some works on university and im felling that everything is high level, easy to use, and far easier than c++ and even java. java is less complicated than c++ but cant be compared with the simplicity of python code. And the code gets pleasant to read...thanks to indentation and no braces...i just lerned to hate the damn braces :P. Saddly the lab where i work only develops on c++ for now... but everything that i can choose i will develop with python, im still green on developing but so far it is the more pleasant language to program...is actually fun to develop on python..all the time....in c++...sometimes is fun....the most part of the time is debugging suffering =/, and mistic compile errors that sometimes gets a lot of time to understand what REALLY is the problem. Its amazing how the compiler can trick you in c++, almost all the times it only points in the wrong direction..the only thing that can help you is experience or someone with experience at your side :P. Python runtime errors always helped me to debug fast and easy, really a joy :D. thanks everyone for helping me On Thu, Mar 6, 2008 at 11:18 AM, Andreas Kostyrka wrote: > > Am Donnerstag, den 06.03.2008, 08:35 -0500 schrieb Kent Johnson: > > C++ is extremely complex. The good side of this is it gives you > > tremendous control - final, const, pass by reference or value, memory > > allocation, etc, etc. The bad side is that it is a lot to think about - > > should this parameter be const? who is going to deallocate this object? > > and there is a lot of room for error, whole books have been written on > > the topic (e.g. Effective C++ which even has a sequel). > > Concur. What is worse, it's to complicated for the average "commercial" > developer. And the claim that you can program C++ effectively without > knowing the whole language does not work in practice. (Hint: Yes, you > can program without understanding the whole language. And no, you have > no chance of debugging your program if you don't understand what that > complicated library is doing. So in practice you end with senior > developers doing the debugging, while the newbies try to understand what > you are doing.) > > As a saving grace to C++ I must note that there are a number of > "features" in Python that can produce something comparativly > newbie-unfriendly as C++. But you will notice that most Python > developers shrink away from using these features, so in effect this is > not a burning issue. Somehow these "advanced" topics don't deter newbies > from writing and debugging Python programs. (E.g. you can program for > years Python without learning the fact that it's not the class that does > the self bounding, instead it's function.__get__ that does it ;) ) > > > > > Java is less complex and flexible than C++. At first I missed the > > control of C++, then I realized that it wasn't really buying me much and > > that the cost was too high - coding Java is much less work than coding > C++. > > Java has automatic memory management, is safe (meaning that typically > the worst thing that happens is traceback), and has an object model that > nearer to a dynamic language like Python or Smalltalk than to C++. > Basically, while it looks much like C++ on a first glance, the > underpinnings come from more dynamic/runtime oriented languages. > > And because it does all these irrelevant details for the developer > automatically, the IT industry can get enough souls to program it. ;) > > > > > Then Python. Python takes away even more low-level control. And I don't > > miss it at all. My Python programs work just fine without static typing, > > constants, etc. > > Worse, something that one likes to forget. Practically in any software > system the amount of code that is heavily exercised, the "inner loop" is > tiny. Meaning that after having written your Python code (usually in a > fraction of the time planned for the C++ implementation), you can > improve the algorithms and speed up these critical sections. (By redoing > them in Python, Pyrex, C/C++.) > > That's the underlying truth to "Python faster than C++" message. Not > because Python is faster than C++ (in execution speed). Of the primitive > operations around 98-98% are slower in Python than in C/C++. But it > allows you to implement your application faster than in C++. The initial > implementation will be slower than a C++ implementation. But it might be > already "fast enough". But the point is, that in most cases, your > friendly C++ coder in the next room is still implementing his initial > implementation while the Python coder is already benchmarking/tuning his > app. Or spends time thinking about the algorithms. > > So the following stands, usually, and you can usually even replace the > languages with Perl, Ruby, PHP, Smalltalk, Lisp, Java, ...: > > C++ is faster than Python (if the resources in money and time are > unlimited: that's why many C++ gurus in academy have a strong different > feeling). > > Python is faster than C++ (in time to market, if resources are limited) > Python is faster than C++ (in execution time, if resources are limited > enough so that the C++ version is an unoptimized first try, while the > Python version is usually a 2nd or 3rd generation implementation). > > > In commercial practice sometimes "political" considerations make for > crazy decisions, e.g. witnessed by me: > > 1.) a new web service needs to be developed. > 2.) the policy of the company is that all developers need to know C > ++/Java. > 3.) the project lead calls in the next free developer to his office, and > as it happens it's one of the local C++ gurus. > 4.) The C++ guru, being slightly bored, tells the project lead that in > his own estimation, it would be faster to do the service in Python, even > with him learning Python first. It would make even more sense > technically to do the webservice in Erlang, as it has to interface with > an Erlang server. He'd be happy to learn more Erlang too ;) > 5.) The project lead makes him to do it in C++ anyway. Would make the > scheduling of the group way to complicated if you could not assign any > developer to every ticket coming in. > > That's the moment where you start scratching your head. > > > Python is simple and flexible and just does what I want with no fuss. > > Java is a heavy straightjacket. C++ is inconceivably complex. > > Concur. It's just that most people in the IT industry don't grasp it. Or > the fact that especially C++ comes like an iceberg with the worst under > the waterline: Debugging that stuff. (Even with the nicest coolest > debugging tools, debugging C++ still takes an experienced developer with > intuition.) > > > So relax and enjoy it, the only risk is that you will never want to > > touch Java and C++ again. > > Well, at least not without getting an premium for all the pain ;) > > Andreas > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080306/a583ac1b/attachment-0001.htm From mlangford.cs03 at gtalumni.org Thu Mar 6 17:08:25 2008 From: mlangford.cs03 at gtalumni.org (Michael Langford) Date: Thu, 6 Mar 2008 11:08:25 -0500 Subject: [Tutor] Const on Python In-Reply-To: <60a9403b0803060751j318e70d0q8ec7c2b91550426@mail.gmail.com> References: <47CF35D5.2050208@inf.ufsc.br> <1204796398.13045.10.camel@localhost> <60a9403b0803060508r47548cfcnfa339f5d872eeca6@mail.gmail.com> <47CFF337.6050600@tds.net> <1204813091.13045.54.camel@localhost> <60a9403b0803060751j318e70d0q8ec7c2b91550426@mail.gmail.com> Message-ID: <82b4f5810803060808x573368f2n7b3b4d462c854bd3@mail.gmail.com> On Thu, Mar 6, 2008 at 10:51 AM, Tiago Katcipis wrote: > Saddly the lab where i > work only develops on c++ for now... but everything that i can choose i will > develop with python, This is not an insurmountable problem. There are various technologies which allow you to use C++ code quite easily from python. The easiest of which is weave: http://www.scipy.org/Weave The more difficult, yet still often eminently worth it one is SWIG: http://www.swig.org/ It also smashes the argument you'll hear in a C++ shop: You can never make it fast enough in the inner loop. That said, there are very few times I've *ever* seen the speed differential between a python and C++ program ever recoup the vastly increased development and maintenance time of a C++ program. (And I'm an embedded software developer by practice, supposedly the area that really matters in). --Michael -- Michael Langford Phone: 404-386-0495 Consulting: http://www.RowdyLabs.com From alan.gauld at btinternet.com Fri Mar 7 00:42:39 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 6 Mar 2008 23:42:39 -0000 Subject: [Tutor] Const on Python References: <47CF35D5.2050208@inf.ufsc.br> <1204796398.13045.10.camel@localhost> Message-ID: > Now coming back to your question, that you want a non-changeable > name, > well, one can create such a beast, e.g.: > > def constant(value): > ... >class Test(object): > const_a = constant(123) > This creates a member that can only be fetched, but not set or > deleted. Only within constant. the member const_a can be changed via simple assignment. > But in practice, I personally never have seen a need for something > like > this. You can always overcome the above constant. Btw, you can do > that > in C++ privates too, worst case by casting around and ending up with > a > pointer that points to the private element ;) I've seen an even more mundane trick to bypass private(rather than const): #define private public #define protected public #include "someclass.h" SomeClass c = new SomeClass; c->someVar = 42; etc... I suppose you could avoid that by prefixing every classs definition with #define private private #define protected protected class SomeClass{....}; But it illustrates the relative fragility of C++ apparently tight control of names and visibility. And with a pointr to the right memory location and a cast you can do just about anything... In that respect I prefer the blatant openness of Python to the perceived protection of C++ Alan G. From alan.gauld at btinternet.com Fri Mar 7 00:54:35 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 6 Mar 2008 23:54:35 -0000 Subject: [Tutor] Const on Python References: <47CF35D5.2050208@inf.ufsc.br><1204796398.13045.10.camel@localhost><60a9403b0803060508r47548cfcnfa339f5d872eeca6@mail.gmail.com><47CFF337.6050600@tds.net> <1204813091.13045.54.camel@localhost> Message-ID: > In commercial practice sometimes "political" considerations make for > crazy decisions, e.g. witnessed by me: > 1.) a new web service needs to be developed. > 2.) the policy of the company is that all developers need to know C ++/Java. > snipped... desire to use Python/Erlang > 5.) The project lead makes him to do it in C++ anyway. Would make > the > scheduling of the group way to complicated if you could not assign > any > developer to every ticket coming in. > > That's the moment where you start scratching your head. Actually I'm with the lead here. The cost of developing a new feature is a tiny proportion of total life cost of code - often only 5-10%. If Erlang is already being used that might make some sense, but of the developers all know Java/C++ then one of those makers more sense. If every modification needs to wait for a Python/Erlang developer to come free that would push the lifetime costs up dramatically. Its not a matter of politics but of business and TCO. I routinely build prototypes in Python, a few of which have been "good enough" for the users, but nonetheless we have had them rewritten in Java because thats what we use in house. Nobody upgrades the Python version on the servers, only a handfull of developers know Python. So it makes commecial sense to rewrite the app in Java where anyone can fix/modify it than have an app in Python than only a select few can work on and costs a fortune in upgrades over the 10 years or more the app may exist for. Alan G From ravikondamuru at gmail.com Fri Mar 7 00:55:52 2008 From: ravikondamuru at gmail.com (Ravi Kondamuru) Date: Thu, 6 Mar 2008 15:55:52 -0800 Subject: [Tutor] Processing unix style timestamp Message-ID: <36601b010803061555v7c1953dbx19d984319634486d@mail.gmail.com> Hi, I have a log file that prints the date and time in the following format: Mon Feb 11 01:34:52 CST 2008 I am expecting multiple timezone entries (eg: PST, PDT and GMT) on the system running in America/Los Angeles time zone. I am looking for a way to internally store all the different timezone entries in GMT. I looked at datetime, but it seems slightly complex to work with non GMT timestamps. Any pointers? thanks, Ravi. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080306/74f3da06/attachment.htm From wescpy at gmail.com Fri Mar 7 01:07:18 2008 From: wescpy at gmail.com (wesley chun) Date: Thu, 6 Mar 2008 16:07:18 -0800 Subject: [Tutor] Processing unix style timestamp In-Reply-To: <36601b010803061555v7c1953dbx19d984319634486d@mail.gmail.com> References: <36601b010803061555v7c1953dbx19d984319634486d@mail.gmail.com> Message-ID: <78b3a9580803061607s291ed8d2q25855fc19938235f@mail.gmail.com> > I looked at datetime, but it seems slightly complex to work with non GMT > timestamps. > > Any pointers? you may also want to take a look at dateutil http://labix.org/python-dateutil i think the online docs has a section devoted to just timestamp parsing. hope this helps! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From alan.gauld at btinternet.com Fri Mar 7 01:10:37 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 7 Mar 2008 00:10:37 -0000 Subject: [Tutor] Const on Python References: <47CF35D5.2050208@inf.ufsc.br> <1204796398.13045.10.camel@localhost><60a9403b0803060508r47548cfcnfa339f5d872eeca6@mail.gmail.com> <47CFF337.6050600@tds.net> Message-ID: "Kent Johnson" wrote > My experience, moving from C++ to Java to Python as the language I > use > every day at work: I did much the same journey but decided I hated Java so much I kind of bypassed it and only once used it on a real project. Instead I became an architect/designer(;-), learned Python, and now hand prototypes over to the development teams to build in Java... > C++ is extremely complex. It was relatively straightforward in v1 and even in v2. But once they started the ANSI standardisation process they started throwing every feature under the sun into it! At that point I lost interest. > Java is less complex and flexible than C++. At first I missed the > control of C++, then I realized that it wasn't really buying me much > and > that the cost was too high - coding Java is much less work than > coding C++. I didn't find that, in the few real tests I did I often found the C++ code shorter and never significantly longer(10% ?). This is because Java removed so many of the features that can really reduce C++ code size - like multiple inheritance and operator overloading and templates. (although the latest Java has a kind of templates with generics). When you add to that the fundamentally broken type system in Java (mix of primitive and object) you often wind up with code that effectively does: if x is primitive type func(x) else x.func() or if y is primitive y += z else y.incrementBy(z) And of course interfaces as an alternative to MI simply mean cut n paste code in every sub class or a complex delegation/dispatch scheme being devised by the developer > Then Python. Python takes away even more low-level control. And I > don't > miss it at all. My Python programs work just fine without static > typing, > constants, etc. And all the missing featires of Java are fixed - all objects are true objects, MI is allowed, and duck typing plus generic containers removes the need for most templates > Python is simple and flexible and just does what I want with no > fuss. > Java is a heavy straightjacket. C++ is inconceivably complex. I agree. Although I do still dabble in Delphi, SmallTalk, Haskell and Lisp from time to time :-) Alan G. From alan.gauld at btinternet.com Fri Mar 7 01:13:52 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 7 Mar 2008 00:13:52 -0000 Subject: [Tutor] Processing unix style timestamp References: <36601b010803061555v7c1953dbx19d984319634486d@mail.gmail.com> Message-ID: "Ravi Kondamuru" wrote > I have a log file that prints the date and time in the following > format: > Mon Feb 11 01:34:52 CST 2008 > I looked at datetime, but it seems slightly complex to work with non > GMT > timestamps. Try the basic time module. It has gmttime functions... Alan G From john at fouhy.net Fri Mar 7 01:20:36 2008 From: john at fouhy.net (John Fouhy) Date: Fri, 7 Mar 2008 13:20:36 +1300 Subject: [Tutor] Processing unix style timestamp In-Reply-To: <36601b010803061555v7c1953dbx19d984319634486d@mail.gmail.com> References: <36601b010803061555v7c1953dbx19d984319634486d@mail.gmail.com> Message-ID: <5e58f2e40803061620r7bc33e8fo62069a087405e5bb@mail.gmail.com> On 07/03/2008, Ravi Kondamuru wrote: > I have a log file that prints the date and time in the following format: > Mon Feb 11 01:34:52 CST 2008 > I am expecting multiple timezone entries (eg: PST, PDT and GMT) on the > system running in America/Los Angeles time zone. > I am looking for a way to internally store all the different timezone > entries in GMT. > I looked at datetime, but it seems slightly complex to work with non GMT > timestamps. Maybe you could split out the information.. e.g.: >>> s = 'Mon Feb 11 01:34:52 CST 2008' >>> s[4:19] + s[23:], s[20:23] ('Feb 11 01:34:52 2008', 'CST') You should be able to parse the former with strptime(). You could then build a dictionary mapping timezones to offsets which you could add to the parsed time to produce a time in GMT. -- John. From andreas at kostyrka.org Fri Mar 7 02:42:21 2008 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Fri, 07 Mar 2008 02:42:21 +0100 Subject: [Tutor] Const on Python In-Reply-To: References: <47CF35D5.2050208@inf.ufsc.br> <1204796398.13045.10.camel@localhost> <60a9403b0803060508r47548cfcnfa339f5d872eeca6@mail.gmail.com> <47CFF337.6050600@tds.net> <1204813091.13045.54.camel@localhost> Message-ID: <1204854143.7994.43.camel@localhost> Yes, the problem is, that these guys are anyway forced to have Python/Erlang developers on board, because of external opensource components they need to maintain. Am Donnerstag, den 06.03.2008, 23:54 +0000 schrieb Alan Gauld: > Actually I'm with the lead here. > > The cost of developing a new feature is a tiny proportion of total > life cost of code - often only 5-10%. If Erlang is already being > used that might make some sense, but of the developers all know > Java/C++ then one of those makers more sense. If every > modification needs to wait for a Python/Erlang developer to > come free that would push the lifetime costs up dramatically. > > Its not a matter of politics but of business and TCO. > > I routinely build prototypes in Python, a few of which have been > "good enough" for the users, but nonetheless we have had > them rewritten in Java because thats what we use in house. > Nobody upgrades the Python version on the servers, only a > handfull of developers know Python. So it makes commecial > sense to rewrite the app in Java where anyone can fix/modify > it than have an app in Python than only a select few can > work on and costs a fortune in upgrades over the 10 years > or more the app may exist for. The problem here is that C++ is a strong mismatch for the job at hand. With strong mismatch I mean hear at least a magnitude more costs. During initial development and during maintenance. Combined with the fact that the group cannot avoid learning Python and Erlang, because external OSS projects used by them that they need to maintain and customize are written in Python & Erlang. So there is no point in avoiding using languages that they are forced to support anyway. (Even if they should decide to redo the OSS components from scratch and even if they decide to do it in the official languages that are not really a good match to the problem domain, they still need to support the current component for at least a year till such replacement could be developed. So they need to do Python and Erlang.) But basically, your argument misses one important aspect: While most languages are equivalent in a theoretical sense (Turing complete), not all languages are created equal. Some languages can and do provide at least a magnitude of improvement compared to other languages. Now add to the fact that software developement does not scale linearly, and the developer efficiency point becomes even more important. If, by using some higher language a problem becomes so "easy" to solve that a single developer can deal with it, instead of say a 4 man team, than this is a critical aspect. It's kind like having a policy that all invoices must be in USD and are payed only in USD. Now two companies bid. Both companies offerings are more than good enough to meet your demands. Company A asks for USD 100000, and Company B asks for EUR10000. Both a track record of delivering, and both are good enough. In theory, product A might have some benefits, but that's not sure, for the moment it's mostly a theorized minor improvement over product B. To paraphrase now your argument, it makes sense to buy product A, it's not just buying the product, you know, it's also all the other stuff like accounting, exchange rates, and so on. (Philosophically, that's not even that bad a comparison, as learning Python is a rather minor thing for a reasonable good developer. Unlearning bad design habits takes some time, but Python programs do run even if you add some kilobytes of superflous get_ and set_ to the source code :-P) So no, I do not concur with you. I understand why it has some value, but you wouldn't argue that your company should use passenger cars to transport 100 tons of goods, just because all employee have a license to drive such, while truck drivers are slightly harder to come by, would you? Andreas -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Dies ist ein digital signierter Nachrichtenteil Url : http://mail.python.org/pipermail/tutor/attachments/20080307/64e835f9/attachment-0001.pgp From ravikondamuru at gmail.com Fri Mar 7 04:14:45 2008 From: ravikondamuru at gmail.com (Ravi Kondamuru) Date: Thu, 6 Mar 2008 19:14:45 -0800 Subject: [Tutor] Processing unix style timestamp In-Reply-To: <5e58f2e40803061620r7bc33e8fo62069a087405e5bb@mail.gmail.com> References: <36601b010803061555v7c1953dbx19d984319634486d@mail.gmail.com> <5e58f2e40803061620r7bc33e8fo62069a087405e5bb@mail.gmail.com> Message-ID: <36601b010803061914k6ae6fd4bw9af5dfd243e20ed6@mail.gmail.com> Thanks for the replies. time.strptime() is able to parse the string if the timezone is local or GMT or UTC. Is there a file of timezones and corresponding time offsets that I can use to build the dictionary? thanks Ravi. >>> import time >>> time.strptime("Mon Feb 11 01:34:52 CST 2008", "%a %b %d %H:%M:%S %Z %Y") Traceback (most recent call last): File "", line 1, in ? File "/usr/lib/python2.4/_strptime.py", line 293, in strptime raise ValueError("time data did not match format: data=%s fmt=%s" % ValueError: time data did not match format: data=Mon Feb 11 01:34:52 CST 2008 fmt=%a %b %d %H:%M:%S %Z %Y >>> time.tzname ('EST', 'EDT') >>> time.strptime("Mon Feb 11 01:34:52 EST 2008", "%a %b %d %H:%M:%S %Z %Y") (2008, 2, 11, 1, 34, 52, 0, 42, 0) >>> time.strptime("Mon Feb 11 01:34:52 UTC 2008", "%a %b %d %H:%M:%S %Z %Y") (2008, 2, 11, 1, 34, 52, 0, 42, 0) On Thu, Mar 6, 2008 at 4:20 PM, John Fouhy wrote: > On 07/03/2008, Ravi Kondamuru wrote: > > I have a log file that prints the date and time in the following format: > > Mon Feb 11 01:34:52 CST 2008 > > I am expecting multiple timezone entries (eg: PST, PDT and GMT) on the > > system running in America/Los Angeles time zone. > > I am looking for a way to internally store all the different timezone > > entries in GMT. > > I looked at datetime, but it seems slightly complex to work with non GMT > > timestamps. > > Maybe you could split out the information.. e.g.: > > >>> s = 'Mon Feb 11 01:34:52 CST 2008' > >>> s[4:19] + s[23:], s[20:23] > ('Feb 11 01:34:52 2008', 'CST') > > You should be able to parse the former with strptime(). You could > then build a dictionary mapping timezones to offsets which you could > add to the parsed time to produce a time in GMT. > > -- > John. > -- ???????? ???????? (Ravi Kondamuru) -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080306/c3e2b3f7/attachment.htm From mwalsh at groktech.org Fri Mar 7 10:09:14 2008 From: mwalsh at groktech.org (Martin Walsh) Date: Fri, 07 Mar 2008 03:09:14 -0600 Subject: [Tutor] Processing unix style timestamp In-Reply-To: <36601b010803061555v7c1953dbx19d984319634486d@mail.gmail.com> References: <36601b010803061555v7c1953dbx19d984319634486d@mail.gmail.com> Message-ID: <47D1063A.2060708@groktech.org> Ravi Kondamuru wrote: > Hi, > > I have a log file that prints the date and time in the following format: > Mon Feb 11 01:34:52 CST 2008 > I am expecting multiple timezone entries (eg: PST, PDT and GMT) on the > system running in America/Los Angeles time zone. > I am looking for a way to internally store all the different timezone > entries in GMT. > I looked at datetime, but it seems slightly complex to work with non GMT > timestamps. > > Any pointers? > If you are not offended by a 3rd-party module, then the string parser included in the egenix mxDateTime module[1] is hard to beat. You may even have it installed already, as it appears to be a popular dependency of other 3rd-party modules, especially db adapters. In [1]: import mx.DateTime In [2]: d = mx.DateTime.DateFrom('Mon Feb 11 01:34:52 CST 2008') In [3]: d Out[3]: In [4]: d.strftime('%a %b %d %H:%M:%S %Y') Out[4]: 'Mon Feb 11 07:34:52 2008' In [5]: d = mx.DateTime.DateFrom('Mon Feb 11 01:34:52 EST 2008') In [6]: d.strftime('%a %b %d %H:%M:%S %Y') Out[6]: 'Mon Feb 11 06:34:52 2008' In [7]: d = mx.DateTime.DateFrom('Mon Feb 11 01:34:52 UTC 2008') In [8]: d.strftime('%a %b %d %H:%M:%S %Y') Out[8]: 'Mon Feb 11 01:34:52 2008' HTH, Marty [1] http://www.egenix.com/products/python/mxBase/mxDateTime/ > thanks, > Ravi. From alan.gauld at btinternet.com Fri Mar 7 10:36:43 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 7 Mar 2008 09:36:43 -0000 Subject: [Tutor] Const on Python References: <47CF35D5.2050208@inf.ufsc.br><1204796398.13045.10.camel@localhost><60a9403b0803060508r47548cfcnfa339f5d872eeca6@mail.gmail.com><47CFF337.6050600@tds.net> <1204813091.13045.54.camel@localhost> <1204854143.7994.43.camel@localhost> Message-ID: "Andreas Kostyrka" wrote > Yes, the problem is, that these guys are anyway forced to have > Python/Erlang developers on board, because of external opensource > components they need to maintain. And that one fact completely changes the economics and thereby renders the lead position non viable. > The problem here is that C++ is a strong mismatch for > the job at hand. > > With strong mismatch I mean hear at least a magnitude > more costs. During initial development and during maintenance. I would be amazed at anuy project where a language made an order of magnitude difference. The difference in moving from assembler to VB is only about double (Thats the only case wehere I have hard experrience). The problem is as Fred Brooks stated in his essay "No Silver Bullet" that the real costs in development are the intengibles - the time spent thinking about theproblem/solution and dealing with people. They far outweigh the time actually writing code. The average project delivers around 20-100 lines of working code per day. But you can type that in mechanically in half an hour or less. The rest of the day is doing the stuff that really costs. > Combined with the fact that the group cannot avoid > learning Python andErlang, because external > OSS projects used by them that they need to > maintain and customize are written in Python & Erlang. But this is the critical bt that was missing from the original problem statement. If they use these languages anyway then it makes sense to expand their code base. If these were niche languages on a dying legacy then it makes no sense to increase their use. > But basically, your argument misses one important aspect: > > While most languages are equivalent in a theoretical sense ... > Some languages can and do provide at least a magnitude > of improvement compared to other languages. I do dispute that and would be interested in any objective figures that you have. All of the figures I've seen suggest the total project cost impact of lanmguage choice is rarely more than 10-20% of TCO > Now add to the fact that software developement does > not scale linearly, and the developer efficiency point > becomes even more important. But as projects get bigger language choice becomes vanishingly small in the equation. Total developer cost in any large projerct rarely exceeds 10% and of that the language might make up 20% at most, so total impact of language reduces to around 1-2% of TCO. > If, by using some higher language a problem becomes > so "easy" to solve that a single developer can deal with > it, instead of say a 4 man team,than this is a critical aspect. In that case I agree and at that small scale of project then language choice is still a valid argument. And for the kind of maintenance type feature fix we were discussing the project is quite small. (Different if the language choice requires a rewrite of the existing app of course!) > It's kind like having a policy that all invoices must be in > USD and are payed only in USD. Now two companies bid. I'm sorry, I think I missed the connection in the analogy. > (Philosophically, that's not even that bad a comparison, as learning > Python is a rather minor thing for a reasonable good developer. I totally agree, but unfortunately in the corporate world where I work there are relatively few "good developers" - typically one or two per team(around 6-10 people). Indeed only about half of our developers are formally trained to University Engineering/Computer Science type level. Many have craft certificvates from a trade school and (even if just psychologicalluy) learning a new language is a huge hurdle for them. They will insist on going ona weeks training course etc. So yes, most "good" developers can pick up Python in a couple of days from the web site, many corporate programmers balk at such an idea. (This is one area where a hobbyist turned pro is better than a journeyman programmer, the hobbyist is much more likely to learn new skills out of interests sake!) > So no, I do not concur with you. I understand why it has > some value, but you wouldn't argue that your company > should use passenger cars to transport 100 tons of goods, > just because all employee have a license to drive such, > while truck drivers are slightly harder to come by, would > you? No, but I might suggest hiring some trailers or using an external haulage company. It all depends on wheher its a one-off job or a new line of work that we need to build skills. So in this analogy we may need to buy a truck and start training a number of staff to drive it, but thats expensive so before doing so I'd look to see if it was one-off and at the other options. If in your example they need Python/Erlang anyway that completely changes the economics. Alan G. From alan.gauld at btinternet.com Fri Mar 7 10:43:41 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 7 Mar 2008 09:43:41 -0000 Subject: [Tutor] Processing unix style timestamp References: <36601b010803061555v7c1953dbx19d984319634486d@mail.gmail.com> <5e58f2e40803061620r7bc33e8fo62069a087405e5bb@mail.gmail.com> Message-ID: "John Fouhy" wrote > You should be able to parse the former with strptime(). You could > then build a dictionary mapping timezones to offsets which you could > add to the parsed time to produce a time in GMT. Just to point out that to do this accurately is incredibly difficult. There are places which change timezone over the year. Places where the timezone differences vary over the year (from whole hours to fractions of an hour etc) and the dates of DST vary from country to country and in some cases from region to region within countries (The former USSR for example). And in small countries it can vary on a whim of the government (I was once on a skiing holiday in Andorra where they delayed the DST change by a week to help preserve the snow cover!! It was announced on local radio and a statutory nortice posted in all hotels and public buildings!) Managing tracking of times across multiple timezones around the world was one of the hardest design challenges I ever faced! Alan G. From kent37 at tds.net Fri Mar 7 13:36:01 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 07 Mar 2008 07:36:01 -0500 Subject: [Tutor] Processing unix style timestamp In-Reply-To: <36601b010803061555v7c1953dbx19d984319634486d@mail.gmail.com> References: <36601b010803061555v7c1953dbx19d984319634486d@mail.gmail.com> Message-ID: <47D136B1.8090500@tds.net> Ravi Kondamuru wrote: > I looked at datetime, but it seems slightly complex to work with non GMT > timestamps. Mark Pilgrim's Universal Feed Parser includes a robust date parser that works with your sample: In [1]: import feedparser as fp In [2]: fp._parse_date('Mon Feb 11 01:34:52 CST 2008') Out[2]: (2008, 2, 11, 7, 34, 52, 0, 42, 0) http://www.feedparser.org/ This appears to be an RFC 2822-format date: http://www.faqs.org/rfcs/rfc2822.html feedparser uses these functions to parse the date string: In [4]: import rfc822 In [5]: rfc822.parsedate_tz('Mon Feb 11 01:34:52 CST 2008') Out[5]: (2008, 2, 11, 1, 34, 52, 0, 1, 0, -21600) In [7]: rfc822.mktime_tz(_5) Out[7]: 1202715292.0 In [8]: import time In [9]: time.gmtime(_7) Out[9]: (2008, 2, 11, 7, 34, 52, 0, 42, 0) The rfc822 module is deprecated; the same functions are now found in email.util. Kent From tetsuo2k6 at web.de Fri Mar 7 14:16:26 2008 From: tetsuo2k6 at web.de (tetsuo2k6 at web.de) Date: Fri, 07 Mar 2008 14:16:26 +0100 Subject: [Tutor] identifying the calling module/function Message-ID: <47D1402A.8000400@web.de> Hello Tutor! I am building a couple of scripts to manage a database for our company. The projects name is 'dgf'. As a lot of the functionality is used in more than one of these scripts, I moved this functionality to a module (dgf.py). It has several functions now. Question: Is there an easy way to determine inside dgf.py where the function call came from? dgf.py: def yetanotherfunction(): """Edit Me!""" if : ... Something like that? Regards -paul From kent37 at tds.net Fri Mar 7 14:16:04 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 07 Mar 2008 08:16:04 -0500 Subject: [Tutor] Const on Python In-Reply-To: References: <47CF35D5.2050208@inf.ufsc.br><1204796398.13045.10.camel@localhost><60a9403b0803060508r47548cfcnfa339f5d872eeca6@mail.gmail.com><47CFF337.6050600@tds.net> <1204813091.13045.54.camel@localhost> <1204854143.7994.43.camel@localhost> Message-ID: <47D14014.9040403@tds.net> Alan Gauld wrote: > The problem is as > Fred Brooks stated in his essay "No Silver Bullet" that the > real costs in development are the intengibles - the time > spent thinking about theproblem/solution and dealing with people. > They far outweigh the time actually writing code. The average > project delivers around 20-100 lines of working code per > day. But you can type that in mechanically in half an hour > or less. The rest of the day is doing the stuff that really costs. (Jumping in against my better judgment :-) Hmm...sure, programming is not about typing, it is about figuring out what to type. With Python the conceptual activity takes place at a higher level because - Python provides easy-to-use, high-level constructs like lists, dicts and first-order functions - Python doesn't require you to think about low-level details like const, private, getters and setters, braces, etc. So Python speeds up the thinking part. As far as the code, those 20-100 lines will do more if they are in Python than they will if they are in Java or C++. I don't see an order of magnitude difference between Python and Java but I have no doubt that I am dramatically more productive in Python. When I have compared code samples, I have found Python code to be 20-60% the size of equivalent Java code. Googling 'python productivity' finds more specific examples. Kent From kent37 at tds.net Fri Mar 7 14:37:45 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 07 Mar 2008 08:37:45 -0500 Subject: [Tutor] identifying the calling module/function In-Reply-To: <47D1402A.8000400@web.de> References: <47D1402A.8000400@web.de> Message-ID: <47D14529.2090803@tds.net> tetsuo2k6 at web.de wrote: > Hello Tutor! > > I am building a couple of scripts to manage a database for our company. > The projects name is 'dgf'. As a lot of the functionality is used in > more than one of these scripts, I moved this functionality to a module > (dgf.py). It has several functions now. > > Question: Is there an easy way to determine inside dgf.py where the > function call came from? Why do you need to do this? It sounds like a design change is needed. Anyway the answer to your question is yes. This recipe should point you in the right direction: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66062 Kent From andreas at kostyrka.org Fri Mar 7 15:02:49 2008 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Fri, 07 Mar 2008 15:02:49 +0100 Subject: [Tutor] identifying the calling module/function In-Reply-To: <47D1402A.8000400@web.de> References: <47D1402A.8000400@web.de> Message-ID: <1204898569.7994.53.camel@localhost> There are basically a number of things you might want: 1.) sys.argv[0] 2.) __main__.__file__ 3.) sys._getframe The first two will tell which script is the main program. The last one will tell you which function has called you. But as Kent has pointed out, this is rarely a good idea. Actually, it's almost never a good idea, and in most cases it's a really bad idea, designwise. Andreas Am Freitag, den 07.03.2008, 14:16 +0100 schrieb tetsuo2k6 at web.de: > Hello Tutor! > > I am building a couple of scripts to manage a database for our company. > The projects name is 'dgf'. As a lot of the functionality is used in > more than one of these scripts, I moved this functionality to a module > (dgf.py). It has several functions now. > > Question: Is there an easy way to determine inside dgf.py where the > function call came from? > > dgf.py: > > def yetanotherfunction(): > """Edit Me!""" > if : > ... > > Something like that? > > > > > Regards > -paul > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Dies ist ein digital signierter Nachrichtenteil Url : http://mail.python.org/pipermail/tutor/attachments/20080307/796b3dd0/attachment.pgp From tetsuo2k6 at web.de Fri Mar 7 15:04:19 2008 From: tetsuo2k6 at web.de (tetsuo2k6 at web.de) Date: Fri, 07 Mar 2008 15:04:19 +0100 Subject: [Tutor] identifying the calling module/function In-Reply-To: <47D14529.2090803@tds.net> References: <47D1402A.8000400@web.de> <47D14529.2090803@tds.net> Message-ID: <47D14B63.6050209@web.de> Kent Johnson schrieb: > tetsuo2k6 at web.de wrote: >> Hello Tutor! >> >> I am building a couple of scripts to manage a database for our >> company. The projects name is 'dgf'. As a lot of the functionality is >> used in more than one of these scripts, I moved this functionality to >> a module (dgf.py). It has several functions now. >> >> Question: Is there an easy way to determine inside dgf.py where the >> function call came from? > > Why do you need to do this? It sounds like a design change is needed. > Anyway the answer to your question is yes. This recipe should point you > in the right direction: > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66062 > > Kent > First, thanks for the link. I want this functionality mainly because it seems like a quick way to accomplish my goals for the project (I'm in a hurry to get this finished). As I advance more in Python, a design change might happen :) From jeff at drinktomi.com Fri Mar 7 20:32:40 2008 From: jeff at drinktomi.com (Jeff Younker) Date: Fri, 7 Mar 2008 11:32:40 -0800 Subject: [Tutor] identifying the calling module/function In-Reply-To: <47D14B63.6050209@web.de> References: <47D1402A.8000400@web.de> <47D14529.2090803@tds.net> <47D14B63.6050209@web.de> Message-ID: <9EE1AEC7-D09D-4D28-B9BE-DD46A329EADE@drinktomi.com> On Mar 7, 2008, at 6:04 AM, tetsuo2k6 at web.de wrote: > Kent Johnson schrieb: >> >> Why do you need to do this? It sounds like a design change is needed. >> Anyway the answer to your question is yes. This recipe should point >> you >> in the right direction: >> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66062 >> >> Kent >> > > First, thanks for the link. I want this functionality mainly because > it > seems like a quick way to accomplish my goals for the project (I'm > in a > hurry to get this finished). As I advance more in Python, a design > change might happen :) Telling us your goal might allow us to recommend a better and faster way of accomplishing it. - Jeff Younker - jeff at drinktomi.com - From alan.gauld at btinternet.com Fri Mar 7 22:13:07 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 7 Mar 2008 21:13:07 -0000 Subject: [Tutor] Const on Python References: <47CF35D5.2050208@inf.ufsc.br><1204796398.13045.10.camel@localhost><60a9403b0803060508r47548cfcnfa339f5d872eeca6@mail.gmail.com><47CFF337.6050600@tds.net> <1204813091.13045.54.camel@localhost> <1204854143.7994.43.camel@localhost> <47D14014.9040403@tds.net> Message-ID: "Kent Johnson" wrote in > (Jumping in against my better judgment :-) :-) > Hmm...sure, programming is not about typing, it is about figuring > out > what to type. With Python the conceptual activity takes place at a > higher level because - Python provides easy-to-use, high-level > constructs like lists, dicts and first-order functions > - Python doesn't require you to think about low-level details like > const, private, getters and setters, braces, etc. Yes but thats not the bit that takes time in my experience its trying to understand the problem. What exactly am I trying to do here? Is it a suimulation exercise, a database problem? A real-time or networking issue? Should my solution include security protection? If so how much? Can I use a standard sort or do i need a custom algorithm? And if so what is it? Designing an algorithm takes far longer than converting it to code in any language. > So Python speeds up the thinking part. It speeds up the thinking abouit code bit, it doesn't help much in the thining about the problem part. > As far as the code, those 20-100 lines will do more if they are in > Python than they will if they are in Java or C++. Absolutely, thats why I write in Python and let the developers do the Java stuff - life is too short! And thats why I am on a Python mailing list not a Java one :-) > I don't see an order of magnitude difference between > Python and Java And thats my point, particularly for bigger projects where the problem complexity completely dominates the code complexity. The coding time will derinitely improve and I suspect you could get as high as 4 or 5 times but I doubt if you'd ever really achieve an order of magnitude. > have compared code samples, I have found Python code > to be 20-60% the size of equivalent Java code. In the few cases I've measured its been about 30% less which nearly falls into your range. But the examples were very small - all less than 1000 lines of Java - about as much Java as I can bring myself to type! Alan G. From ravikondamuru at gmail.com Fri Mar 7 22:18:49 2008 From: ravikondamuru at gmail.com (Ravi Kondamuru) Date: Fri, 7 Mar 2008 13:18:49 -0800 Subject: [Tutor] Processing unix style timestamp In-Reply-To: <47D136B1.8090500@tds.net> References: <36601b010803061555v7c1953dbx19d984319634486d@mail.gmail.com> <47D136B1.8090500@tds.net> Message-ID: <36601b010803071318r2fec6d18r19f1b674d574319c@mail.gmail.com> Thank you all for your insights. mx.DateTime and feedparser seem to be the easiest to work with. Ravi. On Fri, Mar 7, 2008 at 4:36 AM, Kent Johnson wrote: > Ravi Kondamuru wrote: > > I looked at datetime, but it seems slightly complex to work with non GMT > > timestamps. > > Mark Pilgrim's Universal Feed Parser includes a robust date parser that > works with your sample: > In [1]: import feedparser as fp > In [2]: fp._parse_date('Mon Feb 11 01:34:52 CST 2008') > Out[2]: (2008, 2, 11, 7, 34, 52, 0, 42, 0) > > http://www.feedparser.org/ > > This appears to be an RFC 2822-format date: > http://www.faqs.org/rfcs/rfc2822.html > > feedparser uses these functions to parse the date string: > In [4]: import rfc822 > In [5]: rfc822.parsedate_tz('Mon Feb 11 01:34:52 CST 2008') > Out[5]: (2008, 2, 11, 1, 34, 52, 0, 1, 0, -21600) > In [7]: rfc822.mktime_tz(_5) > Out[7]: 1202715292.0 > In [8]: import time > In [9]: time.gmtime(_7) > Out[9]: (2008, 2, 11, 7, 34, 52, 0, 42, 0) > > The rfc822 module is deprecated; the same functions are now found in > email.util. > > Kent > -- ???????? ???????? (Ravi Kondamuru) -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080307/81933a4e/attachment-0001.htm From technorapture at gmail.com Fri Mar 7 22:52:53 2008 From: technorapture at gmail.com (Shrutarshi Basu) Date: Fri, 7 Mar 2008 16:52:53 -0500 Subject: [Tutor] Creating a Python module to drive a robot Message-ID: <376fbdcf0803071352j6ca6a8f1n4a2cdc4e56634241@mail.gmail.com> Hi all, I'd like to create a library of functions that would allow writing Python scripts that would control a Hemisson robots via a serial interface. I'll be using the pyserial module heavily, but I'm wondering what would be the best way to approach this . Should I create a "Robot" class and define everything as functions of the class, such as a function for setting wheel speed, turning, reading from sensors etc. Or is there some other way that would be easier for a user? The project is meant for students who would be using programming the robot as an Intro to programming, so it would be best if users don't need to understand the details of OOP (or similar concepts) to use the code quickly and reliably. Thanks, Basu From ricaraoz at gmail.com Fri Mar 7 14:36:59 2008 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Fri, 07 Mar 2008 10:36:59 -0300 Subject: [Tutor] Const on Python In-Reply-To: References: <47CF35D5.2050208@inf.ufsc.br><1204796398.13045.10.camel@localhost><60a9403b0803060508r47548cfcnfa339f5d872eeca6@mail.gmail.com><47CFF337.6050600@tds.net> <1204813091.13045.54.camel@localhost> Message-ID: <47D144FB.4050502@bigfoot.com> Alan Gauld wrote: >> In commercial practice sometimes "political" considerations make for >> crazy decisions, e.g. witnessed by me: > >> 1.) a new web service needs to be developed. >> 2.) the policy of the company is that all developers need to know C > ++/Java. >> snipped... desire to use Python/Erlang >> 5.) The project lead makes him to do it in C++ anyway. Would make >> the >> scheduling of the group way to complicated if you could not assign >> any >> developer to every ticket coming in. >> >> That's the moment where you start scratching your head. > > Actually I'm with the lead here. > > The cost of developing a new feature is a tiny proportion of total > life cost of code - often only 5-10%. If Erlang is already being > used that might make some sense, but of the developers all know > Java/C++ then one of those makers more sense. If every > modification needs to wait for a Python/Erlang developer to > come free that would push the lifetime costs up dramatically. > > Its not a matter of politics but of business and TCO. > > I routinely build prototypes in Python, a few of which have been > "good enough" for the users, but nonetheless we have had > them rewritten in Java because thats what we use in house. > Nobody upgrades the Python version on the servers, only a > handfull of developers know Python. So it makes commecial > sense to rewrite the app in Java where anyone can fix/modify > it than have an app in Python than only a select few can > work on and costs a fortune in upgrades over the 10 years > or more the app may exist for. > That would be true if you assume that your business practices are established and should remain unchanged. But the essence of business is change, if developers all know Java/C++ you could gradually retrain them to learn Python. Then development costs would go down, you would have Python people for maintenance, and you might keep a core of your more experienced Java/C++ programmers available for optimizations in which you would need to interface Python with C++ functions. Now that would make business sense, if you accept that development practices don't necessarily have to be frozen. Of course all this would depend on the particulars of the business at hand. From ricaraoz at gmail.com Fri Mar 7 14:54:49 2008 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Fri, 07 Mar 2008 10:54:49 -0300 Subject: [Tutor] Const on Python In-Reply-To: <60a9403b0803060508r47548cfcnfa339f5d872eeca6@mail.gmail.com> References: <47CF35D5.2050208@inf.ufsc.br> <1204796398.13045.10.camel@localhost> <60a9403b0803060508r47548cfcnfa339f5d872eeca6@mail.gmail.com> Message-ID: <47D14929.7000505@bigfoot.com> Tiago Katcipis wrote: > thanks for the help Andreas, i dont really need that much a const so i > wont do anything like that to have a const like data. I am very used to > java and c++, thats why i always used acess modifier, but i think i can > live without it now i know that it dont exist in python :P. > > > > On Thu, Mar 6, 2008 at 6:39 AM, Andreas Kostyrka > wrote: > > > Am Mittwoch, den 05.03.2008, 21:07 -0300 schrieb Tiago Katcipis: > > Its a simple question but i have found some trouble to find a good > > answer to it, maybe i just dont searched enough but it wont cost > > anything to ask here, and it will not cost to much to answer :-). > I have > > started do develop on python and i really liked it, but im still > > learning. Im used to develop on c++ and java and i wanted to know if > > there is any way to create a final or const member, a member that > after > > assigned cant be reassigned. Thanks to anyone who tries to help > me and > > sorry to bother with a so silly question. i hope someday i can be > able > > to help :-) > > > > best regards > > > > katcipis In adition to all this I'd like to quote PEP 8 """ In addition, the following special forms using leading or trailing underscores are recognized (these can generally be combined with any case convention): - _single_leading_underscore: weak "internal use" indicator. E.g. "from M import *" does not import objects whose name starts with an underscore. - single_trailing_underscore_: used by convention to avoid conflicts with Python keyword, e.g. Tkinter.Toplevel(master, class_='ClassName') - __double_leading_underscore: when naming a class attribute, invokes name mangling (inside class FooBar, __boo becomes _FooBar__boo; see below). - __double_leading_and_trailing_underscore__: "magic" objects or attributes that live in user-controlled namespaces. E.g. __init__, __import__ or __file__. Never invent such names; only use them as documented. """ As far as I can understand it if I want a class attribute that I'd rather not have touched (weak internal use indicator, I just extend it's use from modules to classes) I'd name it _attribute, if I want an attribute that I forbid to touch (strong internal use indicator, modify at your own risk) then I name it __attribute. That should be enough for any grown up use. PEP 8 : http://www.python.org/dev/peps/pep-0008/ From lauren at protopc.com Fri Mar 7 23:23:29 2008 From: lauren at protopc.com (lauren at protopc.com) Date: Fri, 7 Mar 2008 15:23:29 -0700 (MST) Subject: [Tutor] Automating the windows GUI for testing purposes Message-ID: <1203.69.16.140.5.1204928609.squirrel@www.protopc.com> Hello, I will be automating the windows gui for the purposes of writing automated test scripts. I have worked with Ruby before using the watir test library for testing web applications (more or less similar to PAMIE, I believe) - but now I am required to automate some applications running on windows. I've looked into using pywinauto and also WATSUP. Both are possible libraries I could use...but they lack the documentation I was hoping to hook into. Has anyone on this list done this sucessfully before? What tools/libraries did you use? Which python libraries are best suited for this type of work? Thank you in advance, Lauren From alan.gauld at btinternet.com Sat Mar 8 00:30:43 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 7 Mar 2008 23:30:43 -0000 Subject: [Tutor] Const on Python References: <47CF35D5.2050208@inf.ufsc.br><1204796398.13045.10.camel@localhost><60a9403b0803060508r47548cfcnfa339f5d872eeca6@mail.gmail.com><47CFF337.6050600@tds.net> <1204813091.13045.54.camel@localhost> <47D144FB.4050502@bigfoot.com> Message-ID: "Ricardo Ar?oz" wrote > That would be true if you assume that your business practices are > established and should remain unchanged. But the essence of business > is > change, if developers all know Java/C++ you could gradually retrain > them > to learn Python. Thats true and if it weren'#t we'd still all be programming in octal codes. But in kost businesses I've seen that kind of change is instigated by starting a completely new project using the chosen language (usually chosen after several small trials and evaluations) rather than by introducing a new language into an existing system which was the original scenario. > Python people for maintenance, and you might keep a core of your > more > experienced Java/C++ programmers available for optimizations in > which > you would need to interface Python with C++ functions. Now that > would > make business sense Absolutely. I totally agree that moving an organization to Python or similar modern language is a sensible move for many applications. Only where very high performance or scaleability are required would Python (or similar) be inappropriate and even in the largest organisations that is a minority case. And of course web services provide a glue that any language can utilise to remove most issues of integration between apps in different languages (which used to be a very valid concern). My only dispute is the wisdom of introducing foreign code into an existing app. Andreas has already said in fact the new languages are already supported so that makes the scenario valid also. Alan G From alan.gauld at btinternet.com Sat Mar 8 00:37:10 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 7 Mar 2008 23:37:10 -0000 Subject: [Tutor] Automating the windows GUI for testing purposes References: <1203.69.16.140.5.1204928609.squirrel@www.protopc.com> Message-ID: wrote > I've looked into using pywinauto and also WATSUP. Both are possible > libraries I could use...but they lack the documentation I was hoping > to > hook into. > > Has anyone on this list done this sucessfully before? What > tools/libraries > did you use? I haven't done it from Python but I have done similar things from Delphi using the Win32 API call postmessage() to send Windows events to another application (the one under test). Much more tricky is extracting the data changes from the target app. Its OK if you know the Windows handle of the widgets but otherwise its a painful process of using WinSpy to monitor events in the app and deduce the handles required... If you can find a module that helps do any of that then I'd try it. Maybe use the >>> prompt to send a few test messages and monitor results using something relatively simple like Notepad... Alan G From andreas at kostyrka.org Sat Mar 8 03:16:40 2008 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Sat, 08 Mar 2008 03:16:40 +0100 Subject: [Tutor] Const on Python In-Reply-To: References: <47CF35D5.2050208@inf.ufsc.br> <1204796398.13045.10.camel@localhost> <60a9403b0803060508r47548cfcnfa339f5d872eeca6@mail.gmail.com> <47CFF337.6050600@tds.net> <1204813091.13045.54.camel@localhost> <1204854143.7994.43.camel@localhost> <47D14014.9040403@tds.net> Message-ID: <1204942600.7994.100.camel@localhost> Am Freitag, den 07.03.2008, 21:13 +0000 schrieb Alan Gauld: > Yes but thats not the bit that takes time in my experience its > trying to understand the problem. What exactly am I trying to > do here? Is it a suimulation exercise, a database problem? > A real-time or networking issue? Should my solution include > security protection? If so how much? Can I use a standard > sort or do i need a custom algorithm? And if so what is it? > > Designing an algorithm takes far longer than converting it to > code in any language. Right, but I've encountered it more than once in my professional life, that the C++ guys where still trying to implement a simple algorithm, while I was already finetuning a 2nd or 3rd generation of code. And while it's not always a magnitude, and it's hard to measure, the few times where I had to ability to compare (either because I was working parallel or was replacing a failed C++ project), a magnitude seems to describe the difference in development efficiency. And this incremental improvements is the usual way, because without a working prototype it's hard (and partially foolish) to decide which parts of the design need improvements. (Remember, "Good-Enough" is the relevant criteria when it comes to performance, so designing and implementating the best algorithm from scratch does not make sense (because often vastly simpler algorithms can provide the needed performance, and again, it's really hard to guess which parts will be critical for the performance) > > > So Python speeds up the thinking part. > > It speeds up the thinking abouit code bit, it doesn't help much > in the thining about the problem part. You are forgetting a critical part. When speaking about coding, I'm talking about writing the code, and getting it reasonable bugfree/usable. And that's where Python shines. > > > As far as the code, those 20-100 lines will do more if they are in > > Python than they will if they are in Java or C++. > > Absolutely, thats why I write in Python and let the developers > do the Java stuff - life is too short! And thats why I am on a > Python mailing list not a Java one :-) > > > I don't see an order of magnitude difference between > > Python and Java > > And thats my point, particularly for bigger projects where > the problem complexity completely dominates the code > complexity. The coding time will derinitely improve and I > suspect you could get as high as 4 or 5 times but I doubt > if you'd ever really achieve an order of magnitude. Actually, the project where I achieved over a magnitude speedup was highly complicated, involved partial reverse-engineering of binary formats, embedding Python in a C++ app, refactoring the C++ app to support multiple input handlers, doing a framework, optimizing, portability to all kind of old UNIX boxes (the app had designed minimum life cycle of 30 years), ... The C++ guys gave up in disgust after more than 9 months into the project. I had overtaken all their tries after one month. OTOH, if I'd compare me with the designed time for the project (which was 12 months), I have been only 2-3 times as fast as management had planned. In practice, the C++ guys had massive problems, and if their progress had been any measure, they would have taken at least 24-30 months getting the project going. I know it's unnice, because the project had not complete specifications (well, management claimed that it had all specs needed, as it happens the more important half of the specs needed to be reverse engineered. With data files in the MB range, manual decoding was not an workable solution. But the experimenting wasn't that bad with for me, while the C++ guy never reached the point where deciphering the semantic meaning of the data was relevant to them.) So I stand by the "magnitude" of developer efficiency difference. It's not there for every project, but OTOH there are other projects where you can get even more speedup. (Don't you have ever listened in on projects that are infrastructure building that is just, well, a nonissue in Python?) And btw, it's not just Python, it just happens to me my default language. Highlevel languages do "pay", and it's starting to show slowly in the industry. (Well, 1-2 years ago, my CV was "optimized" to for non-Python experience. The last year, I've been usually able to pick Python contracts without much of troubles, so Python is growing in commercial settings.) > > > have compared code samples, I have found Python code > > to be 20-60% the size of equivalent Java code. > > In the few cases I've measured its been about 30% less > which nearly falls into your range. But the examples were very > small - all less than 1000 lines of Java - about as much > Java as I can bring myself to type! Well, Java is already a relative "high-level" language, it's basically safe, which helps debugging greatly, and is being made into something even more highlevel by all kinds of IDE wizards. I wouldn't expect a magnitude between Java/Python, just because Java is way nearer to Python than that it is to C++. (Despite the syntax.) Andreas -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Dies ist ein digital signierter Nachrichtenteil Url : http://mail.python.org/pipermail/tutor/attachments/20080308/a3d85179/attachment-0001.pgp From ricaraoz at gmail.com Sat Mar 8 04:48:07 2008 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Sat, 08 Mar 2008 00:48:07 -0300 Subject: [Tutor] Const on Python In-Reply-To: References: <47CF35D5.2050208@inf.ufsc.br><1204796398.13045.10.camel@localhost><60a9403b0803060508r47548cfcnfa339f5d872eeca6@mail.gmail.com><47CFF337.6050600@tds.net> <1204813091.13045.54.camel@localhost> <47D144FB.4050502@bigfoot.com> Message-ID: <47D20C77.4050005@bigfoot.com> Alan Gauld wrote: > Absolutely. I totally agree that moving an organization to Python > or similar modern language is a sensible move for many applications. > Only where very high performance or scaleability are required would > Python (or similar) be inappropriate and even in the largest > organisations that is a minority case. And of course web services > provide a glue that any language can utilise to remove most > issues of integration between apps in different languages > (which used to be a very valid concern). > > My only dispute is the wisdom of introducing foreign code > into an existing app. Andreas has already said in fact the > new languages are already supported so that makes the > scenario valid also. > Well, I guess it's about what you think a programmer is. I think if you are a "true" programmer you'll be good in ANY language (though you may have your preferences) and you'll be able to do 80% of your work in any language (and learn 80% of any language in a short time). So there would not really be such a problem with "foreign code", the only issues I foresee are establishing proper "coding rules" for the company, that might take some time and produce some flaky code. As for integration between apps, if the languages are python and C/C++ it seems not to be a problem (never done it), there is : http://www.python.org/doc/ext/intro.html Ricardo From jeff at drinktomi.com Sat Mar 8 05:13:24 2008 From: jeff at drinktomi.com (Jeff Younker) Date: Fri, 7 Mar 2008 20:13:24 -0800 Subject: [Tutor] Const on Python In-Reply-To: <47D20C77.4050005@bigfoot.com> References: <47CF35D5.2050208@inf.ufsc.br><1204796398.13045.10.camel@localhost><60a9403b0803060508r47548cfcnfa339f5d872eeca6@mail.gmail.com><47CFF337.6050600@tds.net> <1204813091.13045.54.camel@localhost> <47D144FB.4050502@bigfoot.com> <47D20C77.4050005@bigfoot.com> Message-ID: <69810C5C-4F9B-41BC-BB95-DCBDA5E1F4CC@drinktomi.com> On Mar 7, 2008, at 7:48 PM, Ricardo Ar?oz wrote: > Alan Gauld wrote: > Well, I guess it's about what you think a programmer is. I think if > you > are a "true" programmer you'll be good in ANY language (though you may > have your preferences) and you'll be able to do 80% of your work in > any > language (and learn 80% of any language in a short time). So there > would > not really be such a problem with "foreign code", the only issues I > foresee are establishing proper "coding rules" for the company, that > might take some time and produce some flaky code. As for integration > between apps, if the languages are python and C/C++ it seems not to > be a > problem (never done it), there is : > http://www.python.org/doc/ext/intro.html It's easy to learn the basic features of a language and to use those, but developing fluency is much harder, and it takes a much longer time. - Jeff Younker - jeff at drinktomi.com - From tetsuo2k6 at web.de Sat Mar 8 13:57:28 2008 From: tetsuo2k6 at web.de (tetsuo2k6 at web.de) Date: Sat, 08 Mar 2008 13:57:28 +0100 Subject: [Tutor] identifying the calling module/function In-Reply-To: <9EE1AEC7-D09D-4D28-B9BE-DD46A329EADE@drinktomi.com> References: <47D1402A.8000400@web.de> <47D14529.2090803@tds.net> <47D14B63.6050209@web.de> <9EE1AEC7-D09D-4D28-B9BE-DD46A329EADE@drinktomi.com> Message-ID: <47D28D38.5060709@web.de> Jeff Younker schrieb: > > Telling us your goal might allow us to recommend a better > and faster way of accomplishing it. > > - Jeff Younker - jeff at drinktomi.com - > > > in dgf.py: (hope the formatting gets good for you, t-bird breaks the lines badly on my machine...) def csvwriter(*column_definitions): """Edit Me!""" if sys.argv[0] == /usr/local/bin/xyz.py: # sorry, I am not allowed to give you guys xyz.py here, or the real name of the script - my boss is a bit paranoid o.O output_csv_filename = "xyz.csv" else: output_csv_filename = raw_input("Name of the file to produce? (ATTENTION: WILL BE OVERWRITTEN!) ") first_row = ";".join(*column_definitions) try: file = open(output_csv_filename, "w") file.write(first_row) file.close() except: print("Couldn't open %s for writing." % output_csv_filename) sys.exit(1) return csv.writer(open(output_csv_filename, "ab"), delimiter=";", quoting=csv.QUOTE_NONE) Well, I am starting to realize that the whole thing might be a bit unnecessary... Just keeps me from creating csv.writer objects everywhere when the dialect is always the same. Also, I don't know if I understood the *argument_list thing correctly... From ricaraoz at gmail.com Sat Mar 8 15:51:43 2008 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Sat, 08 Mar 2008 11:51:43 -0300 Subject: [Tutor] Const on Python In-Reply-To: <69810C5C-4F9B-41BC-BB95-DCBDA5E1F4CC@drinktomi.com> References: <47CF35D5.2050208@inf.ufsc.br><1204796398.13045.10.camel@localhost><60a9403b0803060508r47548cfcnfa339f5d872eeca6@mail.gmail.com><47CFF337.6050600@tds.net> <1204813091.13045.54.camel@localhost> <47D144FB.4050502@bigfoot.com> <47D20C77.4050005@bigfoot.com> <69810C5C-4F9B-41BC-BB95-DCBDA5E1F4CC@drinktomi.com> Message-ID: <47D2A7FF.6010202@bigfoot.com> Jeff Younker wrote: > On Mar 7, 2008, at 7:48 PM, Ricardo Ar?oz wrote: > >> Alan Gauld wrote: >> Well, I guess it's about what you think a programmer is. I think if >> you >> are a "true" programmer you'll be good in ANY language (though you may >> have your preferences) and you'll be able to do 80% of your work in >> any >> language (and learn 80% of any language in a short time). So there >> would >> not really be such a problem with "foreign code", the only issues I >> foresee are establishing proper "coding rules" for the company, that >> might take some time and produce some flaky code. As for integration >> between apps, if the languages are python and C/C++ it seems not to >> be a >> problem (never done it), there is : >> http://www.python.org/doc/ext/intro.html > > It's easy to learn the basic features of a language and to use those, > but > developing fluency is much harder, and it takes a much longer time. > Absolutely true, but we are talking about a knowledgeable programmer coding the app and a newbie to the language (not to coding) has to do some maintenance. The fluency is already coded and can be aped (if what you have to do is maintenance and not a complete rebuild), and if a few un-elegant lines are added, you can live with it. From dave6502 at googlemail.com Sat Mar 8 17:46:27 2008 From: dave6502 at googlemail.com (dave selby) Date: Sat, 8 Mar 2008 16:46:27 +0000 Subject: [Tutor] Problems with ConfigParser set method Message-ID: Hi All, I am using the ConfigParser module, I can 'get' from a config file fine, when I try to set it, it silently fails. the code. parser = ConfigParser.SafeConfigParser() parser.read('./daemon.rc') print parser.get('feeds', 'number') parser.set('feeds', 'number', '99') print parser.get('feeds', 'number') there is a section [feeds], and option number, it is set to 1. If I execute the script I get ... dave at dev-machine:/var/lib/kmotion/daemons$ ./daemon_start.py 1 99 dave at dev-machine:/var/lib/kmotion/daemons$ ./daemon_start.py 1 99 dave at dev-machine:/var/lib/kmotion/daemons$ The first call returns as expected, the second should return 99, 99 not 1, 99. On opening daemons.rc the 'number' option is not changed. Any ideas ? Cheers Dave -- Please avoid sending me Word or PowerPoint attachments. See http://www.gnu.org/philosophy/no-word-attachments.html From alan.gauld at btinternet.com Sat Mar 8 19:29:01 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 8 Mar 2008 18:29:01 -0000 Subject: [Tutor] Problems with ConfigParser set method References: Message-ID: "dave selby" wrote in message news:f52017b60803080846j6ee098dp955403011c1548d2 at mail.gmail.com... > Hi All, > > I am using the ConfigParser module, I can 'get' from a config file > fine, when I try to set it, it silently fails. the code. > > parser = ConfigParser.SafeConfigParser() > parser.read('./daemon.rc') > print parser.get('feeds', 'number') > parser.set('feeds', 'number', '99') > print parser.get('feeds', 'number') I've not used this module but since you have a read at the start shouldn't you use a write at the end? Otherwise it will only be set in memory I presume? Alan G From bryan.fodness at gmail.com Sat Mar 8 20:31:24 2008 From: bryan.fodness at gmail.com (Bryan Fodness) Date: Sat, 8 Mar 2008 14:31:24 -0500 Subject: [Tutor] identifying and parsing string in text file Message-ID: I have a large file that has many lines like this, SITE I would like to identify the line by the tag (300a,0014) and then grab the name (DoseReferenceStructureType) and value (SITE). I would like to create a file that would have the structure, DoseReferenceStructureType = Site ... ... Also, there is a possibility that there are multiple lines with the same tag, but different values. These all need to be recorded. So far, I have a little bit of code to look at everything that is available, for line in open(str(sys.argv[1])): i_line = line.split() if i_line: if i_line[0] == " References: <376fbdcf0803071352j6ca6a8f1n4a2cdc4e56634241@mail.gmail.com> Message-ID: <47D2FCCA.5020305@tds.net> Shrutarshi Basu wrote: > Hi all, > I'd like to create a library of functions that would allow writing > Python scripts that would control a Hemisson robots via a serial > interface. Do you know about Pyro? It supports Hemisson robots: http://pyrorobotics.org/ I'll be using the pyserial module heavily, but I'm > wondering what would be the best way to approach this . Should I > create a "Robot" class and define everything as functions of the > class, such as a function for setting wheel speed, turning, reading > from sensors etc. Or is there some other way that would be easier for > a user? The project is meant for students who would be using > programming the robot as an Intro to programming, so it would be best > if users don't need to understand the details of OOP (or similar > concepts) to use the code quickly and reliably. The simplest way to control a single robot is probably to use module-level functions to control the robot. You can still have a robot class; the module functions can delegate to a single instance of Robot. The turtle module does this, too; it has a global instance of Pen which is used by the global functions. Kent From kent37 at tds.net Sat Mar 8 22:04:03 2008 From: kent37 at tds.net (Kent Johnson) Date: Sat, 08 Mar 2008 16:04:03 -0500 Subject: [Tutor] identifying the calling module/function In-Reply-To: <47D28D38.5060709@web.de> References: <47D1402A.8000400@web.de> <47D14529.2090803@tds.net> <47D14B63.6050209@web.de> <9EE1AEC7-D09D-4D28-B9BE-DD46A329EADE@drinktomi.com> <47D28D38.5060709@web.de> Message-ID: <47D2FF43.7000109@tds.net> tetsuo2k6 at web.de wrote: > in dgf.py: (hope the formatting gets good for you, t-bird breaks the > lines badly on my machine...) > > def csvwriter(*column_definitions): > """Edit Me!""" > if sys.argv[0] == /usr/local/bin/xyz.py: > output_csv_filename = "xyz.csv" > else: > output_csv_filename = raw_input("Name of the file to produce? > (ATTENTION: WILL BE OVERWRITTEN!) ") If you can change xyz.py you can avoid this by adding an optional filename parameter to the function. > first_row = ";".join(*column_definitions) > try: > file = open(output_csv_filename, "w") > file.write(first_row) > file.close() > except: > print("Couldn't open %s for writing." % output_csv_filename) It's not such a good idea to hide the exception like this; you might at least want to print the actual exception. Or just let it propagate. > sys.exit(1) You can use the csv module to write the header row, too. I would write this as def csvwriter(*column_definitions, filename=None): if filename is none: filename = raw_input("Name of the file to produce? (ATTENTION: WILL BE OVERWRITTEN!) ") try: out = csv.writer(open(filename, "ab"), delimiter=";", quoting=csv.QUOTE_NONE) out.writerow(column_definitions) except Exception, e print("Couldn't open %s for writing." % output_csv_filename) print e return out Kent From spanfax at charter.net Sat Mar 8 21:03:42 2008 From: spanfax at charter.net (Enrique Nieves, Jr.) Date: Sat, 8 Mar 2008 15:03:42 -0500 Subject: [Tutor] self-learning Python Message-ID: <000001c88157$9689cbd0$6501a8c0@NETVISTAUSER> I'm not a programmer, but would like to learn to program. I'm considering self-learning python on my spare time. Can you recommend the best books, online training, or other resources? I know nothing about programming. enrique -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080308/1f251f74/attachment.htm From marc.tompkins at gmail.com Sat Mar 8 22:21:52 2008 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Sat, 8 Mar 2008 13:21:52 -0800 Subject: [Tutor] identifying and parsing string in text file In-Reply-To: References: Message-ID: <40af687b0803081321g40514ccfo6f8f15c73fa92394@mail.gmail.com> Sure sounds like XML to me... I'm just snatching a moment from Saturday chores to type this, but there are a bunch of modules available for XML manipulation - elementtree is built-in; I personally prefer Amara - and I'll bet that a few minutes spent with the docs for either module will tell you what you need to know. On Sat, Mar 8, 2008 at 11:31 AM, Bryan Fodness wrote: > I have a large file that has many lines like this, > > name="DoseReferenceStructureType">SITE > I would like to identify the line by the tag (300a,0014) and then grab the > name (DoseReferenceStructureType) and value (SITE). > > I would like to create a file that would have the structure, > > DoseReferenceStructureType = Site > ... > ... > > Also, there is a possibility that there are multiple lines with the same > tag, but different values. These all need to be recorded. > > So far, I have a little bit of code to look at everything that is > available, > > for line in open(str(sys.argv[1])): > i_line = line.split() > if i_line: > if i_line[0] == " a = i_line[1] > b = i_line[5] > print "%s | %s" %(a, b) > > but do not see a clever way of doing what I would like. > > Any help or guidance would be appreciated. > > Bryan > > > > > -- > "The game of science can accurately be described as a never-ending insult > to human intelligence." - Jo?o Magueijo > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080308/04fba62d/attachment-0001.htm From jim at well.com Sat Mar 8 22:23:32 2008 From: jim at well.com (jim stockford) Date: Sat, 8 Mar 2008 13:23:32 -0800 Subject: [Tutor] self-learning Python In-Reply-To: <000001c88157$9689cbd0$6501a8c0@NETVISTAUSER> References: <000001c88157$9689cbd0$6501a8c0@NETVISTAUSER> Message-ID: <4271198ceb794c920c35db3495157772@well.com> i'm working (gratefully) with a small python study group and preparing an intro to python class. if you like, i'll send you my lessons and hope for your questions and feedback. mine is certainly not the best python material (i think it's not bad), but it comes with the ability for you to ask questions and provide feedback. it seems that some colleges and universities are starting to use python for their introductory courses. python is well designed and many people find it particularly fun to use. jim at well.com On Mar 8, 2008, at 12:03 PM, Enrique Nieves, Jr. wrote: > I?m not a programmer, but would like to learn to program.? I?m > considering self-learning python on my spare time.? Can you recommend > the best books, online training, or other resources?? I know nothing > about programming. > ? > enrique > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From kent37 at tds.net Sat Mar 8 22:35:28 2008 From: kent37 at tds.net (Kent Johnson) Date: Sat, 08 Mar 2008 16:35:28 -0500 Subject: [Tutor] identifying and parsing string in text file In-Reply-To: References: Message-ID: <47D306A0.7040800@tds.net> Bryan Fodness wrote: > I have a large file that has many lines like this, > > name="DoseReferenceStructureType">SITE > I would like to identify the line by the tag (300a,0014) and then grab > the name (DoseReferenceStructureType) and value (SITE). > > I would like to create a file that would have the structure, > > DoseReferenceStructureType = Site Presuming that your source file is XML, I think I would use ElementTree.iterparse() to process this. http://effbot.org/zone/element-iterparse.htm http://docs.python.org/lib/elementtree-functions.html Something like this (untested): from xml.etree.ElementTree import iterparse source = open('mydata.xml').read() out = open('myoutput.txt', 'w') for event, elem in iterparse(source): if elem.tag == "element": name = elem['name'] text = elem.text out.write('%s = %s\n' % (name, text) elem.clear() out.close() From kent37 at tds.net Sat Mar 8 22:39:16 2008 From: kent37 at tds.net (Kent Johnson) Date: Sat, 08 Mar 2008 16:39:16 -0500 Subject: [Tutor] self-learning Python In-Reply-To: <000001c88157$9689cbd0$6501a8c0@NETVISTAUSER> References: <000001c88157$9689cbd0$6501a8c0@NETVISTAUSER> Message-ID: <47D30784.3090506@tds.net> Enrique Nieves, Jr. wrote: > I?m not a programmer, but would like to learn to program. I?m > considering self-learning python on my spare time. Can you recommend > the best books, online training, or other resources? I know nothing > about programming. There are several good on-line tutorials for beginners: http://wiki.python.org/moin/BeginnersGuide/NonProgrammers I think the best book for the absolute beginner is "Python Programming for the absolute beginner" by Michael Dawson. You can ask questions here when you get stuck. Kent From alan.gauld at btinternet.com Sun Mar 9 00:35:07 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 8 Mar 2008 23:35:07 -0000 Subject: [Tutor] self-learning Python References: <000001c88157$9689cbd0$6501a8c0@NETVISTAUSER> Message-ID: "Enrique Nieves, Jr." wrote > I'm not a programmer, but would like to learn to program. I'm > considering > self-learning python on my spare time. Can you recommend the best > books, > online training, or other resources? I know nothing about > programming. Yes, you can learn to program Python by teaching yourself using any of several tutorials on the Python web site. When you get stuck ask for help on this mailing list. You will find a list of tutorials here: http://wiki.python.org/moin/BeginnersGuide/NonProgrammers Note that my site is still dead so use the link below if you weant to check it out rather than the one on the Python site... -- Alan Gauld Author of the Learn to Program web site Temorarily at: http://uk.geocities.com/alan.gauld at btinternet.com/ Normally: http://www.freenetpages.co.uk/hp/alan.gauld From andreas at kostyrka.org Sun Mar 9 00:52:13 2008 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Sun, 09 Mar 2008 00:52:13 +0100 Subject: [Tutor] Problems with ConfigParser set method In-Reply-To: References: Message-ID: <1205020333.2230.0.camel@localhost> As I thought, it does not fail silently. You need something like: if not parser.has_section("feeds"): parser.add_section("feeds") Andreas Am Samstag, den 08.03.2008, 16:46 +0000 schrieb dave selby: > Hi All, > > I am using the ConfigParser module, I can 'get' from a config file > fine, when I try to set it, it silently fails. the code. > > parser = ConfigParser.SafeConfigParser() > parser.read('./daemon.rc') > print parser.get('feeds', 'number') > parser.set('feeds', 'number', '99') > print parser.get('feeds', 'number') > > there is a section [feeds], and option number, it is set to 1. If I > execute the script I get ... > > dave at dev-machine:/var/lib/kmotion/daemons$ ./daemon_start.py > 1 > 99 > dave at dev-machine:/var/lib/kmotion/daemons$ ./daemon_start.py > 1 > 99 > dave at dev-machine:/var/lib/kmotion/daemons$ > > > The first call returns as expected, the second should return 99, 99 > not 1, 99. On opening daemons.rc the 'number' option is not changed. > > Any ideas ? > > Cheers > > Dave > > > > > > > > > > > > > > -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Dies ist ein digital signierter Nachrichtenteil Url : http://mail.python.org/pipermail/tutor/attachments/20080309/8df7765f/attachment.pgp From midnightjulia at gmail.com Sun Mar 9 13:16:59 2008 From: midnightjulia at gmail.com (Julia) Date: Sun, 9 Mar 2008 13:16:59 +0100 Subject: [Tutor] self-learning Python Message-ID: > > Message: 3 > Date: Sat, 08 Mar 2008 16:39:16 -0500 > From: Kent Johnson > Subject: Re: [Tutor] self-learning Python > To: "Enrique Nieves, Jr." > Cc: tutor at python.org > Message-ID: <47D30784.3090506 at tds.net> > Content-Type: text/plain; charset=windows-1252; format=flowed > > Enrique Nieves, Jr. wrote: > > I?m not a programmer, but would like to learn to program. I?m > > considering self-learning python on my spare time. Can you recommend > > the best books, online training, or other resources? I know nothing > > about programming. > > There are several good on-line tutorials for beginners: > http://wiki.python.org/moin/BeginnersGuide/NonProgrammers > > I think the best book for the absolute beginner is "Python Programming > for the absolute beginner" by Michael Dawson. > > You can ask questions here when you get stuck. > > Kent To be honest I truly dislike the Dawson book. I wouldn't recommend it to anyone. It's lacks technical clarity, examples and has a messy index. I'm going to sell my example asap. I currently use multiple books for reference and because I haven't found one really good book yet. In the end I'd say python.org is the best resource for learning Python :) /J -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080309/871257d4/attachment.htm From emadnawfal at gmail.com Sun Mar 9 13:28:48 2008 From: emadnawfal at gmail.com (Emad Nawfal) Date: Sun, 9 Mar 2008 08:28:48 -0400 Subject: [Tutor] self-learning Python In-Reply-To: References: Message-ID: <652641e90803090528r63fbc0cv27d3e4c45c7718e3@mail.gmail.com> On Sun, Mar 9, 2008 at 8:16 AM, Julia wrote: > Message: 3 > > Date: Sat, 08 Mar 2008 16:39:16 -0500 > > From: Kent Johnson > > Subject: Re: [Tutor] self-learning Python > > To: "Enrique Nieves, Jr." > > Cc: tutor at python.org > > Message-ID: <47D30784.3090506 at tds.net> > > Content-Type: text/plain; charset=windows-1252; format=flowed > > > > Enrique Nieves, Jr. wrote: > > > I?m not a programmer, but would like to learn to program. I?m > > > considering self-learning python on my spare time. Can you recommend > > > the best books, online training, or other resources? I know nothing > > > about programming. > > > > There are several good on-line tutorials for beginners: > > http://wiki.python.org/moin/BeginnersGuide/NonProgrammers > > > > I think the best book for the absolute beginner is "Python Programming > > for the absolute beginner" by Michael Dawson. > > > > You can ask questions here when you get stuck. > > > > Kent > > > To be honest I truly dislike the Dawson book. I wouldn't recommend it to > anyone. It's lacks technical clarity, examples and has a messy index. I'm > going to sell my example asap. > > I currently use multiple books for reference and because I haven't found > one really good book yet. In the end I'd say python.org is the best > resource for learning Python :) > /J > When I started learning Python, I had had no programming background whatsoever. It was Michael Dawson's book that got me off the ground. I then read another book "Python programming: an introduction to computer science", and things began to make sense to me. Non-programmers have a hard time grasping things programmers take for granted. That's why Dawson's book may not be good for experienced people. I definitely recommend it to true beginners. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- ?? ???? ?????? ????? ????? ??? ???? ??? ????? ?? ?????? ????????.....???? ??????? "No victim has ever been more repressed and alienated than the truth" Emad Soliman Nawfal Indiana University, Bloomington http://emnawfal.googlepages.com -------------------------------------------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080309/0900a382/attachment.htm From kent37 at tds.net Sun Mar 9 13:54:12 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 09 Mar 2008 08:54:12 -0400 Subject: [Tutor] self-learning Python In-Reply-To: <652641e90803090528r63fbc0cv27d3e4c45c7718e3@mail.gmail.com> References: <652641e90803090528r63fbc0cv27d3e4c45c7718e3@mail.gmail.com> Message-ID: <47D3DDF4.9050708@tds.net> Emad Nawfal wrote: > On Sun, Mar 9, 2008 at 8:16 AM, Julia > wrote: > To be honest I truly dislike the Dawson book. I wouldn't recommend > it to anyone. It's lacks technical clarity, examples and has a messy > index. I'm going to sell my example asap. I'm not sure what kind of clarity you want. To be sure Dawson is not nearly as precise and comprehensive as Learning Python, for example, but I think the more casual approach is better for a complete beginner. ISTM Dawson is written almost entirely as a series of extended examples, I'm really surprised that you say it lacks examples. > When I started learning Python, I had had no programming background > whatsoever. It was Michael Dawson's book that got me off the ground. I > then read another book "Python programming: an introduction to computer > science", and things began to make sense to me. I almost mentioned that one too. Python for Dummies might also be a good choice but I haven't seen that. O'Reilly is coming out with a book Head First Programming that uses Python but it isn't scheduled to be published until May. Kent From wesbrooks at gmail.com Sun Mar 9 14:57:36 2008 From: wesbrooks at gmail.com (Wesley Brooks) Date: Sun, 9 Mar 2008 13:57:36 +0000 Subject: [Tutor] Make sound with python? Cross platform? Message-ID: Dear Users, I've been digging around to try and find a way to make python make sound. I would either like to sound out a string of musical notes including rests or simply have something that I set the frequency and duration then sound and repeat for the number of notes. If possible I would prefer a solution that is cross platform, and standard library but would settle for Linux only solutions that can be downloaded - which preferably don't need compiling. Thanks for any suggestions. Yours Faithfully, Wesley Brooks From luciano at ramalho.org Sun Mar 9 15:05:32 2008 From: luciano at ramalho.org (Luciano Ramalho) Date: Sun, 9 Mar 2008 11:05:32 -0300 Subject: [Tutor] Make sound with python? Cross platform? In-Reply-To: References: Message-ID: <4331ad810803090705h6b7b974x23a6cfd0475c2430@mail.gmail.com> On Sun, Mar 9, 2008 at 10:57 AM, Wesley Brooks wrote: > I've been digging around to try and find a way to make python make > sound. I would either like to sound out a string of musical notes [...] Wesley, take a look at PyGame [1]. PyGame is a Python wrapper on top of SDL [2], a multi-platform multimedia library. [1] http://www.pygame.org/news.html [2] http://www.libsdl.org/ Cheers, Luciano On Sun, Mar 9, 2008 at 10:57 AM, Wesley Brooks wrote: > Dear Users, > > I've been digging around to try and find a way to make python make > sound. I would either like to sound out a string of musical notes > including rests or simply have something that I set the frequency and > duration then sound and repeat for the number of notes. > > If possible I would prefer a solution that is cross platform, and > standard library but would settle for Linux only solutions that can be > downloaded - which preferably don't need compiling. > > Thanks for any suggestions. > > Yours Faithfully, > > Wesley Brooks > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Sun Mar 9 15:17:11 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 09 Mar 2008 10:17:11 -0400 Subject: [Tutor] Make sound with python? Cross platform? In-Reply-To: References: Message-ID: <47D3F167.5050306@tds.net> Wesley Brooks wrote: > Dear Users, > > I've been digging around to try and find a way to make python make > sound. I would either like to sound out a string of musical notes > including rests or simply have something that I set the frequency and > duration then sound and repeat for the number of notes. > > If possible I would prefer a solution that is cross platform, and > standard library but would settle for Linux only solutions that can be > downloaded - which preferably don't need compiling. pygame and pyglet+avbin both play sounds, are cross-platform and have binaries available for Windows, Mac and Linux. The "Playing and creating sound" section of this page looks promising: http://wiki.python.org/moin/PythonInMusic Kent From luciano at ramalho.org Sun Mar 9 15:23:00 2008 From: luciano at ramalho.org (Luciano Ramalho) Date: Sun, 9 Mar 2008 11:23:00 -0300 Subject: [Tutor] self-learning Python In-Reply-To: <47D3DDF4.9050708@tds.net> References: <652641e90803090528r63fbc0cv27d3e4c45c7718e3@mail.gmail.com> <47D3DDF4.9050708@tds.net> Message-ID: <4331ad810803090723m7ecfe7d5tafcf7fbcb7b8fd91@mail.gmail.com> My recommendation for a book to learn to program, using Python is "How to think like a Computer Scientist: learning with Python (2nd edition)" [1]. It's a free online book, but a printed version of the first edition is also available. [1] http://openbookproject.net/thinkCSpy/index.xhtml Don't let the "Computer Scientist" in the title scare you: it is a very accessible text which assumes no background in programming, and explains all of the basic concepts and jargon very well. Includes a useful glossary at the end of each chapter. The 2nd edition also has exercises. Cheers, Luciano From wesbrooks at gmail.com Sun Mar 9 15:29:51 2008 From: wesbrooks at gmail.com (Wesley Brooks) Date: Sun, 9 Mar 2008 14:29:51 +0000 Subject: [Tutor] Make sound with python? Cross platform? In-Reply-To: <47D3F167.5050306@tds.net> References: <47D3F167.5050306@tds.net> Message-ID: Thanks very much. Not quite sure why I didn't find those earlier! I'll have a look now. Cheers, Wesley. On 09/03/2008, Kent Johnson wrote: > Wesley Brooks wrote: > > Dear Users, > > > > I've been digging around to try and find a way to make python make > > sound. I would either like to sound out a string of musical notes > > including rests or simply have something that I set the frequency and > > duration then sound and repeat for the number of notes. > > > > If possible I would prefer a solution that is cross platform, and > > standard library but would settle for Linux only solutions that can be > > downloaded - which preferably don't need compiling. > > > pygame and pyglet+avbin both play sounds, are cross-platform and have > binaries available for Windows, Mac and Linux. > > The "Playing and creating sound" section of this page looks promising: > http://wiki.python.org/moin/PythonInMusic > > > Kent > From bhaaluu at gmail.com Sun Mar 9 15:30:16 2008 From: bhaaluu at gmail.com (bhaaluu) Date: Sun, 9 Mar 2008 10:30:16 -0400 Subject: [Tutor] self-learning Python In-Reply-To: <47D3DDF4.9050708@tds.net> References: <652641e90803090528r63fbc0cv27d3e4c45c7718e3@mail.gmail.com> <47D3DDF4.9050708@tds.net> Message-ID: On Sun, Mar 9, 2008 at 8:54 AM, Kent Johnson wrote: > > On Sun, Mar 9, 2008 at 8:16 AM, Julia > To be honest I truly dislike the Dawson book. I wouldn't recommend > > it to anyone. It's lacks technical clarity, examples and has a messy > > index. I'm going to sell my example asap. > > I'm not sure what kind of clarity you want. To be sure Dawson is not > nearly as precise and comprehensive as Learning Python, for example, but > I think the more casual approach is better for a complete beginner. > > ISTM Dawson is written almost entirely as a series of extended examples, > I'm really surprised that you say it lacks examples. I found Dawson's book very approachable for people who are Absolute Beginners to programming. As Kent says, each chapter is a series of extended examples that cover fundamental concepts. The premise of the book is that Game Programming is a FUN way to learn programming. Most of the book uses text-based games as examples. Each chapter ends with a set of Challenges that encourage you to test the skills you've learned up to that point. The Challenges are appropriate for Absolute Beginners (ie. none of them ask you to do anything that hasn't been taught yet). Most of the Challenges require a little thought to complete. Some of the Challenges ask that you modify an example in the chapter to make it do something different, or to add a new feature. Chapter 1 starts out with the "Game Over Program" which is the equivalent of the "Hello, world!" program in most other books. This chapter talks you through getting Python setup and running on your computer, and all sorts of other essential beginning steps that need to be done in order to use Python as your programming language. Chapter 2 uses "The Useless Trivia Program" to cover Types, Variables, and simple Input/Output. Chapter 3 covers Branching (making decisions), 'while' loops, and program planning. The "Guess My Number Game" is used as the main example. All the examples build up to writing the Guessing game. Chapter 4 has "The Word Jumble Game". It covers 'for' loops, Strings, Slicing Strings, and Tuples. Chapter 5 introduces Lists and Dictionaries. Here is "The Hangman Game". Chapter 6 covers functions, and "The Tic-Tac-Toe Game". Chapter 7 has "The Trivia Challenge Game" and covers Files and Exceptions. Chapter 8 begins the Object Oriented Programming (classes, methods, etc.) and has "The Critter Caretaker Program" (a Tamagotchi-type game). Chapter 9 continues the Object Oriented Programming with "The Blackjack Game". Inheritance, Polymorphism, and other OOP concepts are introduced. Chapter 10 starts to get into GUI development with Tkinter. "The Mad Lib Program" is the main game. The Final two chapters use a modified version of the LiveWires package to run the games. You'll need to have PyGame and LiveWires installed for these games to work. LiveWires is a "wrapper" for PyGame which supposedly makes PyGame easier to lear and use. PyGame is a "wrapper" for the SDL library, written in the C programming language. Chapter 11 gets into Graphics, and the examples build up to "The Pizza Panic Game". Backgrounds, Sprites, Collisions, and other basic graphic gaming concepts are covered here. Chapter 12 is a full-blown graphic 2-D arcade-style game called "The Astrocrash Game" (similar to 'Asteroids'). Sound, Animation, and Program Development are covered. Appendix A is a LiveWires reference. Games are a really fun way to learn programming, and Dawson's book makes learning programming a lot of fun! I think the book is meant to be read from cover to cover, since each chapter is built on the concepts introduced in previous chapters. Everything is explained clearly without the use of confusing 'jargon'. Terminology is clearly explained, and examples are explained step-by-step. If you can finish Dawson's book, you'll be well prepared to take on just about any other Python tutorial out there (except maybe the ones that delve into advanced Computer Science theory). > > > When I started learning Python, I had had no programming background > > whatsoever. It was Michael Dawson's book that got me off the ground. I > > then read another book "Python programming: an introduction to computer > > science", and things began to make sense to me. > > I almost mentioned that one too. Python for Dummies might also be a good > choice but I haven't seen that. > > O'Reilly is coming out with a book Head First Programming that uses > Python but it isn't scheduled to be published until May. > > Kent > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > If you finish Dawson's book and are interested in continuing with Python/PyGame programming (without LiveWires) then you might want to look into obtaining a copy of Andy Harris' book: Game Programming published by Wiley (2007). It covers 2-D arcade games with PyGame, and is a good PyGame tutorial. Another PyGame programing book is: Beginning Game Development with Python and Pygame: From Novice to Professional, by Will McGugan. I haven't seen this book yet, but it covers 3-D game programming. Happy Programming! -- b h a a l u u at g m a i l dot c o m "You assist an evil system most effectively by obeying its orders and decrees. An evil system never deserves such allegiance. Allegiance to it means partaking of the evil. A good person will resist an evil system with his or her whole soul." [Mahatma Gandhi] From midnightjulia at gmail.com Sun Mar 9 16:37:04 2008 From: midnightjulia at gmail.com (Julia) Date: Sun, 9 Mar 2008 16:37:04 +0100 Subject: [Tutor] self-learning Python Message-ID: > > Emad Nawfal wrote: > > On Sun, Mar 9, 2008 at 8:16 AM, Julia > > wrote: > > To be honest I truly dislike the Dawson book. I wouldn't recommend > > it to anyone. It's lacks technical clarity, examples and has a messy > > index. I'm going to sell my example asap. > > I'm not sure what kind of clarity you want. To be sure Dawson is not > nearly as precise and comprehensive as Learning Python, for example, but > I think the more casual approach is better for a complete beginner. > > ISTM Dawson is written almost entirely as a series of extended examples, > I'm really surprised that you say it lacks examples. > Yes, Dawson uses few examples. His examples might be extensive but there are still few examples. Compare the number of examples in Dawson book to the (in my opinion better) Beginning Python by Norton (Wrox). The problem is that if you want to know how to use one specific technique then Dawsons great big examples are of limited use. In a book like Beginning Python I can find the same technique isolated and therefore better understand it. When I was a complete beginner I preferred Beginning Python over Dawson and I still do (I'm still a beginner). But that might just me be me :) /Julia -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080309/9edd9a57/attachment.htm From alan.gauld at btinternet.com Sun Mar 9 17:03:44 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 9 Mar 2008 16:03:44 -0000 Subject: [Tutor] self-learning Python References: Message-ID: "Julia" wrote > When I was a complete beginner I preferred Beginning Python over > Dawson and > I still do (I'm still a beginner). But that might just me be me :) Book (and tutorial) choices are very subjective. I know the styles of book I like and dislike. I hate "chatty, informal" style text books, I like precision. I hate books that try to teach by example, I prefer direct instruction followed by short pointed examples - I can invent long examples by myself!. But I know plenty people who prefer the exact opposite. My own book follows my taste, which is almost exactly opposite to Dawson's. Each will suit a different audience. But contrarily I should like the Dietel's "How to Program" and don't and I should dislike Lutz' Programming Python but don't! :-) -- Alan Gauld Author of the Learn to Program web site Temorarily at: http://uk.geocities.com/alan.gauld at btinternet.com/ Normally: http://www.freenetpages.co.uk/hp/alan.gauld From lowelltackett at yahoo.com Sun Mar 9 17:00:16 2008 From: lowelltackett at yahoo.com (Lowell Tackett) Date: Sun, 9 Mar 2008 09:00:16 -0700 (PDT) Subject: [Tutor] self-learning Python In-Reply-To: Message-ID: <379463.82541.qm@web45902.mail.sp1.yahoo.com> Julia wrote: Emad Nawfal wrote: > On Sun, Mar 9, 2008 at 8:16 AM, Julia > wrote: > To be honest I truly dislike the Dawson book. I wouldn't recommend > it to anyone. It's lacks technical clarity, examples and has a messy > index. I'm going to sell my example asap. I'm not sure what kind of clarity you want. To be sure Dawson is not nearly as precise and comprehensive as Learning Python, for example, but I think the more casual approach is better for a complete beginner. ISTM Dawson is written almost entirely as a series of extended examples, I'm really surprised that you say it lacks examples. Yes, Dawson uses few examples. His examples might be extensive but there are still few examples. Compare the number of examples in Dawson book to the (in my opinion better) Beginning Python by Norton (Wrox). The problem is that if you want to know how to use one specific technique then Dawsons great big examples are of limited use. In a book like Beginning Python I can find the same technique isolated and therefore better understand it. When I was a complete beginner I preferred Beginning Python over Dawson and I still do (I'm still a beginner). But that might just me be me :) /Julia There's an essential (in my opinion) principle of learning programming that doesn't seem to have made its' way into this conversation. I'll preface my thoughts by saying that in-again, my opinion- Michael Dawson's book, Python Programming for the absolute beginner is more than a book...it's a hallowed tome. A lot of learning is not only absorbing stuff, but what I call (and I'm certain it didn't originate with me) "finger time". That's simply spending time at the keyboard and vicariously interacting. Things will come to you, but it needs hours and hours of fairly productive interaction. Mr. Dawson's book provides that cycle of, 'do...feedback...oh, yea!' like nothing else available. Of course, a person is gonna need to jump away and do independent stuff. But this book provides concrete milestones from which to jump and apply concepts to independently thought up projects. That, after having used Mr. Dawson's book, and appreciating the solid grounding it provided me, is my humble opinion. Lowell T. _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor >From the virtual desk of Lowell Tackett --------------------------------- Looking for last minute shopping deals? Find them fast with Yahoo! Search. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080309/130cc0d7/attachment.htm From midnightjulia at gmail.com Sun Mar 9 19:03:14 2008 From: midnightjulia at gmail.com (Julia) Date: Sun, 9 Mar 2008 19:03:14 +0100 Subject: [Tutor] self-learning Python In-Reply-To: <379463.82541.qm@web45902.mail.sp1.yahoo.com> References: <379463.82541.qm@web45902.mail.sp1.yahoo.com> Message-ID: On Sun, Mar 9, 2008 at 5:00 PM, Lowell Tackett wrote: > > > There's an essential (in my opinion) principle of learning programming > that doesn't seem to have made its' way into this conversation. I'll > preface my thoughts by saying that in-again, my opinion- Michael Dawson's > book, Python Programming for the absolute beginner is more than a > book...it's a hallowed tome. A lot of learning is not only absorbing stuff, > but what I call (and I'm certain it didn't originate with me) "finger > time". That's simply spending time at the keyboard and vicariously > interacting. Things will come to you, but it needs hours and hours of > fairly productive interaction. Mr. Dawson's book provides that cycle of, > 'do...feedback...oh, yea!' like nothing else available. > > Of course, a person is gonna need to jump away and do independent stuff. > But this book provides concrete milestones from which to jump and apply > concepts to independently thought up projects. > > That, after having used Mr. Dawson's book, and appreciating the solid > grounding it provided me, is my humble opinion. > > Lowell T. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > That was a really interesting post Lowell. Great feedback! I've thought about something like this but I haven't been sure how to express it (English isn't my mother tongue). You also set a better tone then I used in my first reply. I apologize for it. What you are talking about is very important. Succeeding and making something work is a thrill and it will motivate one try even harder the next time. For me "Beginning Python" provided a better ground for this learning experience because I got to try many variations of the many important parts of Python. I wrote the code from the examples and I saw it work. With Dawson there where some really extensive examples but I didn't really understand how the isolated parts worked. There where many more "oh, this is cool" thoughts with "Beginning Python". I also believe that by using a more technical book I gained an experience with the programming methology (e.g. coding and debugging code). What I am claiming is that the productive experience is greater with Beginning Python than with Dawson. Don't be afraid of the big and more technical books. They are big, but big means there's more fun inside. /Julia -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080309/a5e96cf6/attachment-0001.htm From lowelltackett at yahoo.com Sun Mar 9 19:43:35 2008 From: lowelltackett at yahoo.com (Lowell Tackett) Date: Sun, 9 Mar 2008 11:43:35 -0700 (PDT) Subject: [Tutor] self-learning Python In-Reply-To: Message-ID: <611230.81004.qm@web45910.mail.sp1.yahoo.com> Julia wrote: On Sun, Mar 9, 2008 at 5:00 PM, Lowell Tackett wrote: There's an essential (in my opinion) principle of learning programming...learning is not only absorbing stuff, but what I call (and I'm certain it didn't originate with me) "finger time". Mr. Dawson's book provides that cycle of, 'do...feedback...oh, yea!' like nothing else available. Of course, a person is gonna need to jump away...this book provides concrete milestones from which to jump... Lowell T. _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor That was a really interesting post Lowell. Great feedback! I've thought about something like this but I haven't been sure how to express it (English isn't my mother tongue). You also set a better tone then I used in my first reply. I apologize for it. What you are talking about is very important. Succeeding and making something work is a thrill and it will motivate one try even harder the next time. For me "Beginning Python" provided a better ground for this learning experience because I got to try many variations of the many important parts of Python. I wrote the code from the examples and I saw it work. With Dawson there where some really extensive examples but I didn't really understand how the isolated parts worked. There where many more "oh, this is cool" thoughts with "Beginning Python". I also believe that by using a more technical book I gained an experience with the programming methology (e.g. coding and debugging code). What I am claiming is that the productive experience is greater with Beginning Python than with Dawson. Don't be afraid of the big and more technical books. They are big, but big means there's more fun inside. /Julia Ya know what?...if we all had the same opinions and perspective, this forum wouldn't exist! We wouldn't need it (well, yea, I am kinda overlooking the pedagogical value). Actually it was [in part] your provocative comments that inspired my response (but also, I harbor very strong loyalty to Mr. Dawson's book). Please!! no apologies necessary. I am in fact inspired to look at your arguments more closely and see what valuable slant I may have boxed myself out of (sometimes, tunnel-vision tends to creep in.) >From the virtual desk of Lowell Tackett --------------------------------- Never miss a thing. Make Yahoo your homepage. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080309/33111b76/attachment.htm From emadnawfal at gmail.com Sun Mar 9 16:06:58 2008 From: emadnawfal at gmail.com (Emad Nawfal) Date: Sun, 9 Mar 2008 10:06:58 -0500 Subject: [Tutor] Word List Message-ID: <652641e90803090806j7c048ddap3d10985919b41e23@mail.gmail.com> Dear Tutors, I'm trying to get the most frequent words in an Arabic text. I wrote the following code and tried it on English and it works fine, but when I try it on Arabic, all I get is the slashes and x's. I'm not familiar with Unicode. Could somebody please tell me what's wrong here, and how I can get the actual Arabic words? Thank you in anticipation import codecs infile = codecs.open(r'C:\Documents and Settings\Emad\Desktop\milal.txt', 'r', 'utf-8').read().split() num = {} for word in infile: if word not in num: num[word] = 1 num[word] +=1 new = zip(num.values(), num.keys()) new.sort() new.reverse() outfile = codecs.open(r'C:\Documents and Settings\Emad\Desktop\milalwanihal.txt', 'w', 'utf-8') for word in new: print >> out, word out.close() -- ?? ???? ?????? ????? ????? ??? ???? ??? ????? ?? ?????? ????????.....???? ??????? "No victim has ever been more repressed and alienated than the truth" Emad Soliman Nawfal Indiana University, Bloomington http://emnawfal.googlepages.com -------------------------------------------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080309/ec31c381/attachment.htm From kent37 at tds.net Sun Mar 9 21:35:10 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 09 Mar 2008 16:35:10 -0400 Subject: [Tutor] Word List In-Reply-To: <652641e90803090806j7c048ddap3d10985919b41e23@mail.gmail.com> References: <652641e90803090806j7c048ddap3d10985919b41e23@mail.gmail.com> Message-ID: <47D449FE.3070105@tds.net> Emad Nawfal wrote: > Dear Tutors, > I'm trying to get the most frequent words in an Arabic text. I wrote the > following code and tried it on English and it works fine, but when I try > it on Arabic, all I get is the slashes and x's. > import codecs > infile = codecs.open(r'C:\Documents and > Settings\Emad\Desktop\milal.txt', 'r', 'utf-8').read().split() > num = {} > for word in infile: > if word not in num: > num[word] = 1 > num[word] +=1 > new = zip(num.values(), num.keys()) Note that new is a list of pairs of (count, word), *not* a list of words. > new.sort() > new.reverse() > outfile = codecs.open(r'C:\Documents and > Settings\Emad\Desktop\milalwanihal.txt', 'w', 'utf-8') > for word in new: > print >> out, word So here 'word' is a tuple, not a string. When you print a tuple, the output is the repr() of the elements of a tuple, not the str() of the elements. For strings, this means that non-ascii characters are always printed using backslash escapes. For example: In [19]: s='?' In [21]: print s ? In [25]: t=(s,s) In [26]: print t ('\xc3\xa9', '\xc3\xa9') I suggest you format the output yourself. If you want the tuple formatting, try this: for count, word in new: # unpack the tuple to two values out.write('(%s, %s)\n' % (count, word)) Kent From emadnawfal at gmail.com Sun Mar 9 18:09:58 2008 From: emadnawfal at gmail.com (Emad Nawfal) Date: Sun, 9 Mar 2008 12:09:58 -0500 Subject: [Tutor] Word List In-Reply-To: <652641e90803090806j7c048ddap3d10985919b41e23@mail.gmail.com> References: <652641e90803090806j7c048ddap3d10985919b41e23@mail.gmail.com> Message-ID: <652641e90803091009i54547478i8c74c237f621a56e@mail.gmail.com> Dear Tutors, > I'm trying to get the most frequent words in an Arabic text. I wrote the > following code and tried it on English and it works fine, but when I try it > on Arabic, all I get is the slashes and x's. I'm not familiar with Unicode. > Could somebody please tell me what's wrong here, and how I can get the > actual Arabic words? > Thank you in anticipation > > > import codecs > infile = codecs.open(r'C:\Documents and Settings\Emad\Desktop\milal.txt', > 'r', 'utf-8').read().split() > num = {} > for word in infile: > if word not in num: > num[word] = 1 > num[word] +=1 > new = zip(num.values(), num.keys()) > new.sort() > new.reverse() > outfile = codecs.open(r'C:\Documents and > Settings\Emad\Desktop\milalwanihal.txt', 'w', 'utf-8') > for word in new: > print >> out, word > out.close() > > > -- > ?? ???? ?????? ????? ????? ??? ???? ??? ????? ?? ?????? ????????.....???? > ??????? > "No victim has ever been more repressed and alienated than the truth" > > Emad Soliman Nawfal > Indiana University, Bloomington > http://emnawfal.googlepages.com > -------------------------------------------------------- -- ?? ???? ?????? ????? ????? ??? ???? ??? ????? ?? ?????? ????????.....???? ??????? "No victim has ever been more repressed and alienated than the truth" Emad Soliman Nawfal Indiana University, Bloomington http://emnawfal.googlepages.com -------------------------------------------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080309/9e038ee0/attachment.htm From emadnawfal at gmail.com Sun Mar 9 22:59:35 2008 From: emadnawfal at gmail.com (Emad Nawfal) Date: Sun, 9 Mar 2008 17:59:35 -0400 Subject: [Tutor] Word List In-Reply-To: <47D449FE.3070105@tds.net> References: <652641e90803090806j7c048ddap3d10985919b41e23@mail.gmail.com> <47D449FE.3070105@tds.net> Message-ID: <652641e90803091459r2549ad6fya225fc4cf61d927a@mail.gmail.com> 2008/3/9 Kent Johnson : > Emad Nawfal wrote: > > Dear Tutors, > > I'm trying to get the most frequent words in an Arabic text. I wrote the > > following code and tried it on English and it works fine, but when I try > > it on Arabic, all I get is the slashes and x's. > > > import codecs > > infile = codecs.open(r'C:\Documents and > > Settings\Emad\Desktop\milal.txt', 'r', 'utf-8').read().split() > > num = {} > > for word in infile: > > if word not in num: > > num[word] = 1 > > num[word] +=1 > > new = zip(num.values(), num.keys()) > > Note that new is a list of pairs of (count, word), *not* a list of words. > > > new.sort() > > new.reverse() > > outfile = codecs.open(r'C:\Documents and > > Settings\Emad\Desktop\milalwanihal.txt', 'w', 'utf-8') > > for word in new: > > print >> out, word > > So here 'word' is a tuple, not a string. > > When you print a tuple, the output is the repr() of the elements of a > tuple, not the str() of the elements. For strings, this means that > non-ascii characters are always printed using backslash escapes. > > For example: > In [19]: s='?' > In [21]: print s > ? > In [25]: t=(s,s) > In [26]: print t > ('\xc3\xa9', '\xc3\xa9') > > I suggest you format the output yourself. If you want the tuple > formatting, try this: > > for count, word in new: # unpack the tuple to two values > out.write('(%s, %s)\n' % (count, word)) > > Kent > Thank you so much Kent. It works. I have now realized the bad things about self-learning. -- ?? ???? ?????? ????? ????? ??? ???? ??? ????? ?? ?????? ????????.....???? ??????? "No victim has ever been more repressed and alienated than the truth" Emad Soliman Nawfal Indiana University, Bloomington http://emnawfal.googlepages.com -------------------------------------------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080309/8f31fad3/attachment-0001.htm From dineshbvadhia at hotmail.com Sun Mar 9 23:11:50 2008 From: dineshbvadhia at hotmail.com (Dinesh B Vadhia) Date: Sun, 9 Mar 2008 15:11:50 -0700 Subject: [Tutor] Bag of Words and libbow Message-ID: Has anyone come across Python modules/libraries to perform "Bag of Words" text analysis or an interface to the libbow C library? Thank-you! Dinesh -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080309/794a4c1b/attachment.htm From marc.tompkins at gmail.com Sun Mar 9 23:38:20 2008 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Sun, 9 Mar 2008 15:38:20 -0700 Subject: [Tutor] Word List In-Reply-To: <652641e90803091459r2549ad6fya225fc4cf61d927a@mail.gmail.com> References: <652641e90803090806j7c048ddap3d10985919b41e23@mail.gmail.com> <47D449FE.3070105@tds.net> <652641e90803091459r2549ad6fya225fc4cf61d927a@mail.gmail.com> Message-ID: <40af687b0803091538j11f356cq14e489cb94ca6b66@mail.gmail.com> 2008/3/9 Emad Nawfal : > Thank you so much Kent. It works. I have now realized the bad things about > self-learning. > There are bad things? Nobody told me... -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080309/dffc7551/attachment.htm From emadnawfal at gmail.com Sun Mar 9 23:59:59 2008 From: emadnawfal at gmail.com (Emad Nawfal) Date: Sun, 9 Mar 2008 18:59:59 -0400 Subject: [Tutor] Word List In-Reply-To: <40af687b0803091538j11f356cq14e489cb94ca6b66@mail.gmail.com> References: <652641e90803090806j7c048ddap3d10985919b41e23@mail.gmail.com> <47D449FE.3070105@tds.net> <652641e90803091459r2549ad6fya225fc4cf61d927a@mail.gmail.com> <40af687b0803091538j11f356cq14e489cb94ca6b66@mail.gmail.com> Message-ID: <652641e90803091559p6abea7cep1a921659757c0201@mail.gmail.com> On Sun, Mar 9, 2008 at 6:38 PM, Marc Tompkins wrote: > 2008/3/9 Emad Nawfal : > > > Thank you so much Kent. It works. I have now realized the bad things > > about self-learning. > > > > There are bad things? Nobody told me... > > -- > www.fsrtechnologies.com Well, there are times when you need somebody to tell you something, even if it is so obvious. When I wanted to learn Unix, I got a book and started reading. What drove me crazy is that some commands have -1, but those never worked for me. It was only when a friend told me that it is -l (minus EL) not -1 (minus one) that things went right. You see, sometimes self-learning is not enough. (I have to say that I have a problem in my vision. This could be a key factor). Different people learn in different ways. -- ?? ???? ?????? ????? ????? ??? ???? ??? ????? ?? ?????? ????????.....???? ??????? "No victim has ever been more repressed and alienated than the truth" Emad Soliman Nawfal Indiana University, Bloomington http://emnawfal.googlepages.com -------------------------------------------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080309/0ad15ef7/attachment.htm From alan.gauld at btinternet.com Mon Mar 10 00:02:45 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 9 Mar 2008 23:02:45 -0000 Subject: [Tutor] Word List References: <652641e90803090806j7c048ddap3d10985919b41e23@mail.gmail.com><47D449FE.3070105@tds.net><652641e90803091459r2549ad6fya225fc4cf61d927a@mail.gmail.com> <40af687b0803091538j11f356cq14e489cb94ca6b66@mail.gmail.com> Message-ID: "Marc Tompkins" wrote >... I have now realized the bad things about >> self-learning. > > There are bad things? Nobody told me... I appreciate the humor but seriously, yes there are bad things. There are a lot of good things too of course, but it is easy when self learning to learn something that seems to work but is actually bad practice and will lead to problems or complex code later on. As an example self learners often learn one loop style and then try to apply it in every situation. Another common case is that the potential of dictionaries is often not understood and many strange data structures are invented when a simple dictionary could solve the problem. A good teacher will spot and correct those kinds of things. Alan G. From marc.tompkins at gmail.com Mon Mar 10 00:52:50 2008 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Sun, 9 Mar 2008 16:52:50 -0700 Subject: [Tutor] Word List In-Reply-To: References: <652641e90803090806j7c048ddap3d10985919b41e23@mail.gmail.com> <47D449FE.3070105@tds.net> <652641e90803091459r2549ad6fya225fc4cf61d927a@mail.gmail.com> <40af687b0803091538j11f356cq14e489cb94ca6b66@mail.gmail.com> Message-ID: <40af687b0803091652r4b7e2a82iad20a857fc7d4f7a@mail.gmail.com> On Sun, Mar 9, 2008 at 4:02 PM, Alan Gauld wrote: > > "Marc Tompkins" wrote > >... I have now realized the bad things about > >> self-learning. > > > > There are bad things? Nobody told me... > > I appreciate the humor but seriously, yes there are bad things. > It was meant merely as a joke. If I didn't see the benefit of seeking help, I would never have joined this list. -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080309/d505ad64/attachment.htm From varsha.purohit at gmail.com Mon Mar 10 01:53:37 2008 From: varsha.purohit at gmail.com (Varsha Purohit) Date: Sun, 9 Mar 2008 17:53:37 -0700 Subject: [Tutor] [tutor] Finding image statistics In-Reply-To: <47CC57CE.8060202@tds.net> References: <47CADDA2.4070101@tds.net> <47CB4A2D.1000109@tds.net> <47CC57CE.8060202@tds.net> Message-ID: Hello All, I had posted this question in this community. I have a trouble. Actually in my application i need to multiply the resultant value i am getting with a cellsize. I am getting this cellsize by reading an ascii file's header. But when i am trying to multiply it with the result of imagestat i am getting an error. this is my code. def ImageStatistics(file1,file2,inFile): # find the pixels that are different in two images diff = ImageChops.difference(file1,file2) #shows the resultant image diff.show() #convert the different pixels into grayscale so that they are counted once for each pixel diff = ImageOps.grayscale(diff) # read the ascii file hdr = read_ascii.header(inFile) temp= hdr[4].strip().split() # temp is a list which is ['cellsize', '127'] cellsize = temp[1] def clip(x): if x>=1: return 1 else: return 0 # apply the clipping function to eval diff = Image.eval(diff,clip) #return the resultant area val = ImageStat.Stat(diff).sum area = val * cellsize print "area is ",area return area i am getting an error that i cannot combine imagestat with cellsize and i cannot multiply it like that. But in my application i need to multiply cellsize with the value i am getting in the image.eval.... i tried to multiply cellsize with 1 in the clip function where i am writing return 1*cellsize. but even it is not working .... can anyone tell me what i am doing wrong here ??? On Mon, Mar 3, 2008 at 12:55 PM, Kent Johnson wrote: > Varsha Purohit wrote: > > Yeahh so by doing this i am counting only the difference part since we > > have grayscaled the image and assuming it will count only the pixels > > that evolve as difference.... > > Yes > > > if i use sum2 instead of sum i think it > > will give squared sum which is area... and if i just use count it would > > count the number of pixels developed like that... sounds interesting .. > > thanks for throwing light for me in right direction.... > > No. First, pixels are already a measure of area. Second, if each pixel > value is 0 or 1, squaring the values won't make any difference. > > Kent > -- Varsha Purohit, Graduate Student -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080309/86823ad5/attachment.htm From eike.welk at gmx.net Mon Mar 10 02:40:26 2008 From: eike.welk at gmx.net (Eike Welk) Date: Mon, 10 Mar 2008 02:40:26 +0100 Subject: [Tutor] [tutor] Finding image statistics In-Reply-To: References: <47CC57CE.8060202@tds.net> Message-ID: <200803100240.27413.eike.welk@gmx.net> On Monday 10 March 2008 01:53, Varsha Purohit wrote: > ?# read the ascii file > ? ? hdr = read_ascii.header(inFile) > ? ? temp= hdr[4].strip().split() # temp is a list which is > ['cellsize', '127'] > ? ? cellsize = temp[1] "cellsize" is a character string I think! You must convert it to a number to use it in a multiplication: cellsize = float(temp[1]) or cellsize = int(temp[1]) Regards, Eike. From kent37 at tds.net Mon Mar 10 02:41:17 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 09 Mar 2008 21:41:17 -0400 Subject: [Tutor] [tutor] Finding image statistics In-Reply-To: References: <47CADDA2.4070101@tds.net> <47CB4A2D.1000109@tds.net> <47CC57CE.8060202@tds.net> Message-ID: <47D491BD.4070705@tds.net> Varsha Purohit wrote: > Hello All, > I had posted this question in this community. I have a trouble. > Actually in my application i need to multiply the resultant value i am > getting with a cellsize. I am getting this cellsize by reading an ascii > file's header. But when i am trying to multiply it with the result of > imagestat i am getting an error. > temp= hdr[4].strip().split() # temp is a list which is ['cellsize', > '127'] > cellsize = temp[1] Here cellsize is a string, not an integer. Try cellsize = int(temp[1]) > i am getting an error that i cannot combine imagestat with cellsize and > i cannot multiply it like that. It's very helpful if you show us the exact error, including the traceback. Just copy the entire error message and paste it into your email. Kent From varsha.purohit at gmail.com Mon Mar 10 03:19:49 2008 From: varsha.purohit at gmail.com (Varsha Purohit) Date: Sun, 9 Mar 2008 19:19:49 -0700 Subject: [Tutor] [tutor] Finding image statistics In-Reply-To: <47D491BD.4070705@tds.net> References: <47CADDA2.4070101@tds.net> <47CB4A2D.1000109@tds.net> <47CC57CE.8060202@tds.net> <47D491BD.4070705@tds.net> Message-ID: You both were right... i type casted it to int and it works with this..Thanks for catching the error !!!. but i had a question.. i want to find area of all the cells which i obtained by using imagechops.difference.... so should i multiply each cell with cellsize or should i add all the cells and multiply it will the cellsize... accd to me if i have a square of 2X2 then area is 4. if i need to find area of 10such squares then i can just find area for one and multiply it with 10. I donno which approach i should follow..... should i multiply each pixel with cellsize or first i add up all of them and multiply the cumulative result with cellsize............ On Sun, Mar 9, 2008 at 6:41 PM, Kent Johnson wrote: > Varsha Purohit wrote: > > Hello All, > > I had posted this question in this community. I have a trouble. > > Actually in my application i need to multiply the resultant value i am > > getting with a cellsize. I am getting this cellsize by reading an ascii > > file's header. But when i am trying to multiply it with the result of > > imagestat i am getting an error. > > > temp= hdr[4].strip().split() # temp is a list which is ['cellsize', > > '127'] > > cellsize = temp[1] > > Here cellsize is a string, not an integer. Try > cellsize = int(temp[1]) > > > i am getting an error that i cannot combine imagestat with cellsize and > > i cannot multiply it like that. > > It's very helpful if you show us the exact error, including the > traceback. Just copy the entire error message and paste it into your > email. > > Kent > -- Varsha Purohit, Graduate Student -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080309/6dee0acb/attachment.htm From halama at hbz-nrw.de Mon Mar 10 08:24:23 2008 From: halama at hbz-nrw.de (Andre Halama) Date: Mon, 10 Mar 2008 08:24:23 +0100 Subject: [Tutor] Bag of Words and libbow In-Reply-To: References: Message-ID: <47D4E227.5000807@hbz-nrw.de> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Dinesh B Vadhia schrieb: Hi, | Has anyone come across Python modules/libraries to perform "Bag of | Words" text analysis or an interface to the libbow C library? Thank-you! did you already have a look at NLTK (http://nltk.sourceforge.net/index.php/Main_Page)? HTH, A. -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.7 (GNU/Linux) Comment: Using GnuPG with Fedora - http://enigmail.mozdev.org iD8DBQFH1OInKWvEdxF+FtQRAveIAJoDouBDtu6xt+hQrjF5I3KzRfKODwCcDfdB aqwkGp7iYIQp3JrvTF7JqSM= =gQZZ -----END PGP SIGNATURE----- From kent37 at tds.net Mon Mar 10 12:13:26 2008 From: kent37 at tds.net (Kent Johnson) Date: Mon, 10 Mar 2008 07:13:26 -0400 Subject: [Tutor] [tutor] Finding image statistics In-Reply-To: References: <47CADDA2.4070101@tds.net> <47CB4A2D.1000109@tds.net> <47CC57CE.8060202@tds.net> <47D491BD.4070705@tds.net> Message-ID: <47D517D6.9020105@tds.net> Varsha Purohit wrote: > I donno which approach i should follow..... > should i multiply each pixel with cellsize or first i add up all of them > and multiply the cumulative result with cellsize............ If you 'multiply' by assigning a different value in clip() then it probably doesn't matter. I wouldn't multiply the whole image in a separate operation. Kent From tetsuo2k6 at web.de Mon Mar 10 12:43:54 2008 From: tetsuo2k6 at web.de (tetsuo2k6 at web.de) Date: Mon, 10 Mar 2008 12:43:54 +0100 Subject: [Tutor] identifying the calling module/function In-Reply-To: <47D2FF43.7000109@tds.net> References: <47D1402A.8000400@web.de> <47D14529.2090803@tds.net> <47D14B63.6050209@web.de> <9EE1AEC7-D09D-4D28-B9BE-DD46A329EADE@drinktomi.com> <47D28D38.5060709@web.de> <47D2FF43.7000109@tds.net> Message-ID: <47D51EFA.2000702@web.de> Kent Johnson schrieb: > tetsuo2k6 at web.de wrote: > >> in dgf.py: (hope the formatting gets good for you, t-bird breaks the >> lines badly on my machine...) >> >> def csvwriter(*column_definitions): >> """Edit Me!""" >> if sys.argv[0] == /usr/local/bin/xyz.py: >> output_csv_filename = "xyz.csv" >> else: >> output_csv_filename = raw_input("Name of the file to produce? >> (ATTENTION: WILL BE OVERWRITTEN!) ") > > If you can change xyz.py you can avoid this by adding an optional > filename parameter to the function. > >> first_row = ";".join(*column_definitions) >> try: >> file = open(output_csv_filename, "w") >> file.write(first_row) >> file.close() >> except: >> print("Couldn't open %s for writing." % > output_csv_filename) > > It's not such a good idea to hide the exception like this; you might at > least want to print the actual exception. Or just let it propagate. > >> sys.exit(1) > > You can use the csv module to write the header row, too. > > I would write this as > > def csvwriter(*column_definitions, filename=None): > if filename is none: > filename = raw_input("Name of the file to produce? > (ATTENTION: WILL BE OVERWRITTEN!) ") > > try: > out = csv.writer(open(filename, "ab"), > delimiter=";", quoting=csv.QUOTE_NONE) > out.writerow(column_definitions) > except Exception, e > print("Couldn't open %s for writing." % > output_csv_filename) > print e > return out > > Kent > Yeah, I think I get it, thanks! Paul From tetsuo2k6 at web.de Mon Mar 10 15:18:35 2008 From: tetsuo2k6 at web.de (tetsuo2k6 at web.de) Date: Mon, 10 Mar 2008 15:18:35 +0100 Subject: [Tutor] passing arguments to functions - problem with argument order Message-ID: <47D5433B.4030305@web.de> I don't get this - what is the clean way of the order of passing arguments to functions? The called function goes like this: def csvwriter(output_csv_filename=None, *coloumn_definitions): """Edit Me!""" if output_csv_filename == None: output_csv_filename = raw_input("Name der zu erzeugenden Datei (vollst?ndiger Pfad)? (ACHTUNG: WIRD ?BERSCHRIEBEN, FALLS VORHANDEN!) ") first_row = ";".join(coloumn_definitions) print(first_row) try: file = open(output_csv_filename, "w") file.writerow(first_row) file.close() except Exception, e: print("Konnte %s nicht zum Schreiben ?ffnen.") sys.exit(e) return csv.writer(open(output_csv_filename, "ab"), delimiter=";", quoting=csv.QUOTE_NONE) The call to the function seems impossible to do. When I say: writer = dgf.csvwriter(output_csv_filename=None, "kundennummer", "anrede", "vorname", "nachname", "plz", "ort", "adresse", "kontoinhaber", "blz", "kto", "bankname", "status", "spielbeginn", "letzte_aenderung", "importdatum", "briefdatum", "buchungsdatum", "stornodatum") I get: SyntaxError: non-keyword arg after keyword arg -> So I guess I have to put keyword arg at the end... When I put output_csv_writer at the end: writer = dgf.csvwriter("kundennummer", "anrede", "vorname", "nachname", "plz", "ort", "adresse", "kontoinhaber", "blz", "kto", "bankname", "status", "spielbeginn", "letzte_aenderung", "importdatum", "briefdatum", "buchungsdatum", "stornodatum", output_csv_filename=None) I get: TypeError: csvwriter() got multiple values for keyword argument 'output_csv_filename' -> Am I right that output_csv_filename now becomes "kundennummer" at first? Also, changing the function definition gives me syntax error: def csvwriter(*coloumn_definitions, output_csv_filename=None): ^ SyntaxError: invalid syntax What's going on here? I'm confused... Paul From dineshbvadhia at hotmail.com Mon Mar 10 15:39:30 2008 From: dineshbvadhia at hotmail.com (Dinesh B Vadhia) Date: Mon, 10 Mar 2008 07:39:30 -0700 Subject: [Tutor] Bag of Words and libbow References: Message-ID: Andre I had a quick look at NLTK which is an NLP library suite whereas libbow is for statistical text analysis. Cheers Dinesh Message: 3 Date: Mon, 10 Mar 2008 08:24:23 +0100 From: Andre Halama Subject: Re: [Tutor] Bag of Words and libbow To: tutor at python.org Message-ID: <47D4E227.5000807 at hbz-nrw.de> Content-Type: text/plain; charset=ISO-8859-1; format=flowed -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Dinesh B Vadhia schrieb: Hi, | Has anyone come across Python modules/libraries to perform "Bag of | Words" text analysis or an interface to the libbow C library? Thank-you! did you already have a look at NLTK (http://nltk.sourceforge.net/index.php/Main_Page)? HTH, -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080310/a9adb579/attachment.htm From GGraham at cistercian.org Mon Mar 10 16:09:16 2008 From: GGraham at cistercian.org (Greg Graham) Date: Mon, 10 Mar 2008 10:09:16 -0500 Subject: [Tutor] passing arguments to functions - problem with argument order In-Reply-To: <47D5433B.4030305@web.de> References: <47D5433B.4030305@web.de> Message-ID: <4B07785C52C78449A6C036FB2F69BEBD0320B1BB@server1.cistercian.com> Paul, Python does not allow mixing variable length arguments and keyword arguments in that way. To accomplish what you want, you must add an argument preceded by a "**" which will be a dict containing all of the keyword arguments as key, value pairs. You then have to retrieve the arguments from the dict by name. When called, the keyword arguments must be last. Here is a little example: def test(*column_definitions, **options): print "Column Definitions:" + ", ".join(column_definitions) output_csv_filename = options.get('output_csv_filename', None) print "Output csv filename: " + str(output_csv_filename) >>> test("kundennummer", "anrede", "vorname", "nachname", "plz", "ort", "adresse", "kontoinhaber", "blz", "kto", "bankname", "status", "spielbeginn", "letzte_aenderung", "importdatum", "briefdatum", "buchungsdatum", "stornodatum", output_csv_filename=None) Column Definitions:kundennummer, anrede, vorname, nachname, plz, ort, adresse, kontoinhaber, blz, kto, bankname, status, spielbeginn, letzte_aenderung, importdatum, briefdatum, buchungsdatum, stornodatum Output csv filename: None Greg -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of tetsuo2k6 at web.de Sent: Monday, March 10, 2008 9:19 AM To: python tutor Subject: [Tutor] passing arguments to functions - problem with argument order I don't get this - what is the clean way of the order of passing arguments to functions? The called function goes like this: def csvwriter(output_csv_filename=None, *coloumn_definitions): """Edit Me!""" if output_csv_filename == None: output_csv_filename = raw_input("Name der zu erzeugenden Datei (vollst?ndiger Pfad)? (ACHTUNG: WIRD ?BERSCHRIEBEN, FALLS VORHANDEN!) ") first_row = ";".join(coloumn_definitions) print(first_row) try: file = open(output_csv_filename, "w") file.writerow(first_row) file.close() except Exception, e: print("Konnte %s nicht zum Schreiben ?ffnen.") sys.exit(e) return csv.writer(open(output_csv_filename, "ab"), delimiter=";", quoting=csv.QUOTE_NONE) The call to the function seems impossible to do. When I say: writer = dgf.csvwriter(output_csv_filename=None, "kundennummer", "anrede", "vorname", "nachname", "plz", "ort", "adresse", "kontoinhaber", "blz", "kto", "bankname", "status", "spielbeginn", "letzte_aenderung", "importdatum", "briefdatum", "buchungsdatum", "stornodatum") I get: SyntaxError: non-keyword arg after keyword arg -> So I guess I have to put keyword arg at the end... When I put output_csv_writer at the end: writer = dgf.csvwriter("kundennummer", "anrede", "vorname", "nachname", "plz", "ort", "adresse", "kontoinhaber", "blz", "kto", "bankname", "status", "spielbeginn", "letzte_aenderung", "importdatum", "briefdatum", "buchungsdatum", "stornodatum", output_csv_filename=None) I get: TypeError: csvwriter() got multiple values for keyword argument 'output_csv_filename' -> Am I right that output_csv_filename now becomes "kundennummer" at first? Also, changing the function definition gives me syntax error: def csvwriter(*coloumn_definitions, output_csv_filename=None): ^ SyntaxError: invalid syntax What's going on here? I'm confused... Paul _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From tetsuo2k6 at web.de Mon Mar 10 16:28:23 2008 From: tetsuo2k6 at web.de (tetsuo2k6 at web.de) Date: Mon, 10 Mar 2008 16:28:23 +0100 Subject: [Tutor] passing arguments to functions - problem with argument order In-Reply-To: <4B07785C52C78449A6C036FB2F69BEBD0320B1BB@server1.cistercian.com> References: <47D5433B.4030305@web.de> <4B07785C52C78449A6C036FB2F69BEBD0320B1BB@server1.cistercian.com> Message-ID: <47D55397.9000200@web.de> And I thought I might get away without using dicts... Thanks, Greg Greg Graham schrieb: > Paul, > > Python does not allow mixing variable length arguments and keyword arguments in that way. To accomplish what you want, you must add an argument preceded by a "**" which will be a dict containing all of the keyword arguments as key, value pairs. You then have to retrieve the arguments from the dict by name. When called, the keyword arguments must be last. > > Here is a little example: > > def test(*column_definitions, **options): > print "Column Definitions:" + ", ".join(column_definitions) > output_csv_filename = options.get('output_csv_filename', None) > print "Output csv filename: " + str(output_csv_filename) > > >>>> test("kundennummer", "anrede", "vorname", "nachname", "plz", "ort", "adresse", "kontoinhaber", "blz", "kto", "bankname", "status", "spielbeginn", "letzte_aenderung", "importdatum", "briefdatum", "buchungsdatum", "stornodatum", output_csv_filename=None) > Column Definitions:kundennummer, anrede, vorname, nachname, plz, ort, adresse, kontoinhaber, blz, kto, bankname, status, spielbeginn, letzte_aenderung, importdatum, briefdatum, buchungsdatum, stornodatum > Output csv filename: None > > Greg From andreas at kostyrka.org Mon Mar 10 17:17:28 2008 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Mon, 10 Mar 2008 17:17:28 +0100 Subject: [Tutor] passing arguments to functions - problem with argument order In-Reply-To: <47D55397.9000200@web.de> References: <47D5433B.4030305@web.de> <4B07785C52C78449A6C036FB2F69BEBD0320B1BB@server1.cistercian.com> <47D55397.9000200@web.de> Message-ID: <1205165848.2230.21.camel@localhost> What you probably want is to pass: writer(None, "field1", "field2") Andreas Am Montag, den 10.03.2008, 16:28 +0100 schrieb tetsuo2k6 at web.de: > And I thought I might get away without using dicts... > > Thanks, Greg > > > > Greg Graham schrieb: > > Paul, > > > > Python does not allow mixing variable length arguments and keyword arguments in that way. To accomplish what you want, you must add an argument preceded by a "**" which will be a dict containing all of the keyword arguments as key, value pairs. You then have to retrieve the arguments from the dict by name. When called, the keyword arguments must be last. > > > > Here is a little example: > > > > def test(*column_definitions, **options): > > print "Column Definitions:" + ", ".join(column_definitions) > > output_csv_filename = options.get('output_csv_filename', None) > > print "Output csv filename: " + str(output_csv_filename) > > > > > >>>> test("kundennummer", "anrede", "vorname", "nachname", "plz", "ort", "adresse", "kontoinhaber", "blz", "kto", "bankname", "status", "spielbeginn", "letzte_aenderung", "importdatum", "briefdatum", "buchungsdatum", "stornodatum", output_csv_filename=None) > > Column Definitions:kundennummer, anrede, vorname, nachname, plz, ort, adresse, kontoinhaber, blz, kto, bankname, status, spielbeginn, letzte_aenderung, importdatum, briefdatum, buchungsdatum, stornodatum > > Output csv filename: None > > > > Greg > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Dies ist ein digital signierter Nachrichtenteil Url : http://mail.python.org/pipermail/tutor/attachments/20080310/afe28451/attachment.pgp From tetsuo2k6 at web.de Mon Mar 10 19:02:15 2008 From: tetsuo2k6 at web.de (tetsuo2k6 at web.de) Date: Mon, 10 Mar 2008 19:02:15 +0100 Subject: [Tutor] passing arguments to functions - problem with argument order In-Reply-To: <1205165848.2230.21.camel@localhost> References: <47D5433B.4030305@web.de> <4B07785C52C78449A6C036FB2F69BEBD0320B1BB@server1.cistercian.com> <47D55397.9000200@web.de> <1205165848.2230.21.camel@localhost> Message-ID: <47D577A7.10201@web.de> That's it! Paul Andreas Kostyrka schrieb: > What you probably want is to pass: > > writer(None, "field1", "field2") > > Andreas > > Am Montag, den 10.03.2008, 16:28 +0100 schrieb tetsuo2k6 at web.de: >> And I thought I might get away without using dicts... >> >> Thanks, Greg >> >> >> >> Greg Graham schrieb: >>> Paul, >>> >>> Python does not allow mixing variable length arguments and keyword arguments in that way. To accomplish what you want, you must add an argument preceded by a "**" which will be a dict containing all of the keyword arguments as key, value pairs. You then have to retrieve the arguments from the dict by name. When called, the keyword arguments must be last. >>> >>> Here is a little example: >>> >>> def test(*column_definitions, **options): >>> print "Column Definitions:" + ", ".join(column_definitions) >>> output_csv_filename = options.get('output_csv_filename', None) >>> print "Output csv filename: " + str(output_csv_filename) >>> >>> >>>>>> test("kundennummer", "anrede", "vorname", "nachname", "plz", "ort", "adresse", "kontoinhaber", "blz", "kto", "bankname", "status", "spielbeginn", "letzte_aenderung", "importdatum", "briefdatum", "buchungsdatum", "stornodatum", output_csv_filename=None) >>> Column Definitions:kundennummer, anrede, vorname, nachname, plz, ort, adresse, kontoinhaber, blz, kto, bankname, status, spielbeginn, letzte_aenderung, importdatum, briefdatum, buchungsdatum, stornodatum >>> Output csv filename: None >>> >>> Greg >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor From alan.gauld at btinternet.com Mon Mar 10 19:47:52 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 10 Mar 2008 18:47:52 -0000 Subject: [Tutor] passing arguments to functions - problem with argument order References: <47D5433B.4030305@web.de><4B07785C52C78449A6C036FB2F69BEBD0320B1BB@server1.cistercian.com> <47D55397.9000200@web.de> Message-ID: wrote > And I thought I might get away without using dicts... Why would you want to? Dicts are one of the most powerful data structures around. And besides Python is built from dicts so you can never truly get away without using them. Every time you access a feature from a module or class you are using a dict! :-) Alan G From ian at showmedo.com Mon Mar 10 20:41:11 2008 From: ian at showmedo.com (Ian Ozsvald) Date: Mon, 10 Mar 2008 19:41:11 +0000 Subject: [Tutor] self-learning Python In-Reply-To: <000001c88157$9689cbd0$6501a8c0@NETVISTAUSER> References: <000001c88157$9689cbd0$6501a8c0@NETVISTAUSER> Message-ID: <47D58ED7.80407@showmedo.com> Hi Enrique. I'll suggest my ShowMeDo for video tutorials - our 'beginner' subsection for Python has 101 videos: http://showmedo.com/videos/python?topic=beginner_programming Most of the videos are free (3 series - in yellow - require a subscription, everything else is free). Topics covered include learning Python, watching Python modules in action, an online tour of Python web-resources, cool modules like RUR-PLE, Crunchy, pyGame, wxPython and lots of other stuff. There are even more tutorials in the main Python section: http://showmedo.com/videos/python Hope that helps, Ian. Enrique Nieves, Jr. wrote: > I?m not a programmer, but would like to learn to program. I?m > considering self-learning python on my spare time. Can you recommend > the best books, online training, or other resources? I know nothing > about programming. > > > > enrique > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- http://Services.ShowMeDo.com http://ShowMeDo.com Ian at ShowMeDo.com From cappy2112 at gmail.com Tue Mar 11 01:54:53 2008 From: cappy2112 at gmail.com (Tony Cappellini) Date: Mon, 10 Mar 2008 17:54:53 -0700 Subject: [Tutor] Make sound with python? Cross platform? Message-ID: <8249c4ac0803101754s570f6d71x4eb9bb29111d6b50@mail.gmail.com> > Thanks very much. Not quite sure why I didn't find those earlier! I'll > have a look now. I think this cuts more to the chase than using a game framework http://pysonic.sourceforge.net/ From Hua.Zhang at Sun.COM Tue Mar 11 07:35:55 2008 From: Hua.Zhang at Sun.COM (Henry Zhang) Date: Tue, 11 Mar 2008 14:35:55 +0800 Subject: [Tutor] How to get MAC address using Python at Solaris Message-ID: <47D6284B.2040109@sun.com> Hi there, I am curious if there is any way in Python to get MAC address at Solaris? I searched from google, didn't find a good idea. So could anyone give some comment? Thanks, Henry From mail at timgolden.me.uk Tue Mar 11 11:56:59 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 11 Mar 2008 10:56:59 +0000 Subject: [Tutor] How to get MAC address using Python at Solaris In-Reply-To: <47D6284B.2040109@sun.com> References: <47D6284B.2040109@sun.com> Message-ID: <47D6657B.4000801@timgolden.me.uk> Henry Zhang wrote: > Hi there, > > I am curious if there is any way in Python to get MAC address at > Solaris? I searched from google, didn't find a good idea. Not tried it, but this looks hopeful at least: http://pypi.python.org/pypi/netifaces/0.4 TJG From andreas at kostyrka.org Tue Mar 11 12:13:48 2008 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Tue, 11 Mar 2008 12:13:48 +0100 Subject: [Tutor] How to get MAC address using Python at Solaris In-Reply-To: <47D6657B.4000801@timgolden.me.uk> References: <47D6284B.2040109@sun.com> <47D6657B.4000801@timgolden.me.uk> Message-ID: <1205234028.2230.27.camel@localhost> Alternatively, follow the recipe at http://www.tech-recipes.com/solaris_networking_tips785.html You can either just copy&paste the script and use that with popen, or you can reimplement it mostly in Python, calling the seperate programs. The basica gist of this seems to be, figure out your IP address, dump the ARP table and look for the IP address. Andreas Am Dienstag, den 11.03.2008, 10:56 +0000 schrieb Tim Golden: > Henry Zhang wrote: > > Hi there, > > > > I am curious if there is any way in Python to get MAC address at > > Solaris? I searched from google, didn't find a good idea. > > Not tried it, but this looks hopeful at least: > > http://pypi.python.org/pypi/netifaces/0.4 > > TJG > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Dies ist ein digital signierter Nachrichtenteil Url : http://mail.python.org/pipermail/tutor/attachments/20080311/28329173/attachment.pgp From tetsuo2k6 at web.de Tue Mar 11 13:26:20 2008 From: tetsuo2k6 at web.de (tetsuo2k6 at web.de) Date: Tue, 11 Mar 2008 13:26:20 +0100 Subject: [Tutor] passing arguments to functions - problem with argument order In-Reply-To: References: <47D5433B.4030305@web.de><4B07785C52C78449A6C036FB2F69BEBD0320B1BB@server1.cistercian.com> <47D55397.9000200@web.de> Message-ID: <47D67A6C.1070909@web.de> Alan Gauld schrieb: > wrote > >> And I thought I might get away without using dicts... > > Why would you want to? Dicts are one of the most > powerful data structures around. > > And besides Python is built from dicts so you can > never truly get away without using them. Every time > you access a feature from a module or class > you are using a dict! :-) > > Alan G > Well, I know about dicts, however I want to go forward step by step in learning - once I feel really comfortable with functions, object-orientation aso., I'll certainly look into them again. Besides, I _do_ use them sometimes :) Paul From alan.gauld at btinternet.com Tue Mar 11 15:49:17 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 11 Mar 2008 14:49:17 -0000 Subject: [Tutor] passing arguments to functions - problem with argument order References: <47D5433B.4030305@web.de><4B07785C52C78449A6C036FB2F69BEBD0320B1BB@server1.cistercian.com> <47D55397.9000200@web.de> <47D67A6C.1070909@web.de> Message-ID: wrote >>> And I thought I might get away without using dicts... >> >> Why would you want to? Dicts are one of the most >> powerful data structures around. > Well, I know about dicts, however I want to go forward step by step > in > learning - once I feel really comfortable with functions, > object-orientation aso., I'll certainly look into them again. > Besides, I > _do_ use them sometimes :) Fine, but I would seriously consider learning dicts as a prioritry. Certainly way higher that learning OOP. In fact being comfortable with dictionaries will make understanding OOP much easier since a class is really just a special type of dictionary!. Alan G. From alan.gauld at btinternet.com Tue Mar 11 16:00:34 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 11 Mar 2008 15:00:34 -0000 Subject: [Tutor] How to get MAC address using Python at Solaris References: <47D6284B.2040109@sun.com> Message-ID: "Henry Zhang" wrote > I am curious if there is any way in Python to get MAC address at > Solaris? I searched from google, didn't find a good idea. The recipe from Andreas is probably rthe best solution but you might be able you grep it out of the dmesg log file (or even using Popen on dmesg) quick n dirty... Just a thought. Alan G. From tetsuo2k6 at web.de Tue Mar 11 19:58:39 2008 From: tetsuo2k6 at web.de (tetsuo2k6 at web.de) Date: Tue, 11 Mar 2008 19:58:39 +0100 Subject: [Tutor] passing arguments to functions - problem with argument order In-Reply-To: References: <47D5433B.4030305@web.de><4B07785C52C78449A6C036FB2F69BEBD0320B1BB@server1.cistercian.com> <47D55397.9000200@web.de> <47D67A6C.1070909@web.de> Message-ID: <47D6D65F.7040103@web.de> Alan Gauld schrieb: > > Fine, but I would seriously consider learning dicts as a prioritry. > Certainly way higher that learning OOP. In fact being comfortable > with dictionaries will make understanding OOP much easier > since a class is really just a special type of dictionary!. > > Alan G. > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > Well then I guess I will. I appreciate this kind of advice - thanks a lot :) Paul From tayeb.meftah at gmail.com Tue Mar 11 20:41:52 2008 From: tayeb.meftah at gmail.com (Meftah Tayeb) Date: Tue, 11 Mar 2008 20:41:52 +0100 Subject: [Tutor] Begining Python Message-ID: <001e01c883af$fb7ae5b0$0201a8c0@server> hi my friends, please i want to begin developing with python. 1. do you know a tutorial for this ? 2. do you know a Free IDE for Python (for windows) ? Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080311/ae713cf2/attachment.htm From katcipis at inf.ufsc.br Tue Mar 11 20:46:45 2008 From: katcipis at inf.ufsc.br (Tiago Katcipis) Date: Tue, 11 Mar 2008 16:46:45 -0300 Subject: [Tutor] Begining Python In-Reply-To: <001e01c883af$fb7ae5b0$0201a8c0@server> References: <001e01c883af$fb7ae5b0$0201a8c0@server> Message-ID: <60a9403b0803111246y1f01806bxe02b086db29ea8df@mail.gmail.com> tutorial i liked this one when i was starting http://docs.python.org/tut/ free IDE that i use is Eclipse with PyDev plugin. http://pydev.sourceforge.net/ www.eclipse.org On Tue, Mar 11, 2008 at 4:41 PM, Meftah Tayeb wrote: > hi my friends, > please i want to begin developing with python. > 1. do you know a tutorial for this ? > 2. do you know a Free IDE for Python (for windows) ? > > Thanks > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080311/047da0b5/attachment.htm From kent37 at tds.net Tue Mar 11 20:57:32 2008 From: kent37 at tds.net (Kent Johnson) Date: Tue, 11 Mar 2008 15:57:32 -0400 Subject: [Tutor] Begining Python In-Reply-To: <001e01c883af$fb7ae5b0$0201a8c0@server> References: <001e01c883af$fb7ae5b0$0201a8c0@server> Message-ID: <47D6E42C.6010503@tds.net> Meftah Tayeb wrote: > hi my friends, > please i want to begin developing with python. > 1. do you know a tutorial for this ? http://wiki.python.org/moin/BeginnersGuide/NonProgrammers http://wiki.python.org/moin/BeginnersGuide/Programmers > 2. do you know a Free IDE for Python (for windows) ? There are many: http://wiki.python.org/moin/IntegratedDevelopmentEnvironments Some of the popular ones are Eclipse + PyDev eric Komodo PythonWin SPE Kent From bgailer at alum.rpi.edu Tue Mar 11 21:01:47 2008 From: bgailer at alum.rpi.edu (bob gailer) Date: Tue, 11 Mar 2008 16:01:47 -0400 Subject: [Tutor] Begining Python In-Reply-To: <001e01c883af$fb7ae5b0$0201a8c0@server> References: <001e01c883af$fb7ae5b0$0201a8c0@server> Message-ID: <47D6E52B.4060408@alum.rpi.edu> Meftah Tayeb wrote: > 1. do you know a tutorial for this ? This tutor list is also a good place to ask questions. > 2. do you know a Free IDE for Python (for windows) ? Many of us really like http://sourceforge.net/projects/pywin32/ -- Bob Gailer 919-636-4239 Chapel Hill, NC From carroll at tjc.com Wed Mar 12 00:52:06 2008 From: carroll at tjc.com (Terry Carroll) Date: Tue, 11 Mar 2008 16:52:06 -0700 (PDT) Subject: [Tutor] Begining Python In-Reply-To: <001e01c883af$fb7ae5b0$0201a8c0@server> Message-ID: On Tue, 11 Mar 2008, Meftah Tayeb wrote: > 2. do you know a Free IDE for Python (for windows) ? Meftah, I'd suggest you install Activestate's distribution of Python, which includes the PythonWin environment (not quite an IDE, in that there is no GUI designer, for example) and many Windows-specific python modules. http://www.activestate.com/Products/activepython/ From rdm at rcblue.com Wed Mar 12 05:40:35 2008 From: rdm at rcblue.com (Dick Moores) Date: Tue, 11 Mar 2008 21:40:35 -0700 Subject: [Tutor] Translate this VB.NET code into Python for me? In-Reply-To: <8249c4ac0803111213m6ad3f682p281da9e08099e20c@mail.gmail.co m> References: <8249c4ac0803111213m6ad3f682p281da9e08099e20c@mail.gmail.com> Message-ID: <20080312044052.241231E4010@bag.python.org> Forwarding to the list. At 12:13 PM 3/11/2008, Tony Cappellini wrote: >I'm weeks behind on reading my digests, so this may have already been >pointed out. > >Message: 6 >Date: Tue, 04 Mar 2008 17:58:20 -0800 >From: Dick Moores >Subject: Re: [Tutor] Translate this VB.NET code into Python for me? >To: tutor at python.org >Message-ID: <20080305015832.727D71E4007 at bag.python.org> >Content-Type: text/plain; charset="us-ascii"; format=flowed > > > >Since IP can access the same GUI > >library as VB.NET they should be very similar in code structure. > > >>I dug up this paragraph from the new book on IPython due out in Sept. '08: > >>"IronPython uses .NET classes natively and seamlessly, and there are > >I suppose this was just a typo >The book due out in Sept 08 is on Iron Python, not IPython. >These are two completley different things. From halama at hbz-nrw.de Wed Mar 12 09:09:00 2008 From: halama at hbz-nrw.de (Andre Halama) Date: Wed, 12 Mar 2008 09:09:00 +0100 Subject: [Tutor] Bag of Words and libbow In-Reply-To: References: Message-ID: <47D78F9C.10602@hbz-nrw.de> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Dinesh B Vadhia wrote: Hi Dinesh, | I had a quick look at NLTK which is an NLP library suite whereas libbow | is for statistical text analysis. Cheers what exactly are you trying to achieve that the statistical modules included in NLTK don't give you? A. -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.7 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFH14+cKWvEdxF+FtQRAu0hAJ4vqnULzeL/+TytHzVXdnJyzkXPTACeOqFn Xznib3W5iZ3mnbVcv8AFUH8= =XOS5 -----END PGP SIGNATURE----- From tayeb.meftah at gmail.com Wed Mar 12 09:39:46 2008 From: tayeb.meftah at gmail.com (Meftah Tayeb) Date: Wed, 12 Mar 2008 09:39:46 +0100 Subject: [Tutor] Begining Python References: Message-ID: <002601c8841c$a22566d0$0201a8c0@server> hi my friend, i have active python installed and the python-Win is Ready but i have a Very Small problem: i am blind, and i am using a Screen reader this screen reader use the Microsoft Active Accessibiliti (MSAA) to find informations about actual object in the screen cursor for Java Based applications, this screen Reader use the Java Access Bridj (JAB) if it is no installed, java application is no accessible but in python: no accessibiliti layer is found for python ! I'd suggest you: do not develope a new Accessibiliti layer please, develope only a MSAA Server for represanting all python UI object to MSAA based application and for JAVA / Python integration, please develope a JAVA Access Bridj (JAB) server to represanting python UI object to existing JAB Based application Thank you, Meftah Tayeb ----- Original Message ----- From: "Terry Carroll" To: "python tutor" Sent: Wednesday, March 12, 2008 12:52 AM Subject: Re: [Tutor] Begining Python > On Tue, 11 Mar 2008, Meftah Tayeb wrote: > >> 2. do you know a Free IDE for Python (for windows) ? > > Meftah, I'd suggest you install Activestate's distribution of Python, > which includes the PythonWin environment (not quite an IDE, in that > there is no GUI designer, for example) and many Windows-specific python > modules. > > http://www.activestate.com/Products/activepython/ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From macsareback at mac.com Wed Mar 12 15:24:09 2008 From: macsareback at mac.com (Daniel kavic) Date: Wed, 12 Mar 2008 10:24:09 -0400 Subject: [Tutor] Fwd: Begining Python References: <002601c8841c$a22566d0$0201a8c0@server> Message-ID: <8E371533-71A3-42C8-945B-CF2B692B5D31@mac.com> Begin forwarded message: > From: Meftah Tayeb > Date: March 12, 2008 4:39:46 AM EDT > To: Terry Carroll , python tutor > Subject: Re: [Tutor] Begining Python > > hi my friend, > i have active python installed and the python-Win is Ready > but i have a Very Small problem: > i am blind, and i am using a Screen reader > this screen reader use the Microsoft Active Accessibiliti (MSAA) to > find > informations about actual object in the screen cursor > for Java Based applications, this screen Reader use the Java Access > Bridj > (JAB) > if it is no installed, java application is no accessible > > but in python: > no accessibiliti layer is found for python ! > I'd suggest you: > do not develope a new Accessibiliti layer > please, develope only a MSAA Server for represanting all python UI > object to > MSAA based application > and for JAVA / Python integration, please develope a JAVA Access > Bridj (JAB) > server to represanting python UI object to existing JAB Based > application > > Thank you, > Meftah Tayeb > ----- Original Message ----- > From: "Terry Carroll" > To: "python tutor" > Sent: Wednesday, March 12, 2008 12:52 AM > Subject: Re: [Tutor] Begining Python > > >> On Tue, 11 Mar 2008, Meftah Tayeb wrote: >> >>> 2. do you know a Free IDE for Python (for windows) ? >> >> Meftah, I'd suggest you install Activestate's distribution of Python, >> which includes the PythonWin environment (not quite an IDE, in that >> there is no GUI designer, for example) and many Windows-specific >> python >> modules. >> >> http://www.activestate.com/Products/activepython/ >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080312/648372e5/attachment.htm From kaushalshriyan at gmail.com Wed Mar 12 16:14:38 2008 From: kaushalshriyan at gmail.com (Kaushal Shriyan) Date: Wed, 12 Mar 2008 20:44:38 +0530 Subject: [Tutor] self-learning Python In-Reply-To: <47D58ED7.80407@showmedo.com> References: <000001c88157$9689cbd0$6501a8c0@NETVISTAUSER> <47D58ED7.80407@showmedo.com> Message-ID: <6b16fb4c0803120814r62553610ve2460059863ae96a@mail.gmail.com> On Tue, Mar 11, 2008 at 1:11 AM, Ian Ozsvald wrote: > Hi Enrique. I'll suggest my ShowMeDo for video tutorials - our 'beginner' subsection for Python has 101 videos: > http://showmedo.com/videos/python?topic=beginner_programming > > Most of the videos are free (3 series - in yellow - require a subscription, everything else is free). Topics covered include learning Python, watching Python modules in action, an online tour of Python web-resources, cool modules like RUR-PLE, Crunchy, pyGame, wxPython and lots of other stuff. > There are even more tutorials in the main Python section: > http://showmedo.com/videos/python > > Hope that helps, > Ian. > > > > Enrique Nieves, Jr. wrote: > > I'm not a programmer, but would like to learn to program. I'm > > considering self-learning python on my spare time. Can you recommend > > the best books, online training, or other resources? I know nothing > > about programming. > > > > > > > > enrique > > > > > > ------------------------------------------------------------------------ > > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > -- > http://Services.ShowMeDo.com > http://ShowMeDo.com > Ian at ShowMeDo.com > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > Hi all, I am a newbie with no programming experience. As Kent Johnson has already pointed here about the book "Python Programming for the absolute beginner" by Michael Dawson,I checked both in www.amazon.com and www.ebay.com website. Both this website say "Unavailable" or "Out of Stock" where can i get this book. I am eagerly awaiting to buy this book Thanks and Regards Kaushal From kaushalshriyan at gmail.com Wed Mar 12 17:00:04 2008 From: kaushalshriyan at gmail.com (Kaushal Shriyan) Date: Wed, 12 Mar 2008 21:30:04 +0530 Subject: [Tutor] self-learning Python In-Reply-To: <47D7F71F.6080604@tds.net> References: <000001c88157$9689cbd0$6501a8c0@NETVISTAUSER> <47D58ED7.80407@showmedo.com> <6b16fb4c0803120814r62553610ve2460059863ae96a@mail.gmail.com> <47D7F71F.6080604@tds.net> Message-ID: <6b16fb4c0803120900y46bc30e9r4515888f8de35ecc@mail.gmail.com> On Wed, Mar 12, 2008 at 9:00 PM, Kent Johnson wrote: > Kaushal Shriyan wrote: > > I am a newbie with no programming experience. As Kent Johnson has > > already pointed here about the book "Python Programming for the > > absolute beginner" by Michael Dawson,I checked both in www.amazon.com > > and www.ebay.com website. Both this website say "Unavailable" or "Out > > of Stock" > > > > where can i get this book. I am eagerly awaiting to buy this book > > Today it is in stock at Amazon.com: > http://www.amazon.com/Python-Programming-Absolute-Beginner-Second/dp/1598631128/ > > Also it is available direct from the publisher: > http://premierpressbooks.com/ptr_detail.cfm?group=Programming&subcat=Other%20Programming&isbn=1%2D59863%2D112%2D8 > > Incidentally I am amazed to see how many new Python books are in the > works - more than 12 are scheduled for release in the next year! > http://www.amazon.com/s/ref=sr_st?keywords=python+programming&rs=1000&page=1&rh=n%3A1000%2Ck%3Apython+programming&sort=daterank > > Kent > Thanks Kent :-) I placed a ordered for this book Thanks again Thanks and Regards Kaushal From kent37 at tds.net Wed Mar 12 16:30:39 2008 From: kent37 at tds.net (Kent Johnson) Date: Wed, 12 Mar 2008 11:30:39 -0400 Subject: [Tutor] self-learning Python In-Reply-To: <6b16fb4c0803120814r62553610ve2460059863ae96a@mail.gmail.com> References: <000001c88157$9689cbd0$6501a8c0@NETVISTAUSER> <47D58ED7.80407@showmedo.com> <6b16fb4c0803120814r62553610ve2460059863ae96a@mail.gmail.com> Message-ID: <47D7F71F.6080604@tds.net> Kaushal Shriyan wrote: > I am a newbie with no programming experience. As Kent Johnson has > already pointed here about the book "Python Programming for the > absolute beginner" by Michael Dawson,I checked both in www.amazon.com > and www.ebay.com website. Both this website say "Unavailable" or "Out > of Stock" > > where can i get this book. I am eagerly awaiting to buy this book Today it is in stock at Amazon.com: http://www.amazon.com/Python-Programming-Absolute-Beginner-Second/dp/1598631128/ Also it is available direct from the publisher: http://premierpressbooks.com/ptr_detail.cfm?group=Programming&subcat=Other%20Programming&isbn=1%2D59863%2D112%2D8 Incidentally I am amazed to see how many new Python books are in the works - more than 12 are scheduled for release in the next year! http://www.amazon.com/s/ref=sr_st?keywords=python+programming&rs=1000&page=1&rh=n%3A1000%2Ck%3Apython+programming&sort=daterank Kent From python.mail1 at gmail.com Wed Mar 12 21:58:41 2008 From: python.mail1 at gmail.com (Norm All) Date: Wed, 12 Mar 2008 16:58:41 -0400 Subject: [Tutor] Hard time understanding classes Message-ID: Hello, I am learning python and so far have done pretty well, until I got to the subject of classes which I have been struggling to understand for a while. I have not found any easy to understand tutorial on the web or looking in some books for a clear step by step example. Would appreciate any help or links to read. Regards. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080312/a577531d/attachment.htm From tjampman at gmail.com Wed Mar 12 22:12:24 2008 From: tjampman at gmail.com (Ole Henning Jensen) Date: Wed, 12 Mar 2008 22:12:24 +0100 Subject: [Tutor] Hard time understanding classes In-Reply-To: References: Message-ID: <47D84738.5070804@gmail.com> Norm All wrote: > I am learning python and so far have done pretty well, until I got to > the subject of classes which I have been struggling to understand for a > while. I have not found any easy to understand tutorial on the web or > looking in some books for a clear step by step example. Would > appreciate any help or links to read. > While this is a very long discussion thread, I found it extremly helpful in my understanding of classes and how they should be built/designed. http://www.nabble.com/designing-POOP-tc15290468.html From alan.gauld at btinternet.com Thu Mar 13 00:52:43 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 12 Mar 2008 23:52:43 -0000 Subject: [Tutor] Hard time understanding classes References: Message-ID: "Norm All" wrote > I am learning python and so far have done pretty well, until I got > to the > subject of classes which I have been struggling to understand for a > while. First, you are not alone. Some people find the idea of objects easy to grasp but the majority of programmers struggle because it is a different way of thinking about programs and problems. Once you "get it" you will wonder what all the fuss was about :-) Second, while classes are very useful for some things you don't *need* to use classes to program even quite complex programs. So don't panic. > have not found any easy to understand tutorial on the web or looking > in some > books for a clear step by step example. Would appreciate any help > or links > to read. It might help if we know what you have read so far and if you can give some specific things that you find hard to grasp. That gives us a direction to head down. Obligatory plug, you can try the OOP topic in my tutor if you haven't already... HTH, -- Alan Gauld Author of the Learn to Program web site Temorarily at: http://uk.geocities.com/alan.gauld at btinternet.com/ Normally: http://www.freenetpages.co.uk/hp/alan.gauld From rdm at rcblue.com Thu Mar 13 02:07:52 2008 From: rdm at rcblue.com (Dick Moores) Date: Wed, 12 Mar 2008 18:07:52 -0700 Subject: [Tutor] Hard time understanding classes In-Reply-To: References: Message-ID: <20080313010804.DDC6D1E4015@bag.python.org> At 01:58 PM 3/12/2008, Norm All wrote: >Hello, > >I am learning python and so far have done pretty well, until I got >to the subject of classes which I have been struggling to understand >for a while. I have not found any easy to understand tutorial on the >web or looking in some books for a clear step by step example. >Would appreciate any help or links to read. I suggest the new book, _Object-Oriented Programming in Python_, by Goldwasser and Letscher: Dick Moores From allen.fowler at yahoo.com Thu Mar 13 03:59:58 2008 From: allen.fowler at yahoo.com (Allen Fowler) Date: Wed, 12 Mar 2008 19:59:58 -0700 (PDT) Subject: [Tutor] Simple reg-ex syntax? Message-ID: <814557.18562.qm@web45608.mail.sp1.yahoo.com> Hello, I have code that looks something like: self.aString = "abc123xyz" self.theNumber = int(re.search('(\d+)',self.aString).group()) Is there a more Pythonic way of doing this? (Both the reg-ex and the Int coercion.) How about when I will need to extract more than one substring? Thank you, :) ____________________________________________________________________________________ Never miss a thing. Make Yahoo your home page. http://www.yahoo.com/r/hs From allen.fowler at yahoo.com Thu Mar 13 04:06:00 2008 From: allen.fowler at yahoo.com (Allen Fowler) Date: Wed, 12 Mar 2008 20:06:00 -0700 (PDT) Subject: [Tutor] Correct way to call an outside program? Message-ID: <308774.59699.qm@web45612.mail.sp1.yahoo.com> Hello, I need to call an external command line .exe utility from my Python script. What is the best way to capture the output (if any) and (optionally) direct it to my normal standard output? There seem to be many options... Thank you, :) ____________________________________________________________________________________ Be a better friend, newshound, and know-it-all with Yahoo! Mobile. Try it now. http://mobile.yahoo.com/;_ylt=Ahu06i62sR8HDtDypao8Wcj9tAcJ From alan.gauld at btinternet.com Thu Mar 13 05:57:46 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 13 Mar 2008 04:57:46 -0000 Subject: [Tutor] Correct way to call an outside program? References: <308774.59699.qm@web45612.mail.sp1.yahoo.com> Message-ID: "Allen Fowler" wrote > I need to call an external command line .exe utility from my Python > script. > > What is the best way to capture the output (if any) and (optionally) > direct it to my normal standard output? > > There seem to be many options... Historically there have been lots of methods introduced howeever the most recent and officially correct way is now tyo use the subprocess module. There are examples on the web pages to show what you want. Or read the Using the OS topic in my tutorial for the basics. HTH, -- Alan Gauld Author of the Learn to Program web site Temorarily at: http://uk.geocities.com/alan.gauld at btinternet.com/ Normally: http://www.freenetpages.co.uk/hp/alan.gauld From cfuller084 at thinkingplanet.net Thu Mar 13 10:10:43 2008 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Thu, 13 Mar 2008 04:10:43 -0500 Subject: [Tutor] Simple reg-ex syntax? In-Reply-To: <814557.18562.qm@web45608.mail.sp1.yahoo.com> References: <814557.18562.qm@web45608.mail.sp1.yahoo.com> Message-ID: <200803130410.43636.cfuller084@thinkingplanet.net> How I would improve this: compile the regular expression. This is more efficient. self.digit_extractor = re.compile('(\d+)') then, use the findall method: self.allNumbers = self.digit_extractor.findall(self.aString) which will even work with multiline strings, but doesn't convert to integers. To convert, use a list comprehension: self.allNumbers = [int(i) for i in self.digit_extractor.findall(self.aString)] Cheers On Wednesday 12 March 2008 21:59, Allen Fowler wrote: > Hello, > > I have code that looks something like: > > self.aString = "abc123xyz" > self.theNumber = int(re.search('(\d+)',self.aString).group()) > > Is there a more Pythonic way of doing this? (Both the reg-ex and the Int > coercion.) How about when I will need to extract more than one substring? > > Thank you, > > :) > > > ___________________________________________________________________________ >_________ Never miss a thing. Make Yahoo your home page. > http://www.yahoo.com/r/hs > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From kent37 at tds.net Thu Mar 13 11:43:01 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 13 Mar 2008 06:43:01 -0400 Subject: [Tutor] Begining Python In-Reply-To: <002601c8841c$a22566d0$0201a8c0@server> References: <002601c8841c$a22566d0$0201a8c0@server> Message-ID: <47D90535.70307@tds.net> Meftah Tayeb wrote: > hi my friend, > i have active python installed and the python-Win is Ready > but i have a Very Small problem: > i am blind, and i am using a Screen reader > this screen reader use the Microsoft Active Accessibiliti (MSAA) to find > informations about actual object in the screen cursor You can develop Python programs using any text editor so you should be able to find a way to write programs that works with MSAA. Kent From ian at showmedo.com Thu Mar 13 12:40:26 2008 From: ian at showmedo.com (Ian Ozsvald) Date: Thu, 13 Mar 2008 11:40:26 +0000 Subject: [Tutor] Begining Python In-Reply-To: <001e01c883af$fb7ae5b0$0201a8c0@server> References: <001e01c883af$fb7ae5b0$0201a8c0@server> Message-ID: <47D912AA.50406@showmedo.com> Hi Meftah. Under the 'beginner programming' section of Python we have a lot of free video examples of Python coding: http://showmedo.com/videos/python?topic=beginner_programming and if you look under 'all' for Python: http://showmedo.com/videos/python?topic=all you'll find IDE videos on PyDev, SPE, VIM, IPython as well as 2 series on the commercial Wing IDE. Hope that helps, Ian. Meftah Tayeb wrote: > hi my friends, > please i want to begin developing with python. > 1. do you know a tutorial for this ? > 2. do you know a Free IDE for Python (for windows) ? > > Thanks > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- http://Services.ShowMeDo.com http://ShowMeDo.com Ian at ShowMeDo.com From kent37 at tds.net Thu Mar 13 13:05:54 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 13 Mar 2008 08:05:54 -0400 Subject: [Tutor] Correct way to call an outside program? In-Reply-To: <308774.59699.qm@web45612.mail.sp1.yahoo.com> References: <308774.59699.qm@web45612.mail.sp1.yahoo.com> Message-ID: <47D918A2.1040509@tds.net> Allen Fowler wrote: > Hello, > > I need to call an external command line .exe utility from my Python script. > > What is the best way to capture the output (if any) and (optionally) direct it to my normal standard output? subprocess.Popen().communicate() will do it: In [1]: import subprocess In [7]: x=subprocess.Popen('ls', stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate() In [10]: print x[0] ... If you just want stdout and stderr of the subprocess to go to stdout and stderr of the calling process you can omit those arguments to Popen(). Kent From pylinuxian at gmail.com Thu Mar 13 13:31:32 2008 From: pylinuxian at gmail.com (linuxian iandsd) Date: Thu, 13 Mar 2008 12:31:32 +0000 Subject: [Tutor] Correct way to call an outside program? In-Reply-To: <47D918A2.1040509@tds.net> References: <308774.59699.qm@web45612.mail.sp1.yahoo.com> <47D918A2.1040509@tds.net> Message-ID: simplest way to run external commands ! import os cmd="/usr/bin/ssh 10.0.0.20 uptime" os.popen(cmd) my cmd is just an example, use any cmd you want & its output will be displayed to you. hope this helps On Thu, Mar 13, 2008 at 12:05 PM, Kent Johnson wrote: > Allen Fowler wrote: > > Hello, > > > > I need to call an external command line .exe utility from my Python > script. > > > > What is the best way to capture the output (if any) and (optionally) > direct it to my normal standard output? > > subprocess.Popen().communicate() will do it: > > In [1]: import subprocess > In [7]: x=subprocess.Popen('ls', stdout=subprocess.PIPE, > stderr=subprocess.PIPE).communicate() > In [10]: print x[0] > ... > > If you just want stdout and stderr of the subprocess to go to stdout and > stderr of the calling process you can omit those arguments to Popen(). > > Kent > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080313/ab8883e4/attachment.htm From andreas at kostyrka.org Thu Mar 13 14:05:31 2008 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Thu, 13 Mar 2008 14:05:31 +0100 Subject: [Tutor] Begining Python In-Reply-To: <002601c8841c$a22566d0$0201a8c0@server> References: <002601c8841c$a22566d0$0201a8c0@server> Message-ID: <1205413531.7844.57.camel@localhost> Am Mittwoch, den 12.03.2008, 09:39 +0100 schrieb Meftah Tayeb: > hi my friend, > i have active python installed and the python-Win is Ready > but i have a Very Small problem: > i am blind, and i am using a Screen reader > this screen reader use the Microsoft Active Accessibiliti (MSAA) to find > informations about actual object in the screen cursor > for Java Based applications, this screen Reader use the Java Access Bridj > (JAB) > if it is no installed, java application is no accessible > > but in python: > no accessibiliti layer is found for python ! Well, the problem here is, Python is just a language, so by default it has only a minimal UI. OTOH, the good thing from your point of view might be that it is text based. I don't know about the technologies you mentioned, but you might consider using IronPython, which is implemented inside the .NET world, which might have better support (or not) for your tools Andreas > I'd suggest you: > do not develope a new Accessibiliti layer > please, develope only a MSAA Server for represanting all python UI object to > MSAA based application > and for JAVA / Python integration, please develope a JAVA Access Bridj (JAB) > server to represanting python UI object to existing JAB Based application > > Thank you, > Meftah Tayeb > ----- Original Message ----- > From: "Terry Carroll" > To: "python tutor" > Sent: Wednesday, March 12, 2008 12:52 AM > Subject: Re: [Tutor] Begining Python > > > > On Tue, 11 Mar 2008, Meftah Tayeb wrote: > > > >> 2. do you know a Free IDE for Python (for windows) ? > > > > Meftah, I'd suggest you install Activestate's distribution of Python, > > which includes the PythonWin environment (not quite an IDE, in that > > there is no GUI designer, for example) and many Windows-specific python > > modules. > > > > http://www.activestate.com/Products/activepython/ > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Dies ist ein digital signierter Nachrichtenteil Url : http://mail.python.org/pipermail/tutor/attachments/20080313/52ed3c96/attachment.pgp From python.mail1 at gmail.com Thu Mar 13 16:15:16 2008 From: python.mail1 at gmail.com (Norm All) Date: Thu, 13 Mar 2008 11:15:16 -0400 Subject: [Tutor] Hard time understanding classes In-Reply-To: <47D84738.5070804@gmail.com> References: <47D84738.5070804@gmail.com> Message-ID: Thank you for all the suggestions regarding my struggle to understand classes, I will follow up on all the links provided and continue to search. On Wed, Mar 12, 2008 at 5:12 PM, Ole Henning Jensen wrote: > Norm All wrote: > > I am learning python and so far have done pretty well, until I got to > > the subject of classes which I have been struggling to understand for a > > while. I have not found any easy to understand tutorial on the web or > > looking in some books for a clear step by step example. Would > > appreciate any help or links to read. > > > > > While this is a very long discussion thread, I found it extremly helpful > in my understanding of classes and how they should be built/designed. > > http://www.nabble.com/designing-POOP-tc15290468.html > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080313/f653a4b5/attachment.htm From cmarlett at luc.edu Thu Mar 13 15:54:51 2008 From: cmarlett at luc.edu (Christopher Marlett) Date: Thu, 13 Mar 2008 09:54:51 -0500 Subject: [Tutor] Hello Message-ID: <47D8F9EB02000029000732E1@gwial1.it.luc.edu> Hi, I'm in a Python class and we were given the assignment to create our own graphic and my idea was to have a program that asks the user to click six points and then create a circle using the six points they clicked. Once they've done that I want eyes and a mouth to appear in the circle. I was wondering if that was possible or if I need to have them also click the points where the two eyes and nose should appear as well. I have the face written, it looks like this... def main(): winWidth = 200 # give a name to the window width winHeight = 150 # and height win = GraphWin('Face', winWidth, winHeight) # give title and dimensions win.setCoords(0, 0, winWidth, winHeight) # make right side up coordinates! head = Circle(Point(40,100), 25) # set center and radius head.setFill("yellow") head.draw(win) eye1 = Circle(Point(30, 105), 5) eye1.setFill('blue') eye1.draw(win) eye2 = Line(Point(45, 105), Point(55, 105)) # set endpoints eye2.setWidth(3) eye2.draw(win) mouth = Oval(Point(30, 90), Point(50, 85)) # set corners of bounding box mouth.setFill("red") mouth.draw(win) message = Text(Point(winWidth/2, 20), 'Click anywhere to quit.') message.draw(win) win.getMouse() win.close() main() I'm struggling with the Circle, however. This is what I have so far, but it won't work. def main(): winWidth = 300 winHeight = 300 win = GraphWin('Draw a Circle', winWidth, winHeight) win.setCoords(0, 0, winWidth, winHeight) win.setBackground('yellow') message = Text(Point(winWidth/2, 20), 'Click on six points') message.draw(win) # Get and draw six points of circle p1 = win.getMouse() p1.draw(win) p2 = win.getMouse() p2.draw(win) p3 = win.getMouse() p3.draw(win) p4 = win.getMouse() p4.draw(win) p5 = win.getMouse() p5.draw(win) p6 = win.getMouse() p6.draw(win) points = [p1, p2, p3, p4, p5, p6] # Use Oval object to draw the circle Circle = Oval(points) Circle.setFill('green') Circle.setOutline('pink') Circle.setWidth(4) # width of boundary line Circle.draw(win) # Wait for another click to exit message.setText('Click anywhere to quit.') message.setTextColor('red') message.setStyle('italic') message.setSize(20) win.getMouse() win.close() Any advice you have would help out a lot. Thank you for your time. From GGraham at cistercian.org Thu Mar 13 17:17:57 2008 From: GGraham at cistercian.org (Greg Graham) Date: Thu, 13 Mar 2008 11:17:57 -0500 Subject: [Tutor] Hello In-Reply-To: <47D8F9EB02000029000732E1@gwial1.it.luc.edu> References: <47D8F9EB02000029000732E1@gwial1.it.luc.edu> Message-ID: <4B07785C52C78449A6C036FB2F69BEBD0320B2B9@server1.cistercian.com> It appears to me that the following line would not work: > Circle = Oval(points) The variable "points" is a list of six points, and I don't know how one would define a circle or oval with 6 points. At the top part of your program, an oval is defined using two points, which makes sense. Maybe you should use two of the points for the outline of the face, one point for each eye, and two for the mouth, which amounts to 6 points total. Greg -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of Christopher Marlett Sent: Thursday, March 13, 2008 9:55 AM To: tutor at python.org Subject: [Tutor] Hello Hi, I'm in a Python class and we were given the assignment to create our own graphic and my idea was to have a program that asks the user to click six points and then create a circle using the six points they clicked. Once they've done that I want eyes and a mouth to appear in the circle. I was wondering if that was possible or if I need to have them also click the points where the two eyes and nose should appear as well. I have the face written, it looks like this... def main(): winWidth = 200 # give a name to the window width winHeight = 150 # and height win = GraphWin('Face', winWidth, winHeight) # give title and dimensions win.setCoords(0, 0, winWidth, winHeight) # make right side up coordinates! head = Circle(Point(40,100), 25) # set center and radius head.setFill("yellow") head.draw(win) eye1 = Circle(Point(30, 105), 5) eye1.setFill('blue') eye1.draw(win) eye2 = Line(Point(45, 105), Point(55, 105)) # set endpoints eye2.setWidth(3) eye2.draw(win) mouth = Oval(Point(30, 90), Point(50, 85)) # set corners of bounding box mouth.setFill("red") mouth.draw(win) message = Text(Point(winWidth/2, 20), 'Click anywhere to quit.') message.draw(win) win.getMouse() win.close() main() I'm struggling with the Circle, however. This is what I have so far, but it won't work. def main(): winWidth = 300 winHeight = 300 win = GraphWin('Draw a Circle', winWidth, winHeight) win.setCoords(0, 0, winWidth, winHeight) win.setBackground('yellow') message = Text(Point(winWidth/2, 20), 'Click on six points') message.draw(win) # Get and draw six points of circle p1 = win.getMouse() p1.draw(win) p2 = win.getMouse() p2.draw(win) p3 = win.getMouse() p3.draw(win) p4 = win.getMouse() p4.draw(win) p5 = win.getMouse() p5.draw(win) p6 = win.getMouse() p6.draw(win) points = [p1, p2, p3, p4, p5, p6] # Use Oval object to draw the circle Circle = Oval(points) Circle.setFill('green') Circle.setOutline('pink') Circle.setWidth(4) # width of boundary line Circle.draw(win) # Wait for another click to exit message.setText('Click anywhere to quit.') message.setTextColor('red') message.setStyle('italic') message.setSize(20) win.getMouse() win.close() Any advice you have would help out a lot. Thank you for your time. _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From ian at showmedo.com Thu Mar 13 18:35:00 2008 From: ian at showmedo.com (Ian Ozsvald) Date: Thu, 13 Mar 2008 17:35:00 +0000 Subject: [Tutor] Hard time understanding classes In-Reply-To: References: Message-ID: <47D965C4.4050307@showmedo.com> Hi Norm. Jerol created a 3-part video series on Python Objects, he uses IPython to talk about how and why they work: http://showmedo.com/videos/series?name=IntroductionToPythonObjectsUsingIPython_JerolH If you find his videos useful do please leave him a comment - authors love to know that their work is appreciated. Ian. Norm All wrote: > Hello, > > I am learning python and so far have done pretty well, until I got to > the subject of classes which I have been struggling to understand for a > while. I have not found any easy to understand tutorial on the web or > looking in some books for a clear step by step example. Would > appreciate any help or links to read. > > Regards. > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- http://Services.ShowMeDo.com http://ShowMeDo.com Ian at ShowMeDo.com From allen.fowler at yahoo.com Thu Mar 13 19:39:49 2008 From: allen.fowler at yahoo.com (Allen Fowler) Date: Thu, 13 Mar 2008 11:39:49 -0700 (PDT) Subject: [Tutor] Correct way to call an outside program? Message-ID: <359553.1611.qm@web45601.mail.sp1.yahoo.com> Thank you for the help. :) ----- Original Message ---- simplest way to run external commands ! import os cmd="/usr/bin/ssh 10.0.0.20 uptime" os.popen(cmd) my cmd is just an example, use any cmd you want & its output will be displayed to you. hope this helps [SNIP] subprocess.Popen().communicate() will do it: In [1]: import subprocess In [7]: x=subprocess.Popen('ls', stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate() In [10]: print x[0] .... If you just want stdout and stderr of the subprocess to go to stdout and stderr of the calling process you can omit those arguments to Popen(). ____________________________________________________________________________________ Looking for last minute shopping deals? Find them fast with Yahoo! Search. http://tools.search.yahoo.com/newsearch/category.php?category=shopping -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080313/2865ebcf/attachment.htm From allen.fowler at yahoo.com Thu Mar 13 19:43:52 2008 From: allen.fowler at yahoo.com (Allen Fowler) Date: Thu, 13 Mar 2008 11:43:52 -0700 (PDT) Subject: [Tutor] Simple reg-ex syntax? Message-ID: <526158.65023.qm@web45602.mail.sp1.yahoo.com> findall is great. Thank you. :) ----- Original Message ---- > From: Chris Fuller > To: tutor at python.org > Sent: Thursday, March 13, 2008 5:10:43 AM > Subject: Re: [Tutor] Simple reg-ex syntax? > > > How I would improve this: > > compile the regular expression. This is more efficient. > self.digit_extractor = re.compile('(\d+)') > > then, use the findall method: > self.allNumbers = self.digit_extractor.findall(self.aString) > which will even work with multiline strings, but doesn't convert to integers. > > To convert, use a list comprehension: > self.allNumbers = [int(i) for i in self.digit_extractor.findall(self.aString)] > > Cheers > > On Wednesday 12 March 2008 21:59, Allen Fowler wrote: > > Hello, > > > > I have code that looks something like: > > > > self.aString = "abc123xyz" > > self.theNumber = int(re.search('(\d+)',self.aString).group()) > > > > Is there a more Pythonic way of doing this? (Both the reg-ex and the Int > > coercion.) How about when I will need to extract more than one substring? > > > > Thank you, > > > > :) > > > > > > ___________________________________________________________________________ > >_________ Never miss a thing. Make Yahoo your home page. > > http://www.yahoo.com/r/hs > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > ____________________________________________________________________________________ Looking for last minute shopping deals? Find them fast with Yahoo! Search. http://tools.search.yahoo.com/newsearch/category.php?category=shopping From rabidpoobear at gmail.com Thu Mar 13 23:03:16 2008 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Thu, 13 Mar 2008 16:03:16 -0600 Subject: [Tutor] Correct way to call an outside program? In-Reply-To: <359553.1611.qm@web45601.mail.sp1.yahoo.com> References: <359553.1611.qm@web45601.mail.sp1.yahoo.com> Message-ID: <47D9A4A4.9080704@gmail.com> Allen Fowler wrote: > Thank you for the help. :) > > ----- Original Message ---- > > simplest way to run external commands ! > > import os > cmd="/usr/bin/ssh 10.0.0.20 uptime" > os.popen(cmd) This is deprecated in python 2.5+. Use subrpocess instead of os.popen to make sure your code continues to work in the future. From rbtchilders at gmail.com Fri Mar 14 02:02:16 2008 From: rbtchilders at gmail.com (Robert Childers) Date: Thu, 13 Mar 2008 18:02:16 -0700 Subject: [Tutor] hypotenuse Message-ID: I am in an early lesson in "A Byte of Python." Instead of writing a program to find the area of a rectangle I thought it would be useful to write a program to determine the length of the diagonal of a "golden rectangle", which would of course equal the sq root of the sum of the squares of the width and height. Here is my program: >>> height = input ("Height:") Height:1 >>> width = input ("Width:") Width:1.618 >>> int = ((height**2) + (width**2)) >>> print int 3.617924 >>> hypotenuse * hypotenuse = int SyntaxError: can't assign to operator I looked ahead in the lesson and could find no mention of square roots. How do I find the square root of an integer? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080313/f2d4933c/attachment.htm From rabidpoobear at gmail.com Fri Mar 14 03:09:20 2008 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Thu, 13 Mar 2008 20:09:20 -0600 Subject: [Tutor] hypotenuse In-Reply-To: References: Message-ID: <47D9DE50.9070107@gmail.com> Robert Childers wrote: > I am in an early lesson in "A Byte of Python." Instead of writing a > program to find the area of a rectangle I thought it would be useful > to write a program to determine the length of the diagonal of a > "golden rectangle", which would of course equal the sq root of the sum > of the squares of the width and height. Here is my program: > >>> height = input ("Height:") > Height:1 > >>> width = input ("Width:") > Width:1.618 > >>> int = ((height**2) + (width**2)) > >>> print int > 3.617924 > >>> hypotenuse * hypotenuse = int > SyntaxError: can't assign to operator > > I looked ahead in the lesson and could find no mention of square > roots. How do I find the square root of an integer? There is a library called 'math' with a 'sqrt' function. To import modules, you use the 'import' command, as: import math To import a specific function from a module, you use a different syntax: from math import sqrt If you used the first style of import, you'd call the function like this: x = math.sqrt(2) With the second style, you'd call the function like this: x = sqrt(2) One other note: You named your variable 'int'. You should avoid naming your variables after keywords, because you will run into problems later. So you shouldn't use the names int, char, for, while, lambda, def, is, and, and names like that. For example: >>> int('12345') 12345 >>> int = 3 * 3 >>> int('12345') Traceback (most recent call last): File "", line 1, in int('12345') TypeError: 'int' object is not callable As you can see, naming the variable 'int' kept us from being able to call the 'int' function to convert the string into an integer. HTH, -Luke From john at fouhy.net Fri Mar 14 02:13:32 2008 From: john at fouhy.net (John Fouhy) Date: Fri, 14 Mar 2008 14:13:32 +1300 Subject: [Tutor] hypotenuse In-Reply-To: References: Message-ID: <5e58f2e40803131813hff35b11hbca804d704dba504@mail.gmail.com> On 14/03/2008, Robert Childers wrote: > I am in an early lesson in "A Byte of Python." Instead of writing a program > to find the area of a rectangle I thought it would be useful to write a > program to determine the length of the diagonal of a "golden rectangle", > which would of course equal the sq root of the sum of the squares of the > width and height. Here is my program: > >>> height = input ("Height:") > Height:1 > >>> width = input ("Width:") > Width:1.618 > >>> int = ((height**2) + (width**2)) > >>> print int > 3.617924 > >>> hypotenuse * hypotenuse = int > SyntaxError: can't assign to operator > > I looked ahead in the lesson and could find no mention of square roots. How > do I find the square root of an integer? Hi Robert, This kind of thing: >>> hypotenuse * hypotenuse = int will never work. The thing on the left side of an equals sign must always be a single name. (there is an exception to this -- "unpacking" -- but I won't explain it now. You should come to it in time) Python provides a square root function, but it's not available by default. You need to import the math module first -- your tutorial should cover importing. Basically, the code will look something like this: >>> import math >>> hyp_squared = height**2 + width**2 >>> hypotenuse = math.sqrt(hyp_squared) Finally, "int" is a built-in type, so it's bad programming style to use it as a variable name. (the same goes for "list", "str", and a few others) That's why, in my example, I used "hyp_squared" as the name for the hypotenuse squared. -- John. From andreas at kostyrka.org Fri Mar 14 02:27:12 2008 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Fri, 14 Mar 2008 02:27:12 +0100 Subject: [Tutor] hypotenuse In-Reply-To: References: Message-ID: <1205458033.6167.4.camel@localhost> assert 4**0.5 == 2 More generally: nth root of x: x ** (1.0/n) Or even more generally, take the 3rd root of the square of x: x ** (2.0/3.0) And when we are already extending the scope of the mailing list to math basics: 1.0/(x**2) == x**-2 (negating the power gives the inverse.) Andreas Am Donnerstag, den 13.03.2008, 18:02 -0700 schrieb Robert Childers: > I am in an early lesson in "A Byte of Python." Instead of writing a > program to find the area of a rectangle I thought it would be useful > to write a program to determine the length of the diagonal of a > "golden rectangle", which would of course equal the sq root of the sum > of the squares of the width and height. Here is my program: > >>> height = input ("Height:") > Height:1 > >>> width = input ("Width:") > Width:1.618 > >>> int = ((height**2) + (width**2)) > >>> print int > 3.617924 > >>> hypotenuse * hypotenuse = int > SyntaxError: can't assign to operator > > I looked ahead in the lesson and could find no mention of square > roots. How do I find the square root of an integer? > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Dies ist ein digital signierter Nachrichtenteil Url : http://mail.python.org/pipermail/tutor/attachments/20080314/495e56c5/attachment.pgp From john at fouhy.net Fri Mar 14 02:45:40 2008 From: john at fouhy.net (John Fouhy) Date: Fri, 14 Mar 2008 14:45:40 +1300 Subject: [Tutor] hypotenuse In-Reply-To: References: <5e58f2e40803131813hff35b11hbca804d704dba504@mail.gmail.com> Message-ID: <5e58f2e40803131845y5cf18a70sd5417844d8580c24@mail.gmail.com> On 14/03/2008, Scott Kerr wrote: > Hello, > > I am also new to python and programming. Since two have already posted that > you need to import math modules to do square roots, I am curious. > > Why can you not use something like: > > >>>hypotenuse = hyp_squared**1/2 > > or > > >>>hypotenuse = hyp_squared**.5 Hmm, good question :-) I suppose there is no strong reason. The best I can offer is that for many people, the concept of a square root is more accessible through the name "sqrt", whereas fractional exponentiation requires a brief brain pause while they remember what it means. Hence Luke and I, who are familiar with the math module, more easily think "math.sqrt" than "x**0.5". And the same benefit might apply to a hypothetical reader of the code. Interestingly, using x**0.5 seems faster too: Morpork:~ repton$ python -m timeit -s "x = 2" "y = x**0.5" 1000000 loops, best of 3: 0.298 usec per loop Morpork:~ repton$ python -m timeit -s "import math" -s "x = 2" "y = math.sqrt(x)" 1000000 loops, best of 3: 0.487 usec per loop Morpork:~ repton$ python -m timeit -s "import math" -s "m = math.sqrt" -s "x = 2" "y = m(x)" 1000000 loops, best of 3: 0.371 usec per loop though the advantage vanishes if you need a function: Morpork:~ repton$ python -m timeit -s "m = lambda x: x**0.5" -s "x = 2" "y = m(x)" 1000000 loops, best of 3: 0.526 usec per loop (if you've never seen the timeit module before, it's a good way to benchmark short snippets of code. The -s option is used for non-benchmarked startup code. So, for example, ' python -m timeit -s "import math" -s "x = 2" "y = math.sqrt(x)"' means "import math, set x to 2, then run y=math.sqrt(x) many many times to estimate its performance". From the interpreter, type 'import timeit; help(timeit)' for more information) -- John. From lupin at orcon.net.nz Fri Mar 14 02:10:05 2008 From: lupin at orcon.net.nz (Brett Wilkins) Date: Fri, 14 Mar 2008 14:10:05 +1300 (NZDT) Subject: [Tutor] hypotenuse In-Reply-To: References: Message-ID: <51783.210.55.0.190.1205457005.squirrel@webmail.orcon.net.nz> import math math.sqrt(intNumber) Cheers, Brett > I am in an early lesson in "A Byte of Python." Instead of writing a > program > to find the area of a rectangle I thought it would be useful to write a > program to determine the length of the diagonal of a "golden rectangle", > which would of course equal the sq root of the sum of the squares of > the width and height. Here is my program: >>>> height = input ("Height:") > Height:1 >>>> width = input ("Width:") > Width:1.618 >>>> int = ((height**2) + (width**2)) >>>> print int > 3.617924 >>>> hypotenuse * hypotenuse = int > SyntaxError: can't assign to operator > > I looked ahead in the lesson and could find no mention of square roots. > How > do I find the square root of an integer? > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld at btinternet.com Fri Mar 14 09:40:44 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 14 Mar 2008 08:40:44 -0000 Subject: [Tutor] hypotenuse References: <5e58f2e40803131813hff35b11hbca804d704dba504@mail.gmail.com> <5e58f2e40803131845y5cf18a70sd5417844d8580c24@mail.gmail.com> Message-ID: >> Why can you not use something like: >> >> >>>hypotenuse = hyp_squared**1/2 And for completeness that could also be written: hypotenuse = pow(hyp_squared,1/2) Again, without the need to import math. -- Alan Gauld Author of the Learn to Program web site Temorarily at: http://uk.geocities.com/alan.gauld at btinternet.com/ Normally: http://www.freenetpages.co.uk/hp/alan.gauld From wolfram.kraus at fen-net.de Fri Mar 14 10:59:23 2008 From: wolfram.kraus at fen-net.de (Wolfram Kraus) Date: Fri, 14 Mar 2008 10:59:23 +0100 Subject: [Tutor] hypotenuse In-Reply-To: References: <5e58f2e40803131813hff35b11hbca804d704dba504@mail.gmail.com> <5e58f2e40803131845y5cf18a70sd5417844d8580c24@mail.gmail.com> Message-ID: Am 14.03.2008 09:40, Alan Gauld schrieb: >>> Why can you not use something like: >>> >>>>>> hypotenuse = hyp_squared**1/2 > > And for completeness that could also be written: > > hypotenuse = pow(hyp_squared,1/2) > > Again, without the need to import math. > But beware of the integer divison in Python: >>> pow(2,1/2) 1 >>> pow(2,.5) 1.4142135623730951 >>> pow(2,1.0/2) 1.4142135623730951 From cmarlett at luc.edu Fri Mar 14 01:44:25 2008 From: cmarlett at luc.edu (Christopher Marlett) Date: Thu, 13 Mar 2008 19:44:25 -0500 Subject: [Tutor] Idle Message-ID: <47D98419020000290007372C@gwial1.it.luc.edu> Hi, I'm trying to write a program that uses the range function to produce and then print [1, 2, 3, 4]. then prompt the user for an integer n and print the list [1, 2, 3, ... , n] ? including n. Then use a simple repeat loop to print five randomly chosen numbers from the range [1, 2, 3, ... , n] This is what I have done so far print [1,2,3,4] nstring = raw_input("Enter any number: ") n = int(nstring) print range(1,n+1) y = random.randrange(1,n) print y It all works up until I need to print five randomly chosen numbers from the range [1,n]. It tells me that random is not defined. Thank you for your time. From connorsml at gmail.com Fri Mar 14 11:41:56 2008 From: connorsml at gmail.com (Michael Connors) Date: Fri, 14 Mar 2008 11:41:56 +0100 Subject: [Tutor] Idle In-Reply-To: <47D98419020000290007372C@gwial1.it.luc.edu> References: <47D98419020000290007372C@gwial1.it.luc.edu> Message-ID: > > It all works up until I need to print five randomly chosen numbers from > the range [1,n]. It tells me that random is not defined. You need to put : import random in your program before doing: y = random.randrange(1,n) or alternatively use: from random import * and call the function as follows: y = randrange(1,n) Regards, -- Michael Connors -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080314/52c99547/attachment.htm From Pamela.J.Bartruff at supervalu.com Fri Mar 14 13:16:08 2008 From: Pamela.J.Bartruff at supervalu.com (Bartruff, Pamela J.) Date: Fri, 14 Mar 2008 07:16:08 -0500 Subject: [Tutor] Idle In-Reply-To: <47D98419020000290007372C@gwial1.it.luc.edu> References: <47D98419020000290007372C@gwial1.it.luc.edu> Message-ID: I'm very new to Python, but it seems like I just learned in a class for a random number, you would need the : import random -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of Christopher Marlett Sent: Thursday, March 13, 2008 7:44 PM To: tutor at python.org Subject: [Tutor] Idle Hi, I'm trying to write a program that uses the range function to produce and then print [1, 2, 3, 4]. then prompt the user for an integer n and print the list [1, 2, 3, ... , n] - including n. Then use a simple repeat loop to print five randomly chosen numbers from the range [1, 2, 3, ... , n] This is what I have done so far print [1,2,3,4] nstring = raw_input("Enter any number: ") n = int(nstring) print range(1,n+1) y = random.randrange(1,n) print y It all works up until I need to print five randomly chosen numbers from the range [1,n]. It tells me that random is not defined. Thank you for your time. _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From alan.gauld at btinternet.com Fri Mar 14 14:01:47 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 14 Mar 2008 13:01:47 -0000 Subject: [Tutor] Idle References: <47D98419020000290007372C@gwial1.it.luc.edu> Message-ID: "Michael Connors" wrote > You need to put : > import random > > or alternatively use: > from random import * Or better still use from random import randrange import * style is not recommended because of the dangers of polluting the namespace -- Alan Gauld Author of the Learn to Program web site Temorarily at: http://uk.geocities.com/alan.gauld at btinternet.com Normally: http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Fri Mar 14 14:03:00 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 14 Mar 2008 13:03:00 -0000 Subject: [Tutor] hypotenuse References: <5e58f2e40803131813hff35b11hbca804d704dba504@mail.gmail.com> <5e58f2e40803131845y5cf18a70sd5417844d8580c24@mail.gmail.com> Message-ID: "Wolfram Kraus" wrote in message news:frdiev$m4u$1 at ger.gmane.org... > Am 14.03.2008 09:40, Alan Gauld schrieb: >>>> Why can you not use something like: >>>> >>>>>>> hypotenuse = hyp_squared**1/2 >> >> And for completeness that could also be written: >> >> hypotenuse = pow(hyp_squared,1/2) >> >> Again, without the need to import math. >> > But beware of the integer divison in Python: > > >>> pow(2,1/2) > 1 Good catch. Applies to the ** style too. Alan G From rbtchilders at gmail.com Fri Mar 14 17:52:26 2008 From: rbtchilders at gmail.com (Robert Childers) Date: Fri, 14 Mar 2008 09:52:26 -0700 Subject: [Tutor] hypotenuse In-Reply-To: References: <5e58f2e40803131813hff35b11hbca804d704dba504@mail.gmail.com> <5e58f2e40803131845y5cf18a70sd5417844d8580c24@mail.gmail.com> Message-ID: I have rewritten my "hypotenuse" program as follows:>>> #This program calculates the width and diagonal of a golden rectangle >>> print "Calculate the width and diagonal of a golden rectangle." Calculate the width and diagonal of a golden rectangle. >>> height = input ("Input height:") Input height:1 >>> width = height*1.618 >>> print "Width:", width Width: 1.618 >>> import math >>> hyp_squared = height**2 + width**2 >>> hypotenuse = math.sqrt(hyp_squared) >>> print "Diagonal:", hypotenuse Diagonal: 1.90208412012 When I save the program then try to run the module I get an error message that it is invalid. I have been assuming that if no "invalid syntax" error occurs in the shell the program should run. Could this problem be associated with the import math instruction? On Fri, Mar 14, 2008 at 6:03 AM, Alan Gauld wrote: > "Wolfram Kraus" wrote in message > news:frdiev$m4u$1 at ger.gmane.org... > > Am 14.03.2008 09:40, Alan Gauld schrieb: > >>>> Why can you not use something like: > >>>> > >>>>>>> hypotenuse = hyp_squared**1/2 > >> > >> And for completeness that could also be written: > >> > >> hypotenuse = pow(hyp_squared,1/2) > >> > >> Again, without the need to import math. > >> > > But beware of the integer divison in Python: > > > > >>> pow(2,1/2) > > 1 > > Good catch. Applies to the ** style too. > > Alan G > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080314/27d6f841/attachment.htm From dineshbvadhia at hotmail.com Fri Mar 14 18:37:13 2008 From: dineshbvadhia at hotmail.com (Dinesh B Vadhia) Date: Fri, 14 Mar 2008 10:37:13 -0700 Subject: [Tutor] Working with Python Objects Message-ID: I've avoided it as long as possible but I've reached a stage where I have to start using Python objects! The primary reason is that the web framework uses objects and the second is to eliminate a few globals. Here is example pseudo code followed by the question (one of many I suspect!): class A: constantA = 9 def OneOfA: a = class B: variableB = "quick brown fox" def OneOfB: b = c = b * a # the 'a' from def OneOfA in class A Question: 1) how do I access the 'a' from function (method) OneOfA in class A so that it can be used by functions (methods) in class B? Cheers Dinesh -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080314/1427d601/attachment.htm From neal at bcn.boulder.co.us Fri Mar 14 18:43:08 2008 From: neal at bcn.boulder.co.us (Neal McBurnett) Date: Fri, 14 Mar 2008 10:43:08 -0700 (MST) Subject: [Tutor] pydoc introspecting info via OptionParser? Message-ID: <20080314174308.7E5FE8430@lock.gotdns.org> I'm trying to do nice clean documentation for a python script I run from the command-line, and I'd like pydoc or a similar program to document it well. But I don't want to duplicate option information by putting it both in my docstring and in optparse. I would think that pydoc might notice an OptionParser instance at the module level and show the options defined there, but it doesn't seem to. Would it be hard to add to pydoc? Do any other documentation programs do that? I know that on aspn there is a library to parse a docstring and pass options to optparse: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/278844 But it has limitations (doesn't support all of optparse, won't work with -OO) and is a bit uglier. Cheers, Neal McBurnett http://mcburnett.org/neal/ From bgailer at alum.rpi.edu Fri Mar 14 19:20:21 2008 From: bgailer at alum.rpi.edu (bob gailer) Date: Fri, 14 Mar 2008 14:20:21 -0400 Subject: [Tutor] hypotenuse In-Reply-To: References: <5e58f2e40803131813hff35b11hbca804d704dba504@mail.gmail.com> <5e58f2e40803131845y5cf18a70sd5417844d8580c24@mail.gmail.com> Message-ID: <47DAC1E5.9080502@alum.rpi.edu> Robert Childers wrote: > I have rewritten my "hypotenuse" program as follows:>>> #This program > calculates the width and diagonal of a golden rectangle > >>> print "Calculate the width and diagonal of a golden rectangle." > Calculate the width and diagonal of a golden rectangle. > >>> height = input ("Input height:") > Input height:1 > >>> width = height*1.618 > >>> print "Width:", width > Width: 1.618 > >>> import math > >>> hyp_squared = height**2 + width**2 > >>> hypotenuse = math.sqrt(hyp_squared) > >>> print "Diagonal:", hypotenuse > Diagonal: 1.90208412012 > > When I save the program then try to run the module I get an error > message that it is invalid. Please ALWAYS post the code and the traceback. Otherwise we have no way to easily help you. But I will take a guess that you saved the contents of the interactive session and tried to run that. That will not work, as the interactive session is full of >>> and results of print statements. So I suggest you edit the module to see if this is the case; if it is then remove all the junk so you just have pure Python. Run that. If you still get errors post the code and traceback. -- Bob Gailer 919-636-4239 Chapel Hill, NC From GGraham at cistercian.org Fri Mar 14 21:57:58 2008 From: GGraham at cistercian.org (Greg Graham) Date: Fri, 14 Mar 2008 15:57:58 -0500 Subject: [Tutor] Working with Python Objects In-Reply-To: References: Message-ID: <4B07785C52C78449A6C036FB2F69BEBD0320B32A@server1.cistercian.com> Dinesh wrote: > I've avoided it as long as possible but I've reached a stage where I have to > start using Python objects! The primary reason is that the web framework uses > objects and the second is to eliminate a few globals. Here is example pseudo > code followed by the question (one of many I suspect!): > > class A: > constantA = 9 > def OneOfA: > > a = > > class B: > variableB = "quick brown fox" > def OneOfB: > > b = > c = b * a # the 'a' from def OneOfA in class A > > Question: > 1) how do I access the 'a' from function (method) OneOfA in class A so that > it can be used by functions (methods) in class B? I wrote the following classes as an example that might be what you want. 1 class A(object): 2 def one_of_a(self): # self is required for a method 3 self.a = 3 4 print self.a 5 6 class B(object): 7 def one_of_b(self, a_obj): 8 b = 10 9 self.c = b * a_obj.a 10 print self.c First of all, note that the method definitions have a "self" argument. This is how the method has access to the object for which they are called. If you look on line 3, I put "self.a" so that the 3 is stored in the "a" field of the object. Since you wanted to access the a field of an A object in your one_of_b method, it will need access to an A object, so I added a parameter that you can use to pass in an A object (line 7). Assuming an A object is passed in, then the a field of it can be accessed as in line 9, "a_obj.a". Here is how I ran the code (using IPython): In [17]: v1 = A() In [18]: v1.one_of_a() 3 In [19]: v2 = B() In [20]: v2.one_of_b(v1) 30 At [17], I create an instance of A and assign it to variable v1. At [18] I call the one_of_a method on my newly created object, which prints out a 3, the value stored in the "a" field of v1 object. At [19], I create an instance of B and assign it to variable v2. At [20], I call the one_of_b method on my new object, passing in the A object assigned to v1. It prints out 30, which is 10 times the value in the "a" field of v1. The class, variable, and method names are pretty abstract and similar, so I hope that doesn't cause undue confusion. It might be easier to understand with a more concrete example. Greg From alan.gauld at btinternet.com Fri Mar 14 23:00:53 2008 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Fri, 14 Mar 2008 22:00:53 +0000 (GMT) Subject: [Tutor] My tutor is back Message-ID: <638408.37662.qm@web86707.mail.ird.yahoo.com> I have no idea why it took my ISP so long but after 4 weeks my Tutorial is finally back up on its original address... Hooray! Alan G. http://www.freenetpages.co.uk/hp/alan.gauld/ From alan.gauld at btinternet.com Fri Mar 14 23:39:15 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 14 Mar 2008 22:39:15 -0000 Subject: [Tutor] Working with Python Objects References: Message-ID: "Dinesh B Vadhia" wrote ---------------------------- class A: constantA = 9 def OneOfA: a = class B: variableB = "quick brown fox" def OneOfB: b = c = b * a # the 'a' from def OneOfA in class A -------------------------- > Question: > 1) how do I access the 'a' from function (method) OneOfA in > class A so that it can be used by functions (methods) in class B? You don't and shouldn't try to. In this case because the attriute only exists inside the method, it is local, so dies when the method completes. So first of all you need to make it part of the class A. We do that by tagging it as an attribute of self, which should be the fitrst attribute of every method. But one of the concepts of OOP is to think in terms of the objects not the attributes inside them So your question should probably be: How do I access objects of class A inside methods of class B? The answer is by passing an instance into the method as a parameter. You can then manipulate the instance of A by sending messages to it. In Python you can access the instance values of an object by sending a message with the same name as the attribute - in other OOP languages you would need to provide an accessor method. But it is very important conceptually that you try to get away from thinking about accessing attributes of another object inside methods. Access the objects. Metthods should only be manipulating the attributes of their own class. To do otherwise is to break the reusability of your classes. So re writing your pseudo code: class A: constantA = 9 def OneOfA(self): # add self as first parameter self.a = # use 'self' to tag 'a' as an attribute class B: variableB = "quick brown fox" def OneOfB(self, anA): # add self and the instance of A b = c = b * anA.a # the 'a' from the instance anA This way OneOfB() only works with attributes local to it or defined as instance variables or passed in as arguments. Which is as it should be! Real OOP purists don't like direct attribute access but in Python its an accepted idiom and frankly there is little value in writing an accessor method that simply returns the value if you can access it directly. The thing you really should try to avoid though is modifying the attributes directly from another class. Normally you can write a more meaningful method that will do that for you. -- Alan Gauld Author of the Learn to Program web site Temorarily at: http://uk.geocities.com/alan.gauld at btinternet.com/ Normally: http://www.freenetpages.co.uk/hp/alan.gauld From listsdl04 at yahoo.de Sat Mar 15 05:43:06 2008 From: listsdl04 at yahoo.de (Guba) Date: Sat, 15 Mar 2008 12:43:06 +0800 Subject: [Tutor] my first project: a multiplication trainer Message-ID: <47DB53DA.3070908@yahoo.de> Hello everybody, I want to create a simple multiplication trainer which quizzes me on the multiplication table. All multiplication combinations should be asked once, without repetition. Here my pseudo code: ####################### A = [1,2,3,4,5,6,7,8,9] B = [1,2,3,4,5,6,7,8,9] asked_questions = () false_answers = () #block 1 While tuple "asked_questions" contains less than 81 items: Take one random item from A and one random item from B If the question is NOT in "asked_questions": Add question to tuple "asked_questions" Calculate the question and wait for user-input print the question # e.g.: 3x6= If answer is false: add question to the tuple "false_answers" print: "You have answered all questions!" ####################### I would very much appreciate if you could comment on/criticise my pseudo code. In particular: is my approach correct, or would it be more sensible to first generate (or supply?) all possible questions and then select the ready questions randomly? So far I am not concerned about what to do with the tuple "false_answers". This I worry about later. Thanks for your help! Guba From marc.tompkins at gmail.com Sat Mar 15 10:15:49 2008 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Sat, 15 Mar 2008 02:15:49 -0700 Subject: [Tutor] Fwd: my first project: a multiplication trainer In-Reply-To: <40af687b0803150213y1423a2e9kbd37bf9a75779ab2@mail.gmail.com> References: <47DB53DA.3070908@yahoo.de> <40af687b0803150213y1423a2e9kbd37bf9a75779ab2@mail.gmail.com> Message-ID: <40af687b0803150215xfff772aj52bce8b3cfb46ed4@mail.gmail.com> Forgot to Reply All... ---------- Forwarded message ---------- From: Marc Tompkins Date: Sat, Mar 15, 2008 at 2:13 AM Subject: Re: [Tutor] my first project: a multiplication trainer To: Guba On Fri, Mar 14, 2008 at 9:43 PM, Guba wrote: > I want to create a simple multiplication trainer which quizzes me on the > multiplication table. All multiplication combinations should be asked > once, without repetition. > ... I would very much appreciate if you could comment on/criticise my pseudo > code. In particular: is my approach correct, or would it be more > sensible to first generate (or supply?) all possible questions and then > select the ready questions randomly? > Your pseudo code doesn't guarantee that all questions will be asked. I think the only way to guarantee that is to generate the list of possibles first. Myself, I have a horrible time writing pseudocode without slipping into real-code syntax, so please bear with me: import random # need this for the randrange() function possibleQuestions = [(x,y) for x in range(1,10) for y in range(1,10)] # list comprehension - creates a list of tuples from (1,1) through (9,9) while len(possibleQuestions) > 0: question = possibleQuestions.pop(random.randrange (len(possibleQuestions))) # pop() returns the given item and deletes it from list (do the rest of your stuff here) Hope that helps. -- www.fsrtechnologies.com -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080315/f121687e/attachment.htm From alan.gauld at btinternet.com Sat Mar 15 10:26:17 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 15 Mar 2008 09:26:17 -0000 Subject: [Tutor] my first project: a multiplication trainer References: <47DB53DA.3070908@yahoo.de> Message-ID: "Guba" wrote > I want to create a simple multiplication trainer which quizzes me on > the > multiplication table. All multiplication combinations should be > asked > once, without repetition. > > Here my pseudo code: > I would very much appreciate if you could comment on/criticise my > pseudo > code. In particular: is my approach correct, or would it be more > sensible to first generate (or supply?) all possible questions and > then > select the ready questions randomly? Personally I'd go for the second approach as being much simpler. Once you have a list tthere are tools to get random selections from that or, even easier, to shuffle them into random order before selection. That will make the code much easier to write I think. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From cfuller084 at thinkingplanet.net Sat Mar 15 11:17:24 2008 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Sat, 15 Mar 2008 05:17:24 -0500 Subject: [Tutor] my first project: a multiplication trainer In-Reply-To: <47DB53DA.3070908@yahoo.de> References: <47DB53DA.3070908@yahoo.de> Message-ID: <200803150517.25013.cfuller084@thinkingplanet.net> The basic approach I use in these sorts of problems is to generate the choices, remove them from a list as they are asked, and then stop when this list is empty. If you don't need the list of questions afterwards, this will work: from random import choice questions = [ [i,j] for i in range(1,10) for j in range(1,10) ] false_answers = [] while questions: q = choice(questions) del questions[questions.index(q)] # stuff If you'd like to keep the original question list, make a proxy list, and choose from that: questions = [ [i,j] for i in range(1,10) for j in range(1,10) ] false_answers = [] choices = range(len(questions)) while choices: proxyq = choice(choics) del choices[choices.index(proxyq)] q = questions[proxyq] # stuff Cheers From ricaraoz at gmail.com Sat Mar 15 13:17:35 2008 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Sat, 15 Mar 2008 09:17:35 -0300 Subject: [Tutor] my first project: a multiplication trainer In-Reply-To: <200803150517.25013.cfuller084@thinkingplanet.net> References: <47DB53DA.3070908@yahoo.de> <200803150517.25013.cfuller084@thinkingplanet.net> Message-ID: <47DBBE5F.8000501@bigfoot.com> Chris Fuller wrote: > The basic approach I use in these sorts of problems is to generate the > choices, remove them from a list as they are asked, and then stop when this > list is empty. > > > If you don't need the list of questions afterwards, this will work: > > from random import choice > > questions = [ [i,j] for i in range(1,10) for j in range(1,10) ] > false_answers = [] > > while questions: > q = choice(questions) > del questions[questions.index(q)] > > # stuff > > > If you'd like to keep the original question list, make a proxy list, and > choose from that: > > questions = [ [i,j] for i in range(1,10) for j in range(1,10) ] > false_answers = [] > > choices = range(len(questions)) > > while choices: > proxyq = choice(choics) > del choices[choices.index(proxyq)] > > q = questions[proxyq] > > # stuff > Considering the fact that choices[x] == x, shouldn't it be : del choices[proxyq] From kent37 at tds.net Sat Mar 15 13:51:50 2008 From: kent37 at tds.net (Kent Johnson) Date: Sat, 15 Mar 2008 08:51:50 -0400 Subject: [Tutor] my first project: a multiplication trainer In-Reply-To: <47DB53DA.3070908@yahoo.de> References: <47DB53DA.3070908@yahoo.de> Message-ID: <47DBC666.8090703@tds.net> Guba wrote: > Hello everybody, > > I want to create a simple multiplication trainer which quizzes me on the > multiplication table. All multiplication combinations should be asked > once, without repetition. I would - create the list of questions - random.shuffle the list - iterate over the questions in the list with a for loop Kent From kent37 at tds.net Sat Mar 15 13:53:28 2008 From: kent37 at tds.net (Kent Johnson) Date: Sat, 15 Mar 2008 08:53:28 -0400 Subject: [Tutor] Fwd: my first project: a multiplication trainer In-Reply-To: <40af687b0803150215xfff772aj52bce8b3cfb46ed4@mail.gmail.com> References: <47DB53DA.3070908@yahoo.de> <40af687b0803150213y1423a2e9kbd37bf9a75779ab2@mail.gmail.com> <40af687b0803150215xfff772aj52bce8b3cfb46ed4@mail.gmail.com> Message-ID: <47DBC6C8.5010206@tds.net> Marc Tompkins wrote: > Myself, I have a horrible time writing pseudocode without slipping into > real-code syntax Me too - often Python is more concise, precise and expressive than English for expressing an algorithm. > while len(possibleQuestions) > 0: could be simply while possibleQuestions: Kent From kent37 at tds.net Sat Mar 15 13:56:18 2008 From: kent37 at tds.net (Kent Johnson) Date: Sat, 15 Mar 2008 08:56:18 -0400 Subject: [Tutor] my first project: a multiplication trainer In-Reply-To: <47DBBE5F.8000501@bigfoot.com> References: <47DB53DA.3070908@yahoo.de> <200803150517.25013.cfuller084@thinkingplanet.net> <47DBBE5F.8000501@bigfoot.com> Message-ID: <47DBC772.4000300@tds.net> Ricardo Ar?oz wrote: > Considering the fact that choices[x] == x, Only until the first delete (that is not at the end). > shouldn't it be : > del choices[proxyq] No. Kent From keridee at jayco.net Sun Mar 16 17:16:13 2008 From: keridee at jayco.net (tiger12506) Date: Sun, 16 Mar 2008 11:16:13 -0500 Subject: [Tutor] my first project: a multiplication trainer References: <47DB53DA.3070908@yahoo.de><200803150517.25013.cfuller084@thinkingplanet.net> <47DBBE5F.8000501@bigfoot.com> Message-ID: <002d01c88781$0e87c950$0702a8c0@home> > Considering the fact that choices[x] == x, shouldn't it be : > del choices[proxyq] choices = [9,2,1,3,6,4,7,8,5,0] for idx, x in enumerate(choices): print idx == x False False False True False False False False False False Not always. From swartmumba at yahoo.com Sat Mar 15 17:07:26 2008 From: swartmumba at yahoo.com (SwartMumba snake) Date: Sat, 15 Mar 2008 09:07:26 -0700 (PDT) Subject: [Tutor] login Message-ID: <40219.38151.qm@web44816.mail.sp1.yahoo.com> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080315/058778bf/attachment.htm From ricaraoz at gmail.com Sat Mar 15 18:16:02 2008 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Sat, 15 Mar 2008 14:16:02 -0300 Subject: [Tutor] my first project: a multiplication trainer In-Reply-To: <47DBC772.4000300@tds.net> References: <47DB53DA.3070908@yahoo.de> <200803150517.25013.cfuller084@thinkingplanet.net> <47DBBE5F.8000501@bigfoot.com> <47DBC772.4000300@tds.net> Message-ID: <47DC0452.9070000@bigfoot.com> Kent Johnson wrote: > Ricardo Ar?oz wrote: >> Considering the fact that choices[x] == x, > > Only until the first delete (that is not at the end). > >> shouldn't it be : >> del choices[proxyq] > > No. > > Kent > Ooops! Missed that one, sorry. From kent37 at tds.net Sat Mar 15 17:44:34 2008 From: kent37 at tds.net (Kent Johnson) Date: Sat, 15 Mar 2008 12:44:34 -0400 Subject: [Tutor] login In-Reply-To: <40219.38151.qm@web44816.mail.sp1.yahoo.com> References: <40219.38151.qm@web44816.mail.sp1.yahoo.com> Message-ID: <47DBFCF2.8020507@tds.net> SwartMumba snake wrote: > I am trying to get the cookies from the site when I login, though > html.info(). The problem is that when I check the source ( html.read() ) > it shows that it does not recognize me as logged in. Also, if I chech > html.info(), the cookies that I am suppose to receive, if I logged in > successfully, are not there. What am I doing wrong? urllib2 does not support cookies by default, you have to configure it with a CookieJar: import cookielib, urllib2 cj = cookielib.CookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) Then use this opener as below. I think you will have to look at the CookieJar to see the cookies. Kent > opener.addheaders = [('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT > 6.0; en-US; rv:1.8.1.12) Gecko/20080201 Firefox/2.0.0.12'), > ('Referer', 'http://www.site.org/index.php') > ] > > values = urllib.urlencode({'user_name': 'MyUsername', 'user_pass': > 'MyPass^^', 'login' : 'Login'}) > req = urllib2.Request('http://www.site.org/index.php', values) > > html = opener.open(req) From swartmumba at yahoo.com Sat Mar 15 17:57:04 2008 From: swartmumba at yahoo.com (SwartMumba snake) Date: Sat, 15 Mar 2008 09:57:04 -0700 (PDT) Subject: [Tutor] login Message-ID: <727328.75217.qm@web44816.mail.sp1.yahoo.com> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080315/a28aed24/attachment.htm From tjampman at gmail.com Sat Mar 15 20:02:08 2008 From: tjampman at gmail.com (Ole Henning Jensen) Date: Sat, 15 Mar 2008 20:02:08 +0100 Subject: [Tutor] hypotenuse In-Reply-To: <47DAC1E5.9080502@alum.rpi.edu> References: <5e58f2e40803131813hff35b11hbca804d704dba504@mail.gmail.com> <5e58f2e40803131845y5cf18a70sd5417844d8580c24@mail.gmail.com> <47DAC1E5.9080502@alum.rpi.edu> Message-ID: <47DC1D30.1060005@gmail.com> bob gailer wrote: > Robert Childers wrote: >> I have rewritten my "hypotenuse" program as follows:>>> #This program >> calculates the width and diagonal of a golden rectangle >>>>> print "Calculate the width and diagonal of a golden rectangle." >> Calculate the width and diagonal of a golden rectangle. >>>>> height = input ("Input height:") >> Input height:1 >>>>> width = height*1.618 >>>>> print "Width:", width >> Width: 1.618 >>>>> import math >>>>> hyp_squared = height**2 + width**2 >>>>> hypotenuse = math.sqrt(hyp_squared) >>>>> print "Diagonal:", hypotenuse >> Diagonal: 1.90208412012 >> >> When I save the program then try to run the module I get an error >> message that it is invalid. > > Please ALWAYS post the code and the traceback. Otherwise we have no way > to easily help you. > > But I will take a guess that you saved the contents of the interactive > session and tried to run that. That will not work, as the interactive > session is full of >>> and results of print statements. > > So I suggest you edit the module to see if this is the case; if it is > then remove all the junk so you just have pure Python. Run that. If you > still get errors post the code and traceback. > Yes like Bob says you most likly saved the interactive session. What you should do is open IDLE as usual, and *before* you start typing you program, you should open a "new wind" from the file menu. This should open a blank sheet, into which you can type your program, just as you did before (but without the >>>). When you have done that, save the file and *remember* to add ".py" to the filename (without the quotes), then press the F5 key to run the program. Happy programming. BR Ole Jensen From kent37 at tds.net Sat Mar 15 22:17:35 2008 From: kent37 at tds.net (Kent Johnson) Date: Sat, 15 Mar 2008 17:17:35 -0400 Subject: [Tutor] login In-Reply-To: <727328.75217.qm@web44816.mail.sp1.yahoo.com> References: <727328.75217.qm@web44816.mail.sp1.yahoo.com> Message-ID: <47DC3CEF.8000603@tds.net> SwartMumba snake wrote: > Using the cookie jar is not going to solve my problem. I don't want to > use the cookie jar. I just want to send the right request so that I will > be sent back the right header, which will contain the information that I > want. Apparently I am not sending the right request because the header > that I am receieving does not have the "Set-Cookie"s that I want. i.e. I > am being recognized as not logged in (non member etc). How do you normally log on with a browser? There are two common methods - basic authentication - this is where the browser pops up a window where you enter your user name and password. This type of authentication is part of the HTTP protocol. It is supported in urllib2 with the HTTPBasicAuthHandler. - forms-based auth - this is where the web site puts up a form. In this case you have to post your credentials to the form. In either case, if you want to make subsequent requests to the site with urllib2, as an authenticated user, you should use the CookieJar as I showed you. The cookie jar remembers the cookie and subsequent requests with the same opener will send the cookie for you. You don't have to be concerned with the headers at all. Kent From bryan.fodness at gmail.com Sat Mar 15 23:13:35 2008 From: bryan.fodness at gmail.com (Bryan Fodness) Date: Sat, 15 Mar 2008 18:13:35 -0400 Subject: [Tutor] Parsing DICOMRT file In-Reply-To: <5e58f2e40712121457x20e5d3d4rf43724bda49878b2@mail.gmail.com> References: <5e58f2e40712112001q578b2674u7156b806d2c70ba5@mail.gmail.com> <5e58f2e40712121457x20e5d3d4rf43724bda49878b2@mail.gmail.com> Message-ID: Haven't had a chance to look at this in a while. On Wed, Dec 12, 2007 at 6:57 PM, John Fouhy wrote: > On 13/12/2007, Bryan Fodness wrote: > > I am new to doing anything like this. I have looked at > > http://www.leadtools.com/SDK/Medical/DICOM/ltdc1.htm and am > > not sure how to proceed. > > I haven't much experience here, but this is how I'd proceed, I think: > > 1. Start by reading the file. It's binary data (I guess) so there's > no point in reading lines.: > rawData = open('file.dcm', 'rb').read() > > 2. Write a function to parse the preamble: > > def parsePreamble(data): > preamble = data[:128] > dicm = data[128:132] > > # you might need to read up on encodings and things to make sure > this test is valid > if dicm == 'DICM': > return preamble, 132 > else: > raise NotAPreambleException This satisfies the if statement. > > > 3. Write functions to parse data elements. The functions are going to > try to parse a data element starting at a particular position, and if > successful, return the position of the end of the element. > > def parseDataelement(data, start): > # do stuff -- the web page you linked didn't have enough information > here > return element, pos I would like to extract 10-20 values from the file. Starting at byte 132, the data elements are specified in the Explicit VR little endian transfer syntax with a group number of 0002. The data element (0002, 0010) contains the Transfer Syntax UID, which specifies how the data elements following the file meta information are encoded. For this one, it is 1.2.840.10008.1.2 which is equal to LittleEndianImplicit. where there is the 2-byte group number, a 2-byte element number, a 4-byte value length (VL) field, and a value field containing VL bytes. Could someone help me get started. I did an xml dump with another program and got, PHOTON as an output example. > > > 4. Parse the whole thing; > > def parseDICOM(data): > elements = [] > try: > preamble, next = parsePreamble(data) > except NotAPreambleException: > preamble, next = None, 0 > > while True: > element, next = parseDataElement(data, next) > elements.append(element) > # you will need some way of breaking out of this loop, either by > checking the structure of > # element for an end condition, or by parseDataElement raising > an exception. > > return elements # and maybe preamble too if you want it > > HTH! > -- "The game of science can accurately be described as a never-ending insult to human intelligence." - Jo?o Magueijo -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080315/54c54961/attachment.htm From dave6502 at googlemail.com Sun Mar 16 00:15:18 2008 From: dave6502 at googlemail.com (dave selby) Date: Sat, 15 Mar 2008 23:15:18 +0000 Subject: [Tutor] signal trapping in a class instance Message-ID: Hi all, I have a series of class instances saved in an array. I need the instances to respond to a SIGKILL by writing to a file and sys.exit()-ing. Am I right in codeing it as below ? ... does the sys.exit() kill the instance or the instance & the instance holding array definition above it ? Cheers Dave def signal_kill(self, signum, frame): """ On SIGKILL update journal_snap with a special #$86400 'no snapshot' string """ now_secs = time.strftime('%H') * 60 * 60 now_secs = time.strftime('%M') * 60 + now_secs now_secs = time.strftime('%S') + now_secs update_journal(self, time.strftime('%Y%m%d'), self.feed, now_secs, 86400) sys.exit() -- Please avoid sending me Word or PowerPoint attachments. See http://www.gnu.org/philosophy/no-word-attachments.html From cfuller084 at thinkingplanet.net Sun Mar 16 01:17:09 2008 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Sat, 15 Mar 2008 19:17:09 -0500 Subject: [Tutor] signal trapping in a class instance In-Reply-To: References: Message-ID: <200803151917.09956.cfuller084@thinkingplanet.net> SIGKILL is not trappable. You probably want SIGTERM. Furthermore, this signal will be sent to the process, not some thread or class instance within a process. Maybe you need some other mechanism? Is the signal going to be from the same python process? If so, just call it directly. Otherwise, there are a great deal of other interprocess communications options. Sockets are probably the most cross platform nd widely understood. Check out the UDPServer class in the standard library. You'd need to write a client script to send the commands, but this is trivial once you have the server set up. Cheers From cfuller084 at thinkingplanet.net Sun Mar 16 01:41:23 2008 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Sat, 15 Mar 2008 19:41:23 -0500 Subject: [Tutor] signal trapping in a class instance In-Reply-To: References: Message-ID: <200803151941.23561.cfuller084@thinkingplanet.net> I read your post again, and it looks as though you might want to use the atexit module. ?Another idea would be to trap the SIGTERM signal and to keep a registry of instances, and then to invoke a cleanup method of each instance. Another important note: trapping signals will have no effect if your process terminates itself. Cheers From tyler.smith at mail.mcgill.ca Sun Mar 16 03:35:28 2008 From: tyler.smith at mail.mcgill.ca (Tyler Smith) Date: Sun, 16 Mar 2008 02:35:28 +0000 (UTC) Subject: [Tutor] noob python cgi Message-ID: Hi, I'm writing a webpage as a learning exercise. My first objective is to allow myself to upload files to directories in /images/, and have cgi scripts automatically generate the pages that will allow users to navigate through the images. I have a very basic prototype that does what I want, at least for a website served by Apache on my laptop (not web-accessible). Any comments or feedback on the sanity of this approach, or ways to improve it generally would be appreciated! I understand what I've done, but I have no idea what other approaches there might be. I'd like to avoid a complicated CMS at this point, as I want to learn about the basics of serving up webpages. Three files follow. First, the html index page, followed by the gallery picker, followed by the thumbnail displayer. Thanks! Tyler index: My home page

Home

Only one thing to do - visit the galleries. gallery picker: #! /usr/bin/python import cgitb; cgitb.enable() import cgi, os print """Content-type: text/html Galleries

Select a gallery:

""" thumbviewer: #! /usr/bin/python import cgitb; cgitb.enable() import cgi, os form = cgi.FieldStorage() gal = form["gallery"].value print """Content-type: text/html """ print '%s' % gal print"""

%s gallery:

""" % gal for file in os.listdir("".join(("../images/", gal))): print '

' % (gal, file) print """""" From rabidpoobear at gmail.com Sun Mar 16 04:54:28 2008 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sat, 15 Mar 2008 21:54:28 -0600 Subject: [Tutor] noob python cgi In-Reply-To: References: Message-ID: <47DC99F4.4000303@gmail.com> Tyler Smith wrote: > Hi, > [snip explanation] > Three files follow. First, the html index page, followed by the > gallery picker, followed by the thumbnail displayer. > > Thanks! > > Tyler > [snip code] > In the future please include your code as attachments, to avoid e-mail programs mangling the code, unless it's just a few lines. Thanks, -Luke From neal at bcn.boulder.co.us Sun Mar 16 04:32:35 2008 From: neal at bcn.boulder.co.us (Neal McBurnett) Date: Sat, 15 Mar 2008 20:32:35 -0700 Subject: [Tutor] pydoc introspecting info via OptionParser? In-Reply-To: <20080314174308.7E5FE8430@lock.gotdns.org> References: <20080314174308.7E5FE8430@lock.gotdns.org> Message-ID: <20080316033235.GT27177@feynman> On Fri, Mar 14, 2008 at 10:43:08AM -0700, Neal McBurnett wrote: > I'm trying to do nice clean documentation for a python script I run > from the command-line, and I'd like pydoc or a similar program to > document it well. But I don't want to duplicate option information by > putting it both in my docstring and in optparse. > > I would think that pydoc might notice an OptionParser instance at the > module level and show the options defined there, but it doesn't seem > to. Would it be hard to add to pydoc? Do any other documentation > programs do that? For now I've instead put this quasi-template-tag in my docstring in an appropriate place: %InsertOptionParserUsage% and added this code to the module to incorporate the usage into the docstring after it is defined: # incorporate OptionParser usage documentation in our docstring __doc__ = __doc__.replace("%InsertOptionParserUsage%\n", parser.format_help()) That gets me pretty close. The biggest problem is that when pydoc prints it, the usage statement starts with "Usage: pydoc [options]" rather than "Usage: myprogram [options]". I could set the OptionParser "prog" option to override that, but I prefer that in real life the program provide usage referencing sys.argv[0] rather than hard-coding it, in case it gets deployed under a different name. Comments? Neal McBurnett http://mcburnett.org/neal/ From dineshbvadhia at hotmail.com Sun Mar 16 04:33:39 2008 From: dineshbvadhia at hotmail.com (Dinesh B Vadhia) Date: Sat, 15 Mar 2008 20:33:39 -0700 Subject: [Tutor] Working with Python Objects Message-ID: Alan/Greg I've combined your code fragments and added a function call too, to determine how 'a' is passed between objects and classes: def addNumbers(i, j): k = i + j return k class A: def oneA(self): z = 2 self.a = self.a * z class B: def oneB(self): inA = A() # instance of class A y = 5 b = y * inA.a c = addNumbers(y, b) Is this correct? Dinesh ................................................................................ class A: constantA = 9 def OneOfA: a = class B: variableB = "quick brown fox" def OneOfB: b = c = b * a # the 'a' from def OneOfA in class A -------------------------- > Question: > 1) how do I access the 'a' from function (method) OneOfA in > class A so that it can be used by functions (methods) in class B? You don't and shouldn't try to. In this case because the attriute only exists inside the method, it is local, so dies when the method completes. So first of all you need to make it part of the class A. We do that by tagging it as an attribute of self, which should be the fitrst attribute of every method. But one of the concepts of OOP is to think in terms of the objects not the attributes inside them So your question should probably be: How do I access objects of class A inside methods of class B? The answer is by passing an instance into the method as a parameter. You can then manipulate the instance of A by sending messages to it. In Python you can access the instance values of an object by sending a message with the same name as the attribute - in other OOP languages you would need to provide an accessor method. But it is very important conceptually that you try to get away from thinking about accessing attributes of another object inside methods. Access the objects. Metthods should only be manipulating the attributes of their own class. To do otherwise is to break the reusability of your classes. So re writing your pseudo code: class A: constantA = 9 def OneOfA(self): # add self as first parameter self.a = # use 'self' to tag 'a' as an attribute class B: variableB = "quick brown fox" def OneOfB(self, anA): # add self and the instance of A b = c = b * anA.a # the 'a' from the instance anA This way OneOfB() only works with attributes local to it or defined as instance variables or passed in as arguments. Which is as it should be! Real OOP purists don't like direct attribute access but in Python its an accepted idiom and frankly there is little value in writing an accessor method that simply returns the value if you can access it directly. The thing you really should try to avoid though is modifying the attributes directly from another class. Normally you can write a more meaningful method that will do that for you. -- Alan Gauld Author of the Learn to Program web site Temorarily at: http://uk.geocities.com/alan.gauld at btinternet.com/ Normally: http://www.freenetpages.co.uk/hp/alan.gauld -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080315/3946a7b0/attachment.htm From varsha.purohit at gmail.com Sun Mar 16 07:43:13 2008 From: varsha.purohit at gmail.com (Varsha Purohit) Date: Sat, 15 Mar 2008 23:43:13 -0700 Subject: [Tutor] [tutor] PyGame tutorials Message-ID: Hello all, I have learnt python and wxPython. Now i want to learn making games using pygame engine. Can anyone tellme from where i can learn pygame and start making basic games using this module. Which version i should download and is there any user group like this one for pyGame ?? thanks, -- Varsha Purohit -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080315/4796f889/attachment.htm From alan.gauld at btinternet.com Sun Mar 16 09:48:43 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 16 Mar 2008 08:48:43 -0000 Subject: [Tutor] Working with Python Objects References: Message-ID: "Dinesh B Vadhia" wrote > I've combined your code fragments and added a function > call too, to determine how 'a' is passed between objects > and classes: ------------------------- class A: def oneA(self): z = 2 self.a = self.a * z class B: def oneB(self): inA = A() # instance of class A y = 5 b = y * inA.a c = addNumbers(y, b) ------------------- > Is this correct? Not really. First the line in oneA that assigns to self.a won't work because self.a doesn't exist at that point. So you can't multiply it by z. You might want to introduce an __init__ method to initialize self.a to some value: Secondly by creating an instance of A inside oneB you create a new instance of A each time. That instance will always have the same value. You would be better creating an instance of A outside of B and passing that into B's methods. Like this: class A: def __init__(self, aValue = 0) # initialize witrh a default value self.a = aValue # create self.a def oneA(self): z = 2 self.a = self.a * z # this now works class B: def oneB(self, anA): # pass in an instance of A y = 5 b = y * anA.a print b def addNumbers(anA,aB): theA = A(42) theB = B() theA.oneA() # sets theA.a to 84 theB.oneB(theA) # pass theA to B.oneB HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From tayeb.meftah at gmail.com Sun Mar 16 10:34:16 2008 From: tayeb.meftah at gmail.com (Meftah Tayeb) Date: Sun, 16 Mar 2008 10:34:16 +0100 Subject: [Tutor] What is the benefi of Embedding Python in my application ? Message-ID: <003c01c88748$e99ffaf0$0201a8c0@server> hi my friends, please : 1. What is the benefi of Embedding Python in my application ? 2. if python is embedded in my application: is require a Library to by redistributed ? Thanks !!!!! -------------- Meftah Tayeb Software Developer, Database Administrator, Business Manager and Network Administrator -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080316/ed4b6a87/attachment.htm From tayeb.meftah at gmail.com Sun Mar 16 10:34:16 2008 From: tayeb.meftah at gmail.com (Meftah Tayeb) Date: Sun, 16 Mar 2008 10:34:16 +0100 Subject: [Tutor] What is the benefi of Embedding Python in my application ? Message-ID: <003c01c88748$e99ffaf0$0201a8c0@server> hi my friends, please : 1. What is the benefi of Embedding Python in my application ? 2. if python is embedded in my application: is require a Library to by redistributed ? Thanks !!!!! -------------- Meftah Tayeb Software Developer, Database Administrator, Business Manager and Network Administrator -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080316/ed4b6a87/attachment-0001.htm From tayeb.meftah at gmail.com Sun Mar 16 10:34:16 2008 From: tayeb.meftah at gmail.com (Meftah Tayeb) Date: Sun, 16 Mar 2008 10:34:16 +0100 Subject: [Tutor] What is the benefi of Embedding Python in my application ? Message-ID: <003c01c88748$e99ffaf0$0201a8c0@server> hi my friends, please : 1. What is the benefi of Embedding Python in my application ? 2. if python is embedded in my application: is require a Library to by redistributed ? Thanks !!!!! -------------- Meftah Tayeb Software Developer, Database Administrator, Business Manager and Network Administrator -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080316/ed4b6a87/attachment-0002.htm From michael.lim at student.qut.edu.au Sun Mar 16 10:17:42 2008 From: michael.lim at student.qut.edu.au (Michael Lim) Date: Sun, 16 Mar 2008 19:17:42 +1000 (EST) Subject: [Tutor] [TUTOR] Stupid Pythony Newbie Question: Basic Operators; Message-ID: <20080316191742.CYW09265@mail-msgstore01.qut.edu.au> Sorry guys, this is a newbie question... can someone please help me with what the following 2 basic operators do in like simple english: 1. ^ 2. % From rabidpoobear at gmail.com Sun Mar 16 12:33:12 2008 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sun, 16 Mar 2008 05:33:12 -0600 Subject: [Tutor] Stupid Pythony Newbie Question: Basic Operators; In-Reply-To: <20080316191742.CYW09265@mail-msgstore01.qut.edu.au> References: <20080316191742.CYW09265@mail-msgstore01.qut.edu.au> Message-ID: <47DD0578.3040702@gmail.com> Michael Lim wrote: > Sorry guys, this is a newbie question... can someone please help me with what the following 2 basic operators do in like simple english: > Well, it depends on the situation you use the operation in. I'll give you some examples. > 1. > > ^ > This is a bitwise exclusive-or. If you don't know what that's used for, you probably don't need it. Basically it goes bit-by-bit and performs an exclusive-or on each bit pair. For example: 2 ^ 4 is 6, because 0010 (2) xor 0100 (4) equals 0110 (6) I won't go into more detail about xor, that should be enough to go on if you know what an exlusive-or is supposed to do. > 2. > > % > This performs a few functions. Firstly, just as a normal arithmetic operator, it's called the "mod" or "modulus" operator. It gives you the remainder after an integer division. you know that 6 can go into 19 three whole times, but there will be some left over. Mod gives you the leftover. >>> 19 / 6 3 >>> 19 % 6 1 Because when you divide 19 by 6 you get 3 and 1/6th. Another thing % is used for is string substitution. print "Hello, %s!" % "world" is a basic substitution. Then there are more complex, multi-valued substitutions: import math print "pi: %1.6f, cos(0): %.0f" % (math.pi, math.cos(0)) Note that the collection of values on the right needs to be a tuple (the comma denotes a tuple) Then there's dictionary string substitution: students = {'number' : 2, 'names' : ['joe','bob'] } print "There are %(number)i students in your class. The students are %(names)s." % students There may be other uses for these operators. You really should give us a specific case where you don't understand, cause then we could explain it better. By the way, don't put [TUTOR] in the subject. The mailing list automatically adds [Tutor] so if you manually add it, it just makes your subject harder to read because there are then two tags. Hope that helps, -Luke From gregor.lingl at aon.at Sun Mar 16 11:45:40 2008 From: gregor.lingl at aon.at (Gregor Lingl) Date: Sun, 16 Mar 2008 11:45:40 +0100 Subject: [Tutor] Stupid Pythony Newbie Question: Basic Operators; In-Reply-To: <47DD0578.3040702@gmail.com> References: <20080316191742.CYW09265@mail-msgstore01.qut.edu.au> <47DD0578.3040702@gmail.com> Message-ID: <47DCFA54.5050505@aon.at> Michael Lim schrieb: > Sorry guys, this is a newbie question... can someone please help me > with what the following 2 basic operators do in like simple english: > > 1. > > ^ This operator performs a logical operation, the exclusive or, also xor, for the binary digits af two integer numbers. The operation will be performed bitwise. You will understand this only if you know what the binary representation of a integer is. It goes like this: xor of two digits 0 or 1 returns 1 if these are different and 0 else. 12 ---> '1100' (which means 12 = 8 + 4) 9 ---> '1001' (which means 9 = 8 + 1) xor: '0101' so the result is 4 + 1 = 5 >>> 12 ^ 9 5 >>> > > 2. > % This is simpler: % returns the remainder you get if you perform an integer division. Example 17 divided by 5 results in the quotient 3 and the remainder 2. >>> 17 % 5 2 If you want to know both, quotient and remainder, you can use the divmod function: >>> divmod(17,5) (3, 2) With best regards, Gregor > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From listsdl04 at yahoo.de Sun Mar 16 14:03:25 2008 From: listsdl04 at yahoo.de (Guba) Date: Sun, 16 Mar 2008 21:03:25 +0800 Subject: [Tutor] my first project: a multiplication trainer In-Reply-To: <200803150517.25013.cfuller084@thinkingplanet.net> References: <47DB53DA.3070908@yahoo.de> <200803150517.25013.cfuller084@thinkingplanet.net> Message-ID: <47DD1A9D.1040306@yahoo.de> Hello! I like the idea of retaining my original questions by creating a proxy list, but I wasn't able to understand (find) the proxy list: Chris Fuller wrote: > from random import choice > questions = [ [i,j] for i in range(1,10) for j in range(1,10) ] > false_answers = [] > > choices = range(len(questions)) This I don't understand: len(questions) simply gives 81; range(len(questions)) counts them all up: 0,1,2...80. > > while choices: > proxyq = choice(choices) here choice(choices) picks ONE item out of choices (e.g. 56) and assigns it to proxyq > del choices[choices.index(proxyq)] here the item (56) just assigned to proxyq gets removed from choices (question: why not use pop() for these last two steps?) > > q = questions[proxyq] here q is assigned to item 56, i.e. [7, 3], out of questions (which contains all 81 possible questions). Now, because we are operating in a while loop, 81 item are generated and 81 items are accordingly picked out of the questions list, all this without repetition of items.. If I am right (am I?) with my interpretation, then I still don't understand how/where we generated a proxy list... I think we are just running a while loop without having generated a list out of its ouput!?? Cheers for a short comment! Guba From kent37 at tds.net Sun Mar 16 16:14:05 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 16 Mar 2008 11:14:05 -0400 Subject: [Tutor] [tutor] PyGame tutorials In-Reply-To: References: Message-ID: <47DD393D.7080206@tds.net> Varsha Purohit wrote: > Hello all, > I have learnt python and wxPython. Now i want to learn making > games using pygame engine. Can anyone tellme from where i can learn > pygame and start making basic games using this module. Which version i > should download and is there any user group like this one for pyGame ?? There are numerous tutorials on the PyGame web site: http://www.pygame.org/wiki/tutorials Downloads are here, the correct one depends on what platform you are running: http://www.pygame.org/download.shtml There is a pygame-users mailing list. Kent From cfuller084 at thinkingplanet.net Sun Mar 16 16:34:31 2008 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Sun, 16 Mar 2008 10:34:31 -0500 Subject: [Tutor] my first project: a multiplication trainer In-Reply-To: <47DD1A9D.1040306@yahoo.de> References: <47DB53DA.3070908@yahoo.de> <200803150517.25013.cfuller084@thinkingplanet.net> <47DD1A9D.1040306@yahoo.de> Message-ID: <200803161034.31697.cfuller084@thinkingplanet.net> On Sunday 16 March 2008 08:03, Guba wrote: > Hello! > > I like the idea of retaining my original questions by creating a proxy > list, but I wasn't able to understand (find) the proxy list: > > Chris Fuller wrote: > > from random import choice > > > > questions = [ [i,j] for i in range(1,10) for j in range(1,10) ] > > false_answers = [] > > > > choices = range(len(questions)) > > This I don't understand: len(questions) simply gives 81; > range(len(questions)) counts them all up: 0,1,2...80. Each element in the proxy list is the index of a distinct element in the original list. > > > while choices: > > proxyq = choice(choices) > > here choice(choices) picks ONE item out of choices (e.g. 56) and > assigns it to proxyq > > > del choices[choices.index(proxyq)] > > here the item (56) just assigned to proxyq gets removed from choices > (question: why not use pop() for these last two steps?) choice() returns a random element from the list of choices, not its index. One could call pop() instead of del, but del is probably a little faster, and doesn't return a value that we wouldn't use anyway. pop() wouldn't give us a random element, unless passed a random argument, such as pop(choice(range(len(choices)))), but that would be very cumbersome. > > > q = questions[proxyq] > > here q is assigned to item 56, i.e. [7, 3], out of questions (which > contains all 81 possible questions). > > Now, because we are operating in a while loop, 81 item are generated and > 81 items are accordingly picked out of the questions list, all this > without repetition of items.. > > If I am right (am I?) with my interpretation, then I still don't > understand how/where we generated a proxy list... I think we are just > running a while loop without having generated a list out of its ouput!?? This isn't like a for loop that iterates through the elements of a list. It is a while loop that repeats until some condition is false. I used a bit of a shortcut when I used "while choices:": this is equivalent to "while len(choices)>0", or "stop the loop when the choices list is empty". The deletion is necessary, so that choice() doesn't return the same element again later. It seems to me that a better way to do this would be to use random.shuffle() on the choices list, and iterate through that in a for loop. > > Cheers for a short comment! Ha! How about a long one? I have attached some example code. It is easier to see how this works with working code. The first uses choice(), the second, shuffle(). > > Guba -------------- next part -------------- A non-text attachment was scrubbed... Name: mt1.py Type: application/x-python Size: 396 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20080316/7963b925/attachment.bin -------------- next part -------------- A non-text attachment was scrubbed... Name: mt2.py Type: application/x-python Size: 357 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20080316/7963b925/attachment-0001.bin From keridee at jayco.net Mon Mar 17 17:50:40 2008 From: keridee at jayco.net (tiger12506) Date: Mon, 17 Mar 2008 11:50:40 -0500 Subject: [Tutor] my first project: a multiplication trainer References: <47DB53DA.3070908@yahoo.de><200803150517.25013.cfuller084@thinkingplanet.net><47DD1A9D.1040306@yahoo.de> <200803161034.31697.cfuller084@thinkingplanet.net> Message-ID: <001601c8884f$0b83a570$0702a8c0@home> > choice() returns a random element from the list of choices, not its index. > One could call pop() instead of del, but del is probably a little faster, > and > doesn't return a value that we wouldn't use anyway. pop() wouldn't give > us a > random element, unless passed a random argument, such as > pop(choice(range(len(choices)))), but that would be very cumbersome. I like the shuffle idea. n = [1,2,5,1,2,34,2,4,7,3,3,45,1,76,8] proxy = random.shuffle(xrange(len(n))) for idx in proxy: dowith(n[idx]) From cfuller084 at thinkingplanet.net Sun Mar 16 17:00:38 2008 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Sun, 16 Mar 2008 11:00:38 -0500 Subject: [Tutor] my first project: a multiplication trainer In-Reply-To: <47DD1A9D.1040306@yahoo.de> References: <47DB53DA.3070908@yahoo.de> <200803150517.25013.cfuller084@thinkingplanet.net> <47DD1A9D.1040306@yahoo.de> Message-ID: <200803161100.38822.cfuller084@thinkingplanet.net> Oops, I based those examples on my initial solution, not the preferred one that preserved the questions. Here is some better code. They only use the shuffle method, and I've elaborated a bit on the basic solution, to illustrate some ideas for improvement. Some things you might try as an exercise: provide an escape command, rather than having to use ctrl-c; eliminate the symmetrical questions, i.e. only one of 3x5 and 5x3 need be presented. Cheers -------------- next part -------------- A non-text attachment was scrubbed... Name: mt1.py Type: application/x-python Size: 477 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20080316/25aa4dd3/attachment.bin -------------- next part -------------- A non-text attachment was scrubbed... Name: mt2.py Type: application/x-python Size: 599 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20080316/25aa4dd3/attachment-0001.bin -------------- next part -------------- A non-text attachment was scrubbed... Name: mt3.py Type: application/x-python Size: 870 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20080316/25aa4dd3/attachment-0002.bin From nephish at gmail.com Sun Mar 16 17:44:02 2008 From: nephish at gmail.com (shawn bright) Date: Sun, 16 Mar 2008 11:44:02 -0500 Subject: [Tutor] how to get response from os.system() Message-ID: <384c93600803160944w23a583a3t823ae8b104852828@mail.gmail.com> Lo there all, I am needing to get a response back from a system command. i can do this: os.system('mailq | wc -l") if i do this in the terminal mailq | wc -l , it will spit out a number. How do i get that number as a python variable ? OK, thanks. shawn From kent37 at tds.net Sun Mar 16 18:18:14 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 16 Mar 2008 13:18:14 -0400 Subject: [Tutor] my first project: a multiplication trainer In-Reply-To: <001601c8884f$0b83a570$0702a8c0@home> References: <47DB53DA.3070908@yahoo.de><200803150517.25013.cfuller084@thinkingplanet.net><47DD1A9D.1040306@yahoo.de> <200803161034.31697.cfuller084@thinkingplanet.net> <001601c8884f$0b83a570$0702a8c0@home> Message-ID: <47DD5656.9070204@tds.net> tiger12506 wrote: > n = [1,2,5,1,2,34,2,4,7,3,3,45,1,76,8] > proxy = random.shuffle(xrange(len(n))) shuffle() shuffles in place, it doesn't return the shuffled list. > for idx in proxy: > dowith(n[idx]) Why not shuffle n directly? n = ... random.shuffle(n) for x in n: dowith(x) Kent From lord_cooper at hotmail.co.uk Sun Mar 16 18:59:05 2008 From: lord_cooper at hotmail.co.uk (jake cooper) Date: Sun, 16 Mar 2008 17:59:05 +0000 Subject: [Tutor] newbie needs help with rpg code in python Message-ID: Hey everyone :) I'm extremely new to programming as python is the first language I have attempted to learn (and I only started yesterday!) I decided to start learning by attempting to create a short textbased rpg. My progress so far has been rather haphazard to say the least, but I think I might be finally getting somewhere with this. Below is my code as it currently exists: #Character stats (lv 1) max_c_hp = 180max_c_mp = 30c_strength = 50c_defence = 25c_agility = 50c_fireball = 60c_heal = 100 #Skeleton stats (lv1) max_e_hp = 230max_e_mp = 30e_strength = 48e_defence = 30e_agility = 50e_fireball = 75 #Battle functions def battle_start(): #Allows player to choose to fight or run print 'A skeleton appears from the shadows!' fight_or_run = int(raw_input ('Do you fight[1] or run[2]?')) if fight_or_run == 1: print 'You engage the enemy.' battle_menu() #Sends player to battle menu elif fight_or_run == 2: escape() def battle_menu(): #Allows player to choose primary action in battle print 'Attack[1]' print 'Magic[2]' print 'Escape[3]' menu_selection = int(raw_input ('Enter your choice.')) if menu_selection == 1: c_attack() elif menu_selection == 2: c_m_attack() elif menu_selection == 3: escape() def c_attack(): #Processes damage dealt by a physical attack damage_to_enemy = c_strength - e_defence print 'You inflicted', damage_to_enemy, "points of damage to your enemy" #shows damage dealt temp_e_hp - damage_to_enemy #!!!attempts to deduct damage_to_enemy from temp_e_hp!!! print temp_e_hp if temp_e_hp == 0: victory() else: battle_menu() def escape(): #Allows player to escape from a battle print 'You attempt to flee the battle!' if c_agility > e_agility: print 'You succssfully escape' #!!!Need to quit battle and return to field!!! elif c_agility < e_agility: print 'You fail to escape and miss a battle turn.' #!!!Need to find a way to miss a turn after tb system written!!! battle_menu() elif c_agility == e_agility: print 'You fail to escape and are forced to contine engaging the enemy.' battle_menu() #Sends player to battle menu #Battle flowtemp_c_hp = max_c_hp # creates a temporary stat for characters hp, just to be used in this battletemp_e_hp = max_e_hp #creates a temporary stat for enemies hp, just to be used in this battlebattle_start() # launches battle sequence As you can see, I've annotated it rather thoroughly to display the (simple) processes being performed and there are several issues slowing my progress. The main one I need help with is in the c_attack function. For some reason, I cant manage to subtract damage_to_enemy from temp_e_hp. Any help with my script (especially with this problem) would be highly appreciated. And for one final question, is there a way to use random percentages of a number. For example, to subtract 80 - 120 % of damage_to_enemy from temp_e_hp? Sorry for all the questions, but I'm totally stumped at the moment. Thanks for your time -Jake _________________________________________________________________ Free games, great prizes - get gaming at Gamesbox. http://www.searchgamesbox.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080316/a145989c/attachment-0001.htm From sirgnip at gmail.com Sun Mar 16 20:01:54 2008 From: sirgnip at gmail.com (Scott Nelson) Date: Sun, 16 Mar 2008 13:01:54 -0600 Subject: [Tutor] win32gui, SetForegroundWindow() and setting focus Message-ID: <2682ac9b0803161201i2b6c3882wa6e3fa5b3ad27c27@mail.gmail.com> Greetings all... I'm looking to use the win32api and win32gui modules to do a bit of Windows tinkering (win2k) and I've hit a snag. I'd like to programmatically set which window has the focus. But win32gui.SetForegroundWindow(hwnd) seems to be what I'm looking for, but, it isn't working quite as I expect meaning I probably have a bad assumption. SetForegroundWindow() works like a charm in simple cases from the command line. However, when I enumerate all top level windows and try to set each one as the foreground window in turn, it gets thru 1-2 windows out of the 8-10 I have open before giving me this: Traceback (most recent call last): File "D:\_code\python\apps\WinTests.py", line 25, in ? cycle_foreground() File "D:\_code\python\apps\WinTests.py", line 20, in cycle_foreground win32gui.SetForegroundWindow(handle) pywintypes.error: (0, 'SetForegroundWindow', 'No error message is available') What am I doing wrong in this case? Can my app "give away" its own focus but can't force a different app's window with focus to "give away" its focus? Is there any other way to accomplish this? I've attempted using a mix of SetFocus(), BringWindowToTop(), and EnableWindow() but couldn't find the magic combo. I've attached my test script. Run it as "WinTests cycle" to attempt to cycle the focus through all top level windows and see the traceback above. Run it as "WinTests 12345" to set focus the window with hwnd of 12345. Run it as "WinTests" to get a list of all top level windows and their hwnd's. I've tried reading the very-sparse win32 docs provided with ActiveState's PythonWin, I've read a bit on the win32 API on MSDN and I've googled around a bit, and haven't found much. Thanks for making this a great list, all... -Scott -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: WinTests.py Url: http://mail.python.org/pipermail/tutor/attachments/20080316/fd88a01a/attachment.txt From rabidpoobear at gmail.com Sun Mar 16 21:06:25 2008 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sun, 16 Mar 2008 14:06:25 -0600 Subject: [Tutor] how to get response from os.system() In-Reply-To: <384c93600803160944w23a583a3t823ae8b104852828@mail.gmail.com> References: <384c93600803160944w23a583a3t823ae8b104852828@mail.gmail.com> Message-ID: <47DD7DC1.8050903@gmail.com> shawn bright wrote: > Lo there all, > > I am needing to get a response back from a system command. > i can do this: > > os.system('mailq | wc -l") > > if i do this in the terminal mailq | wc -l , it will spit out a number. > How do i get that number as a python variable ? You need to use the subprocess module, specifically subprocess.Popen, to open an input pipe from the command so you can read() the data in. From pylinuxian at gmail.com Sun Mar 16 20:12:51 2008 From: pylinuxian at gmail.com (linuxian iandsd) Date: Sun, 16 Mar 2008 19:12:51 +0000 Subject: [Tutor] how to get response from os.system() In-Reply-To: <47DD7DC1.8050903@gmail.com> References: <384c93600803160944w23a583a3t823ae8b104852828@mail.gmail.com> <47DD7DC1.8050903@gmail.com> Message-ID: use os.popen("your cmd here") On Sun, Mar 16, 2008 at 8:06 PM, Luke Paireepinart wrote: > shawn bright wrote: > > Lo there all, > > > > I am needing to get a response back from a system command. > > i can do this: > > > > os.system('mailq | wc -l") > > > > if i do this in the terminal mailq | wc -l , it will spit out a > number. > > How do i get that number as a python variable ? > You need to use the subprocess module, specifically subprocess.Popen, to > open an input pipe from the command so you can read() the data in. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080316/b82f8ab4/attachment.htm From pylinuxian at gmail.com Sun Mar 16 20:17:08 2008 From: pylinuxian at gmail.com (linuxian iandsd) Date: Sun, 16 Mar 2008 19:17:08 +0000 Subject: [Tutor] how to get response from os.system() In-Reply-To: References: <384c93600803160944w23a583a3t823ae8b104852828@mail.gmail.com> <47DD7DC1.8050903@gmail.com> Message-ID: i guess that was too short tutorial well, here is an example from a live session on the interpreter. [root at serv ~]# python Python 2.5.1 (r251:54863, Nov 23 2007, 16:16:53) [GCC 4.1.1 20070105 (Red Hat 4.1.1-51)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> >>> cmd='ping -c 1 localhost' >>> import os >>> a=os.popen(cmd) >>> print a >>> print a.read() PING serv.kontactel.loc (127.0.0.1) 56(84) bytes of data. 64 bytes from serv.kontactel.loc (127.0.0.1): icmp_seq=1 ttl=64 time=0.134ms --- serv.kontactel.loc ping statistics --- 1 packets transmitted, 1 received, 0% packet loss, time 0ms rtt min/avg/max/mdev = 0.134/0.134/0.134/0.000 ms >>> i hope you can understand that now u have the output in a variable called "a" that you can parse & use as you wish. On Sun, Mar 16, 2008 at 7:12 PM, linuxian iandsd wrote: > use os.popen("your cmd here") > > > On Sun, Mar 16, 2008 at 8:06 PM, Luke Paireepinart > wrote: > > > shawn bright wrote: > > > Lo there all, > > > > > > I am needing to get a response back from a system command. > > > i can do this: > > > > > > os.system('mailq | wc -l") > > > > > > if i do this in the terminal mailq | wc -l , it will spit out a > > number. > > > How do i get that number as a python variable ? > > You need to use the subprocess module, specifically subprocess.Popen, to > > open an input pipe from the command so you can read() the data in. > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080316/37384335/attachment.htm From nomb85 at comcast.net Sun Mar 16 20:29:29 2008 From: nomb85 at comcast.net (Nathan McBride) Date: Sun, 16 Mar 2008 15:29:29 -0400 Subject: [Tutor] how to get response from os.system() Message-ID: <20080316193056.166601E402E@bag.python.org> Why don't you just use 'commands.getoutput'? -----Original Message----- From: linuxian iandsd Sent: Sunday, March 16, 2008 3:12 PM To: tutor at python.org Subject: Re: [Tutor] how to get response from os.system() use os.popen("your cmd here") On Sun, Mar 16, 2008 at 8:06 PM, Luke Paireepinart wrote: > shawn bright wrote: > > Lo there all, > > > > I am needing to get a response back from a system command. > > i can do this: > > > > os.system('mailq | wc -l") > > > > if i do this in the terminal mailq | wc -l , it will spit out a > number. > > How do i get that number as a python variable ? > You need to use the subprocess module, specifically subprocess.Popen, to [The entire original message is not included] From nomb85 at comcast.net Sun Mar 16 20:47:54 2008 From: nomb85 at comcast.net (Nathan McBride) Date: Sun, 16 Mar 2008 15:47:54 -0400 Subject: [Tutor] how to get response from os.system() Message-ID: <20080316194922.00C571E4028@bag.python.org> Would you mind perhaps show an example running an interactive command like su and show how to send input to the commands waiting propmts? -----Original Message----- From: linuxian iandsd Sent: Sunday, March 16, 2008 3:17 PM To: tutor at python.org Subject: Re: [Tutor] how to get response from os.system() i guess that was too short tutorial well, here is an example from a live session on the interpreter. [root at serv ~]# python Python 2.5.1 (r251:54863, Nov 23 2007, 16:16:53) [GCC 4.1.1 20070105 (Red Hat 4.1.1-51)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> >>> cmd='ping -c 1 localhost' >>> import os >>> a=os.popen(cmd) >>> print a >>> print a.read() PING serv.kontactel.loc (127.0.0.1) 56(84) bytes of data. 64 bytes from serv.kontactel.loc (127.0.0.1): icmp_seq=1 ttl=64 time=0.134ms [The entire original message is not included] From marc.tompkins at gmail.com Sun Mar 16 20:57:37 2008 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Sun, 16 Mar 2008 12:57:37 -0700 Subject: [Tutor] newbie needs help with rpg code in python In-Reply-To: References: Message-ID: <40af687b0803161257k76851068ib921c4a670fb5350@mail.gmail.com> On Sun, Mar 16, 2008 at 10:59 AM, jake cooper wrote: > print 'You inflicted', damage_to_enemy, "points of damage to your > enemy" #shows damage dealt > temp_e_hp - damage_to_enemy #!!!attempts to deduct damage_to_enemy > from temp_e_hp!!! > print temp_e_hp** > * if temp_e_hp == 0:*** > * victory()*** > For some reason, I cant manage to subtract damage_to_enemy from temp_e_hp. > Any help with my script (especially with this problem) would be highly > appreciated. > You're subtracting, but not assigning the result of your subtraction to anything. Try this: temp_e_hp = temp_e_hp - damage_to_enemy May I suggest that you change your victory condition from "equals 0" to "less than or equal to 0"? As it stands, the player can never win unless he hits for exactly as much damage as the enemy has remaining - if he goes over, the enemy becomes immortal. And for one final question, is there a way to use random percentages of a > number. For example, to subtract 80 - 120 % of damage_to_enemy from > temp_e_hp? > The random module is what you want. random.random() returns a number between 0 and 1 - you can use that directly for percentage calculations. OR random.randint(a,b) returns an integer between a and b inclusive - e.g., if a=1 and b=10, possible results include 1 and 10. Something like this, perhaps: import random # this goes at the top of your code temp_e_hp = temp_e_hp - random.randint( (damage_to_enemy*0.8), (damage_to_enemy*1.2)) Of course, you shouldn't hard-code values like 0.8 and 1.2 - but I wanted to keep it simple. -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080316/7df352d0/attachment-0001.htm From mlangford.cs03 at gtalumni.org Sun Mar 16 21:00:29 2008 From: mlangford.cs03 at gtalumni.org (Michael Langford) Date: Sun, 16 Mar 2008 16:00:29 -0400 Subject: [Tutor] newbie needs help with rpg code in python In-Reply-To: References: Message-ID: <82b4f5810803161300n2348a89di594ec096dffdc4a7@mail.gmail.com> If you'd like to damage_to_enemy from temp_e_hp, you do the following temp_e_hp -= damage_to_enemy or temp_e_hp = temp_e_hp- damage_to_enemy. Read the single equals sign as the word "gets" in your head. To get a random integer between two numbers, you do the folowing: import random random.randrange(a, b) Where it will give you an integer of at least a and less than b. So in your case, you could do temp_e_hp -= random.randrange(damage_to_enemy * 0.80 ,damage_to_enemy * 1.2) Which will do between 80-120% the damage_to_enemy to the enemy. --Michael On Sun, Mar 16, 2008 at 1:59 PM, jake cooper wrote: > > Hey everyone :) > I'm extremely new to programming as python is the first language I have > attempted to learn (and I only started yesterday!) > I decided to start learning by attempting to create a short textbased rpg. > My progress so far has been rather haphazard to say the least, but I think > I might be finally getting somewhere with this. > > Below is my code as it currently exists: > > #Character stats (lv 1) > max_c_hp = 180 > max_c_mp = 30 > c_strength = 50 > c_defence = 25 > c_agility = 50 > c_fireball = 60 > c_heal = 100 > #Skeleton stats (lv1) > max_e_hp = 230 > max_e_mp = 30 > e_strength = 48 > e_defence = 30 > e_agility = 50 > e_fireball = 75 > #Battle functions > def battle_start(): #Allows player to choose to fight or run > print 'A skeleton appears from the shadows!' > fight_or_run = int(raw_input ('Do you fight[1] or run[2]?')) > if fight_or_run == 1: > print 'You engage the enemy.' > battle_menu() #Sends player to battle menu > elif fight_or_run == 2: > escape() > def battle_menu(): #Allows player to choose primary action in battle > print 'Attack[1]' > print 'Magic[2]' > print 'Escape[3]' > menu_selection = int(raw_input ('Enter your choice.')) > if menu_selection == 1: > c_attack() > elif menu_selection == 2: > c_m_attack() > elif menu_selection == 3: > escape() > def c_attack(): #Processes damage dealt by a physical attack > damage_to_enemy = c_strength - e_defence > print 'You inflicted', damage_to_enemy, "points of damage to your enemy" > #shows damage dealt > temp_e_hp - damage_to_enemy #!!!attempts to deduct damage_to_enemy from > temp_e_hp!!! > print temp_e_hp > if temp_e_hp == 0: > victory() > else: > battle_menu() > def escape(): #Allows player to escape from a battle > print 'You attempt to flee the battle!' > if c_agility > e_agility: > print 'You succssfully escape' #!!!Need to quit battle and return to > field!!! > elif c_agility < e_agility: > print 'You fail to escape and miss a battle turn.' #!!!Need to find > a way to miss a turn after tb system written!!! > battle_menu() > elif c_agility == e_agility: > print 'You fail to escape and are forced to contine engaging the > enemy.' > battle_menu() #Sends player to battle menu > #Battle flow > temp_c_hp = max_c_hp # creates a temporary stat for characters hp, just to > be used in this battle > temp_e_hp = max_e_hp #creates a temporary stat for enemies hp, just to be > used in this battle > battle_start() # launches battle sequence > > As you can see, I've annotated it rather thoroughly to display the (simple) > processes being performed and there are several issues slowing my progress. > The main one I need help with is in the c_attack function. For some reason, > I cant manage to subtract damage_to_enemy from temp_e_hp. Any help with my > script (especially with this problem) would be highly appreciated. > And for one final question, is there a way to use random percentages of a > number. For example, to subtract 80 - 120 % of damage_to_enemy from > temp_e_hp? > > Sorry for all the questions, but I'm totally stumped at the moment. > Thanks for your time > > -Jake > > ________________________________ > She said what? About who? Shameful celebrity quotes on Search Star! > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Michael Langford Phone: 404-386-0495 Consulting: http://www.RowdyLabs.com From mlangford.cs03 at gtalumni.org Sun Mar 16 21:03:25 2008 From: mlangford.cs03 at gtalumni.org (Michael Langford) Date: Sun, 16 Mar 2008 16:03:25 -0400 Subject: [Tutor] newbie needs help with rpg code in python In-Reply-To: <40af687b0803161257k76851068ib921c4a670fb5350@mail.gmail.com> References: <40af687b0803161257k76851068ib921c4a670fb5350@mail.gmail.com> Message-ID: <82b4f5810803161303m5793a3a4pd2b37786f93c21b8@mail.gmail.com> IMO, in programming real applications, you should not hardcode most values. In programming games, you should often hardcode values, and sometimes not. (Games are not made to be reusable, and excessive softcoding makes changing them an exercise in config file tweaking). > > Of course, you shouldn't hard-code values like 0.8 and 1.2 - but I wanted to > keep it simple. --Michael -- Michael Langford Phone: 404-386-0495 Consulting: http://www.RowdyLabs.com From mlangford.cs03 at gtalumni.org Sun Mar 16 21:05:35 2008 From: mlangford.cs03 at gtalumni.org (Michael Langford) Date: Sun, 16 Mar 2008 16:05:35 -0400 Subject: [Tutor] login In-Reply-To: <727328.75217.qm@web44816.mail.sp1.yahoo.com> References: <727328.75217.qm@web44816.mail.sp1.yahoo.com> Message-ID: <82b4f5810803161305r5966f5eage7e95be053bc01ba@mail.gmail.com> Perhaps try mechanize? http://wwwsearch.sourceforge.net/mechanize/ On Sat, Mar 15, 2008 at 12:57 PM, SwartMumba snake wrote: > Using the cookie jar is not going to solve my problem. I don't want to use > the cookie jar. I just want to send the right request so that I will be sent > back the right header, which will contain the information that I want. > Apparently I am not sending the right request because the header that I am > receieving does not have the "Set-Cookie"s that I want. i.e. I am being > recognized as not logged in (non member etc). > > --- On Sat, 3/15/08, Kent Johnson wrote: > > From: Kent Johnson > Subject: Re: [Tutor] login > To: swartmumba at yahoo.com > Cc: Tutor at python.org > Date: Saturday, March 15, 2008, 11:44 AM > > SwartMumba snake wrote: > > I am trying to get the cookies from the site when I login, though > > html.info(). The problem is that when I check the source ( html.read() > ) > > it shows that it does not recognize me as logged in. Also, if I chech > > html.info(), the cookies that I am suppose to receive, if I logged in > > successfully, are not there. What am I doing wrong? > > urllib2 does not support cookies by default, you have to configure it > with a CookieJar: > > import cookielib, urllib2 > > cj = cookielib.CookieJar() > opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) > > Then use this opener as below. I think you will have to look at the > CookieJar to see the cookies. > > Kent > > > opener.addheaders = [('User-Agent', 'Mozilla/5.0 (Windows; U; > Windows NT > > 6.0; en-US; rv:1.8.1.12) Gecko/20080201 Firefox/2.0.0.12'), > > ('Referer', > 'http://www.site.org/index.php') > > ] > > > > values = urllib.urlencode({'user_name': 'MyUsername', > 'user_pass': > > 'MyPass^^', 'login' : 'Login'}) > > req = urllib2.Request('http://www.site.org/index.php', values) > > > > html = opener.open(req) > ________________________________ > Be a better friend, newshound, and know-it-all with Yahoo! Mobile. Try it > now. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Michael Langford Phone: 404-386-0495 Consulting: http://www.RowdyLabs.com From mail at timgolden.me.uk Sun Mar 16 21:31:58 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Sun, 16 Mar 2008 20:31:58 +0000 Subject: [Tutor] win32gui, SetForegroundWindow() and setting focus In-Reply-To: <2682ac9b0803161201i2b6c3882wa6e3fa5b3ad27c27@mail.gmail.com> References: <2682ac9b0803161201i2b6c3882wa6e3fa5b3ad27c27@mail.gmail.com> Message-ID: <47DD83BE.1030702@timgolden.me.uk> Scott Nelson wrote: > Greetings all... > > I'm looking to use the win32api and win32gui modules to do a bit of > Windows tinkering (win2k) and I've hit a snag. > > I'd like to programmatically set which window has the focus. But > win32gui.SetForegroundWindow(hwnd) seems to be what I'm looking for, > but, it isn't working quite as I expect meaning I probably have a bad > assumption. Hi, Scott. I never can remember what the incantations are to get this right, but if you trawl the various Microsoft-oriented newsgroups (via Google, say) then you see them littered with the corpses of people on the same trail. Assuming no-one on this list comes across with the answer, check out the question on the wider web: translating the answer back into Python is going to be the easiest part ;) TJG From rabidpoobear at gmail.com Sun Mar 16 23:12:08 2008 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sun, 16 Mar 2008 16:12:08 -0600 Subject: [Tutor] how to get response from os.system() In-Reply-To: References: <384c93600803160944w23a583a3t823ae8b104852828@mail.gmail.com> <47DD7DC1.8050903@gmail.com> Message-ID: <47DD9B38.4090802@gmail.com> linuxian iandsd wrote: > use os.popen("your cmd here") This is deprecated in 2.5+, you're supposed to use subprocess module now. From rabidpoobear at gmail.com Sun Mar 16 23:13:05 2008 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sun, 16 Mar 2008 16:13:05 -0600 Subject: [Tutor] how to get response from os.system() In-Reply-To: <20080316194922.00C571E4028@bag.python.org> References: <20080316194922.00C571E4028@bag.python.org> Message-ID: <47DD9B71.4010301@gmail.com> Nathan McBride wrote: > Would you mind perhaps show an example running an interactive command like su and show how to send input to the commands waiting propmts? Using the subprocess module, open a command and save the stdin and stdout pipes as variables. Then write to the stdin to send data to the program, and read from stdout to get data from it. From pylinuxian at gmail.com Sun Mar 16 22:37:09 2008 From: pylinuxian at gmail.com (linuxian iandsd) Date: Sun, 16 Mar 2008 21:37:09 +0000 Subject: [Tutor] login In-Reply-To: <82b4f5810803161305r5966f5eage7e95be053bc01ba@mail.gmail.com> References: <727328.75217.qm@web44816.mail.sp1.yahoo.com> <82b4f5810803161305r5966f5eage7e95be053bc01ba@mail.gmail.com> Message-ID: well, you first get to the authenticating page, that is where you put your username & pass ! & then you post them to be authenticated by server which then sends you a session id, which is a cookie. now to make the server think you're loged in to the site you have to send him back the cookie. now to send him the cookie you need the cookielib so lets do it right now : import urllib, urllib2, cookielib user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' url='http(s)://www.website_to_treat_nicely_and_not_abuse_using_python_scripts.com' cj=cookielib.LWPCookieJar() values={'username':'python_user', 'passwd':'elephant'} # let me explain here what values stand for : # values will represent every one element of a form that is in the authentication page. # yes you got it what is between the

and
& there might be more # so you ll have to add them. # headers={'User-Agent' : user_agent} opener=urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) urllib2.install_opener(opener) # install_opener ? ???? what the hell is this ? ??? # well, now every request will take with it the cookie you got from server # in other words you will be logged-in to this website from now on # data=urllib.urlencode(values) # this is where actin starts (login page here) req=urllib2.Request(url, data, headers) response=urllib2.urlopen(req) url2='http(s)://www.website_to_treat_nicely_and_not_abuse_using_python_scripts.com/second_page' response2=urllib2.urlopen(url2) response2.read() #you can get the page because urlopen manages the session/cookie for you for free. url3='http(s)://www.website_to_treat_nicely_and_not_abuse_using_python_scripts.com/second_page' response3=urllib2.urlopen(url3) response3.read() well, hope this helps -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080316/28474f75/attachment.htm From jeff at drinktomi.com Sun Mar 16 23:59:28 2008 From: jeff at drinktomi.com (Jeff Younker) Date: Sun, 16 Mar 2008 15:59:28 -0700 Subject: [Tutor] how to get response from os.system() In-Reply-To: <20080316194922.00C571E4028@bag.python.org> References: <20080316194922.00C571E4028@bag.python.org> Message-ID: > Would you mind perhaps show an example running an interactive > command like su and show how to send input to the commands waiting > propmts? If you're doing that then you *really* want to be using the pexpect module. cmd = pexpect.spawn('su - SOMEINTERACTIVECOMMAND') cmd.expect('# ') # the prompt cmd.sendline('A COMMAND') cmd.expect('# ') # wait for the prompt again output = cmd.before # the stuff before the prompt cmd.sendline('exit') cmd.close() - Jeff Younker - jeff at drinktomi.com - From nomb85 at comcast.net Mon Mar 17 00:10:18 2008 From: nomb85 at comcast.net (Nathan McBride) Date: Sun, 16 Mar 2008 19:10:18 -0400 Subject: [Tutor] how to get response from os.system() Message-ID: <20080316231146.EAA561E401A@bag.python.org> Yup I use the pexpect module for a lot however couldn't get 'pexpect.run' to work with mysqldump piping to gzip -----Original Message----- From: Jeff Younker Sent: Sunday, March 16, 2008 6:59 PM To: Nathan McBride Cc: tutor at python.org Subject: Re: [Tutor] how to get response from os.system() > Would you mind perhaps show an example running an interactive > command like su and show how to send input to the commands waiting > propmts? If you're doing that then you *really* want to be using the pexpect module. cmd = pexpect.spawn('su - SOMEINTERACTIVECOMMAND') cmd.expect('# ') # the prompt cmd.sendline('A COMMAND') cmd.expect('# ') # wait for the prompt again output = cmd.before # the stuff before the prompt cmd.sendline('exit') cmd.close() - Jeff Younker - jeff at drinktomi.com - From nephish at gmail.com Mon Mar 17 01:34:25 2008 From: nephish at gmail.com (shawn bright) Date: Sun, 16 Mar 2008 19:34:25 -0500 Subject: [Tutor] how to get response from os.system() In-Reply-To: <20080316231146.EAA561E401A@bag.python.org> References: <20080316231146.EAA561E401A@bag.python.org> Message-ID: <384c93600803161734l4e61a9f4xb5bd2bab338c0a3c@mail.gmail.com> thanks all, appreciate it much. shawn On Sun, Mar 16, 2008 at 6:10 PM, Nathan McBride wrote: > Yup I use the pexpect module for a lot however couldn't get 'pexpect.run' to work with mysqldump piping to gzip > > > -----Original Message----- > From: Jeff Younker > Sent: Sunday, March 16, 2008 6:59 PM > To: Nathan McBride > Cc: tutor at python.org > Subject: Re: [Tutor] how to get response from os.system() > > > > > > Would you mind perhaps show an example running an interactive > > command like su and show how to send input to the commands waiting > > propmts? > > If you're doing that then you *really* want to be using the pexpect > module. > > cmd = pexpect.spawn('su - SOMEINTERACTIVECOMMAND') > cmd.expect('# ') # the prompt > cmd.sendline('A COMMAND') > cmd.expect('# ') # wait for the prompt again > output = cmd.before # the stuff before the prompt > cmd.sendline('exit') > cmd.close() > > > - Jeff Younker - jeff at drinktomi.com - > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From tyler.smith at mail.mcgill.ca Mon Mar 17 02:26:44 2008 From: tyler.smith at mail.mcgill.ca (Tyler Smith) Date: Mon, 17 Mar 2008 01:26:44 +0000 (UTC) Subject: [Tutor] noob python cgi References: <47DC99F4.4000303@gmail.com> Message-ID: On 2008-03-16, Luke Paireepinart wrote: > Tyler Smith wrote: >> Hi, >> [snip explanation] >> Three files follow. First, the html index page, followed by the >> gallery picker, followed by the thumbnail displayer. >> >> Thanks! >> >> Tyler >> [snip code] >> > In the future please include your code as attachments, to avoid e-mail > programs mangling the code, unless it's just a few lines. Not to be obtuse, but what did you see? I sent plain ascii text, no tabs, so I'm not sure what there was that an email program might want to mangle. Tyler From alan.gauld at btinternet.com Mon Mar 17 02:32:07 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 17 Mar 2008 01:32:07 -0000 Subject: [Tutor] win32gui, SetForegroundWindow() and setting focus References: <2682ac9b0803161201i2b6c3882wa6e3fa5b3ad27c27@mail.gmail.com> Message-ID: "Scott Nelson" wrote > I'd like to programmatically set which window has the focus. But > win32gui.SetForegroundWindow(hwnd) seems to be what I'm looking for, > but, it isn't working quite as I expect meaning I probably have a > bad > assumption. Thats pretty common with windows API calls :-( > SetForegroundWindow() works like a charm in simple cases from the > command line. However, when I enumerate all top level windows and > try > win32gui.SetForegroundWindow(handle) > pywintypes.error: (0, 'SetForegroundWindow', 'No error message is > available') > > What am I doing wrong in this case? No idea, but it could be that you don;t have security rights to some of the processes on your machine - maybe something in the system tray. Or maybe its a service that doesn't have a GUI and therefore no Window as such to which it can give focus. There are several scenarios, none esy to debug and none well explained in the API docs. My only advice is probably to only set focus to a known window don't try setting focus to an arbitrary collection of windows. > I've tried reading the very-sparse win32 docs provided with > ActiveState's PythonWin, I've read a bit on the win32 API on MSDN > and > I've googled around a bit, and haven't found much. You are not alone. But thats little comfort I'm sure. Alan G From mwalsh at groktech.org Mon Mar 17 14:38:22 2008 From: mwalsh at groktech.org (Martin Walsh) Date: Mon, 17 Mar 2008 08:38:22 -0500 Subject: [Tutor] how to get response from os.system() In-Reply-To: <20080316231146.EAA561E401A@bag.python.org> References: <20080316231146.EAA561E401A@bag.python.org> Message-ID: <47DE744E.2020203@groktech.org> Hi Nathan, Nathan McBride wrote: > Yup I use the pexpect module for a lot however couldn't get 'pexpect.run' to work with mysqldump piping to gzip > Just to hazard a guess -- when you want to pipe commands with pexpect you have to spawn ('run', it seems, would work the same way) the shell command as an argument to bash (or similar) since pexpect does not natively interpret shell operators or wildcards, like redirect, pipe, etc... from http://pexpect.sourceforge.net/pexpect.html """ Remember that Pexpect does NOT interpret shell meta characters such as redirect, pipe, or wild cards (>, |, or *). This is a common mistake. If you want to run a command and pipe it through another command then you must also start a shell. For example:: child = pexpect.spawn('/bin/bash -c "ls -l | grep LOG > log_list.txt"') child.expect(pexpect.EOF) """ HTH, Marty > -----Original Message----- > From: Jeff Younker > Sent: Sunday, March 16, 2008 6:59 PM > To: Nathan McBride > Cc: tutor at python.org > Subject: Re: [Tutor] how to get response from os.system() > > >> Would you mind perhaps show an example running an interactive >> command like su and show how to send input to the commands waiting >> propmts? > > If you're doing that then you *really* want to be using the pexpect > module. > > cmd = pexpect.spawn('su - SOMEINTERACTIVECOMMAND') > cmd.expect('# ') # the prompt > cmd.sendline('A COMMAND') > cmd.expect('# ') # wait for the prompt again > output = cmd.before # the stuff before the prompt > cmd.sendline('exit') > cmd.close() > > > - Jeff Younker - jeff at drinktomi.com - > From listsdl04 at yahoo.de Mon Mar 17 16:14:48 2008 From: listsdl04 at yahoo.de (Guba) Date: Mon, 17 Mar 2008 23:14:48 +0800 Subject: [Tutor] my first project: a multiplication trainer In-Reply-To: <200803161100.38822.cfuller084@thinkingplanet.net> References: <47DB53DA.3070908@yahoo.de> <200803150517.25013.cfuller084@thinkingplanet.net> <47DD1A9D.1040306@yahoo.de> <200803161100.38822.cfuller084@thinkingplanet.net> Message-ID: <47DE8AE8.7050708@yahoo.de> Dear Chris, list, cheers for the great help: very valuable indeed. Chris Fuller wrote: ###################### for proxyq in choices: q = questions[proxyq] answer = raw_input('%dx%d = ' % tuple(q)) if int(answer) == q[0]*q[1]: print 'correct' else: print 'incorrect' false_answers.append(q) ###################### I was unable to find information on tuple(). (The Python help function was rather conservative in its output, Google not helpful). What exactly is the use of tuple(q) here, and why does not a simple q instead of tuple(q) do? The latter would have been my intuitive expectation... The other thing I have on my mind is this: how could I have the program ask the math questions not horizontally but vertically? An example: 4 x7 = instead of 4x7= Thank you all, Guba From nomb85 at comcast.net Mon Mar 17 16:29:18 2008 From: nomb85 at comcast.net (Nathan McBride) Date: Mon, 17 Mar 2008 11:29:18 -0400 Subject: [Tutor] how to get response from os.system() Message-ID: <20080317153050.6BB701E401F@bag.python.org> That's a great tip I'll have to save than. -----Original Message----- From: Martin Walsh Sent: Monday, March 17, 2008 9:38 AM To: Nathan McBride Cc: tutor at python.org Subject: Re: [Tutor] how to get response from os.system() Hi Nathan, Nathan McBride wrote: > Yup I use the pexpect module for a lot however couldn't get 'pexpect.run' to work with mysqldump piping to gzip > Just to hazard a guess -- when you want to pipe commands with pexpect you have to spawn ('run', it seems, would work the same way) the shell command as an argument to bash (or similar) since pexpect does not natively interpret shell operators or wildcards, like redirect, pipe, etc.. From cfuller084 at thinkingplanet.net Mon Mar 17 17:39:49 2008 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Mon, 17 Mar 2008 11:39:49 -0500 Subject: [Tutor] my first project: a multiplication trainer In-Reply-To: <47DE8AE8.7050708@yahoo.de> References: <47DB53DA.3070908@yahoo.de> <200803161100.38822.cfuller084@thinkingplanet.net> <47DE8AE8.7050708@yahoo.de> Message-ID: <200803171139.49971.cfuller084@thinkingplanet.net> You should try some of the Python tutorials out there. There's a difference between tuples and lists, and the parameter list passed to the string formatting operator must be a tuple. String formatting will also solve your second problem. Also, the library reference is your friend. I particularly like the Beazley book, if you want something in hardcopy, but one of the less terse and more introductory O'Rielly books might suit you better. Here's a partial list of (mostly) tutorial resources that I've compiled: http://wiki.python.org/moin/BeginnersGuide http://www.uselesspython.com/gettingstarted.html http://www.freenetpages.co.uk/hp/alan.gauld/ http://www.secnetix.de/olli/Python/ http://pythonology.org/ Cheers From nomb85 at comcast.net Mon Mar 17 18:54:09 2008 From: nomb85 at comcast.net (Nathan McBride) Date: Mon, 17 Mar 2008 13:54:09 -0400 Subject: [Tutor] how to get response from os.system() Message-ID: <20080317175543.8AAB61E4013@bag.python.org> That's a great tip I'll have to save than. -----Original Message----- From: Martin Walsh Sent: Monday, March 17, 2008 9:38 AM To: Nathan McBride Cc: tutor at python.org Subject: Re: [Tutor] how to get response from os.system() Hi Nathan, Nathan McBride wrote: > Yup I use the pexpect module for a lot however couldn't get 'pexpect.run' to work with mysqldump piping to gzip > Just to hazard a guess -- when you want to pipe commands with pexpect you have to spawn ('run', it seems, would work the same way) the shell command as an argument to bash (or similar) since pexpect does not natively interpret shell operators or wildcards, like redirect, pipe, etc.. From bmais at maisco.com Mon Mar 17 22:10:08 2008 From: bmais at maisco.com (Bill Mais) Date: Mon, 17 Mar 2008 13:10:08 -0800 Subject: [Tutor] python, wxpython and postgresql Message-ID: <47DEDE30.1030604@maisco.com> I'm a newbie to python and would like to build a database app with wxpython and postgresql. Aside from Dabo, I have not found any tutorials that cover reading and writing to a database. Is it so easy that examples are not needed or so impossible that no one can do it. Can someone point me in the right direction. I've got more specific questions but figured this would be a good place to start. Thanks, Bill From rabidpoobear at gmail.com Mon Mar 17 22:35:20 2008 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Mon, 17 Mar 2008 15:35:20 -0600 Subject: [Tutor] python, wxpython and postgresql In-Reply-To: <47DEDE30.1030604@maisco.com> References: <47DEDE30.1030604@maisco.com> Message-ID: <47DEE418.1010008@gmail.com> Bill Mais wrote: > I'm a newbie to python and would like to build a database app with > wxpython and postgresql. Aside from Dabo, I have not found any > tutorials that cover reading and writing to a database. Is it so easy > that examples are not needed or so impossible that no one can do it. > It's neither. There are plenty of examples, but it is fairly easy to do. Ask Google: http://www.google.com/search?hl=en&q=python+postgresql+tutorial&btnG=Google+Search Try the first two results from About.com. If you have an issue with a particular tutorial, we can help you with that as well. > Can someone point me in the right direction. > It's always helpful to do a bit of googling before you ask. You don't want people assuming you're just being lazy ;) > I've got more specific questions but figured this would be a good place > to start. > Sure, ask away. -Luke From nomb85 at comcast.net Mon Mar 17 21:36:53 2008 From: nomb85 at comcast.net (Nathan McBride) Date: Mon, 17 Mar 2008 16:36:53 -0400 Subject: [Tutor] how to get response from os.system() Message-ID: <20080317203821.409631E400E@bag.python.org> That's a great tip I'll have to save than. -----Original Message----- From: Martin Walsh Sent: Monday, March 17, 2008 9:38 AM To: Nathan McBride Cc: tutor at python.org Subject: Re: [Tutor] how to get response from os.system() Hi Nathan, Nathan McBride wrote: > Yup I use the pexpect module for a lot however couldn't get 'pexpect.run' to work with mysqldump piping to gzip > Just to hazard a guess -- when you want to pipe commands with pexpect you have to spawn ('run', it seems, would work the same way) the shell command as an argument to bash (or similar) since pexpect does not natively interpret shell operators or wildcards, like redirect, pipe, etc.. From nomb85 at comcast.net Mon Mar 17 22:31:03 2008 From: nomb85 at comcast.net (Nathan McBride) Date: Mon, 17 Mar 2008 17:31:03 -0400 Subject: [Tutor] how to get response from os.system() Message-ID: <20080317213234.3B6F81E400E@bag.python.org> That's a great tip I'll have to save than. -----Original Message----- From: Martin Walsh Sent: Monday, March 17, 2008 9:38 AM To: Nathan McBride Cc: tutor at python.org Subject: Re: [Tutor] how to get response from os.system() Hi Nathan, Nathan McBride wrote: > Yup I use the pexpect module for a lot however couldn't get 'pexpect.run' to work with mysqldump piping to gzip > Just to hazard a guess -- when you want to pipe commands with pexpect you have to spawn ('run', it seems, would work the same way) the shell command as an argument to bash (or similar) since pexpect does not natively interpret shell operators or wildcards, like redirect, pipe, etc.. From rabidpoobear at gmail.com Mon Mar 17 23:35:49 2008 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Mon, 17 Mar 2008 16:35:49 -0600 Subject: [Tutor] how to get response from os.system() In-Reply-To: <20080317213234.3B6F81E400E@bag.python.org> References: <20080317213234.3B6F81E400E@bag.python.org> Message-ID: <47DEF245.8050803@gmail.com> Nathan McBride wrote: > That's a great tip I'll have to save than. Nathan, I'm not sure why you sent this three times, but we've gotten it, if you're worried about it. Thanks, -Luke From eric at ericwalstad.com Mon Mar 17 22:49:24 2008 From: eric at ericwalstad.com (Eric Walstad) Date: Mon, 17 Mar 2008 14:49:24 -0700 Subject: [Tutor] python, wxpython and postgresql In-Reply-To: <47DEDE30.1030604@maisco.com> References: <47DEDE30.1030604@maisco.com> Message-ID: <47DEE764.7000309@ericwalstad.com> Hey Bill, Bill Mais wrote: > I'm a newbie to python and would like to build a database app with > wxpython and postgresql. I would suggest you first write the basic app to work from the command line. It's easy to debug that way and enables you to focus on the critical features of your app without wasting much, if any, of your time. Once you are able to do the basics from the command line it is generally easy to wrap it in wxPython. As Luke said, there are a lot of examples out there on how to read/write to a postgresql db. At some point, probably after you try a code example or two, you may find the DB API pep helpful: http://www.python.org/dev/peps/pep-0249/ It defines the interface the db adapters (psycopg, for example) are supposed to provide you. We are happy to help when you have specific questions, too. Best, Eric. other keyword pointers include: optparse (makes handling command line options a breeze) raw_input (get user input from the command line) psycopg2 (postgresql database adapter) doctest (document your code with runnable tests) From bmais at maisco.com Tue Mar 18 00:31:28 2008 From: bmais at maisco.com (Bill Mais) Date: Mon, 17 Mar 2008 15:31:28 -0800 Subject: [Tutor] python, wxpython and postgresql In-Reply-To: <47DEE418.1010008@gmail.com> References: <47DEDE30.1030604@maisco.com> <47DEE418.1010008@gmail.com> Message-ID: <47DEFF50.1090701@maisco.com> Hey, I thought programming was all about the shortcuts ;-) I'm sorry to not be clear. I've done several excellent python + postgresql tutorials, but the one I have not found is wxPython + postgresql (or any database). Specifically, how would you take your sql results and set the values of your wxTextCtrls and wxListCtrls? For example if the sql select statement returns 20 fields the function would find the wxPython controls with the same name and set their values. And how would you build a sql statement with only the wxPython controls that have been modified by the user? So if only the address field was modified the sql would be: UPDATE table1 SET address = '123 Easy Street' WHERE rec_id = 1 Thanks again, Bill From cfuller084 at thinkingplanet.net Mon Mar 17 22:49:54 2008 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Mon, 17 Mar 2008 21:49:54 GMT Subject: [Tutor] python, wxpython and postgresql Message-ID: <200803172149.m2HLnsjG014703@mail.authsmtp.com> Unless you have a specific reason for choosing postgresql (an excellent database, just not the easiest), such as having an existing installation, desiring networked access, or nice features such as type safety, you might want to consider SQLite instead. Also, if you stick to the DB-API spec, you will have a fairly easy time of switching databases later, should you wish to. http://www.python.org/peps/pep-0249.html Cheers From cfuller084 at thinkingplanet.net Tue Mar 18 01:37:49 2008 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Mon, 17 Mar 2008 19:37:49 -0500 Subject: [Tutor] python, wxpython and postgresql In-Reply-To: <47DF1247.3020002@maisco.com> References: <200803172149.m2HLnsjG014703@mail.authsmtp.com> <47DF1247.3020002@maisco.com> Message-ID: <200803171937.49327.cfuller084@thinkingplanet.net> There are at least a couple of python interfaces to postgresql, but psycopg follows the DB-API spec. You shouldn't have to use the postgresql engine directly. http://www.initd.org/pub/software/psycopg/ The cool bit is that the examples you see that follow DB-API will apply to postgresql, except for the initial connection part. Cheers From lavendula6654 at yahoo.com Tue Mar 18 02:42:34 2008 From: lavendula6654 at yahoo.com (Elaine) Date: Mon, 17 Mar 2008 18:42:34 -0700 (PDT) Subject: [Tutor] Foothill College Spring Courses Message-ID: <196647.687.qm@web31712.mail.mud.yahoo.com> Spring quarter classes start Monday, 7 April, at Foothill College. These two may be of interest to you: 1) Introduction to Python Programming - 5 units Prerequisite: Any programming language experience CIS 68K - Monday evenings at Middlefield campus in Palo Alto 2) Application Software Development with Ajax - 5 units Prerequisite: Knowledge of HTML and JavaScript COIN 71 - Tuesday evenings at Middlefield campus in Palo Alto If you are interested in taking a class, please register as soon as possible by going to: http://www.foothill.fhda.edu/reg/index.php If not enough students sign up, a class may be cancelled. If you have any questions, please contact the instructor, Elaine Haight, at haightElaine at foothill.edu ____________________________________________________________________________________ Never miss a thing. Make Yahoo your home page. http://www.yahoo.com/r/hs From technorapture at gmail.com Tue Mar 18 04:21:38 2008 From: technorapture at gmail.com (Shrutarshi Basu) Date: Mon, 17 Mar 2008 23:21:38 -0400 Subject: [Tutor] Should config file parser be in module's __init__.py Message-ID: <376fbdcf0803172021y653a7477vb64802eea5dd378@mail.gmail.com> I'm working on a module consisting of a number of scripts that handle communications over a serial connection. I would like someway for the user to be able to specify which serial port to be used based on a config file in the same directory as the user's program. Should I place the parsing system in the module's init.py, considering that the port will actually be accessed by a different python script in the same module? How could I then let the other scripts access the port information obtained by the parser? Thanks, Shrutarshi From yennes at gmail.com Tue Mar 18 07:31:25 2008 From: yennes at gmail.com (Nirmal Sakthi) Date: Tue, 18 Mar 2008 02:31:25 -0400 Subject: [Tutor] Need help with structure unpacking module Message-ID: <402570eb0803172331g56b6c442v940fa8eb8d381d17@mail.gmail.com> I am using module struct.unpack() to decode data from a binary file, so that I can use the value in a calculation. I have been able to extract an integer value. >>>length = struct.unpack('i', '\x9c\x00\x00\x00') >>>length = int(length[0]) >>>print length 156 I want to be able to extract a string. I have tried, >>>first = struct.unpack('s', '\x02\x00') >>>first = str(first[0]) >>>print first Traceback (most recent call last): ...... error: unpack requires a string argument of length 1 and, >>>first = struct.unpack('cccc', '\x02\x00') >>>first = str(first[0]) >>>print first Traceback (most recent call last): ...... return o.unpack(s) error: unpack requires a string argument of length 4 My desired result would be the string '0200'. Actually, I would like to be able to invert the bytes to get '0002'. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080318/e4905db3/attachment.htm From kent37 at tds.net Tue Mar 18 11:52:10 2008 From: kent37 at tds.net (Kent Johnson) Date: Tue, 18 Mar 2008 06:52:10 -0400 Subject: [Tutor] Should config file parser be in module's __init__.py In-Reply-To: <376fbdcf0803172021y653a7477vb64802eea5dd378@mail.gmail.com> References: <376fbdcf0803172021y653a7477vb64802eea5dd378@mail.gmail.com> Message-ID: <47DF9EDA.6060906@tds.net> Shrutarshi Basu wrote: > I'm working on a module consisting of a number of scripts that handle > communications over a serial connection. I would like someway for the > user to be able to specify which serial port to be used based on a > config file in the same directory as the user's program. Should I > place the parsing system in the module's init.py, considering that the > port will actually be accessed by a different python script in the > same module? How could I then let the other scripts access the port > information obtained by the parser? There are several common ways to do this. - have a configuration module that parses the settings and contains the results. Modules that need access to the configuration import the config module and read its values - create a configuration object that is passed as a parameter to functions that need it, or pass individual configuration items to the functions. - create a configuration object that is stored as an attribute of a class and accessed that way Kent From rabidpoobear at gmail.com Tue Mar 18 16:10:40 2008 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Tue, 18 Mar 2008 09:10:40 -0600 Subject: [Tutor] Need help with structure unpacking module In-Reply-To: <402570eb0803172331g56b6c442v940fa8eb8d381d17@mail.gmail.com> References: <402570eb0803172331g56b6c442v940fa8eb8d381d17@mail.gmail.com> Message-ID: <47DFDB70.7070401@gmail.com> Nirmal Sakthi wrote: > I am using module struct.unpack() to decode data from a binary file, > so that I can use the value in a calculation. > > I have been able to extract an integer value. > > >>>length = struct.unpack('i', '\x9c\x00\x00\x00') > >>>length = int(length[0]) > >>>print length > 156 > > I want to be able to extract a string. > > I have tried, > > >>>first = struct.unpack('s', '\x02\x00') > >>>first = str(first[0]) > >>>print first > Traceback (most recent call last): > ...... > error: unpack requires a string argument of length 1 I believe you have to provide the string length for this, like struct.unpack('2s', '\x02\x00') or something. > and, > > >>>first = struct.unpack('cccc', '\x02\x00') > >>>first = str(first[0]) > >>>print first > Traceback (most recent call last): > ...... > return o.unpack(s) > error: unpack requires a string argument of length 4 That's because \x02\x00 is only 2 characters long. You don't get direct access to the hex, just to the characters. vals = struct.unpack('cc','\x02\x00') #unpack values > > My desired result would be the string '0200'. Actually, I would like > to be able to invert the bytes to get '0002'. >>> x = ['a','b'] >>> x.reverse() >>> x ['b', 'a'] Sorry I don't have more time to explain, I have to run to class. HTH, -Luke From alan.gauld at btinternet.com Tue Mar 18 15:14:26 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 18 Mar 2008 14:14:26 -0000 Subject: [Tutor] Need help with structure unpacking module References: <402570eb0803172331g56b6c442v940fa8eb8d381d17@mail.gmail.com> Message-ID: "Nirmal Sakthi" wrote > I want to be able to extract a string. > > I have tried, > > >>>first = struct.unpack('s', '\x02\x00') > >>>first = str(first[0]) > >>>print first > Traceback (most recent call last): > ...... > error: unpack requires a string argument of length 1 Which is correct because you asked for a string of length 1 but fed it 2 bytes > >>>first = struct.unpack('cccc', '\x02\x00') > >>>first = str(first[0]) > >>>print first > Traceback (most recent call last): > ...... > return o.unpack(s) > error: unpack requires a string argument of length 4 And here you asked for 54 characters but only gave it two bytes. And the two byes were 02 and 00 which are not printable characters. > My desired result would be the string '0200'. To get that string you would need to feed that string in: To see what that string looks like we need to use the ord() function: >>> for c in '0200': print hex(ord(c)) ... 0x30 0x32 0x30 0x30 >>> So your string needs to be: '\x30\x32\x30\x30' Now in struct: >>> struct.unpack('4s','\x30\x32\x30\x30') ('0200',) >>> > Actually, I would like to be able to invert the bytes to get '0002'. Well, in that case you ned to feed struct with 0002: >>> struct.unpack('4s','\x30\x30\x30\x32') ('0002',) >>> No magic in struct it reads out what you ask it to read from the data you give it. It makes no attempt to guess what the data means it asumes you as programmer know what the data looks like and how to interpret it properly. This of course means that when using struct to extract data you need to validate that what you got out matches what you expected to get! HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Tue Mar 18 16:12:06 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 18 Mar 2008 15:12:06 -0000 Subject: [Tutor] Need help with structure unpacking module References: <402570eb0803172331g56b6c442v940fa8eb8d381d17@mail.gmail.com> Message-ID: "Alan Gauld" wrote >> >>>first = struct.unpack('cccc', '\x02\x00') >> error: unpack requires a string argument of length 4 > > And here you asked for 54 characters but only gave > it two bytes. And the two byes were 02 and 00 which > are not printable characters. Oops! This should of course have been 4 characters. And the printableness is an observation but does not have any direct effect on the viability of the operation. Alan G From mlangford.cs03 at gtalumni.org Tue Mar 18 16:19:49 2008 From: mlangford.cs03 at gtalumni.org (Michael Langford) Date: Tue, 18 Mar 2008 11:19:49 -0400 Subject: [Tutor] python, wxpython and postgresql In-Reply-To: <47DEFF50.1090701@maisco.com> References: <47DEDE30.1030604@maisco.com> <47DEE418.1010008@gmail.com> <47DEFF50.1090701@maisco.com> Message-ID: <82b4f5810803180819j4213fbbfs58ea2e5b4fa803e5@mail.gmail.com> I don't recall a modified flag on controls in wxPython. If you only want to update that which has changed, you probably have to keep a copy of the result of the query you filled the control with, and determine the change from comparing it to the current state of the control. These guys may have something more sophisticated: http://lists.wxwidgets.org/cgi-bin/ezmlm-cgi/11 --Michael On Mon, Mar 17, 2008 at 7:31 PM, Bill Mais wrote: > Hey, I thought programming was all about the shortcuts ;-) > > I'm sorry to not be clear. I've done several excellent python + > postgresql tutorials, but the one I have not found is wxPython + > postgresql (or any database). > > Specifically, how would you take your sql results and set the values of > your wxTextCtrls and wxListCtrls? For example if the sql select > statement returns 20 fields the function would find the wxPython > controls with the same name and set their values. > > And how would you build a sql statement with only the wxPython controls > that have been modified by the user? So if only the address field was > modified the sql would be: UPDATE table1 SET address = '123 Easy Street' > WHERE rec_id = 1 > > Thanks again, > > > Bill > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Michael Langford Phone: 404-386-0495 Consulting: http://www.RowdyLabs.com From pyprog05 at gmail.com Tue Mar 18 16:23:47 2008 From: pyprog05 at gmail.com (PyProg PyProg) Date: Tue, 18 Mar 2008 16:23:47 +0100 Subject: [Tutor] Help with a loop Message-ID: Hello, I have a little problem, I have two lists: >>> a=[1, 2, 3, 4, 5, 6] >>> b=['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'] ... and I want to obtain: >>> [('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5), ('f', 6), ('g', 1), ('h', 2), ('i', 3), ('j', 4)] I want to obtain that with a comprehension-list. Lists can have dimension completely different. Can you help me please ?. a+ -- http://ekd.tolosano.info From andreas at kostyrka.org Tue Mar 18 17:05:19 2008 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Tue, 18 Mar 2008 17:05:19 +0100 Subject: [Tutor] Help with a loop In-Reply-To: References: Message-ID: <1205856319.15031.31.camel@localhost> Assuming that len(b) > len(a): >>> zip(itertools.cycle(a), b) [(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd'), (5, 'e'), (6, 'f'), (1, 'g'), (2, 'h'), (3, 'i'), (4, 'j')] Andreas Am Dienstag, den 18.03.2008, 16:23 +0100 schrieb PyProg PyProg: > Hello, > > I have a little problem, I have two lists: > > >>> a=[1, 2, 3, 4, 5, 6] > >>> b=['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'] > > ... and I want to obtain: > > >>> [('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5), ('f', 6), ('g', > 1), ('h', 2), ('i', 3), ('j', 4)] > > I want to obtain that with a comprehension-list. > > Lists can have dimension completely different. > > Can you help me please ?. > > a+ > -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Dies ist ein digital signierter Nachrichtenteil Url : http://mail.python.org/pipermail/tutor/attachments/20080318/94af11a0/attachment.pgp From kent37 at tds.net Tue Mar 18 17:06:37 2008 From: kent37 at tds.net (Kent Johnson) Date: Tue, 18 Mar 2008 12:06:37 -0400 Subject: [Tutor] Help with a loop In-Reply-To: References: Message-ID: <47DFE88D.4020105@tds.net> PyProg PyProg wrote: > Hello, > > I have a little problem, I have two lists: > >>>> a=[1, 2, 3, 4, 5, 6] >>>> b=['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'] > > ... and I want to obtain: > >>>> [('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5), ('f', 6), ('g', > 1), ('h', 2), ('i', 3), ('j', 4)] > > I want to obtain that with a comprehension-list. > > Lists can have dimension completely different. Here is one way using itertools.cycle() to repeat elements of a. This will return a list the same length as b, with elements of a repeated as needed: In [140]: from itertools import cycle In [141]: zip(b, cycle(a)) Out[141]: [('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5), ('f', 6), ('g', 1), ('h', 2), ('i', 3), ('j', 4)] If b might sometimes be the shorter list you will have to work a little harder, perhaps cycle both lists and take the first max(len(a), len(b)) elements: In [142]: from itertools import cycle, islice, izip In [143]: list(islice(izip(cycle(b), cycle(a)), max(len(a), len(b)))) Out[143]: [('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5), ('f', 6), ('g', 1), ('h', 2), ('i', 3), ('j', 4)] Kent From wsmith36 at comcast.net Tue Mar 18 21:07:47 2008 From: wsmith36 at comcast.net (TFIA Consulting, Inc.) Date: Tue, 18 Mar 2008 16:07:47 -0400 Subject: [Tutor] Python learning curve Message-ID: <000801c88933$bd552370$0201a8c0@bill1eb684d52d> Hi. I am doing some work for a company that uses Python for their application. I have never used Python before, but I have programmed for over 35 years, maybe 12 languages including 4 assembly level. Your site says it should take just a "few days" to learn Python, so I told these folks to give me 12 days in case I was stupider than average. My question is : Who is right? A 'few days', or going thru the docs below? (which seems a bit more complex than that). Is this REALLY a "few days" task to learn? Would you agree to guarantee coming up to speed in a few days @ no charge? Thank you for your advice, ...Bill Smith Here is their documentation on compiling : ============================================================================== Building Miro Windows ? This page documents how to build Miro for Windows. We need more brave souls willing to help us conquer this platform. Getting started ? The supported Windows port of Miro is based on Mozilla XUL and found in the source:trunk/tv/platform/windows-xul directory. There's an abandoned "native" Windows port in source:trunk/tv/platform/windows don't mess with it. You may be able to find more information here: source:trunk/tv/platform/windows-xul/setup.py source:trunk/tv/platform/windows-xul/README Question : Why don't you use XUL for all platforms? ? Every couple of weeks someone flames us for not using XUL on all platforms. The XUL port of Miro is by far the most complicated and ugliest. XUL doesn't really do what we want to do well. It has a lot of "security" restrictions that we have to work around. The OS X Cocoa port is simpler, and the GTK/X11 port is by far the simplest. Since we have to embed all sorts of platform specific libraries, XUL's cross platformness doesn't make porting to other platforms easier. For example, embedding OS X's quicktime in XUL would be a very large project. >From a UI perspective, we want a native look and feel on all of our platforms, except Windows where we think the platform look sucks. A real native look and feel would require lots of tweaking for GTK, and isn't even possible on XUL/OS X. Compilers ? Visual Studio 2003 ? Miro makes heavy use of Python extensions. Python extensions compiled with a different compiler than Python itself are not guaranteed to work. Since the official Python distribution for Windows is compiled with Microsoft Visual C++ 7.1 (AKA Visual C++ .NET 2003), we only support the MSVC++ 7.1 family of compilers for official builds. Unfortunately, Microsoft has discontinued the no-cost "Visual C++ Toolkit 2003" compiler. Miro also depends on Mozilla XULRunner, PyXPCOM, VLC, and other sundries. However, building Mozilla on Win32 platforms, much less applying our patches, is such a time consuming process that we include pre-built binaries for these in source:trunk/dtv-binary-kit. Unless you need to debug issues with Miro's use of Mozilla code, it's recommended that you use these binaries. Currently, the binaries included are built using Mozilla 1.8 branch. MinGW (GCC) ? We've putting together instructions on building Miro with free tools. The instructions for doing this are here BuildingMiroWithMinGW. We are working hard on improving these instructions. Email us if you're interested in taking this on. If you're interested in helping but are getting stuck on compiler issues, email us, and we'll do our best to help you. Eventually, we'll merge these instructions into this document. Getting dependencies and setting up the build environment ? As of version 0.9.6, we will be using Python 2.5. The binary kit now contains XULRunner 1.8.0.4 linked against Python 2.5. You'll need: MSVC++ 7.1 (2003) compiler Subversion Either install the one from http://tortoisesvn.tigris.org/ or the one that comes with cygwin. The Windows binary release of Python2.5 from python.org I use http://www.python.org/ftp/python/2.5/python-2.5.msi PyRex? - http://www.cosc.canterbury.ac.nz/~greg/python/Pyrex/ I use http://www.cosc.canterbury.ac.nz/greg.ewing/python/Pyrex/oldtar/Pyrex-0.9.5.1.1.tar.gz which when untarred is Pyrex-0.9.5.1a Untar the tarball and run python setup.py install. Psyco - http://psyco.sourceforge.net/ I run svn co -r42037 http://codespeak.net/svn/psyco/dist/ Be sure to run python setup.py install. Py2exe - http://www.py2exe.org I use (http://internap.dl.sourceforge.net/sourceforge/py2exe/py2exe-0.6.6.win32-py2.5.exe Null Soft Installer - http://nsis.sf.net/Download The latest sqlite3.dll file from SQLite I use http://www.sqlite.org/sqlitedll-3_5_2.zip Copy the sqlite3.dll file from the SQLite website over the one in your python directory (Usually C:\Python25\DLLs). If you forget to do this, on certain platforms your build will have this issue. http://mail.python.org/pipermail/python-list/2007-June/444281.html The Windows SDK 6.1 (for Vista headers) http://www.microsoft.com/downloads/details.aspx?FamilyId=E6E1C3DF-A74F-4207-8586-711EBE331CDC&displaylang=en Note: Make sure you use the versions of psyco and pyrex that are recommended. If you don't, you may get weird behavior. If you find other combinations that work, please let us know by listing them on this wiki or sending the working combination to the develop mailing list. Install all the requirements. After you do that, set up your PATH, LIB, and INCLUDE environment variables so that Python distutils can compile modules. It's important to pay attention to the order of the paths in these variables. Generally speaking, Windows compilers and tools should be first, followed by third party tools with Cygwin (if you use it) going last. You'll need to edit your vsvars32.bat to use the updated SDK's LIB and INCLUDE environment variables. I use the following lines. You may need to modify them to reflect the paths on your system. @set INCLUDE=%MSVCDir%\ATLMFC\INCLUDE;%MSVCDir%\INCLUDE;C:\Program Files\Microsoft Visual Studio 9.0\VC\Include;C:\Program Files\Microsoft SDKs\Windows\v6.1\Include;C:\Program Files\Microsoft SDKs\Windows\v6.1\Include\gl @set LIB=%MSVCDir%\ATLMFC\LIB;%MSVCDir%\LIB;C:\Program Files\Microsoft Visual Studio 9.0\VC\Lib;C:\Program Files\Microsoft SDKs\Windows\v6.1\Lib It's good to copy this file into your Miro directory and then add your Python and subversion directories after the @goto end or at the end of the file like this: @set PATH=%PATH%;C:\Program Files\subversion\bin;C:\Python25 Alternatively, you can add c:\Python25\ to the Path environment variable in Control Panel -> System -> Advanced tab -> Environment Variables. Execute vcvars32.bat in the DOS command prompt to pick up the build environment variables. Getting the prebuilt dependency kit ? As mentioned above, these instructions assume that you're using our prebuilt dependency kit. Simply check it out as dtv-binary-kit in the same directory where you checked out DTV and the DTV build script will find the dependency kit automatically. If you want to get the DTV source at the same time, the easiest way is to check out the entire Miro tree, including Miro, the dependency kit, and Broadcast Machine: svn co https://svn.participatoryculture.org/svn/dtv/trunk miro In case your version of svn isn't validating certificates for some reason, our https certificate's fingerprint is 53:db:fa:7d:7f:41:33:cb:c3:c3:05:2b:16:0e:a8:37:60:13:07:30 Note: As of July 28 2006, the dtv-binary and tv repositories account for 146 MB of the total 186 MB repository. Make sure that your path doesn't have any spaces in it. There are bugs in python's spawnl that make setup not work if you're in a directory with a space in it. That will create a directory named 'miro' and create tv and dtv-binary-kit (and bmachine for Broadcast Machine) as subdirectories of it. On the other hand, if you don't want to use the dependency kit, edit platform\windows-xul\setup.py and change the paths in the top section according to the instructions. You will still need to check out dtv-binary-kit (or browse it online), because it contains patches that will need to be applied to some of the dependencies before building. Building and Running ? To build Miro as quickly as possible and run it out of the development tree, do: This is broken as of 06-06-06. Use bdist_xul_dumb instead for now. python setup.py runxul Video playback won't work. VLC doesn't know how to find its plugin directory when DTV is run this way. To build a self-contained, redistributable folder with an actual Miro.exe, do: python setup.py bdist_xul_dumb This creates a directory dist. To build a single-file installer, suitable for distribution to end users: python setup.py bdist_xul This will create something like dist/Miro-.exe. See TestingDtv for the options and environment variables supported, and information on the debugging logfile. There is no way to pass command-line options in runxul mode, other than to edit setup.py. Recompiling Mozilla ? You shouldn't have to do this unless you're debugging Mozilla specific issues. The first time, set aside a few days to figure out how to do it. Compile Mozilla according to the instructions found here using Mozilla 1.9. BuildingXULRunner has Miro specific instructions Recompiling Boost ? You shouldn't have to do this unless you're debugging Boost specific issues. Download the latest Boost source and the Boost jam utility http://superb-east.dl.sourceforge.net/sourceforge/boost/boost_1_33_1.tar.bz2 http://superb-west.dl.sourceforge.net/sourceforge/boost/boost-jam-3.1.13-1-ntx86.zip Extract bjam.exe into c:\mozilla-build\msys\local\bin\ Open a Mozilla build environment terminal (See BuildingXULRunner) Run tar xfvj boost_1_33_1.tar.bz2 cd boost_1_33_1 bjam -sTOOLS=vc-7_1 --with-python --with-python-root=C:\\mozilla-build\\python25 --with-python-version=2.5 stage Troubleshooting ? Pyrex and psyco ? You need to have the exact versions we've listed above for psyco and Pyrex. !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080318/836fee98/attachment-0001.htm From hunter92383 at gmail.com Tue Mar 18 21:42:03 2008 From: hunter92383 at gmail.com (elis aeris) Date: Tue, 18 Mar 2008 13:42:03 -0700 Subject: [Tutor] Anyone fancy giving me some tips and an expert opinion?? In-Reply-To: References: Message-ID: <674d5ce60803181342h4cc3e300s8f05e2c5ad46ec07@mail.gmail.com> i am not sure if I am still in the mailing list of tutor at python.org so please use reply all to send me a email directly please! x = 0 y = 0 for x in xrange (20, 0): print x this doesn't work because it goes from a big number to a small number, which does nothing but what if I need the for loop to go from a big number to a small number? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080318/0e37dead/attachment.htm From kent37 at tds.net Tue Mar 18 22:02:10 2008 From: kent37 at tds.net (Kent Johnson) Date: Tue, 18 Mar 2008 17:02:10 -0400 Subject: [Tutor] Python learning curve In-Reply-To: <000801c88933$bd552370$0201a8c0@bill1eb684d52d> References: <000801c88933$bd552370$0201a8c0@bill1eb684d52d> Message-ID: <47E02DD2.8010906@tds.net> TFIA Consulting, Inc. wrote: > Hi. I am doing some work for a company that uses Python for their > application. > I have never used Python before, but I have programmed for over 35 > years, maybe 12 languages including 4 assembly level. > Your site says it should take just a "few days" to learn Python, so I > told these folks to give me 12 days in case I was stupider than average. > > My question is : Who is right? A 'few days', or going thru the docs > below? (which seems a *bit* more complex than that). The docs you quote have little to do with learning Python the language. They are instructions for *building* an application that "makes heavy use of Python extensions" and which, apparently, is a bit tricky to build correctly under Windows. > Is this *REALLY* a "few days" task to learn? Maybe. I wouldn't count on it. > Would *you* agree to > guarantee coming up to speed in a few days @ no charge? I might agree to spend a few days learning the *language* at no charge. I don't think I would agree to learn how to build their application at no charge. What if it was a language you know, perhaps C, and they wanted you to figure out how to build it on your own time? Doesn't seem reasonable to me. > Here is their documentation on compiling : From here: https://develop.participatoryculture.org/trac/democracy/wiki/WindowsBuildDocs Kent From kent37 at tds.net Tue Mar 18 22:03:57 2008 From: kent37 at tds.net (Kent Johnson) Date: Tue, 18 Mar 2008 17:03:57 -0400 Subject: [Tutor] Anyone fancy giving me some tips and an expert opinion?? In-Reply-To: <674d5ce60803181342h4cc3e300s8f05e2c5ad46ec07@mail.gmail.com> References: <674d5ce60803181342h4cc3e300s8f05e2c5ad46ec07@mail.gmail.com> Message-ID: <47E02E3D.7050902@tds.net> elis aeris wrote: > for x in xrange (20, 0): > print x > but what if I need the for loop to go from a big number to a small number? Just give a step value: for x in xrange(20, 0, -1): print x Kent From hunter92383 at gmail.com Tue Mar 18 22:04:15 2008 From: hunter92383 at gmail.com (elis aeris) Date: Tue, 18 Mar 2008 14:04:15 -0700 Subject: [Tutor] xrange Message-ID: <674d5ce60803181404i51980495ibbbc0e496041eaaf@mail.gmail.com> x = 0 y = 0 for x in xrange (20, 0): print x this doesn't work because it goes from a big number to a small number, which does nothing but what if I need the for loop to go from a big number to a small number? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080318/f0cb7809/attachment.htm From hunter92383 at gmail.com Tue Mar 18 22:10:29 2008 From: hunter92383 at gmail.com (elis aeris) Date: Tue, 18 Mar 2008 14:10:29 -0700 Subject: [Tutor] c++::return Message-ID: <674d5ce60803181410x508ba4bdv539682c8dce06c75@mail.gmail.com> what do I do if i want the program/function to end? in c++ of int main(){} I do a return 0; -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080318/5a1784c7/attachment.htm From mlangford.cs03 at gtalumni.org Tue Mar 18 22:19:53 2008 From: mlangford.cs03 at gtalumni.org (Michael Langford) Date: Tue, 18 Mar 2008 17:19:53 -0400 Subject: [Tutor] Python learning curve In-Reply-To: <000801c88933$bd552370$0201a8c0@bill1eb684d52d> References: <000801c88933$bd552370$0201a8c0@bill1eb684d52d> Message-ID: <82b4f5810803181419w6f89b624u850a5842a939a828@mail.gmail.com> I looked at the Miro gig too. Good luck! As far as "learn python in 12 days", yes and no. You can do fantastic things in that time frame with python and the standard library. I know I had completely written my first code analysis program in 2004 in that time frame just using this PDF as reference: (http://www.diveintopython.org). I see no reason you can't do that sort of thing. However, using all these complicated things at the edge of python is going to be a little tough to come up to speed on that fast, as some of the bugs you'll suffer in these edge cases will be very hard to debug without background which you will not have. If it is a "coming up to speed enough to ask intelligent questions as to why the build is failing", that's probably doable, as long as they know your background. If its being fully functional in a complex build/library environment, no way that will happen in that time frame, especially without the ability to sit down next to someone who gets it (which is the problem with doing their teleworking arrangement for you). On fixing that last issue, you could invest in Logmein.com or some CoPilot.com time to get tutelage from their more experienced developers on the arcane warnings and errors that come out of building the libraries. If you're going to try, I suggest you do the following: 1. Build a toy program/text processing utility on the command line 2. Try building a graphical utility using a prebuilt library of their graphic toolkit 3. Then try to work on the actual code base. --Michael And on whether you do it or not for free....I'd say python is the language that has the most accessible libraries I've ever seen. I literally can use any C, C++ or Fortran library with it in a couple minutes often, a couple hours if more complex. If nothing else you're going to pick up a very versatile tool, even if you don't get the gig. On Tue, Mar 18, 2008 at 4:07 PM, TFIA Consulting, Inc. wrote: > > > Hi. I am doing some work for a company that uses Python for their > application. > I have never used Python before, but I have programmed for over 35 years, > maybe 12 languages including 4 assembly level. > Your site says it should take just a "few days" to learn Python, so I told > these folks to give me 12 days in case I was stupider than average. > > My question is : Who is right? A 'few days', or going thru the docs below? > (which seems a bit more complex than that). > > Is this REALLY a "few days" task to learn? Would you agree to guarantee > coming up to speed in a few days @ no charge? > > Thank you for your advice, > ...Bill Smith > > Here is their documentation on compiling : > > ============================================================================== > Building Miro Windows ? > This page documents how to build Miro for Windows. We need more brave souls > willing to help us conquer this platform. > > Getting started ? > The supported Windows port of Miro is based on Mozilla XUL and found in the > source:trunk/tv/platform/windows-xul directory. There's an abandoned > "native" Windows port in source:trunk/tv/platform/windows don't mess with > it. > > You may be able to find more information here: > source:trunk/tv/platform/windows-xul/setup.py > source:trunk/tv/platform/windows-xul/README > > Question : Why don't you use XUL for all platforms? ? > Every couple of weeks someone flames us for not using XUL on all platforms. > > The XUL port of Miro is by far the most complicated and ugliest. XUL doesn't > really do what we want to do well. It has a lot of "security" restrictions > that we have to work around. The OS X Cocoa port is simpler, and the GTK/X11 > port is by far the simplest. > > Since we have to embed all sorts of platform specific libraries, XUL's cross > platformness doesn't make porting to other platforms easier. For example, > embedding OS X's quicktime in XUL would be a very large project. > > From a UI perspective, we want a native look and feel on all of our > platforms, except Windows where we think the platform look sucks. A real > native look and feel would require lots of tweaking for GTK, and isn't even > possible on XUL/OS X. > > Compilers ? > Visual Studio 2003 ? > Miro makes heavy use of Python extensions. Python extensions compiled with a > different compiler than Python itself are not guaranteed to work. Since the > official Python distribution for Windows is compiled with Microsoft Visual > C++ 7.1 (AKA Visual C++ .NET 2003), we only support the MSVC++ 7.1 family of > compilers for official builds. Unfortunately, Microsoft has discontinued the > no-cost "Visual C++ Toolkit 2003" compiler. > > Miro also depends on Mozilla XULRunner, PyXPCOM, VLC, and other sundries. > However, building Mozilla on Win32 platforms, much less applying our > patches, is such a time consuming process that we include pre-built binaries > for these in source:trunk/dtv-binary-kit. > Unless you need to debug issues with Miro's use of Mozilla code, it's > recommended that you use these binaries. Currently, the binaries included > are built using Mozilla 1.8 branch. > > MinGW (GCC) ? > We've putting together instructions on building Miro with free tools. The > instructions for doing this are here BuildingMiroWithMinGW. We are working > hard on improving these instructions. Email us if you're interested in > taking this on. If you're interested in helping but are getting stuck on > compiler issues, email us, and we'll do our best to help you. Eventually, > we'll merge these instructions into this document. > > Getting dependencies and setting up the build environment ? > As of version 0.9.6, we will be using Python 2.5. The binary kit now > contains XULRunner 1.8.0.4 linked against Python 2.5. > > You'll need: > > MSVC++ 7.1 (2003) compiler > Subversion > Either install the one from http://tortoisesvn.tigris.org/ or the one that > comes with cygwin. > > The Windows binary release of Python2.5 from python.org > I use http://www.python.org/ftp/python/2.5/python-2.5.msi > > PyRex? - http://www.cosc.canterbury.ac.nz/~greg/python/Pyrex/ > I use > http://www.cosc.canterbury.ac.nz/greg.ewing/python/Pyrex/oldtar/Pyrex-0.9.5.1.1.tar.gz > which when untarred is Pyrex-0.9.5.1a > > Untar the tarball and run python setup.py install. > > Psyco - http://psyco.sourceforge.net/ > I run svn co -r42037 http://codespeak.net/svn/psyco/dist/ > > Be sure to run python setup.py install. > > Py2exe - http://www.py2exe.org > I use > (http://internap.dl.sourceforge.net/sourceforge/py2exe/py2exe-0.6.6.win32-py2.5.exe > > Null Soft Installer - http://nsis.sf.net/Download > The latest sqlite3.dll file from SQLite > I use http://www.sqlite.org/sqlitedll-3_5_2.zip > > Copy the sqlite3.dll file from the SQLite website over the one in your > python directory (Usually C:\Python25\DLLs). If you forget to do this, on > certain platforms your build will have this issue. > http://mail.python.org/pipermail/python-list/2007-June/444281.html > > The Windows SDK 6.1 (for Vista headers) > http://www.microsoft.com/downloads/details.aspx?FamilyId=E6E1C3DF-A74F-4207-8586-711EBE331CDC&displaylang=en > Note: Make sure you use the versions of psyco and pyrex that are > recommended. If you don't, you may get weird behavior. If you find other > combinations that work, please let us know by listing them on this wiki or > sending the working combination to the develop mailing list. > > Install all the requirements. After you do that, set up your PATH, LIB, and > INCLUDE environment variables so that Python distutils can compile modules. > It's important to pay attention to the order of the paths in these > variables. Generally speaking, Windows compilers and tools should be first, > followed by third party tools with Cygwin (if you use it) going last. > > You'll need to edit your vsvars32.bat to use the updated SDK's LIB and > INCLUDE environment variables. I use the following lines. You may need to > modify them to reflect the paths on your system. > > @set INCLUDE=%MSVCDir%\ATLMFC\INCLUDE;%MSVCDir%\INCLUDE;C:\Program > Files\Microsoft Visual Studio 9.0\VC\Include;C:\Program Files\Microsoft > SDKs\Windows\v6.1\Include;C:\Program Files\Microsoft > SDKs\Windows\v6.1\Include\gl > > @set LIB=%MSVCDir%\ATLMFC\LIB;%MSVCDir%\LIB;C:\Program Files\Microsoft > Visual Studio 9.0\VC\Lib;C:\Program Files\Microsoft SDKs\Windows\v6.1\Lib > It's good to copy this file into your Miro directory and then add your > Python and subversion directories after the @goto end or at the end of the > file like this: > > @set PATH=%PATH%;C:\Program Files\subversion\bin;C:\Python25 > Alternatively, you can add c:\Python25\ to the Path environment variable in > Control Panel -> System -> Advanced tab -> Environment Variables. > > Execute vcvars32.bat in the DOS command prompt to pick up the build > environment variables. > > Getting the prebuilt dependency kit ? > As mentioned above, these instructions assume that you're using our prebuilt > dependency kit. Simply check it out as dtv-binary-kit in the same directory > where you checked out DTV and the DTV build script will find the dependency > kit automatically. If you want to get the DTV source at the same time, the > easiest way is to check out the entire Miro tree, including Miro, the > dependency kit, and Broadcast Machine: > > svn co https://svn.participatoryculture.org/svn/dtv/trunk miro > In case your version of svn isn't validating certificates for some reason, > our https certificate's fingerprint is > 53:db:fa:7d:7f:41:33:cb:c3:c3:05:2b:16:0e:a8:37:60:13:07:30 > > Note: As of July 28 2006, the dtv-binary and tv repositories account for 146 > MB of the total 186 MB repository. > > Make sure that your path doesn't have any spaces in it. There are bugs in > python's spawnl that make setup not work if you're in a directory with a > space in it. > > That will create a directory named 'miro' and create tv and dtv-binary-kit > (and bmachine for Broadcast Machine) as subdirectories of it. > > On the other hand, if you don't want to use the dependency kit, edit > platform\windows-xul\setup.py and change the paths in the top section > according to the instructions. You will still need to check out > dtv-binary-kit (or browse it online), because it contains patches that will > need to be applied to some of the dependencies before building. > > Building and Running ? > To build Miro as quickly as possible and run it out of the development tree, > do: This is broken as of 06-06-06. Use bdist_xul_dumb instead for now. > > python setup.py runxul > Video playback won't work. VLC doesn't know how to find its plugin directory > when DTV is run this way. > > To build a self-contained, redistributable folder with an actual Miro.exe, > do: > > python setup.py bdist_xul_dumb > This creates a directory dist. > > To build a single-file installer, suitable for distribution to end users: > > python setup.py bdist_xul > This will create something like dist/Miro-.exe. > > See TestingDtv for the options and environment variables supported, and > information on the debugging logfile. There is no way to pass command-line > options in runxul mode, other than to edit setup.py. > > Recompiling Mozilla ? > You shouldn't have to do this unless you're debugging Mozilla specific > issues. The first time, set aside a few days to figure out how to do it. > > Compile Mozilla according to the instructions found here using Mozilla 1.9. > > BuildingXULRunner has Miro specific instructions > > Recompiling Boost ? > You shouldn't have to do this unless you're debugging Boost specific issues. > > Download the latest Boost source and the Boost jam utility > http://superb-east.dl.sourceforge.net/sourceforge/boost/boost_1_33_1.tar.bz2 > http://superb-west.dl.sourceforge.net/sourceforge/boost/boost-jam-3.1.13-1-ntx86.zip > Extract bjam.exe into c:\mozilla-build\msys\local\bin\ > Open a Mozilla build environment terminal (See BuildingXULRunner) > Run tar xfvj boost_1_33_1.tar.bz2 > cd boost_1_33_1 > bjam -sTOOLS=vc-7_1 --with-python > --with-python-root=C:\\mozilla-build\\python25 --with-python-version=2.5 > stage > Troubleshooting ? > Pyrex and psyco ? > You need to have the exact versions we've listed above for psyco and Pyrex. > > !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Michael Langford Phone: 404-386-0495 Consulting: http://www.RowdyLabs.com From eric at ericwalstad.com Tue Mar 18 22:35:46 2008 From: eric at ericwalstad.com (Eric Walstad) Date: Tue, 18 Mar 2008 14:35:46 -0700 Subject: [Tutor] c++::return In-Reply-To: <674d5ce60803181410x508ba4bdv539682c8dce06c75@mail.gmail.com> References: <674d5ce60803181410x508ba4bdv539682c8dce06c75@mail.gmail.com> Message-ID: <47E035B2.2060303@ericwalstad.com> elis aeris wrote: > what do I do if i want the program/function to end? > > > in c++ of > > int main(){} > > I do a return 0; What have you tried in Python? How did it work and what didn't work the way you expected? What Python documentation or tutorials have you read? Maybe helpful: http://www.google.com/search?q=python+function+return http://www.google.com/search?hl=en&q=eric+smart+question From alan.gauld at btinternet.com Tue Mar 18 22:39:47 2008 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Tue, 18 Mar 2008 21:39:47 +0000 (GMT) Subject: [Tutor] Need help with structure unpacking module Message-ID: <896119.80835.qm@web86702.mail.ird.yahoo.com> CCing the list. Please use Reply All when responding. > I am still little confused since I was under the impression, > that if a c program was able to write this binary code, > then if we know how c "packed" the data/string then > we able to decode/unpack it using python. Thats correct but you have to specify the correct decode string to match what C wrote. > Does python not know how c packs the strings? Python knows nothing about what C does its up to the programmer to tell Python how to interpret binary data. So its the programmer who must know how C stores binary strings. > Please help me understand as to why unpack works > for numbers but not for strings. It does work for strings as both Luke and I demonstrated. But you have to tell Python how long the string is. You only specified 's' so Python looked for a single byte string. You needed to specify '4s' for a 4 byte string. Let me put it this way: When you call decode you supply a pattern which struct uses to determine how many bytes it needs and how to assign those bytes to Pyhon data types Python and struct have no idea how those bytes got there they simply take the sequence of bytes and try to interpret them in the way indicated by the format string. Thus if you write an integer into a binary file you will write 4 bytes. Knowing that you can tell struct to decode that as an integer. But you could equally well tell struct to decode those same bytes as 4 characters and struct will do so, because thats what you asked for. The 4 characters will be the ASCII characters with the values of the 4 bytes making up the original number. So the onus is on you, the programmer, to know what the correct decode pattern is for each sequence of bytes read. You can find out what that pattern is and how many bytes it equates to by using things like len(), ord(), hex() etc Youcan see an example of that in my File Handling topic in my tutorial. Look at the section on struct. HTH, Alan G. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080318/813cea41/attachment.htm From hunter92383 at gmail.com Tue Mar 18 22:40:05 2008 From: hunter92383 at gmail.com (elis aeris) Date: Tue, 18 Mar 2008 14:40:05 -0700 Subject: [Tutor] c++::return In-Reply-To: <674d5ce60803181439g66ab2364hd9bf04ac34ca66ea@mail.gmail.com> References: <674d5ce60803181410x508ba4bdv539682c8dce06c75@mail.gmail.com> <47E035B2.2060303@ericwalstad.com> <674d5ce60803181439g66ab2364hd9bf04ac34ca66ea@mail.gmail.com> Message-ID: <674d5ce60803181440o328a1a09iad31875faea50f17@mail.gmail.com> and also, I didn't need to break function is that program, to which i am amazed of, now come to think of it. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080318/c3cba3a8/attachment.htm From alan.gauld at btinternet.com Tue Mar 18 23:03:06 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 18 Mar 2008 22:03:06 -0000 Subject: [Tutor] Python learning curve References: <000801c88933$bd552370$0201a8c0@bill1eb684d52d> Message-ID: "TFIA Consulting, Inc." wrote > Your site says it should take just a "few days" to learn Python, Thats true if you are talking about the core language and a few of the most common libraries - sys, re, os, and maybe 1 or 2 more. But thats not iincluding the hundred or so other more specialised libraries, the database and web programming frameworks, a GUI toolkit etc etc. So after a few days you could write a basic Python program. You could probably also tackle a project using one specialised library such as the database API or maybe the CSV module or the socket module. > so I told these folks to give me 12 days in case I > was stupider than average. Thats probably enough to master the core and a chosen selection of modules needed for your project. But... > Here is their documentation on compiling : Pythopn is not naturally a compiled language so immediately you are into non-standard tools and libraries. You ould reasonably charge for any of these: > Building Miro Windows ? This seems to be the more project specific bit. > The supported Windows port of Miro is based on > Mozilla XUL Again non standard and worse, not even a commonly used library. Bybtheir own admition its not a standard Windows GUI solution because they don't like the windows look n feel - interestingly they don't seem to care that their Windows users probably do! Whatever happened to customer choice? > The XUL port of Miro is by far the most complicated and ugliest. So you can't be expected to learn it for free! > The OS X Cocoa port is simpler, and the GTK/X11 port > is by far the simplest. So two new frameworks on top of the XUL. I'd allow at least a week for any GUI framework (unless you already know the underlying framework - eg Cocoa) And its defintely not core Python. > embedding OS X's quicktime in XUL would be a very large project. So you need QT as well as GUI Cocoa. Thats another fairly big chunk of learning if you don;t already know it. And the Python wrapper on top of that. Again not standard Python and fairly advanced Cocoa. > Miro makes heavy use of Python extensions. The "few days" for Python definitely doesn't include building Python extensions. But this is sometjing that the extra for 12 days might allow to be included. So you might consider giving this for free. MSVC++ 7.1 (2003) compiler Subversion PyRex? Psyco - http://psyco.sourceforge.net/ Py2exe - http://www.py2exe.org Null Soft Installer - http://nsis.sf.net/Download The latest sqlite3.dll file from SQLite The Windows SDK 6.1 (for Vista headers) How much of the above you charge for is up to you. Arguably SVN and MSVC++ and the WinSDK could be expected knowledge from a contractor, but all the rest are definitely beyond the basic language learning for Python. Looks like you need to do some negotiating! -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Tue Mar 18 23:06:19 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 18 Mar 2008 22:06:19 -0000 Subject: [Tutor] xrange References: <674d5ce60803181404i51980495ibbbc0e496041eaaf@mail.gmail.com> Message-ID: "elis aeris" wrote > for x in xrange (20, 0): > print x > > this doesn't work because it goes from a big number to a small > number, which > does nothing > but what if I need the for loop to go from a big number to a small > number? Add a 3rd step-value argument to range. (You don't need the xrange on modern versions of Python BTW) If you make the step negative it will count down: >>> range(20,0,-4) [20, 16, 12, 8, 4] >>> HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From hunter92383 at gmail.com Tue Mar 18 23:08:50 2008 From: hunter92383 at gmail.com (elis aeris) Date: Tue, 18 Mar 2008 15:08:50 -0700 Subject: [Tutor] xrange In-Reply-To: References: <674d5ce60803181404i51980495ibbbc0e496041eaaf@mail.gmail.com> Message-ID: <674d5ce60803181508n3bb8ed98i4457dc5ef807f0f9@mail.gmail.com> ok. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080318/f7ffb83a/attachment.htm From alan.gauld at btinternet.com Tue Mar 18 23:09:12 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 18 Mar 2008 22:09:12 -0000 Subject: [Tutor] c++::return References: <674d5ce60803181410x508ba4bdv539682c8dce06c75@mail.gmail.com> Message-ID: "elis aeris" wrote > what do I do if i want the program/function to end? > > in c++ of > > int main(){} > > I do a return 0; Actually you don;t. In your e4xample yuou just have empty braces and that will end just fine! Similarly in Python it will just silently drop off the end of the code. However if you want to return a value to the OS other than 0 you can use the exit function from the sys module. (Or raise a SystemExit exception with an argument of the required error code) sys.exit() is explained in the Simple Sequences topic of my tutorial. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Tue Mar 18 23:21:21 2008 From: kent37 at tds.net (Kent Johnson) Date: Tue, 18 Mar 2008 18:21:21 -0400 Subject: [Tutor] xrange In-Reply-To: References: <674d5ce60803181404i51980495ibbbc0e496041eaaf@mail.gmail.com> Message-ID: <47E04061.4070205@tds.net> Alan Gauld wrote: > Add a 3rd step-value argument to range. (You don't need the xrange > on modern versions of Python BTW) Only if by 'modern' you mean Python 3; on Python 2.x there is a difference between range() and xrange(). Though for a list of 20 ints I don't think it matters much. Kent From hunter92383 at gmail.com Tue Mar 18 23:25:07 2008 From: hunter92383 at gmail.com (elis aeris) Date: Tue, 18 Mar 2008 15:25:07 -0700 Subject: [Tutor] xrange In-Reply-To: <47E04061.4070205@tds.net> References: <674d5ce60803181404i51980495ibbbc0e496041eaaf@mail.gmail.com> <47E04061.4070205@tds.net> Message-ID: <674d5ce60803181525w792c22e0m6cc0eb5d58d14808@mail.gmail.com> ok i need about 500~1000 is that ok? my pet practice works works fine with it,but what should I watch out for? sorry for double reply kent, forgot to reply all. On Tue, Mar 18, 2008 at 3:21 PM, Kent Johnson wrote: > Alan Gauld wrote: > > > Add a 3rd step-value argument to range. (You don't need the xrange > > on modern versions of Python BTW) > > Only if by 'modern' you mean Python 3; on Python 2.x there is a > difference between range() and xrange(). Though for a list of 20 ints I > don't think it matters much. > > Kent > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080318/d34f895c/attachment.htm From eric at ericwalstad.com Tue Mar 18 23:45:28 2008 From: eric at ericwalstad.com (Eric Walstad) Date: Tue, 18 Mar 2008 15:45:28 -0700 Subject: [Tutor] c++::return In-Reply-To: <674d5ce60803181439g66ab2364hd9bf04ac34ca66ea@mail.gmail.com> References: <674d5ce60803181410x508ba4bdv539682c8dce06c75@mail.gmail.com> <47E035B2.2060303@ericwalstad.com> <674d5ce60803181439g66ab2364hd9bf04ac34ca66ea@mail.gmail.com> Message-ID: <47E04608.70306@ericwalstad.com> elis aeris wrote: > I seriously have done my homework on writing in python I wonder if I am misunderstanding your question. This is a simple question about how functions work in Python, right? Something that most every beginning tutorial covers? You wouldn't be asking here if you had done your homework. > below is a 29 kb > .py file that I wrote to do something, although you may not care what it > does Wow, that's one long function! It looks like either you don't understand what you wrote: consective_zero = 0 ## I don't know what this is or maybe someone else has commented your code? > please just tell me in plain words: how do I break function? And seriously, you'll likely get better answers, faster, when you ask better questions. It's faster, more efficient and more rewarding. A smart question also shows us that you will value the time we spend on the answer. Taking the time to formulate a smart question will often help you answer the question on your own. Actually you did find the answer on your own (assuming I understand the question and that you wrote the function yourself): 'return'. http://docs.python.org/tut/node6.html From hunter92383 at gmail.com Tue Mar 18 23:47:56 2008 From: hunter92383 at gmail.com (elis aeris) Date: Tue, 18 Mar 2008 15:47:56 -0700 Subject: [Tutor] c++::return In-Reply-To: <47E04608.70306@ericwalstad.com> References: <674d5ce60803181410x508ba4bdv539682c8dce06c75@mail.gmail.com> <47E035B2.2060303@ericwalstad.com> <674d5ce60803181439g66ab2364hd9bf04ac34ca66ea@mail.gmail.com> <47E04608.70306@ericwalstad.com> Message-ID: <674d5ce60803181547v6793bf47p274a3f51fea63a50@mail.gmail.com> i was reading it the second time 6months after and in fact i am working on version 3 of it with update to functionality. (and yes, it is MY code) how do I return a function? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080318/5612ac41/attachment.htm From simozack at yahoo.it Mon Mar 17 17:15:48 2008 From: simozack at yahoo.it (Simone) Date: Mon, 17 Mar 2008 17:15:48 +0100 Subject: [Tutor] my first project: a multiplication trainer In-Reply-To: <47DE8AE8.7050708@yahoo.de> References: <47DB53DA.3070908@yahoo.de> <200803150517.25013.cfuller084@thinkingplanet.net> <47DD1A9D.1040306@yahoo.de> <200803161100.38822.cfuller084@thinkingplanet.net> <47DE8AE8.7050708@yahoo.de> Message-ID: <47DE9934.4070301@yahoo.it> Guba ha scritto: > I was unable to find information on tuple(). (The Python help function > was rather conservative in its output, Google not helpful). > What exactly is the use of tuple(q) here, and why does not a simple q > instead of tuple(q) do? The latter would have been my intuitive > expectation... The print statement "%dx%d = " needs a tuple of arguments. The tuple() command, that converts a list or a set of values in a tuple of values, prevent that error (for example, if the list of values is a list o of list, the print statemnte returns the error "TypeError: in argument reguired"). For example: >>>a = [[1, 2], [3, 4]] # a is a list of lists with 2 values >>>type(a[0]) >>>type(tuple(a[0])) Or: >>>a = [(1, 2), (3, 4)] # a is a list of tuples with 2 values >>>type(a[0]) > The other thing I have on my mind is this: how could I have the program > ask the math questions not horizontally but vertically? An example: > > 4 > x7 > = Simply insert a \n in the print statement, like this: print "%d\nx%d\n = " Simone Chiacchiera con i tuoi amici in tempo reale! http://it.yahoo.com/mail_it/foot/*http://it.messenger.yahoo.com From mb_shkup at yahoo.com Tue Mar 18 23:48:08 2008 From: mb_shkup at yahoo.com (Mensur Bakija) Date: Tue, 18 Mar 2008 15:48:08 -0700 (PDT) Subject: [Tutor] Welcome to the "Tutor" mailing list (Digest mode) In-Reply-To: Message-ID: <308665.41421.qm@web45502.mail.sp1.yahoo.com> tutor-request at python.org wrote: Welcome to the Tutor at python.org mailing list! This list is for folks who want to ask (and/or answer) questions from folks who wish to learn how to program with Python. Feel free to ask even the most basic of questions -- that's what the list is for! For best results when asking a question on this list: - Try to write some code to solve your problem - Show the code you have written - Describe what the code does and what you want it to do - If the code generates an error, copy and paste the entire error message, including the traceback, into your email. When replying to a posting: - Use Reply All to reply to the entire list - Don't top post - put your reply after the text to which you are replying For all posts: - Format your email as plain text, not HTML To post to this list, send your email to: tutor at python.org General information about the mailing list is at: http://mail.python.org/mailman/listinfo/tutor If you ever want to unsubscribe or change your options (eg, switch to or from digest mode, change your password, etc.), visit your subscription page at: http://mail.python.org/mailman/options/tutor/mb_shkup%40yahoo.com You can also make such adjustments via email by sending a message to: Tutor-request at python.org with the word `help' in the subject or body (don't include the quotes), and you will get back a message with instructions. You must know your password to change your options (including changing the password, itself) or to unsubscribe. It is: Vizija1 Normally, Mailman will remind you of your python.org mailing list passwords once every month, although you can disable this if you prefer. This reminder will also include instructions on how to unsubscribe or change your account options. There is also a button on your options page that will email your current password to you. --------------------------------- Looking for last minute shopping deals? Find them fast with Yahoo! Search. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080318/7ec0d380/attachment.htm From technorapture at gmail.com Tue Mar 18 23:55:01 2008 From: technorapture at gmail.com (Shrutarshi Basu) Date: Tue, 18 Mar 2008 18:55:01 -0400 Subject: [Tutor] xrange In-Reply-To: <674d5ce60803181525w792c22e0m6cc0eb5d58d14808@mail.gmail.com> References: <674d5ce60803181404i51980495ibbbc0e496041eaaf@mail.gmail.com> <47E04061.4070205@tds.net> <674d5ce60803181525w792c22e0m6cc0eb5d58d14808@mail.gmail.com> Message-ID: <376fbdcf0803181555v732e2a7eh704b8c991b024bfc@mail.gmail.com> I'm not entirely sure about this, but I think for range(), the entire range of numbers is generated at one go, which could cause a slow-down. But xrange() generates the list of numbers one at a time. For a thousand, there shouldn't be much of a difference, but if you need a million or so go with xrange() Basu From allen.fowler at yahoo.com Wed Mar 19 01:24:36 2008 From: allen.fowler at yahoo.com (Allen Fowler) Date: Tue, 18 Mar 2008 17:24:36 -0700 (PDT) Subject: [Tutor] Calling super classs __init__? Message-ID: <931023.43222.qm@web45611.mail.sp1.yahoo.com> Hello, Now, perhaps this not the best way write code, but I have a few questions regrading calling the super classes constructor: I have a super class that accepts many arguments to it's constructor, and a subclass that should define one additional argument. What's the most "pythonic" way to make this work? class MySuperClass(object): def __init__(self, opt_1, opt_2, opt_3, opt_n): # stuff done here pass class MySubClass(MySuperClass): def __init__(self, just_a_sub_option): # what about other args? **args? # do stuff with "just_a_sub_option" MySuperClass.__init__() # Should this be first? What args to use? **args? pass Basically, I'd like to avoid maintaining a verbose list of arguments in the subclass. Thanks, :) ____________________________________________________________________________________ Be a better friend, newshound, and know-it-all with Yahoo! Mobile. Try it now. http://mobile.yahoo.com/;_ylt=Ahu06i62sR8HDtDypao8Wcj9tAcJ From allen.fowler at yahoo.com Wed Mar 19 01:36:03 2008 From: allen.fowler at yahoo.com (Allen Fowler) Date: Tue, 18 Mar 2008 17:36:03 -0700 (PDT) Subject: [Tutor] kwargs to object proporties? Message-ID: <425780.43453.qm@web45602.mail.sp1.yahoo.com> Hello, What's the best way convert keyword arguments to object properties? Basically, I have a defined list of valid object properties that I'd like to optionally specify in the call to the constructor. I've got ideas about using __getattr__ but I'm not sure if that's the right way. Plus, that kind of makes it hard to use tab completion of objects in iPython. Thanks, :) ____________________________________________________________________________________ Never miss a thing. Make Yahoo your home page. http://www.yahoo.com/r/hs From john at fouhy.net Wed Mar 19 01:37:53 2008 From: john at fouhy.net (John Fouhy) Date: Wed, 19 Mar 2008 13:37:53 +1300 Subject: [Tutor] Calling super classs __init__? In-Reply-To: <931023.43222.qm@web45611.mail.sp1.yahoo.com> References: <931023.43222.qm@web45611.mail.sp1.yahoo.com> Message-ID: <5e58f2e40803181737u5101ab5bw861e3e8d2100e014@mail.gmail.com> On 19/03/2008, Allen Fowler wrote: > I have a super class that accepts many arguments to it's constructor, and a subclass that should define one additional argument. > > What's the most "pythonic" way to make this work? class BaseClass(object): def __init__(self, x, y, z, foo='foo'): # whatever # etc class SubClass(BaseClass): def __init__(self, t, *args, **kw): BaseClass.__init__(self, *args, **kw) # do something with t This does mean that the special sub class argument has to come before the base class arguments when you create instances. Whether you call BaseClass.__init__ early or late in the subclass init method could depend on what your classes are doing. Remember, in Python, __init__ only initializes objects, it doesn't create them. It's just another bit of code that you can call whenever you want. -- John. From john at fouhy.net Wed Mar 19 01:57:12 2008 From: john at fouhy.net (John Fouhy) Date: Wed, 19 Mar 2008 13:57:12 +1300 Subject: [Tutor] kwargs to object proporties? In-Reply-To: <425780.43453.qm@web45602.mail.sp1.yahoo.com> References: <425780.43453.qm@web45602.mail.sp1.yahoo.com> Message-ID: <5e58f2e40803181757x75e76af0x28ffac8670a24971@mail.gmail.com> On 19/03/2008, Allen Fowler wrote: > Hello, > > What's the best way convert keyword arguments to object properties? You can mess around with self.__dict__.update(kwargs) or update(locals()). I'm not sure exactly what you want to do.. See this recipe: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/286185 It has some suggestions and discussion that you might find helpful. -- John. From alan.gauld at btinternet.com Wed Mar 19 01:59:48 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 19 Mar 2008 00:59:48 -0000 Subject: [Tutor] xrange References: <674d5ce60803181404i51980495ibbbc0e496041eaaf@mail.gmail.com> <47E04061.4070205@tds.net> Message-ID: "Kent Johnson" wrote >> Add a 3rd step-value argument to range. (You don't need the xrange >> on modern versions of Python BTW) > > Only if by 'modern' you mean Python 3; on Python 2.x there is a > difference between range() and xrange(). Though for a list of 20 > ints I > don't think it matters much. Ah! I thought the unification happened when generators were introduced I didn't realised it was put back to v3. Thanks for the pointer Kent. Alan G. From alan.gauld at btinternet.com Wed Mar 19 02:11:59 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 19 Mar 2008 01:11:59 -0000 Subject: [Tutor] c++::return References: <674d5ce60803181410x508ba4bdv539682c8dce06c75@mail.gmail.com><47E035B2.2060303@ericwalstad.com><674d5ce60803181439g66ab2364hd9bf04ac34ca66ea@mail.gmail.com><47E04608.70306@ericwalstad.com> <674d5ce60803181547v6793bf47p274a3f51fea63a50@mail.gmail.com> Message-ID: "elis aeris" wrote > how do I return a function? > Do you realise that this is an entirely different question to the one you asked originally, namely: >> what do I do if i want the program/function to end? >> >> in c++ of >>int main(){} >>I do a return 0; One is asking about *ending* the program(or function), the other about returning. Those are two different concepts. In particular returning implies that the program does not end but goes on to use the returnedvalue in some way. Assuming that it is returning you are interested in then all the tutorials that discuss Python functions (including mine) will tell you how to return a value from a function. You use the return statement exactly like in C++. Where did you look if you couldn't find it? Even searching "return" on the Python web site gets me this as the first link: 6.7 The return statement When return passes control out of a try statement with a finally clause, that finally clause is executed before really leaving the function. ... docs.python.org/ref/return.html - 7k - Cached - Similar pages And visiting it it tells me: -----------------------return_stmt ::= "return" [expression_list] return may only occur syntactically nested in a function definition, not within a nested class definition. If an expression list is present, it is evaluated, else None is substituted. return leaves the current function call with the expression list (or None) as return value. --------------------------------- Now, its not that we mind answering questions, but if you claim to have looked for an answer and then ask a somewhat vaguely worded question we will assume you are looking for something deeper. Its easier for all of us if you are as specific as possible in your questions. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Wed Mar 19 03:33:57 2008 From: kent37 at tds.net (Kent Johnson) Date: Tue, 18 Mar 2008 22:33:57 -0400 Subject: [Tutor] Calling super classs __init__? In-Reply-To: <931023.43222.qm@web45611.mail.sp1.yahoo.com> References: <931023.43222.qm@web45611.mail.sp1.yahoo.com> Message-ID: <47E07B95.5010607@tds.net> Allen Fowler wrote: > What's the most "pythonic" way to make this work? > > class MySuperClass(object): > > def __init__(self, opt_1, opt_2, opt_3, opt_n): > # stuff done here > pass > > > class MySubClass(MySuperClass): > > def __init__(self, just_a_sub_option): # what about other args? **args? I think I would go ahead and list the superclass parameters and put the new one at the end: def __init__(self, opt_1, opt_2, opt_3, opt_n, just_a_sub_option): > MySuperClass.__init__() # Should this be first? What args to use? **args? MySuperClass.__init__(self, opt_1, opt_2, opt_3, opt_n) John's method will also work but I prefer to add the new parameter at the end of the argument list. Kent From hunter92383 at gmail.com Wed Mar 19 04:41:45 2008 From: hunter92383 at gmail.com (elis aeris) Date: Tue, 18 Mar 2008 20:41:45 -0700 Subject: [Tutor] xrange In-Reply-To: <376fbdcf0803181555v732e2a7eh704b8c991b024bfc@mail.gmail.com> References: <674d5ce60803181404i51980495ibbbc0e496041eaaf@mail.gmail.com> <47E04061.4070205@tds.net> <674d5ce60803181525w792c22e0m6cc0eb5d58d14808@mail.gmail.com> <376fbdcf0803181555v732e2a7eh704b8c991b024bfc@mail.gmail.com> Message-ID: <674d5ce60803182041g452a57acp73561385c8c3da08@mail.gmail.com> Oh i am good with range then, because it's not a real time program. On Tue, Mar 18, 2008 at 3:55 PM, Shrutarshi Basu wrote: > I'm not entirely sure about this, but I think for range(), the entire > range of numbers is generated at one go, which could cause a > slow-down. But xrange() generates the list of numbers one at a time. > For a thousand, there shouldn't be much of a difference, but if you > need a million or so go with xrange() > Basu > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080318/1ed27453/attachment.htm From luciano at ramalho.org Wed Mar 19 04:45:33 2008 From: luciano at ramalho.org (Luciano Ramalho) Date: Wed, 19 Mar 2008 00:45:33 -0300 Subject: [Tutor] Calling super classs __init__? In-Reply-To: <5e58f2e40803181737u5101ab5bw861e3e8d2100e014@mail.gmail.com> References: <931023.43222.qm@web45611.mail.sp1.yahoo.com> <5e58f2e40803181737u5101ab5bw861e3e8d2100e014@mail.gmail.com> Message-ID: <4331ad810803182045v237d226by23361bf4587de965@mail.gmail.com> Nowadays the best practice for invoking a method from all superclasses (yes, multiple inheritance) is this: class SubClass(BaseClass): def __init__(self, t, *args, **kw): super(SubClass, self).__init__(*args, **kw) # do something with t That way you let Python decide which superclasses your SubClass has, instead of hard-coding it in several places. Cheers, Luciano On Tue, Mar 18, 2008 at 9:37 PM, John Fouhy wrote: > On 19/03/2008, Allen Fowler wrote: > > I have a super class that accepts many arguments to it's constructor, and a subclass that should define one additional argument. > > > > What's the most "pythonic" way to make this work? > > class BaseClass(object): > def __init__(self, x, y, z, foo='foo'): # whatever > # etc > > class SubClass(BaseClass): > def __init__(self, t, *args, **kw): > BaseClass.__init__(self, *args, **kw) > # do something with t > > This does mean that the special sub class argument has to come before > the base class arguments when you create instances. > > Whether you call BaseClass.__init__ early or late in the subclass init > method could depend on what your classes are doing. Remember, in > Python, __init__ only initializes objects, it doesn't create them. > It's just another bit of code that you can call whenever you want. > > -- > John. > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From hunter92383 at gmail.com Wed Mar 19 04:45:40 2008 From: hunter92383 at gmail.com (elis aeris) Date: Tue, 18 Mar 2008 20:45:40 -0700 Subject: [Tutor] c++::return In-Reply-To: References: <674d5ce60803181410x508ba4bdv539682c8dce06c75@mail.gmail.com> <47E035B2.2060303@ericwalstad.com> <674d5ce60803181439g66ab2364hd9bf04ac34ca66ea@mail.gmail.com> <47E04608.70306@ericwalstad.com> <674d5ce60803181547v6793bf47p274a3f51fea63a50@mail.gmail.com> Message-ID: <674d5ce60803182045y55fb8713uf8d144400786cc81@mail.gmail.com> I actually said "ending" to avoid problems with different terminology between different languages - but i guess a return is still a return in python. i did this search http://www.google.ca/search?hl=en&q=python+tutorial+return&btnG=Google+Search&meta= and it didn't return any particularly obvious answer. The funny thing is, i wrote that program last june and managed to not know/use a single return :) On Tue, Mar 18, 2008 at 6:11 PM, Alan Gauld wrote: > "elis aeris" wrote > > > how do I return a function? > > > Do you realise that this is an entirely different question > to the one you asked originally, namely: > > >> what do I do if i want the program/function to end? > >> > >> in c++ of > >>int main(){} > >>I do a return 0; > > > One is asking about *ending* the program(or function), the > other about returning. Those are two different concepts. > In particular returning implies that the program does not > end but goes on to use the returnedvalue in some way. > > Assuming that it is returning you are interested in then > all the tutorials that discuss Python functions (including > mine) will tell you how to return a value from a function. > > You use the return statement exactly like in C++. > > Where did you look if you couldn't find it? > > Even searching "return" on the Python web site gets me this as > the first link: > > 6.7 The return statement > When return passes control out of a try statement with a finally > clause, that finally clause is executed before really leaving the > function. ... > docs.python.org/ref/return.html - 7k - Cached - Similar pages > > > And visiting it it tells me: > > -----------------------return_stmt ::= "return" [expression_list] > > > return may only occur syntactically nested in a function definition, > not within a nested class definition. > > If an expression list is present, it is evaluated, else None is > substituted. > > return leaves the current function call with the expression list (or > None) as return value. > --------------------------------- > > Now, its not that we mind answering questions, but if you claim > to have looked for an answer and then ask a somewhat vaguely > worded question we will assume you are looking for something > deeper. Its easier for all of us if you are as specific as possible > in your questions. > > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.freenetpages.co.uk/hp/alan.gauld > > > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080318/95f946a4/attachment.htm From allen.fowler at yahoo.com Wed Mar 19 04:55:55 2008 From: allen.fowler at yahoo.com (Allen Fowler) Date: Tue, 18 Mar 2008 20:55:55 -0700 (PDT) Subject: [Tutor] Calling super classs __init__? Message-ID: <879028.90001.qm@web45615.mail.sp1.yahoo.com> > > class MySubClass(MySuperClass): > > > > def __init__(self, just_a_sub_option): # what about other args? **args? > > I think I would go ahead and list the superclass parameters and put the > new one at the end: > def __init__(self, opt_1, opt_2, opt_3, opt_n, just_a_sub_option): > > > MySuperClass.__init__() # Should this be first? > What args to use? **args? > > MySuperClass.__init__(self, opt_1, opt_2, opt_3, opt_n) > > John's method will also work but I prefer to add the new parameter at > the end of the argument list. (Hmm.. I should have pointed out that I generally use keyword args. ) Right. So, I can certainly call the MySuperClass.__init__() with a long list of kwargs, but that gets annoying quickly when the superclass is also under active development and it's call signature frequently changes. ____________________________________________________________________________________ Never miss a thing. Make Yahoo your home page. http://www.yahoo.com/r/hs From allen.fowler at yahoo.com Wed Mar 19 05:01:25 2008 From: allen.fowler at yahoo.com (Allen Fowler) Date: Tue, 18 Mar 2008 21:01:25 -0700 (PDT) Subject: [Tutor] Calling super classs __init__? Message-ID: <831568.21806.qm@web45611.mail.sp1.yahoo.com> > > What's the most "pythonic" way to make this work? > > class BaseClass(object): > def __init__(self, x, y, z, foo='foo'): # whatever > # etc > > class SubClass(BaseClass): > def __init__(self, t, *args, **kw): > BaseClass.__init__(self, *args, **kw) > # do something with t > > This does mean that the special sub class argument has to come before > the base class arguments when you create instances. > > Whether you call BaseCla Thank you... Excellent idea. I haven't tried it yet, but I suppose **kwarg.pop()'ing and *args manipulation could help ease subclass instantiation call signature limitations. (?) Thanks, :) ____________________________________________________________________________________ Looking for last minute shopping deals? Find them fast with Yahoo! Search. http://tools.search.yahoo.com/newsearch/category.php?category=shopping From brindly at gmail.com Wed Mar 19 08:33:39 2008 From: brindly at gmail.com (brindly sujith) Date: Wed, 19 Mar 2008 13:03:39 +0530 Subject: [Tutor] how to search a directory from a Tkinter program Message-ID: hi i am developing an application in tkinter i want to know whether we have any option to search a directory from tkinter program please answer me thank you -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080319/4bde650e/attachment.htm From rabidpoobear at gmail.com Wed Mar 19 11:03:42 2008 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Wed, 19 Mar 2008 04:03:42 -0600 Subject: [Tutor] c++::return In-Reply-To: <674d5ce60803182045y55fb8713uf8d144400786cc81@mail.gmail.com> References: <674d5ce60803181410x508ba4bdv539682c8dce06c75@mail.gmail.com> <47E035B2.2060303@ericwalstad.com> <674d5ce60803181439g66ab2364hd9bf04ac34ca66ea@mail.gmail.com> <47E04608.70306@ericwalstad.com> <674d5ce60803181547v6793bf47p274a3f51fea63a50@mail.gmail.com> <674d5ce60803182045y55fb8713uf8d144400786cc81@mail.gmail.com> Message-ID: <47E0E4FE.3020508@gmail.com> elis aeris wrote: > I actually said "ending" to avoid problems with different terminology > between different languages - but i guess a return is still a return > in python. Return does not exit a program. A return statement denotes a point in a function when the function will stop executing and the specified value will be returned to the calling function. In C++, a return in your main function will cause the program to stop executing, because there was no calling function to give control back to. > > i did this search > > http://www.google.ca/search?hl=en&q=python+tutorial+return&btnG=Google+Search&meta= > > > and it didn't return any particularly obvious answer. There probably won't be a whole tutorial on a 'return' statement - it's a fundamental part of functions and you should've picked up on it in any tutorial discussing how to define functions. > > The funny thing is, i wrote that program last june and managed to not > know/use a single return :) This is not a good thing. You shouldn't have a function that is this long. The entire point of functions is small snippets of reusable code - having one massive function do everything negates the whole benefit of functions. You may just as well have not put it in a function at all. Where is this code, by the way? I didn't receive a copy of it. From alan.gauld at btinternet.com Wed Mar 19 09:55:47 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 19 Mar 2008 08:55:47 -0000 Subject: [Tutor] how to search a directory from a Tkinter program References: Message-ID: "brindly sujith" wrote > i am developing an application in tkinter > > i want to know whether we have any option to search a directory from > tkinter > program I'm not sure what you mean. You can use the standard Python modules to search a directory, or indeed an entire directory tree using walk(). I demonstrate this in the OS topic of my tutor. OTOH if you mean is there a standard directory dialog so that the user can browse a directory then yes, look in the standard dialogs package as described in the documentation and tutorials. More on those here: http://www.pythonware.com/library/tkinter/introduction/x1164-data-entry.htm And exploring the module with dir() etc will throw up more info. So either way it is pretty straightforward. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From jacklucas at mac.com Wed Mar 19 06:15:07 2008 From: jacklucas at mac.com (Jack Lucas) Date: Tue, 18 Mar 2008 22:15:07 -0700 Subject: [Tutor] Converter Message-ID: <1F9942B2-0118-1000-CB26-0FB002CCB77D-Webmail-10007@mac.com> I am trying to make a converter for Python on my Mac. I know I can find one online, but this is more satisfying. I am not sure exactly where to start. I want to be able to input a "Unit to Convert" a "Unit to Convert to" and an "Amount of Unit to Convert" For example Unit to Convert: centimeters, Unit to Convert to: inches, Amount of Unit to Convert: 2.5. Thus you would get 2.5 Centimeters is equal to 1 inch. Or something like that to display. I have no idea where to start, as I want to be able to input any Unit to Convert (will keep it simple for now, feet, inches etc. and add more later.) and have it display the unit I want to convert to, and not all the other junk. Can anyone help me? Atleast get one setup, as I am sure I can then copy and paste, and make minor changes for the rest. Also if someone would not mind explaining WHY I do certain functions, as I am new to Python. Thanks From kent37 at tds.net Wed Mar 19 11:44:54 2008 From: kent37 at tds.net (Kent Johnson) Date: Wed, 19 Mar 2008 06:44:54 -0400 Subject: [Tutor] Should config file parser be in module's __init__.py In-Reply-To: <376fbdcf0803182122s6eee927axf589e8eee79eecd8@mail.gmail.com> References: <376fbdcf0803172021y653a7477vb64802eea5dd378@mail.gmail.com> <47DF9EDA.6060906@tds.net> <376fbdcf0803182122s6eee927axf589e8eee79eecd8@mail.gmail.com> Message-ID: <47E0EEA6.5020106@tds.net> Shrutarshi Basu wrote: > Thanks for that, i think that creating a configuration submodule and > importing it into the modules that need it will be the most elegant > solution for me. I was wondering whether the following solution would > work / be good practice? > 1. have the parser system in __init__.py You could do that but I would put it in a config module. > 2. have the parser store the result in a string, say confstr If you only have one configuration parameter this is OK. If you have multiple parameters you should put them in a class or dict, otherwise the individual modules still have to parse the string. > 3. have modules in the package access it with __init__.confstr No, if it is in __init__.py you access it at package scope, it would be mypackage.confstr. Kent PS Please use Reply All to reply to the list. From timmichelsen at gmx-topmail.de Wed Mar 19 13:17:22 2008 From: timmichelsen at gmx-topmail.de (Timmie) Date: Wed, 19 Mar 2008 12:17:22 +0000 (UTC) Subject: [Tutor] Converter References: <1F9942B2-0118-1000-CB26-0FB002CCB77D-Webmail-10007@mac.com> Message-ID: > start, as I want to be able to input any Unit to Convert (will keep it simple for now, feet, inches etc. and add Maybe you want to get inspired by a Gnome deskbar handler: http://www.kryogenix.org/days/2006/09/06/converter-deskbar From alan.gauld at btinternet.com Wed Mar 19 16:34:11 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 19 Mar 2008 15:34:11 -0000 Subject: [Tutor] Converter References: <1F9942B2-0118-1000-CB26-0FB002CCB77D-Webmail-10007@mac.com> Message-ID: "Jack Lucas" wrote >I am trying to make a converter for Python on my Mac. > I know I can find one online, but this is more satisfying. Have you looked at the Cocoa tutorial on using Python on MacOS? It is just such a convertor(for currency). Using that as a template it should be easy to modify it to use different units. http://pyobjc.sourceforge.net/documentation/pyobjc-core/tutorial/index.html > Also if someone would not mind explaining WHY I do certain > functions, > as I am new to Python. Its best if you give us examples. If you don't know why then ask here. You may find the Cocoa tutorial too deep if you are that new and a simple text based solution might be more appropriate. But the actual coding in the Cocoa app is very little and it does look a lot better! :-). Alan G. From allen.fowler at yahoo.com Wed Mar 19 18:22:32 2008 From: allen.fowler at yahoo.com (Allen Fowler) Date: Wed, 19 Mar 2008 10:22:32 -0700 (PDT) Subject: [Tutor] Calling super classs __init__? Message-ID: <652219.17575.qm@web45604.mail.sp1.yahoo.com> > Nowadays the best practice for invoking a method from all superclasses > (yes, multiple inheritance) is this: > > class SubClass(BaseClass): > def __init__(self, t, *args, **kw): > super(SubClass, self).__init__(*args, **kw) > # do something with t > > That way you let Python decide which superclasses your SubClass has, > instead of hard-coding it in several places. > Excellent. Thank you. This seems far more logical. Is there a proper way to handle the case when SubClass() is called using positional arguments, and you do not desire "t" to be at the beginning? Thanks again, :) ____________________________________________________________________________________ Be a better friend, newshound, and know-it-all with Yahoo! Mobile. Try it now. http://mobile.yahoo.com/;_ylt=Ahu06i62sR8HDtDypao8Wcj9tAcJ From me at mikeholloway.co.uk Wed Mar 19 21:14:56 2008 From: me at mikeholloway.co.uk (Mike Holloway) Date: Wed, 19 Mar 2008 20:14:56 +0000 Subject: [Tutor] Using pyusb Message-ID: <47E17440.1060407@mikeholloway.co.uk> Hi all, I'm very new to this list, so hello all! I'm just starting out using python, my background is lamp. I have a Prolific Technologies bridged usb cable that I wish to talk to using pyusb and libusb, I've tried following examples and compiling my own code but I'm really struggling getting it to work. I'm trying to send a sequence of letters to the cable, for them to reappear on the other side. I've been trying to use bulkWrite and bulkRead methods but I'm not sure I'm using them right. There's also controlMethod, but I'm not sure what that is used for. Can anyone help get me started, I'm concerned mostly with the communication, I reckon I could actually get somewhere if I can just nail the first bit, here's my code so far: * Cheers in advance, Mike. import usb import sys import os import time from array import array class DeviceDescriptor: def __init__(self, vendor_id, product_id, interface_id) : self.vendor_id = vendor_id self.product_id = product_id self.interface_id = interface_id def get_device(self) : buses = usb.busses() for bus in buses : for device in bus.devices : if device.idVendor == self.vendor_id : if device.idProduct == self.product_id : return device return None class XFPS(): VENDOR_ID = 0x067B #: Vendor Id PRODUCT_ID = 0x0000 #: Product Id for the bridged usb cable INTERFACE_ID = 0 #: The interface we use to talk to the device BULK_IN_EP = 0x83 #: Endpoint for Bulk reads BULK_OUT_EP = 0x02 #: Endpoint for Bulk writes PACKET_LENGTH = 0x40 #: 64 bytes device_descriptor = DeviceDescriptor(VENDOR_ID, \ PRODUCT_ID, INTERFACE_ID) def __init__(self,) : # The actual device (PyUSB object) self.device = self.device_descriptor.get_device() # Handle that is used to communicate with device. Setup in L{open} self.handle = None def open(self) : self.device = self.device_descriptor.get_device() if not self.device: print >> sys.stderr, "Cable isn't plugged in" try: self.handle = self.device.open() self.handle.claimInterface(self.device_descriptor.interface_id) except usb.USBError, err: print >> sys.stderr, err def close(self): """ Release device interface """ try: self.handle.reset() self.handle.releaseInterface() except Exception, err: print >> sys.stderr, err self.handle, self.device = None, None def my_bulk_write(self): A = chr(0x75) # u B = chr(0x69) # i X = chr(0x6F) # o Y = chr(0x70) # p LB = chr(0x6C) # l RB = chr(0x6B) # k LT = chr(0x68) # h RT = chr(0x6A) # j S = chr(0x32) s = chr(0x73) self.close() self.open() msg = [A,B,A,B,A,B,A,B] #help(self.handle.bulkWrite) help(self.handle.interruptWrite) sent_bytes = self.handle.interruptWrite(XFPS.BULK_OUT_EP,msg,1000) print sent_bytes if sent_bytes: read_bytes = self.handle.interruptRead(0x81,sent_bytes); print read_bytes xfps = XFPS() xfps.open() xfps.my_bulk_write() From alan.gauld at btinternet.com Wed Mar 19 22:22:32 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 19 Mar 2008 21:22:32 -0000 Subject: [Tutor] Using pyusb References: <47E17440.1060407@mikeholloway.co.uk> Message-ID: "Mike Holloway" wrote > I have a Prolific Technologies bridged usb cable that I wish to talk > to > using pyusb and libusb, Sorry I can't help but thanks for pointing these out. I've been intending to write a USB module for over a year, now I don't need to! :-) -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From technorapture at gmail.com Wed Mar 19 22:30:23 2008 From: technorapture at gmail.com (Shrutarshi Basu) Date: Wed, 19 Mar 2008 17:30:23 -0400 Subject: [Tutor] Should config file parser be in module's __init__.py In-Reply-To: <47E0EEA6.5020106@tds.net> References: <376fbdcf0803172021y653a7477vb64802eea5dd378@mail.gmail.com> <47DF9EDA.6060906@tds.net> <376fbdcf0803182122s6eee927axf589e8eee79eecd8@mail.gmail.com> <47E0EEA6.5020106@tds.net> Message-ID: <376fbdcf0803191430g30672a96q99c8ed4aed4587f9@mail.gmail.com> Ok, I'm starting to understand how things work. Just one last question: suppose my package has a config.py (which contains a config dict) which another module in the package imports by "import config". If the user of my package has a config.py in the directory from where they run their program (which uses my package), then which config.py will be used? The user's or the packages? The python tutorial section on modules leads me to believe it will be the users, since the current directory is searched first, but I'm not sure because it is my package which does the import, not the users program. Thanks again, Basu From kent37 at tds.net Wed Mar 19 22:46:37 2008 From: kent37 at tds.net (Kent Johnson) Date: Wed, 19 Mar 2008 17:46:37 -0400 Subject: [Tutor] Should config file parser be in module's __init__.py In-Reply-To: <376fbdcf0803191430g30672a96q99c8ed4aed4587f9@mail.gmail.com> References: <376fbdcf0803172021y653a7477vb64802eea5dd378@mail.gmail.com> <47DF9EDA.6060906@tds.net> <376fbdcf0803182122s6eee927axf589e8eee79eecd8@mail.gmail.com> <47E0EEA6.5020106@tds.net> <376fbdcf0803191430g30672a96q99c8ed4aed4587f9@mail.gmail.com> Message-ID: <47E189BD.1020200@tds.net> Shrutarshi Basu wrote: > Ok, I'm starting to understand how things work. Just one last > question: suppose my package has a config.py (which contains a config > dict) which another module in the package imports by "import config". > If the user of my package has a config.py in the directory from where > they run their program (which uses my package), then which config.py > will be used? The user's or the packages? The python tutorial section > on modules leads me to believe it will be the users, since the current > directory is searched first, but I'm not sure because it is my package > which does the import, not the users program. It will be the user's config.py. Look at sys.path to see the order in which directories are searched for imports. Ken From timmichelsen at gmx-topmail.de Wed Mar 19 23:15:41 2008 From: timmichelsen at gmx-topmail.de (Tim Michelsen) Date: Wed, 19 Mar 2008 23:15:41 +0100 Subject: [Tutor] loading modules only when needed and PEP 008 Message-ID: Hello fellow Pythonistas, I have a question concerning import statements. My code uses matplotlib to plot the results of my calculations. Since I want to make this plotting functionality a optional feature I would like to import matplotlib only when needed because it takes a lot of time for a TKinter-GUI to start up. And this start-up time is even longer when matplotlib is imported. I am still in doubt because PEP 008 [1] states that all imports should come right at the beginning of the code. My current code goes something like: import sys import matplotlib ## .... ## do some calcs ## ... matplotlib.plot(mydata) a optimized version would be: import sys plot_data = 'yes' # option: yes/no if plot_data == 'yes': import matplotlib else: pass ## .... ## do some calcs ## ... if plot_data == 'yes': matplotlib.plot(mydata) else: pass How would you handle such a case? What is recommended in such a case? Does anyone have experience with this? Thanks for your suggestions in advance! Kind regards, Tim [1] PEP 8 -- Style Guide for Python Code - http://www.python.org/dev/peps/pep-0008/ From timmichelsen at gmx-topmail.de Wed Mar 19 23:56:22 2008 From: timmichelsen at gmx-topmail.de (Tim Michelsen) Date: Wed, 19 Mar 2008 23:56:22 +0100 Subject: [Tutor] reading parts of a input string into different variables based on units. Message-ID: Hello, I would like to read several parts of a string into different variables based on the (physical) units of the quantities. Here's my testing code: ############### mystring = '2m 4cm 3mm' # can also be '1pound 30pence', ... mylist = mystring.split(" ") print mylist first = mylist[0] second = mylist[1] third = mylist[2] print "first", first print "second", second print "third", third m = 0 cm = 0 mm = 0 ## first list item if first.endswith("m",-1): m = first.strip("m") elif first.endswith("cm",-2): cm = first.strip("cm") elif first.endswith("mm",-2): mm = first.strip("mm") else: print 'Wrong unit!' ## second list item if second.endswith("m",-1): m = second.strip("m") elif second.endswith("cm",-2): cm = second.strip("cm") elif second.endswith("mm",-2): mm = second.strip("mm") else: print 'Wrong unit!' ## third list item if second.endswith("m",-1): m = second.strip("m") elif second.endswith("cm",-2): cm = second.strip("cm") elif second.endswith("mm",-2): mm = second.strip("mm") else: print 'Wrong unit!' print m, cm, mm ############### Well, I cannot get the meters assigned to the m variable, the centimeters to the cm variable and the milimeters to the mm variable. All units end with "m" and therefore my code confuses the strings I am looking for. I would always reassign the m variable. I would be very grateful of someone could give me a point or hint how I read the quantites (read: numbers) into my variables m, cm, mm. Thanks and kind regards, Timmie From eric at ericwalstad.com Thu Mar 20 00:06:50 2008 From: eric at ericwalstad.com (Eric Walstad) Date: Wed, 19 Mar 2008 16:06:50 -0700 Subject: [Tutor] loading modules only when needed and PEP 008 In-Reply-To: References: Message-ID: <47E19C8A.9000203@ericwalstad.com> Hi Tim, Tim Michelsen wrote: > Hello fellow Pythonistas, > I have a question concerning import statements. ... > it takes a lot > of time for a TKinter-GUI to start up. And this start-up time is even > longer when matplotlib is imported .... > a optimized version would be: > import sys > > plot_data = 'yes' # option: yes/no > > if plot_data == 'yes': > import matplotlib > else: > pass ... > How would you handle such a case? > What is recommended in such a case? > Does anyone have experience with this? Beware that code later in your module that calls matplotlib.foo() may fail if plot_data is not 'yes'. When I do this sort of thing I like to move my imports into my functions/methods. The 'main' code then conditionally calls the function/method. All the code in the function safely assumes that the import has been done but code in the calling function assumes the import hasn't been done. ----- if plot_data: show_plot_data(mydata) ----- def show_plot_data(data): "load matplotlib and show the user the data" import matplotlib ...do stuff with matplotlib... ----- And as we are talking about style, note that your else: pass isn't really necessary but it does make it explicitly clear that you are choosing not to do anything if the plot_data isn't 'yes'. Are those tabs you're using? Four spaces are preferred, according to the style guide. From alan.gauld at btinternet.com Thu Mar 20 00:27:00 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 19 Mar 2008 23:27:00 -0000 Subject: [Tutor] reading parts of a input string into different variables based on units. References: Message-ID: "Tim Michelsen" wrote > I would like to read several parts of a string into different > variables > based on the (physical) units of the quantities. > > Here's my testing code: > ############### > mystring = '2m 4cm 3mm' # can also be '1pound 30pence', ... > mylist = mystring.split(" ") For something like this I'd use regular expressions. If your strings vary in length then I'd use a separate regular expression per unit then use that to findall matching substrings for each unit. > if first.endswith("m",-1): > m = first.strip("m") > elif first.endswith("cm",-2): > cm = first.strip("cm") > elif first.endswith("mm",-2): > mm = first.strip("mm") I'd also look at using a dictionary to store the results so that you can use the unit as a key. > Well, I cannot get the meters assigned to the m variable, the > centimeters to the cm variable and the milimeters to the mm > variable. > All units end with "m" and therefore my code confuses the strings I > am > looking for. I would always reassign the m variable. A regex would avoid that since it would detect an m as being diffrent to a cm or mm. Of course you will have to work out the right regex but that shouldn't be too difficult if you are sure you have a whitespace separator and a number followed by the unit string. The code then becomes (in pseudo code) cm_re = # whatever mm_re = # whatever m_re = # whatever units['cm'] = cm_re.findall(theString) units['mm'] = mm_re.findall(theString) units['m'] = m_re.findall(theString) Now you have a list of values for each unit, you just need to convert the string values to numeric and sum them or whatever else you need to do. HTH, Alan G. From mlangford.cs03 at gtalumni.org Thu Mar 20 00:26:39 2008 From: mlangford.cs03 at gtalumni.org (Michael Langford) Date: Wed, 19 Mar 2008 19:26:39 -0400 Subject: [Tutor] Using pyusb In-Reply-To: <47E17440.1060407@mikeholloway.co.uk> References: <47E17440.1060407@mikeholloway.co.uk> Message-ID: <82b4f5810803191626w5c88ddd9r728b4d8e0b5604cc@mail.gmail.com> I've never heard of the type of cable you're using. Can you send a link to one to the list? You're missing most of the USB ideas more than the python ideas. USB is very very complicated. The USB spec (of which you care about chapter 9) is nothing like how most people actually use USB. Most people use a HID device (even for things that have nothing to do with human interfaces) and communicate that way. If you're going to go with a raw control then: First off: Are you sure you're getting handle to the device? What is the fault you are seeing? Secondly: How do you know what endpoints your device has? Are you sure you have the right addresses for them? You should be able to see this with a USB snooping utility. Control is used to use channel 0 on the USB. It only allows 8 bytes of data and a time and is usually used to switch between modes on a device in my experience. You may have to do a write here to put the device in a mode to do something . This is incredibly device specific. Secondly, why are you using two different endpoints for read and write? Usually you can use 82 and 02 both. Is this something in the cable documentation that tells you to do this? As you have bulk endpoints, you should be using bulk read/write. There are 4 types of USB endpoints: Control, Isochronous, Interrupt and Bulk. Control Transfers are only sent over endpoint 0. Isochronous Transfers are sent periodically and are used for "real time" devices such as web cams (in practice, very very few people ever use this mode) Interrupts Transfers are next, they have a high priority after the first two types and are limited to 256 bytes (IIRC) Bulk Transfers are JUST like interrupt transfers, except, they are lower priority. As you apparently are using a bulk endpoint, you need to use bulk transfers with it. The priorities are only with regards to the USB system. Just as long as your device is using all the same priority, don't worry about which one you use. Your OS should have some tool to allow you to view the USB descriptors of the device. This will at least tell you where the endpoints are that you maybe could be communicating over. Please check your control panel or the command line utils (or /proc device) that tells you this info, as well as where you're stuck before we can help you more. --Michael PS: I would have loved to have know about these modules a couple months ago. I could have avoided some C kernel modules perhaps. On Wed, Mar 19, 2008 at 4:14 PM, Mike Holloway wrote: > Hi all, > > I'm very new to this list, so hello all! > I'm just starting out using python, my background is lamp. > t > I have a Prolific Technologies bridged usb cable that I wish to talk to > using pyusb and libusb, I've tried following examples and compiling my > own code but I'm really struggling getting it to work. > > I'm trying to send a sequence of letters to the cable, for them to > reappear on the other side. I've been trying to use bulkWrite and > bulkRead methods but I'm not sure I'm using them right. There's also > controlMethod, but I'm not sure what that is used for. > > Can anyone help get me started, I'm concerned mostly with the > communication, I reckon I could actually get somewhere if I can just > nail the first bit, here's my code so far: > > * Cheers in advance, Mike. > > > import usb > import sys > import os > import time > from array import array > > class DeviceDescriptor: > def __init__(self, vendor_id, product_id, interface_id) : > self.vendor_id = vendor_id > self.product_id = product_id > self.interface_id = interface_id > > def get_device(self) : > buses = usb.busses() > for bus in buses : > for device in bus.devices : > if device.idVendor == self.vendor_id : > if device.idProduct == self.product_id : > return device > return None > > class XFPS(): > VENDOR_ID = 0x067B #: Vendor Id > PRODUCT_ID = 0x0000 #: Product Id for the bridged usb cable > INTERFACE_ID = 0 #: The interface we use to talk to the device > BULK_IN_EP = 0x83 #: Endpoint for Bulk reads > BULK_OUT_EP = 0x02 #: Endpoint for Bulk writes > PACKET_LENGTH = 0x40 #: 64 bytes > > device_descriptor = DeviceDescriptor(VENDOR_ID, \ > PRODUCT_ID, INTERFACE_ID) > > def __init__(self,) : > # The actual device (PyUSB object) > self.device = self.device_descriptor.get_device() > # Handle that is used to communicate with device. Setup in L{open} > self.handle = None > > def open(self) : > self.device = self.device_descriptor.get_device() > if not self.device: > print >> sys.stderr, "Cable isn't plugged in" > try: > self.handle = self.device.open() > self.handle.claimInterface(self.device_descriptor.interface_id) > except usb.USBError, err: > print >> sys.stderr, err > > def close(self): > """ Release device interface """ > try: > self.handle.reset() > self.handle.releaseInterface() > except Exception, err: > print >> sys.stderr, err > self.handle, self.device = None, None > > def my_bulk_write(self): > A = chr(0x75) # u > B = chr(0x69) # i > X = chr(0x6F) # o > Y = chr(0x70) # p > LB = chr(0x6C) # l > RB = chr(0x6B) # k > LT = chr(0x68) # h > RT = chr(0x6A) # j > > S = chr(0x32) > s = chr(0x73) > > self.close() > self.open() > > msg = [A,B,A,B,A,B,A,B] > #help(self.handle.bulkWrite) > help(self.handle.interruptWrite) > sent_bytes = self.handle.interruptWrite(XFPS.BULK_OUT_EP,msg,1000) > print sent_bytes > if sent_bytes: > read_bytes = self.handle.interruptRead(0x81,sent_bytes); > print read_bytes > > xfps = XFPS() > xfps.open() > xfps.my_bulk_write() > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Michael Langford Phone: 404-386-0495 Consulting: http://www.RowdyLabs.com From mlangford.cs03 at gtalumni.org Thu Mar 20 00:33:45 2008 From: mlangford.cs03 at gtalumni.org (Michael Langford) Date: Wed, 19 Mar 2008 19:33:45 -0400 Subject: [Tutor] Using pyusb In-Reply-To: <82b4f5810803191626w5c88ddd9r728b4d8e0b5604cc@mail.gmail.com> References: <47E17440.1060407@mikeholloway.co.uk> <82b4f5810803191626w5c88ddd9r728b4d8e0b5604cc@mail.gmail.com> Message-ID: <82b4f5810803191633l1c269fe1l77d3b35030fd4c18@mail.gmail.com> Btw, the win32 version of libusb is not maintained anymore, and bogus in my experience. I didn't really get to use libusb much on linux, but it seemed to get a descriptor at least. IIRC, they were upset with their interface and in the middle of vastly changing it. --Michael On Wed, Mar 19, 2008 at 7:26 PM, Michael Langford wrote: > I've never heard of the type of cable you're using. Can you send a > link to one to the list? > > You're missing most of the USB ideas more than the python ideas. > > USB is very very complicated. The USB spec (of which you care about > chapter 9) is nothing like how most people actually use USB. Most > people use a HID device (even for things that have nothing to do with > human interfaces) and communicate that way. > > If you're going to go with a raw control then: > First off: Are you sure you're getting handle to the device? What is > the fault you are seeing? > > Secondly: How do you know what endpoints your device has? Are you sure > you have the right addresses for them? You should be able to see this > with a USB snooping utility. > > Control is used to use channel 0 on the USB. It only allows 8 bytes of > data and a time and is usually used to switch between modes on a > device in my experience. You may have to do a write here to put the > device in a mode to do something . This is incredibly device specific. > > Secondly, why are you using two different endpoints for read and > write? Usually you can use 82 and 02 both. Is this something in the > cable documentation that tells you to do this? > > As you have bulk endpoints, you should be using bulk read/write. There > are 4 types of USB endpoints: Control, Isochronous, Interrupt and > Bulk. > > Control Transfers are only sent over endpoint 0. > Isochronous Transfers are sent periodically and are used for "real > time" devices such as web cams (in practice, very very few people ever > use this mode) > Interrupts Transfers are next, they have a high priority after the > first two types and are limited to 256 bytes (IIRC) > Bulk Transfers are JUST like interrupt transfers, except, they are > lower priority. > > As you apparently are using a bulk endpoint, you need to use bulk > transfers with it. The priorities are only with regards to the USB > system. Just as long as your device is using all the same priority, > don't worry about which one you use. > > Your OS should have some tool to allow you to view the USB descriptors > of the device. This will at least tell you where the endpoints are > that you maybe could be communicating over. > > Please check your control panel or the command line utils (or /proc > device) that tells you this info, as well as where you're stuck before > we can help you more. > > --Michael > > PS: I would have loved to have know about these modules a couple > months ago. I could have avoided some C kernel modules perhaps. > > > > > On Wed, Mar 19, 2008 at 4:14 PM, Mike Holloway wrote: > > Hi all, > > > > I'm very new to this list, so hello all! > > I'm just starting out using python, my background is lamp. > > t > > I have a Prolific Technologies bridged usb cable that I wish to talk to > > using pyusb and libusb, I've tried following examples and compiling my > > own code but I'm really struggling getting it to work. > > > > I'm trying to send a sequence of letters to the cable, for them to > > reappear on the other side. I've been trying to use bulkWrite and > > bulkRead methods but I'm not sure I'm using them right. There's also > > controlMethod, but I'm not sure what that is used for. > > > > Can anyone help get me started, I'm concerned mostly with the > > communication, I reckon I could actually get somewhere if I can just > > nail the first bit, here's my code so far: > > > > * Cheers in advance, Mike. > > > > > > import usb > > import sys > > import os > > import time > > from array import array > > > > class DeviceDescriptor: > > def __init__(self, vendor_id, product_id, interface_id) : > > self.vendor_id = vendor_id > > self.product_id = product_id > > self.interface_id = interface_id > > > > def get_device(self) : > > buses = usb.busses() > > for bus in buses : > > for device in bus.devices : > > if device.idVendor == self.vendor_id : > > if device.idProduct == self.product_id : > > return device > > return None > > > > class XFPS(): > > VENDOR_ID = 0x067B #: Vendor Id > > PRODUCT_ID = 0x0000 #: Product Id for the bridged usb cable > > INTERFACE_ID = 0 #: The interface we use to talk to the device > > BULK_IN_EP = 0x83 #: Endpoint for Bulk reads > > BULK_OUT_EP = 0x02 #: Endpoint for Bulk writes > > PACKET_LENGTH = 0x40 #: 64 bytes > > > > device_descriptor = DeviceDescriptor(VENDOR_ID, \ > > PRODUCT_ID, INTERFACE_ID) > > > > def __init__(self,) : > > # The actual device (PyUSB object) > > self.device = self.device_descriptor.get_device() > > # Handle that is used to communicate with device. Setup in L{open} > > self.handle = None > > > > def open(self) : > > self.device = self.device_descriptor.get_device() > > if not self.device: > > print >> sys.stderr, "Cable isn't plugged in" > > try: > > self.handle = self.device.open() > > self.handle.claimInterface(self.device_descriptor.interface_id) > > except usb.USBError, err: > > print >> sys.stderr, err > > > > def close(self): > > """ Release device interface """ > > try: > > self.handle.reset() > > self.handle.releaseInterface() > > except Exception, err: > > print >> sys.stderr, err > > self.handle, self.device = None, None > > > > def my_bulk_write(self): > > A = chr(0x75) # u > > B = chr(0x69) # i > > X = chr(0x6F) # o > > Y = chr(0x70) # p > > LB = chr(0x6C) # l > > RB = chr(0x6B) # k > > LT = chr(0x68) # h > > RT = chr(0x6A) # j > > > > S = chr(0x32) > > s = chr(0x73) > > > > self.close() > > self.open() > > > > msg = [A,B,A,B,A,B,A,B] > > #help(self.handle.bulkWrite) > > help(self.handle.interruptWrite) > > sent_bytes = self.handle.interruptWrite(XFPS.BULK_OUT_EP,msg,1000) > > print sent_bytes > > if sent_bytes: > > read_bytes = self.handle.interruptRead(0x81,sent_bytes); > > print read_bytes > > > > xfps = XFPS() > > xfps.open() > > xfps.my_bulk_write() > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > > -- > Michael Langford > Phone: 404-386-0495 > Consulting: http://www.RowdyLabs.com > -- Michael Langford Phone: 404-386-0495 Consulting: http://www.RowdyLabs.com From dineshbvadhia at hotmail.com Thu Mar 20 00:52:57 2008 From: dineshbvadhia at hotmail.com (Dinesh B Vadhia) Date: Wed, 19 Mar 2008 16:52:57 -0700 Subject: [Tutor] Python to C++ Message-ID: Say because of performance, you might want to re-write/convert Python code to C++. What is the best way (or best practice) to do this wrt the tools available? Dinesh -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080319/291de88c/attachment.htm From timmichelsen at gmx-topmail.de Thu Mar 20 00:59:03 2008 From: timmichelsen at gmx-topmail.de (Tim Michelsen) Date: Thu, 20 Mar 2008 00:59:03 +0100 Subject: [Tutor] loading modules only when needed and PEP 008 In-Reply-To: <47E19C8A.9000203@ericwalstad.com> References: <47E19C8A.9000203@ericwalstad.com> Message-ID: > When I do this sort of thing I like > to move my imports into my functions/methods. Would this then be compliant with the style recommendations? > The 'main' code then > conditionally calls the function/method. All the code in the > function safely assumes that the import has been done but code in the > calling function assumes the import hasn't been done. Yes, this should a the solution. > And as we are talking about style, note that your else: pass isn't > really necessary but it does make it explicitly clear that you are > choosing not to do anything if the plot_data isn't 'yes'. Ok, so I already got some style here, at least... > Are those > tabs you're using? Four spaces are preferred, according to the > style guide. I always use 4 spaces. This sometimes leads to confusions when working with the same editor on text files that rely tabs but this is another issue... Thanks very much for your fast response! Kind regards, Timmie From timmichelsen at gmx-topmail.de Thu Mar 20 01:04:06 2008 From: timmichelsen at gmx-topmail.de (Tim Michelsen) Date: Thu, 20 Mar 2008 01:04:06 +0100 Subject: [Tutor] reading parts of a input string into different variables based on units. In-Reply-To: References: Message-ID: Hello, thank you for the fast reply! > A regex would avoid that since it would detect an m > as being diffrent to a cm or mm. > > Of course you will have to work out the right regex but that > shouldn't be too difficult if you are sure you have a whitespace > separator and a number followed by the unit string. I will see whether I can get the right regex together. Ease for educated computer scientist but for me coming from a Non-Programmer background the rege still bears some fear... and a learning curve. > Now you have a list of values for each unit, you just need > to convert the string values to numeric and sum them or > whatever else you need to do. I will try to step forward and the send my results back. Thanks and regards, Timmie From kent37 at tds.net Thu Mar 20 02:02:24 2008 From: kent37 at tds.net (Kent Johnson) Date: Wed, 19 Mar 2008 21:02:24 -0400 Subject: [Tutor] reading parts of a input string into different variables based on units. In-Reply-To: References: Message-ID: <47E1B7A0.20604@tds.net> Alan Gauld wrote: > For something like this I'd use regular expressions. > If your strings vary in length then I'd use a separate regular > expression per unit then use that to findall matching > substrings for each unit. > Of course you will have to work out the right regex but that > shouldn't be too difficult if you are sure you have a whitespace > separator and a number followed by the unit string. One regex can split apart a numeric part and a non-numeric unit: In [22]: import re In [23]: splitter = re.compile(r'(\d+)(\S+)') In [24]: splitter.findall('2m 4cm 3mm') Out[24]: [('2', 'm'), ('4', 'cm'), ('3', 'mm')] In [25]: splitter.findall('1pound 30pence') Out[25]: [('1', 'pound'), ('30', 'pence')] If you want to allow decimals change the regex to r'([\d.]+)(\S+)' Kent From wackedd at mac.com Thu Mar 20 01:55:49 2008 From: wackedd at mac.com (wackedd at mac.com) Date: Wed, 19 Mar 2008 17:55:49 -0700 Subject: [Tutor] Converter Message-ID: <974A2AB8-0118-1000-DC39-2B257D733EEC-Webmail-10006@mac.com> print "Converter" number = 2.5 n = int(raw_input("Insert Feet Amount")) while n > 0: print n, "Feet is" print n*12, "inches" print n*30, "centimeters" print Currently this is what I am working with. 2 problems I am facing. 1. When I run the script and type in the amount of feet it calculates it OVER AND OVER. ex: 1 Feet is 12 inches 30 centimeters 1 Feet is 12 inches 30 centimeters 1 Feet is 2. Currently this script only works for the amount of feet, is their a way to have it choose feet, inches, to convert into whatever, without having to right the script over and over, and all in different programs. Maybe using if raw_input = feet then do this equation. I am coding in pure Python on my mac, so please nothing in C as have been some answers I have received. Thanks From bgailer at alum.rpi.edu Thu Mar 20 02:18:47 2008 From: bgailer at alum.rpi.edu (bob gailer) Date: Wed, 19 Mar 2008 21:18:47 -0400 Subject: [Tutor] Converter In-Reply-To: <974A2AB8-0118-1000-DC39-2B257D733EEC-Webmail-10006@mac.com> References: <974A2AB8-0118-1000-DC39-2B257D733EEC-Webmail-10006@mac.com> Message-ID: <47E1BB77.8090004@alum.rpi.edu> wackedd at mac.com wrote: > print "Converter" > number = 2.5 > n = int(raw_input("Insert Feet Amount")) > while n > 0: > print n, "Feet is" > print n*12, "inches" > print n*30, "centimeters" > print > > Currently this is what I am working with. > 2 problems I am facing. > 1. When I run the script and type in the amount of feet it calculates it OVER AND OVER. > I'd like to introduce you to the concept known as "desk checking". Pretend you are the computer executing this program. Mentally (or even better on paper) execute each statement in the order that the computer would. Write down the values of variables as they change. Especially pay attention to the value of n. Also ask of what use is the variable numnber? > [snip] > > 2. Currently this script only works for the amount of feet, is their a way to have it choose feet, inches, to convert into whatever, without having to right the script over and over, and all in different programs. I don't understand this part of the question. > Maybe using if raw_input = feet then do this equation. I am coding in pure Python on my mac, so please nothing in C as have been some answers I have received. -- Bob Gailer 919-636-4239 Chapel Hill, NC From mlangford.cs03 at gtalumni.org Thu Mar 20 02:42:09 2008 From: mlangford.cs03 at gtalumni.org (Michael Langford) Date: Wed, 19 Mar 2008 21:42:09 -0400 Subject: [Tutor] Python to C++ In-Reply-To: References: Message-ID: <82b4f5810803191842q784c8bb2pe2e003d520e283ab@mail.gmail.com> Weave is probably what you really want to do, although it doesn't do what you said: http://wiki.python.org/moin/weave Pyrex actually does what you said: http://wiki.python.org/moin/Pyrex On Wed, Mar 19, 2008 at 7:52 PM, Dinesh B Vadhia wrote: > > > Say because of performance, you might want to re-write/convert Python code > to C++. What is the best way (or best practice) to do this wrt the tools > available? > > Dinesh > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Michael Langford Phone: 404-386-0495 Consulting: http://www.RowdyLabs.com From marc.tompkins at gmail.com Thu Mar 20 04:02:34 2008 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Wed, 19 Mar 2008 20:02:34 -0700 Subject: [Tutor] reading parts of a input string into different variables based on units. In-Reply-To: References: Message-ID: <40af687b0803192002n3e975344ub94d6102087c19f8@mail.gmail.com> On Wed, Mar 19, 2008 at 3:56 PM, Tim Michelsen wrote: > m = 0 > cm = 0 > mm = 0 > ## first list item > if first.endswith("m",-1): > m = first.strip("m") > elif first.endswith("cm",-2): > cm = first.strip("cm") > elif first.endswith("mm",-2): > mm = first.strip("mm") > else: > print 'Wrong unit!' > ## second list item > if second.endswith("m",-1): > m = second.strip("m") > elif second.endswith("cm",-2): > cm = second.strip("cm") > elif second.endswith("mm",-2): > mm = second.strip("mm") > else: > print 'Wrong unit!' > ## third list item > if second.endswith("m",-1): > m = second.strip("m") > elif second.endswith("cm",-2): > cm = second.strip("cm") > elif second.endswith("mm",-2): > mm = second.strip("mm") > else: > print 'Wrong unit!' > Since they all end in "m", if you do that test first it catches all three cases. It's almost as if you put the "else" before the "if". Regexes are a wonderful thing to learn - do that by all means - but the simplest thing would be to reverse the order of your tests: check against "mm" first, then "cm", THEN "m". To clarify - regexes are probably the best solution for your current program, but as a general rule it helps to look at tests like this from a different angle. -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080319/d969053d/attachment.htm From eric at ericwalstad.com Thu Mar 20 04:32:01 2008 From: eric at ericwalstad.com (Eric Walstad) Date: Wed, 19 Mar 2008 20:32:01 -0700 Subject: [Tutor] loading modules only when needed and PEP 008 In-Reply-To: References: <47E19C8A.9000203@ericwalstad.com> Message-ID: <47E1DAB1.5070400@ericwalstad.com> Hey Timmie, Tim Michelsen wrote: >> When I do this sort of thing I like >> to move my imports into my functions/methods. > Would this then be compliant with the style recommendations? Hm, I'm not sure. I guess that if you consider that somewhere near the top of the style guide it says something about 'foolish consistency' than I suppose it does . I think it's ok to deviate from the pep when it makes sense to do so. Define 'makes sense'. I'm assuming that importing the matplotlib at the top of your file is making your app unusably slow; to me that is a great reason to break from the style guide. >> And as we are talking about style, note that your else: pass isn't >> really necessary but it does make it explicitly clear that you are >> choosing not to do anything if the plot_data isn't 'yes'. > Ok, so I already got some style here, at least... I wouldn't include the 'else' bits, but that's my style. >> Are those >> tabs you're using? Four spaces are preferred, according to the >> style guide. > I always use 4 spaces. This sometimes leads to confusions when working > with the same editor on text files that rely tabs but this is another > issue... Sorry. In my mail reader the indentation looked like tabs. From alan.gauld at btinternet.com Thu Mar 20 10:25:00 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 20 Mar 2008 09:25:00 -0000 Subject: [Tutor] Converter References: <974A2AB8-0118-1000-DC39-2B257D733EEC-Webmail-10006@mac.com> Message-ID: wrote > Currently this is what I am working with. Thanks for posting that it gives us a much better idea of what stage you are at and lets us target our answers. Forget the Cocoa suggestion I made earlier, your basic Python skills need improving before you get to that. > 2 problems I am facing. > 1. When I run the script and type in the amount of feet it > calculates it OVER AND OVER. Bob already gave you a good suggestion there. Your loop repeats while n is greater than zero. Work through the code on paper, as if you were the computer, and see when/if n stops being greater than zero. > 2. Currently this script only works for the amount of > feet, is their a way to have it choose feet, inches, > to convert into whatever, without having to write > the script over and over, and all in different programs. Yes of course. All you need is to tell the program which units to read and which to convert to. So you need a program that looks to the user like: Input Units (in,cm,ml,km,lbs,kg)> in Output Units(in,cm,ml,km,lbs,kg) > cm How many inches? 6 6 inches is 15 centimetres Can you write a program that does that? You know how to read input with raw_input. Do you understand how to use if/elif/else to make decisions inside your code? You know how to do the basic calculations. You know how to print the output. > Maybe using if raw_input = feet then > do this equation. Exactly so. > I am coding in pure Python on my mac, so > please nothing in C as have been some > answers I have received. I have no idea why anyone would suggest C for something like this, it is exactly the kind of program you would use Python for. I don't know which book/tutorial you are using but the information you need for this problem can be found in the following topics of my tutor: - Simple Sequences - Talking to the User - Branching And optionally you may also want - Loops but they aren't strictly necessary for this. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Thu Mar 20 10:33:38 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 20 Mar 2008 09:33:38 -0000 Subject: [Tutor] reading parts of a input string into different variables based on units. References: <47E1B7A0.20604@tds.net> Message-ID: "Kent Johnson" wrote > One regex can split apart a numeric part and a non-numeric unit: > In [24]: splitter.findall('2m 4cm 3mm') > Out[24]: [('2', 'm'), ('4', 'cm'), ('3', 'mm')] As ever Kent, a neat solution. Much more efficient than my 3 way search and relatively easy to split the list apart for analysis. Even the regex is cleaner! :-) Alan G. From kent37 at tds.net Thu Mar 20 11:45:37 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 20 Mar 2008 06:45:37 -0400 Subject: [Tutor] reading parts of a input string into different variables based on units. In-Reply-To: <47E1B7A0.20604@tds.net> References: <47E1B7A0.20604@tds.net> Message-ID: <47E24051.6080300@tds.net> Kent Johnson wrote: > One regex can split apart a numeric part and a non-numeric unit: A little explanation: > In [22]: import re > In [23]: splitter = re.compile(r'(\d+)(\S+)') The regex finds one or more digits \d+ followed by one or more non-whitespace characters \S+. The parentheses define groups which will be returned by the match. > In [24]: splitter.findall('2m 4cm 3mm') > Out[24]: [('2', 'm'), ('4', 'cm'), ('3', 'mm')] findall() finds all matches for the regex in the string. When the regex contains groups, the value returned is a list of tuples. Each tuple contains the value of all the groups in the regex. > If you want to allow decimals change the regex to r'([\d.]+)(\S+)' This makes the first group match digits and period instead of just digits. Kent From andreas at kostyrka.org Thu Mar 20 15:48:29 2008 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Thu, 20 Mar 2008 15:48:29 +0100 Subject: [Tutor] Python to C++ In-Reply-To: References: Message-ID: <1206024509.13580.76.camel@localhost> If you need to rewrite Python code for performance, I'd recommend using Pyrex/Cython. (www.cython.org). It let's you get away with small changes to your code as a starter (Cython is relative compatible syntax-wise with Python), and you can add "C type annotations" as needed. (And no, C++ is not cost effective compared to C in this "Python speedup" scenario: you get a more complex solution without readily available benefits.) It's also integrated with distutils/setuptools. Andreas Am Mittwoch, den 19.03.2008, 16:52 -0700 schrieb Dinesh B Vadhia: > Say because of performance, you might want to re-write/convert Python > code to C++. What is the best way (or best practice) to do this wrt > the tools available? > > Dinesh > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Dies ist ein digital signierter Nachrichtenteil Url : http://mail.python.org/pipermail/tutor/attachments/20080320/86706298/attachment.pgp From alan.gauld at btinternet.com Thu Mar 20 18:21:52 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 20 Mar 2008 17:21:52 -0000 Subject: [Tutor] Python to C++ References: Message-ID: "Dinesh B Vadhia" wrote > Say because of performance, you might want to re-write/convert > Python code to C++. What is the best way (or best practice) > to do this wrt the tools available? It may be obvious but its worth noting that optimised Python may be faster than a badly written C port. So first make sure you have squeezed the best performance out of Python. Secondly only rewrite the bits that need it so use the profiler to identify the bottlenecks in your Python code and move those to a separate module to reduce conversion effort. After that the advice already given re pyrex/psycho etc is all good. You might also find SWIG a useful alternative if you decide to rewrite the slow functions by hand. SWIG will help wrap those functions so that the remaining Python code can access them. Alan G. From me at mikeholloway.co.uk Thu Mar 20 15:08:09 2008 From: me at mikeholloway.co.uk (Michael Holloway) Date: Thu, 20 Mar 2008 14:08:09 +0000 Subject: [Tutor] Using pyusb In-Reply-To: <82b4f5810803191633l1c269fe1l77d3b35030fd4c18@mail.gmail.com> References: <47E17440.1060407@mikeholloway.co.uk> <82b4f5810803191626w5c88ddd9r728b4d8e0b5604cc@mail.gmail.com> <82b4f5810803191633l1c269fe1l77d3b35030fd4c18@mail.gmail.com> Message-ID: <47E26FC9.9040309@mikeholloway.co.uk> I hope I'm using this system correctly by just hitting reply-all in my email client :s Thanks very much Michael, I've been a bit thin on the other details I see. My platform is Mac Os 10.4, I'm using USB snooper to get the data I need, I'll post it at the end of this message. Forgive me, I've been trying to be bloody-minded about getting this to work and haven't read the USB spec. I'm not the sort of person to sit down and read pages of information before I get to the stuff I need, as I loose interest fast, I'd much rather bash away until I start seeing results. Regarding the actual hardware, here's a pic: http://www.maplin.co.uk/images/Full/tf06g_new.jpg I brought it from Maplin, here's a link (note that the first picture shown ISN'T the same cable): http://www.maplin.co.uk/Search.aspx?criteria=TF06G&DOY=20m3 I can't actually find the manufacturers site, but I have since learned that Prolific Tech. are the company responsible for the chip that deals with the routing, I believe it goes usb a -> serial -> chip -> serial -> usb a When I run my script, I am definately connecting, if I don't have the cable plugged in it tells me so, when I plug the cable in and run it, I get the following output: //some help description 8 (160,160,160,160,160,160,160,160) I'm using bulk read/write just because it sounded right, your insight has definately opened my eyes a bit, I guess I really need to help myself by spoffing up on the books. The cable documentation is extremely basic and poor. Where can I get the information I need specifically on how to get the cable to accept data sent from my mac? Here's the snoop: Full Speed device @ 3 (0x1D100000): ............................................. Composite device from Prolific Technology, Inc. Device Descriptor Descriptor Version Number: 0x0100 Device Class: 0 (Composite) Device Subclass: 0 Device Protocol: 0 Device MaxPacketSize: 8 Device VendorID/ProductID: 0x067B/0x0000 (Prolific Technology, Inc.) Device Version Number: 0x0000 Number of Configurations: 1 Manufacturer String: 1 "Prolific Technology Inc." Product String: 0 (none) Serial Number String: 0 (none) Configuration Descriptor Length (and contents): 39 Raw Descriptor (hex) 0000: 09 02 27 00 01 01 00 A0 32 09 04 00 00 03 FF 00 Raw Descriptor (hex) 0010: 00 00 07 05 81 03 01 00 01 07 05 02 02 40 00 00 Raw Descriptor (hex) 0020: 07 05 83 02 40 00 00 Number of Interfaces: 1 Configuration Value: 1 Attributes: 0xA0 (bus-powered, remote wakeup) MaxPower: 100 ma Interface #0 - Vendor-specific Alternate Setting 0 Number of Endpoints 3 Interface Class: 255 (Vendor-specific) Interface Subclass; 0 (Vendor-specific) Interface Protocol: 0 Endpoint 0x81 - Interrupt Input Address: 0x81 (IN) Attributes: 0x03 (Interrupt no synchronization data endpoint) Max Packet Size: 1 Polling Interval: 1 ms Endpoint 0x02 - Bulk Output Address: 0x02 (OUT) Attributes: 0x02 (Bulk no synchronization data endpoint) Max Packet Size: 64 Polling Interval: 0 ms Endpoint 0x83 - Bulk Input Address: 0x83 (IN) Attributes: 0x02 (Bulk no synchronization data endpoint) Max Packet Size: 64 Polling Interval: 0 ms Michael Langford wrote: > Btw, the win32 version of libusb is not maintained anymore, and bogus > in my experience. I didn't really get to use libusb much on linux, but > it seemed to get a descriptor at least. IIRC, they were upset with > their interface and in the middle of vastly changing it. > > --Michael > > On Wed, Mar 19, 2008 at 7:26 PM, Michael Langford > wrote: > >> I've never heard of the type of cable you're using. Can you send a >> link to one to the list? >> >> You're missing most of the USB ideas more than the python ideas. >> >> USB is very very complicated. The USB spec (of which you care about >> chapter 9) is nothing like how most people actually use USB. Most >> people use a HID device (even for things that have nothing to do with >> human interfaces) and communicate that way. >> >> If you're going to go with a raw control then: >> First off: Are you sure you're getting handle to the device? What is >> the fault you are seeing? >> >> Secondly: How do you know what endpoints your device has? Are you sure >> you have the right addresses for them? You should be able to see this >> with a USB snooping utility. >> >> Control is used to use channel 0 on the USB. It only allows 8 bytes of >> data and a time and is usually used to switch between modes on a >> device in my experience. You may have to do a write here to put the >> device in a mode to do something . This is incredibly device specific. >> >> Secondly, why are you using two different endpoints for read and >> write? Usually you can use 82 and 02 both. Is this something in the >> cable documentation that tells you to do this? >> >> As you have bulk endpoints, you should be using bulk read/write. There >> are 4 types of USB endpoints: Control, Isochronous, Interrupt and >> Bulk. >> >> Control Transfers are only sent over endpoint 0. >> Isochronous Transfers are sent periodically and are used for "real >> time" devices such as web cams (in practice, very very few people ever >> use this mode) >> Interrupts Transfers are next, they have a high priority after the >> first two types and are limited to 256 bytes (IIRC) >> Bulk Transfers are JUST like interrupt transfers, except, they are >> lower priority. >> >> As you apparently are using a bulk endpoint, you need to use bulk >> transfers with it. The priorities are only with regards to the USB >> system. Just as long as your device is using all the same priority, >> don't worry about which one you use. >> >> Your OS should have some tool to allow you to view the USB descriptors >> of the device. This will at least tell you where the endpoints are >> that you maybe could be communicating over. >> >> Please check your control panel or the command line utils (or /proc >> device) that tells you this info, as well as where you're stuck before >> we can help you more. >> >> --Michael >> >> PS: I would have loved to have know about these modules a couple >> months ago. I could have avoided some C kernel modules perhaps. >> >> >> >> >> On Wed, Mar 19, 2008 at 4:14 PM, Mike Holloway wrote: >> > Hi all, >> > >> > I'm very new to this list, so hello all! >> > I'm just starting out using python, my background is lamp. >> > t >> > I have a Prolific Technologies bridged usb cable that I wish to talk to >> > using pyusb and libusb, I've tried following examples and compiling my >> > own code but I'm really struggling getting it to work. >> > >> > I'm trying to send a sequence of letters to the cable, for them to >> > reappear on the other side. I've been trying to use bulkWrite and >> > bulkRead methods but I'm not sure I'm using them right. There's also >> > controlMethod, but I'm not sure what that is used for. >> > >> > Can anyone help get me started, I'm concerned mostly with the >> > communication, I reckon I could actually get somewhere if I can just >> > nail the first bit, here's my code so far: >> > >> > * Cheers in advance, Mike. >> > >> > >> > import usb >> > import sys >> > import os >> > import time >> > from array import array >> > >> > class DeviceDescriptor: >> > def __init__(self, vendor_id, product_id, interface_id) : >> > self.vendor_id = vendor_id >> > self.product_id = product_id >> > self.interface_id = interface_id >> > >> > def get_device(self) : >> > buses = usb.busses() >> > for bus in buses : >> > for device in bus.devices : >> > if device.idVendor == self.vendor_id : >> > if device.idProduct == self.product_id : >> > return device >> > return None >> > >> > class XFPS(): >> > VENDOR_ID = 0x067B #: Vendor Id >> > PRODUCT_ID = 0x0000 #: Product Id for the bridged usb cable >> > INTERFACE_ID = 0 #: The interface we use to talk to the device >> > BULK_IN_EP = 0x83 #: Endpoint for Bulk reads >> > BULK_OUT_EP = 0x02 #: Endpoint for Bulk writes >> > PACKET_LENGTH = 0x40 #: 64 bytes >> > >> > device_descriptor = DeviceDescriptor(VENDOR_ID, \ >> > PRODUCT_ID, INTERFACE_ID) >> > >> > def __init__(self,) : >> > # The actual device (PyUSB object) >> > self.device = self.device_descriptor.get_device() >> > # Handle that is used to communicate with device. Setup in L{open} >> > self.handle = None >> > >> > def open(self) : >> > self.device = self.device_descriptor.get_device() >> > if not self.device: >> > print >> sys.stderr, "Cable isn't plugged in" >> > try: >> > self.handle = self.device.open() >> > self.handle.claimInterface(self.device_descriptor.interface_id) >> > except usb.USBError, err: >> > print >> sys.stderr, err >> > >> > def close(self): >> > """ Release device interface """ >> > try: >> > self.handle.reset() >> > self.handle.releaseInterface() >> > except Exception, err: >> > print >> sys.stderr, err >> > self.handle, self.device = None, None >> > >> > def my_bulk_write(self): >> > A = chr(0x75) # u >> > B = chr(0x69) # i >> > X = chr(0x6F) # o >> > Y = chr(0x70) # p >> > LB = chr(0x6C) # l >> > RB = chr(0x6B) # k >> > LT = chr(0x68) # h >> > RT = chr(0x6A) # j >> > >> > S = chr(0x32) >> > s = chr(0x73) >> > >> > self.close() >> > self.open() >> > >> > msg = [A,B,A,B,A,B,A,B] >> > #help(self.handle.bulkWrite) >> > help(self.handle.interruptWrite) >> > sent_bytes = self.handle.interruptWrite(XFPS.BULK_OUT_EP,msg,1000) >> > print sent_bytes >> > if sent_bytes: >> > read_bytes = self.handle.interruptRead(0x81,sent_bytes); >> > print read_bytes >> > >> > xfps = XFPS() >> > xfps.open() >> > xfps.my_bulk_write() >> > >> > _______________________________________________ >> > Tutor maillist - Tutor at python.org >> > http://mail.python.org/mailman/listinfo/tutor >> > >> >> >> >> -- >> Michael Langford >> Phone: 404-386-0495 >> Consulting: http://www.RowdyLabs.com >> >> > > > > From cfuller084 at thinkingplanet.net Thu Mar 20 17:18:45 2008 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Thu, 20 Mar 2008 11:18:45 -0500 Subject: [Tutor] Python to C++ In-Reply-To: References: Message-ID: <200803201118.45565.cfuller084@thinkingplanet.net> On Wednesday 19 March 2008 18:52, Dinesh B Vadhia wrote: > Say because of performance, you might want to re-write/convert Python code > to C++. What is the best way (or best practice) to do this wrt the tools > available? > > Dinesh You also might want to use some profiling tools, or skip that step if it's known, and simply rewrite the slowest parts. It isn't too hard to integrate Python with C code, there are tutorials in the bundled documentation (also available on the Python website). http://docs.python.org/ext/ext.html Cheers From inthefridge at gmail.com Thu Mar 20 22:16:05 2008 From: inthefridge at gmail.com (Spencer Parker) Date: Thu, 20 Mar 2008 15:16:05 -0600 Subject: [Tutor] CSV file processing... Message-ID: I am trying to read a CSV file and the get that information into a MySQL database. I am able to do this, but I have a small problem. I have a piece of software that runs and each iteration is one like. It only runs once right now; there is only one line + the headers. I use the csv module to kill the headers and import the one line. The problem is...I need to have it split the csv file at some point. I need to first 20 items taken off and then have the next 7 + the first 20 imported into the database...then have it do this for the next 7 + the first 20...so on and so forth until hits the end of the line. Any ideas? -- Spencer Parker _______________________________________________________ "if you can't go to heaven, may you at least die in Ireland." _______________________________________________________ -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080320/2dbcb614/attachment.htm From listsdl04 at yahoo.de Fri Mar 21 00:32:21 2008 From: listsdl04 at yahoo.de (Guba) Date: Fri, 21 Mar 2008 07:32:21 +0800 Subject: [Tutor] question concerning Boolean operators Message-ID: <47E2F405.9090303@yahoo.de> Dear list, from Guido's tutorial: It is possible to assign the result of a comparison or other Boolean expression to a variable. For example, >>> string1, string2, string3 = '', 'Trondheim', 'Hammer Dance' >>> non_null = string1 or string2 or string3 >>> non_null 'Trondheim' How does this work?? How does Python know that we are looking for non_null? After all, we don't provide this information here, right? (I take non_null is a variable.) I must be missing something... Can anyone help? Many thanks, Guba From kent37 at tds.net Fri Mar 21 00:42:28 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 20 Mar 2008 19:42:28 -0400 Subject: [Tutor] CSV file processing... In-Reply-To: References: Message-ID: <47E2F664.3030907@tds.net> Spencer Parker wrote: > I am trying to read a CSV file and the get that information into a MySQL > database. I am able to do this, but I have a small problem. I have a > piece of software that runs and each iteration is one like. It only > runs once right now; there is only one line + the headers. I use the > csv module to kill the headers and import the one line. The problem > is...I need to have it split the csv file at some point. I need to first > 20 items taken off and then have the next 7 + the first 20 imported into > the database...then have it do this for the next 7 + the first 20...so > on and so forth until hits the end of the line. I'm not sure I understand. It sounds like you have a very long line of data from the csv file and you want to split it into groups of 7, after taking the first 20 items. If that is correct, something like this might work: row = ... # your long row prefix = row[:20] # the twenty items that repeat for i in range(20, len(row), 7): next = prefix + row[i:i+7] # Handle 'next' - add it to the database or whateve Kent From eric at ericwalstad.com Fri Mar 21 00:49:45 2008 From: eric at ericwalstad.com (Eric Walstad) Date: Thu, 20 Mar 2008 16:49:45 -0700 Subject: [Tutor] CSV file processing... In-Reply-To: References: Message-ID: <47E2F819.10705@ericwalstad.com> Hi Spencer Spencer Parker wrote: > I have a > piece of software that runs and each iteration is one like. I don't understand what this means. > It only > runs once right now; there is only one line + the headers. I use the > csv module to kill the headers and import the one line. Does 'kill the headers' mean the same as ignoring them in your code? > The problem > is...I need to have it split the csv file at some point. I need to first > 20 items taken off and then have the next 7 + the first 20 imported into > the database...then have it do this for the next 7 + the first 20...so > on and so forth until hits the end of the line. Define 'item' here. Is it a field, a character, is it a line? I'm going to assume that you mean that you want to loop through the file line by line, inserting to the database the line's fields in this order: fields[20], ..., fields[27], fields[0], fields[1], ..., fields[n-1] This example: http://dpaste.com/hold/40503/ shows how the csv.reader lets you loop over csv data line by line, each line is a list of fields. Using Python's slicing operations you can easily rearrange the line's fields to suit your output needs. See also: http://www.diveintopython.org/native_data_types/lists.html Eric. From jim at well.com Fri Mar 21 00:55:17 2008 From: jim at well.com (jim stockford) Date: Thu, 20 Mar 2008 16:55:17 -0700 Subject: [Tutor] question concerning Boolean operators In-Reply-To: <47E2F405.9090303@yahoo.de> References: <47E2F405.9090303@yahoo.de> Message-ID: <9a4b97e148299f47d367bc5185112be6@well.com> i'm guessing assignment, which actually associates a reference, will skip referencing an identifier to a null and will make the association (assignment) to the first non-null value in the expression, which is string2 in this case. that the identifier is non_null is immaterial; you could write >>> string1, string2, string3 = '', 'Trondheim', 'Hammer Dance' >>> jackson = string1 or string2 or string3 >>> jackson 'Trondheim' On Mar 20, 2008, at 4:32 PM, Guba wrote: > Dear list, > > from Guido's tutorial: > > It is possible to assign the result of a comparison or other Boolean > expression to a variable. For example, > > >>> string1, string2, string3 = '', 'Trondheim', 'Hammer Dance' > >>> non_null = string1 or string2 or string3 > >>> non_null > 'Trondheim' > > How does this work?? How does Python know that we are looking for > non_null? After all, we don't provide this information here, right? (I > take non_null is a variable.) > I must be missing something... Can anyone help? > > Many thanks, > > Guba > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From steve at alchemy.com Fri Mar 21 01:02:10 2008 From: steve at alchemy.com (Steve Willoughby) Date: Thu, 20 Mar 2008 17:02:10 -0700 Subject: [Tutor] question concerning Boolean operators In-Reply-To: <9a4b97e148299f47d367bc5185112be6@well.com> References: <47E2F405.9090303@yahoo.de> <9a4b97e148299f47d367bc5185112be6@well.com> Message-ID: <20080321000210.GB88223@dragon.alchemy.com> On Thu, Mar 20, 2008 at 04:55:17PM -0700, jim stockford wrote: > >>> string1, string2, string3 = '', 'Trondheim', 'Hammer Dance' > >>> jackson = string1 or string2 or string3 > >>> jackson > 'Trondheim' The key here is the "or" operator which, in an expression like a or b will return a if a is a True boolean value or b otherwise. The upshot is that the result will be True if a OR b is True, and False only if they are both False. The *actual* value returned will be the value of a or b. so here we have: string1 or string2 or string3 If string1 is True (which a string is if it's not empty), then that's the result returned, and we can stop right there. non_null = '' or 'Trondheim' or 'Hammer Dance' However, string1 ('') is empty, which in a Boolean context is False, so Python goes on to string2 ('Trondheim') That's non-empty (or True) so we get that value and don't look further. non_null = 'Trondheim' which is a True value. If you said: if non_null: print non_null, 'is not null' else: print "it's null" The result would be to print: Trondheim is not null Hope that helps steve > On Mar 20, 2008, at 4:32 PM, Guba wrote: > > > Dear list, > > > > from Guido's tutorial: > > > > It is possible to assign the result of a comparison or other Boolean > > expression to a variable. For example, > > > > >>> string1, string2, string3 = '', 'Trondheim', 'Hammer Dance' > > >>> non_null = string1 or string2 or string3 > > >>> non_null > > 'Trondheim' > > > > How does this work?? How does Python know that we are looking for > > non_null? After all, we don't provide this information here, right? (I > > take non_null is a variable.) > > I must be missing something... Can anyone help? > > > > Many thanks, > > > > Guba > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- Steve Willoughby | Using billion-dollar satellites steve at alchemy.com | to hunt for Tupperware. From dkuhlman at rexx.com Fri Mar 21 01:09:16 2008 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Thu, 20 Mar 2008 17:09:16 -0700 Subject: [Tutor] CSV file processing... In-Reply-To: References: Message-ID: <20080321000916.GA23637@cutter.rexx.com> On Thu, Mar 20, 2008 at 03:16:05PM -0600, Spencer Parker wrote: > I am trying to read a CSV file and the get that information into a MySQL > database. I am able to do this, but I have a small problem. I have a piece > of software that runs and each iteration is one like. It only runs once > right now; there is only one line + the headers. I use the csv module to > kill the headers and import the one line. The problem is...I need to have > it split the csv file at some point. I need to first 20 items taken off and > then have the next 7 + the first 20 imported into the database...then have > it do this for the next 7 + the first 20...so on and so forth until hits the > end of the line. > > Any ideas? Consider the following bit of code: In [6]: f = open('csv_report.csv', 'r') In [7]: r = csv.reader(f) In [8]: lines = [line for line in r] In [9]: lines Out[9]: [['Name', 'Description', 'Rating'], ['Lemon', 'Bright yellow and tart', '5'], ['Eggplant', 'Purple and shiny', '6'], ['Tangerine', 'Succulent', '8']] Once you get a list of lists (a list of rows containing lists of fields), you can process and skip whichever rows you wish. Are the items you want to skip/process the rows or the fields. If it's the fields, then you might consider flattening your list of lists. If you need to do that, then the following might help: In [23]: fields = [] In [24]: for line in lines: ....: for field in line: ....: fields.append(field) ....: In [25]: fields Out[25]: ['Name', 'Description', 'Rating', 'Lemon', 'Bright yellow and tart', '5', 'Eggplant', 'Purple and shiny', '6', 'Tangerine', 'Succulent', '8'] Then process *that* list. Does someone know a slicker way to flatten a list? I could not find anything helpful in itertools. Or, is your input so large that you do not want to read it in all at once. It would have to be quite large before that would be a problem. - Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman From alan.gauld at btinternet.com Fri Mar 21 01:56:52 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 21 Mar 2008 00:56:52 -0000 Subject: [Tutor] question concerning Boolean operators References: <47E2F405.9090303@yahoo.de> Message-ID: "Guba" wrote > >>> string1, string2, string3 = '', 'Trondheim', 'Hammer Dance' > >>> non_null = string1 or string2 or string3 > >>> non_null > 'Trondheim' > > How does this work?? How does Python know that we are looking for > non_null? After all, we don't provide this information here, right? > (I > take non_null is a variable.) You created non_null as a variable when you did the assignment. >>> non_null = string1 or string2 or string3 That's how we create variables in Python by assigning a value The next oddity is that an 'or' operation returned a string rather than a boolean value. That's because of two features of Python: First, Python evaluates boolean expressions using "short circuit" evaluation. That means that for an OR it evaluates the first element and if its True it doesn't bother with the rest since if any one is True the whole must be true. Second, Python considers any non zero/non empty value to be true, so a string is deemed to be a True value in boolean terms to Python. Putting that all together, you created a variable called non_null, assigned it the value of a boolean or expression which because of short circuit evaluation turned out to be the first element. > I must be missing something... Can anyone help? You don't say if you already program in another language but if not you will probably find one of the non-programmers tutorials easier than Guido's official tutor which assumes some previous experience. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From keridee at jayco.net Sat Mar 22 03:48:41 2008 From: keridee at jayco.net (tiger12506) Date: Fri, 21 Mar 2008 21:48:41 -0500 Subject: [Tutor] Calling super classs __init__? References: <652219.17575.qm@web45604.mail.sp1.yahoo.com> Message-ID: <00c301c88bc7$3d9bc2b0$0702a8c0@home> >> class SubClass(BaseClass): >> def __init__(self, t, *args, **kw): >> super(SubClass, self).__init__(*args, **kw) >> # do something with t > Is there a proper way to handle the case when SubClass() is called using > positional arguments, and you do not desire "t" to be at the beginning? Sorry. If you are using *args and **kw then t has to be at the beginning. Hmm... Unless you consider t to be part of *args or **kw, then you could process those before the call to super's __init__. After the def and before the call to the super's __init__, *args and **kw are just a list and a dictionary. You can edit them however you wish. ;-) Also, does anyone want to clarify? I thought that super() only return one of the base classes and was frowned upon for objects using multiple inheritance??? From esilvers68 at hotmail.com Fri Mar 21 03:21:29 2008 From: esilvers68 at hotmail.com (Elliot Silvers) Date: Thu, 20 Mar 2008 19:21:29 -0700 Subject: [Tutor] Help this newbie Message-ID: I am as new as you can get to Python. I have just learned how to save my work (very simple work of course). I created a folder on C:\ (in this case C:\Elliot) for my work. I am able to use the cmd prompt to run it (cd \Elliot -> C:\Elliot 'filename.py') however I cannot figure out how to import it using the python (command line). Please help. There is most likely a very simple solution. I have just not been able to figure it out. Thanks Elliot _________________________________________________________________ Windows Live Hotmail is giving away Zunes. http://www.windowslive-hotmail.com/ZuneADay/?locale=en-US&ocid=TXT_TAGLM_Mobile_Zune_V3 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080320/81f6bfe4/attachment.htm From andreas at kostyrka.org Fri Mar 21 03:34:29 2008 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Fri, 21 Mar 2008 03:34:29 +0100 Subject: [Tutor] Calling super classs __init__? In-Reply-To: <00c301c88bc7$3d9bc2b0$0702a8c0@home> References: <652219.17575.qm@web45604.mail.sp1.yahoo.com> <00c301c88bc7$3d9bc2b0$0702a8c0@home> Message-ID: <1206066869.17587.8.camel@localhost> Am Freitag, den 21.03.2008, 21:48 -0500 schrieb tiger12506: Actually, super returns all base classes, all in it's own time. Basically, every class has a member __mro__, that contains a consistently ordered list of classes. super needs the class from where it is being called to locate the right place in the __mro__ and to hand you a wrapper around self for the next base class in this list. This way, if all classes use super, they can cooperativly call all implementations of a given method. That's the theory. In practice there are a number of pitfalls which makes super problematic. ;) Andreas > Also, does anyone want to clarify? I thought that super() only return one of > the base classes and was frowned upon for objects using multiple > inheritance??? > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Dies ist ein digital signierter Nachrichtenteil Url : http://mail.python.org/pipermail/tutor/attachments/20080321/dffca54d/attachment.pgp From keridee at jayco.net Sat Mar 22 04:38:28 2008 From: keridee at jayco.net (tiger12506) Date: Fri, 21 Mar 2008 22:38:28 -0500 Subject: [Tutor] Help this newbie References: Message-ID: <000d01c88bce$31379830$0702a8c0@home> This is Windows I presume? Try: cd\python25 python C:\Elliot\filename.py But for windows you shouldn't have to. You can just double-click the file. On the other hand, if you mean 'import' as it means in the context of the actual python language, then you would put the line "import filename" at the top of a script which is supposed to use your module. ----- Original Message ----- From: Elliot Silvers To: tutor at python.org Sent: Thursday, March 20, 2008 9:21 PM Subject: [Tutor] Help this newbie I am as new as you can get to Python. I have just learned how to save my work (very simple work of course). I created a folder on C:\ (in this case C:\Elliot) for my work. I am able to use the cmd prompt to run it (cd \Elliot -> C:\Elliot 'filename.py') however I cannot figure out how to import it using the python (command line). Please help. There is most likely a very simple solution. I have just not been able to figure it out. Thanks Elliot Windows Live Hotmail is giving away Zunes. Enter for your chance to win. _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From bgailer at alum.rpi.edu Fri Mar 21 04:08:25 2008 From: bgailer at alum.rpi.edu (bob gailer) Date: Thu, 20 Mar 2008 23:08:25 -0400 Subject: [Tutor] CSV file processing... In-Reply-To: <20080321000916.GA23637@cutter.rexx.com> References: <20080321000916.GA23637@cutter.rexx.com> Message-ID: <47E326A9.4080400@alum.rpi.edu> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080320/c68b5efd/attachment.htm From keridee at jayco.net Sat Mar 22 05:11:37 2008 From: keridee at jayco.net (tiger12506) Date: Fri, 21 Mar 2008 23:11:37 -0500 Subject: [Tutor] Calling super classs __init__? References: <652219.17575.qm@web45604.mail.sp1.yahoo.com> <00c301c88bc7$3d9bc2b0$0702a8c0@home> <1206066869.17587.8.camel@localhost> Message-ID: <001e01c88bd2$d3087900$0702a8c0@home> Woah. Either you're leaving out essential info, or python got a lot more complicated. Firstly, super returns all base classes. How? Does it return a tuple of them, or a container object, or is this something horribly worse such as syntactic sugar? It doesn't make sense for it to return a tuple, then super().__init__ would call the init method of the tuple, not each class, so then syntactic sugar would have to be involved. I doubt that.. A container object could use __getattr__ to magically call each of the __init__ methods of the contained class references. The most logical is the container object. But that leaves things open for duplicate calls to __init__ So the container would have to keep track of the base classes it has already called... which might be the ordered list __mro__, but those are class specific, not global, so each super class would not know if an __init__ has been called or not... But then again, you would need duplicate calls because each level of super would need different initiation. I apologize. Would you care to explain this a little more technically? Specific and accurate are better than translated into layman's terms. I've been with python for a while now. thanks. >Actually, super returns all base classes, all in it's own time. > >Basically, every class has a member __mro__, that contains a >consistently ordered list of classes. > >super needs the class from where it is being called to locate the right >place in the __mro__ and to hand you a wrapper around self for the next >base class in this list. > >This way, if all classes use super, they can cooperativly call all >implementations of a given method. > >That's the theory. In practice there are a number of pitfalls which >makes super problematic. ;) > >Andreas From sli1que at yahoo.com Fri Mar 21 04:23:22 2008 From: sli1que at yahoo.com (Eric Walker) Date: Thu, 20 Mar 2008 20:23:22 -0700 (PDT) Subject: [Tutor] grammer Message-ID: <114118.75802.qm@web65416.mail.ac4.yahoo.com> Hello, I have been reading about python grammers for processing text files. Does anyone have any simple examples? Thanks ____________________________________________________________________________________ Never miss a thing. Make Yahoo your home page. http://www.yahoo.com/r/hs From kaushalshriyan at gmail.com Fri Mar 21 08:08:49 2008 From: kaushalshriyan at gmail.com (Kaushal Shriyan) Date: Fri, 21 Mar 2008 12:38:49 +0530 Subject: [Tutor] rsync python script Message-ID: <6b16fb4c0803210008k249c205bj4efee762f990aa99@mail.gmail.com> Hi MAILTO=kaushal at example.com 0 18 * * * rsync -av /var/lib/mysql kaushal at host77:/var/lib/ If i put this two lines in crontab it will run correctly,My requirement was to create a python script, this python script should indicate success or failures and the reason for failure Any ideas Thanks and Regards Kaushal -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080321/4cdb811c/attachment.htm From alan.gauld at btinternet.com Fri Mar 21 09:24:38 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 21 Mar 2008 08:24:38 -0000 Subject: [Tutor] Help this newbie References: Message-ID: "Elliot Silvers" wrote > I am as new as you can get to Python. I have just learned > how to save my work (very simple work of course). > I created a folder on C:\ (in this case C:\Elliot) for my work. > I am able to use the cmd prompt to run it Congratulations. You should also be able to run it by double clicking in explorer. > however I cannot figure out how to import it using the > python (command line). Can you show us what happens when you try. Cut n paste from the command window into your email. However there are two areas which might be messing things up: 1) do not specify the .py when importing ie to import foo.py type import foo 2) Make sure your Elliot folder is in the import path. There are several waays to do this, the simplest is to add your folder to the PYTHONPATH environment variable. (If 2 is the problem then the impoprt should work OK if you CD to your folder before starting Python...) To set environment variables see the sidebar in the Moresequences topic in my tutorial... You will probably need to create PYTHONPATH as a new variable. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Fri Mar 21 09:25:52 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 21 Mar 2008 08:25:52 -0000 Subject: [Tutor] grammer References: <114118.75802.qm@web65416.mail.ac4.yahoo.com> Message-ID: "Eric Walker" wrote > I have been reading about python grammers for processing > text files. Does anyone have any simple examples? Can you give us a context? eg. Where were you doing the reading? Alan G From andreas at kostyrka.org Fri Mar 21 10:25:36 2008 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Fri, 21 Mar 2008 10:25:36 +0100 Subject: [Tutor] Calling super classs __init__? In-Reply-To: <001e01c88bd2$d3087900$0702a8c0@home> References: <652219.17575.qm@web45604.mail.sp1.yahoo.com> <00c301c88bc7$3d9bc2b0$0702a8c0@home> <1206066869.17587.8.camel@localhost> <001e01c88bd2$d3087900$0702a8c0@home> Message-ID: <1206091536.17587.11.camel@localhost> It does not return them at once. It returns them piece by piece: andreas at andi-lap:/tmp> cat mro.py class A(object): v=lambda self: "A" class B(object): v=lambda self: "B" class C(B,A): v=lambda self: "C" print C.__mro__ c=C() print c.v() print super(C, c).v() print super(B, c).v() andreas at andi-lap:/tmp> python2.5 mro.py (, , , ) C B A Andreas Am Freitag, den 21.03.2008, 23:11 -0500 schrieb tiger12506: > Woah. Either you're leaving out essential info, or python got a lot more > complicated. > > Firstly, super returns all base classes. How? Does it return a tuple of > them, or a container object, or is this something horribly worse such as > syntactic sugar? > > It doesn't make sense for it to return a tuple, then super().__init__ would > call the init method of the tuple, not each class, so then syntactic sugar > would have to be involved. I doubt that.. > > A container object could use __getattr__ to magically call each of the > __init__ methods of the contained class references. > The most logical is the container object. But that leaves things open for > duplicate calls to __init__ > So the container would have to keep track of the base classes it has already > called... which might be the ordered list __mro__, but those are class > specific, not global, so each super class would not know if an __init__ has > been called or not... But then again, you would need duplicate calls because > each level of super would need different initiation. > > I apologize. Would you care to explain this a little more technically? > Specific and accurate are better than translated into layman's terms. I've > been with python for a while now. thanks. > > >Actually, super returns all base classes, all in it's own time. > > > >Basically, every class has a member __mro__, that contains a > >consistently ordered list of classes. > > > >super needs the class from where it is being called to locate the right > >place in the __mro__ and to hand you a wrapper around self for the next > >base class in this list. > > > >This way, if all classes use super, they can cooperativly call all > >implementations of a given method. > > > >That's the theory. In practice there are a number of pitfalls which > >makes super problematic. ;) > > > >Andreas > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Dies ist ein digital signierter Nachrichtenteil Url : http://mail.python.org/pipermail/tutor/attachments/20080321/38fe9cad/attachment.pgp From tktucker at gmail.com Fri Mar 21 11:57:21 2008 From: tktucker at gmail.com (Tom Tucker) Date: Fri, 21 Mar 2008 06:57:21 -0400 Subject: [Tutor] rsync python script In-Reply-To: <6b16fb4c0803210008k249c205bj4efee762f990aa99@mail.gmail.com> References: <6b16fb4c0803210008k249c205bj4efee762f990aa99@mail.gmail.com> Message-ID: <2a278ffe0803210357w3df4c877oddc3698450088f5d@mail.gmail.com> The success or failure could be confirmed by checking the exit status and/or confirming host77 has the same /var/lib file structure as the source host. The later is the most accurate, however a bit more complicated to confirm. As for determining the reason for failure, possible causes off the top of my head might be name resolution, network failure, either system being offline, crond problems on originating system, /var/lib filesystem full on host77, etc. I would continue to brainstorm other possible causes and think of ways to check for it in your script. For example, perform a name resolution check on host77. If resolvable, proceed to ping check method. Good luck. On Fri, Mar 21, 2008 at 3:08 AM, Kaushal Shriyan wrote: > Hi > > MAILTO=kaushal at example.com > 0 18 * * * rsync -av /var/lib/mysql kaushal at host77:/var/lib/ > > If i put this two lines in crontab it will run correctly,My requirement > was to create a python script, this python script should indicate success or > failures and the reason for failure > > Any ideas > > Thanks and Regards > > Kaushal > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080321/af90fdd5/attachment-0001.htm From kent37 at tds.net Fri Mar 21 12:48:30 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 21 Mar 2008 07:48:30 -0400 Subject: [Tutor] Calling super classs __init__? In-Reply-To: <1206066869.17587.8.camel@localhost> References: <652219.17575.qm@web45604.mail.sp1.yahoo.com> <00c301c88bc7$3d9bc2b0$0702a8c0@home> <1206066869.17587.8.camel@localhost> Message-ID: <47E3A08E.70508@tds.net> tiger12506 wrote: > Also, does anyone want to clarify? I thought that super() only return one of > the base classes and was frowned upon for objects using multiple > inheritance??? super() returns the next class in method-resolution order. super() was added to the language specifically to address some problems introduced by multiple inheritance. http://www.python.org/doc/2.2.3/whatsnew/sect-rellinks.html#SECTION000330000000000000000 Actually super() doesn't return a class at all, it returns an object of type 'super' that is a proxy for the actual class. And the class it proxies may not even be an ancestor of the class named as the first argument. For example: class A(object): def v(self): print 'A' class B(A): def v(self): print 'B' super(B, self).v() class C(A): def v(self): print 'C' super(C, self).v() class D(B, C): def v(self): print 'D' super(D, self).v() D().v() prints D B C A so super(B, D()) points to C which is not a base class of B at all; it *is* the next class after B in D.__mro__ which is (, , , , ) The super() docs are quite inaccurate on this point. There is already an issue for this in Roundup that seems to have foundered on how to explain some of the finer points of super(). (Hmmm... "If the implementation is hard to explain, it's a bad idea." What if it is impossible to explain :-) The issue has some suggested improvements for the docs: http://bugs.python.org/issue1163367 Andreas Kostyrka wrote: > This way, if all classes use super, they can cooperativly call all > implementations of a given method. The key here is "if all classes use super". super() needs to be used consistently in an inheritance hierarchy. > That's the theory. In practice there are a number of pitfalls which > makes super problematic. ;) Yes. Here is a fairly lengthy document from the Chandler project about the correct way to use super: http://chandlerproject.org/bin/view/Projects/UsingSuper The complications lead some people to conclude either that super() is either too broken or too complicated to use: http://fuhm.net/super-harmful/ Guido's response to the above: http://mail.python.org/pipermail/python-dev/2005-January/050656.html For myself, I have concluded that super() is difficult to use correctly and addresses problems that I have never had in practice, so I don't use it. Kent From kent37 at tds.net Fri Mar 21 13:01:23 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 21 Mar 2008 08:01:23 -0400 Subject: [Tutor] grammer In-Reply-To: <114118.75802.qm@web65416.mail.ac4.yahoo.com> References: <114118.75802.qm@web65416.mail.ac4.yahoo.com> Message-ID: <47E3A393.1070501@tds.net> Eric Walker wrote: > Hello, > I have been reading about python grammers for processing text files. Does anyone have any simple examples? Do you mean parsers written in Python for processing text files? A grammar is usually an abstract specification of a format, not something that will actually process the format. There are many add-on packages for writing parsers in Python. A good list is here: http://nedbatchelder.com/text/python-parsers.html IMO pyparsing is one of the easiest to use. It comes with many examples: http://pyparsing.wikispaces.com/ One of the pyparsing examples parses grammar descriptions in Extended Backus-Naur Form (EBNF) and produces a pyparsing parser for the grammar: http://pyparsing.wikispaces.com/space/showimage/ebnf.py David Mertz' book Text Processing in Python has many examples: http://gnosis.cx/TPiP/ HTH Kent From inthefridge at gmail.com Fri Mar 21 15:41:41 2008 From: inthefridge at gmail.com (Spencer Parker) Date: Fri, 21 Mar 2008 08:41:41 -0600 Subject: [Tutor] CSV file processing... In-Reply-To: <47E326A9.4080400@alum.rpi.edu> References: <20080321000916.GA23637@cutter.rexx.com> <47E326A9.4080400@alum.rpi.edu> Message-ID: This is why I should not be allowed to write emails at the end of the day. At least ones that need deep explanation. Let's try this a second time. I am running virt-top on a Xen box. This grabs information about various things. I can set how many iterations of it I want to run. I only have it running once now. It dumps all of its information into a CSV file. Now I have 10 virtual machines running on this Xen box right now. It has one line that is all of the headers. Then on the next line it lists all of the machines information...all on one line. So I basically have something that is 70 columns long + 2 columns of host machine specific data. I want to insert all of this into a MySQL database that then is processed it all into a webpage. I have a test server that only had one machine running so I could experiment in getting the data into the database. That part I have working properly. My problem is that I need to be able to get all of the data of all the machine running into the database as well. All of them in their own specific row. The first 20 columns in the CSV are for the host machine...then the next 7 items are specific to the virtual machine. All it lists after the first 20+7 is virtual machine data. So I want to join the first 20 columns up with the first 7...then the first 20 columns up with the next 7...so on and so forth. This is what I have now... #!/usr/bin/python import MySQLdb import csv import sys try: db = MySQLdb.connect (host = "localhost",user = "user",passwd = "password",db = "stats") except MySQLdb.Error, e: print "Error %d: %s" % (e.args[0], e.args[1]) sys.exit (1) try: co = db.cursor() csv_data = csv.reader(file('output.txt','r')) for row in csv_data: print row co.execute(""" INSERT INTO stats (Hostname, Time, Arch, PhysicalCPU, Count, Running, Blocked, Paused, Shutdown, Shutoff, Crashed, Active, Inactive, PCPU, TotalMemory, Totalguestmemory, TotalCPUtime, DomainID, Domainname, CPUTime, PGCPU, RDRQ, WRRQ, RXBY, TXBY) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s); """,row) co.close() except MySQLdb.Error, e: print "Error %d: %s" % (e.args[0], e.args[1]) sys.exit (1) db.commit() db.close() Sorry for the confusion I caused everyone...trying to run out of work...and write an email is not the best combo ever. Thanks again for all of the help. On Thu, Mar 20, 2008 at 9:08 PM, bob gailer wrote: > On Thu, Mar 20, 2008 at 03:16:05PM -0600, Spencer Parker wrote: > > I've interspersed a bunch of comments to show you how hard it has been to > read and understand your problem description. After going thru it I think I > understand the question. > > Please in the future try to express the question more clearly. > > I am trying to read a CSV file and the get that information into a MySQL > database. I am able to do this > > > You are able to do what? Read csv files? Insert into my SQL? > > but I have a small problem. I have a piece of software > > Is this a Python program? Will you post it so we can see it? > > that runs > > Good - it is nice to have running software > > and each iteration is one like > > Like what? > > It only runs once right now > > Is that a problem? > > there is only one line + the headers. > > In the input file?? > > I use the csv module to kill > > Kill? > > the headers and import > > import in Python has a specific meaning. I don't think you mean import in > the Python sense. > > the one line. > > > The problem is...I need to have it split the csv file > > the file or the line following the headers? > > at some point. I need to first 20 items taken off > > Of what? To understand this we'd need to see an example of the csv file. > > and then have the next 7 + the first 20 imported into the database > > Huh? I know all of this makes sense to you but not to me. So you need to > give me a much better picture. > > then have it do this for the next 7 + the first 20...so on and so forth until hits the > end of the line. > > > Having waded thru all that I will make a guess: > > The csv file format is: > Headers Line > Data Line > > and Data Line looks like: > item1,. item2, ... item20, data11, data12, ... data17, data21, data22, ... > data27, etc. > > And you want to insert into the datbase: > item1,. item2, ... item20, data11, data12, ... data17 > item1,. item2, ... item20, data21, data22, ... data27 > etc > > Any ideas? > > > If I were you and my guesses above are correct I'd reduce the problem > statement to: > given a line from a csv file of the format: > item1,. item2, ... item20, data11, data12, ... data17, data21, data22, ... > data27, etc. > How do I create a series of INSERT statements to insert into the database > item1,. item2, ... item20, data11, data12, ... data17 > item1,. item2, ... item20, data21, data22, ... data27 > > -- > Bob Gailer > 919-636-4239 Chapel Hill, NC > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Spencer Parker _______________________________________________________ "if you can't go to heaven, may you at least die in Ireland." _______________________________________________________ -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080321/be7f4f6f/attachment.htm From keridee at jayco.net Sat Mar 22 17:44:18 2008 From: keridee at jayco.net (tiger12506) Date: Sat, 22 Mar 2008 11:44:18 -0500 Subject: [Tutor] Calling super classs __init__? References: <652219.17575.qm@web45604.mail.sp1.yahoo.com> <00c301c88bc7$3d9bc2b0$0702a8c0@home> <1206066869.17587.8.camel@localhost> <001e01c88bd2$d3087900$0702a8c0@home> <1206091536.17587.11.camel@localhost> Message-ID: <000201c88c3c$09816320$0702a8c0@home> So super(A, c) refers to the baseclass object? I don't like this. It partially suggests that A is a superclass of B. I guess I have to be sure to notice the second parameter which tells of which instance I'm finding the superclass. fyi I totally didn't notice the first parameter of super... was it there in previous versions of python? ----- Original Message ----- From: "Andreas Kostyrka" To: "tiger12506" Cc: Sent: Friday, March 21, 2008 4:25 AM Subject: Re: [Tutor] Calling super classs __init__? class A(object): v=lambda self: "A" class B(object): v=lambda self: "B" class C(B,A): v=lambda self: "C" print C.__mro__ c=C() print c.v() print super(C, c).v() print super(B, c).v() (, , , ) C B A From eric at ericwalstad.com Fri Mar 21 17:01:31 2008 From: eric at ericwalstad.com (Eric Walstad) Date: Fri, 21 Mar 2008 09:01:31 -0700 Subject: [Tutor] CSV file processing... In-Reply-To: References: <20080321000916.GA23637@cutter.rexx.com> <47E326A9.4080400@alum.rpi.edu> Message-ID: <47E3DBDB.90606@ericwalstad.com> Hey Spencer, Spencer Parker wrote: > This is why I should not be allowed to write emails at the end of the > day. At least ones that need deep explanation. Let's try this a second > time. Thanks, this looks better, but... > This is what I have now... *What isn't working* the way you want? Traceback? I'll guess that you don't want to have to hardcode the columns for a fixed number of virtual machine data into your sql string... > try: > co = db.cursor() > csv_data = csv.reader(file('output.txt','r')) > > for row in csv_data: print row > co.execute(""" > INSERT INTO stats (Hostname, Time, Arch, PhysicalCPU, Count, > Running, Blocked, Paused, Shutdown, Shutoff, Crashed, Active, Inactive, > PCPU, TotalMemory, Totalguestmemory, TotalCPUtime, DomainID, Domainname, > CPUTime, PGCPU, RDRQ, WRRQ, RXBY, TXBY) > VALUES > (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s); > """,row) > > co.close() Huh? I was expecting to see 27 fields (20 for the host machine and 7 for the virtual machine), you have 25 above. Yes, a traceback or explanation of what's going wrong would be helpful. Other things I'd recommend are: 1. I'm pretty sure that your 'row' above is a list of values. Investigate Python's list slicing operator[1] that other responses to your first email have used. Doing so will help you understand... 2. Kent's response to your first email looks great. Reread it and I think you'll find it does what you want (handle a variable number of virtual machines and their data). See also: the range function and it's 'step' argument[2]. 3. Nice that you are sending the 'row' list to the database adapter and letting it escape the values. In your case I don't think you have to worry about SQL injection, but it's a good habit to get into if you ever need to stuff end-user data into a database. hth, Eric. [1] http://www.diveintopython.org/native_data_types/lists.html#odbchelper.list.3.1 [2] http://docs.python.org/tut/node6.html#SECTION006300000000000000000 From eric at ericwalstad.com Fri Mar 21 17:10:09 2008 From: eric at ericwalstad.com (Eric Walstad) Date: Fri, 21 Mar 2008 09:10:09 -0700 Subject: [Tutor] rsync python script In-Reply-To: <6b16fb4c0803210008k249c205bj4efee762f990aa99@mail.gmail.com> References: <6b16fb4c0803210008k249c205bj4efee762f990aa99@mail.gmail.com> Message-ID: <47E3DDE1.2080200@ericwalstad.com> Kaushal Shriyan wrote: > Hi > > MAILTO=kaushal at example.com > 0 18 * * * rsync -av /var/lib/mysql kaushal at host77:/var/lib/ > > If i put this two lines in crontab it will run correctly,My requirement > was to create a python script, this python script should indicate > success or failures and the reason for failure It looks like rsync can output to a text file. Python makes text parsing a breeze. Have you defined 'indicate', 'success' and 'failure' yet? When will your python script run? Who/What will run it? From kaushalshriyan at gmail.com Fri Mar 21 17:22:04 2008 From: kaushalshriyan at gmail.com (Kaushal Shriyan) Date: Fri, 21 Mar 2008 21:52:04 +0530 Subject: [Tutor] rsync python script In-Reply-To: <47E3DDE1.2080200@ericwalstad.com> References: <6b16fb4c0803210008k249c205bj4efee762f990aa99@mail.gmail.com> <47E3DDE1.2080200@ericwalstad.com> Message-ID: <6b16fb4c0803210922s7d184a24ya4df4d90931ec40a@mail.gmail.com> On Fri, Mar 21, 2008 at 9:40 PM, Eric Walstad wrote: > Kaushal Shriyan wrote: > > Hi > > > > MAILTO=kaushal at example.com > > 0 18 * * * rsync -av /var/lib/mysql kaushal at host77:/var/lib/ > > > > If i put this two lines in crontab it will run correctly,My requirement > > was to create a python script, this python script should indicate > > success or failures and the reason for failure > It looks like rsync can output to a text file. Python makes text > parsing a breeze. Have you defined 'indicate', 'success' and 'failure' > yet? When will your python script run? Who/What will run it? > Hi Eric Can i have a sample python script which can take care of this rsync application and at the same time indicating success and failure and the reason for failure Thanks and Regards Kaushal -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080321/fcb28ca4/attachment.htm From inthefridge at gmail.com Fri Mar 21 18:47:09 2008 From: inthefridge at gmail.com (Spencer Parker) Date: Fri, 21 Mar 2008 11:47:09 -0600 Subject: [Tutor] CSV file processing... In-Reply-To: <47E2F664.3030907@tds.net> References: <47E2F664.3030907@tds.net> Message-ID: So if my long row is row two...how do I tell it to use row 2? On Thu, Mar 20, 2008 at 5:42 PM, Kent Johnson wrote: > Spencer Parker wrote: > > I am trying to read a CSV file and the get that information into a MySQL > > database. I am able to do this, but I have a small problem. I have a > > piece of software that runs and each iteration is one like. It only > > runs once right now; there is only one line + the headers. I use the > > csv module to kill the headers and import the one line. The problem > > is...I need to have it split the csv file at some point. I need to first > > 20 items taken off and then have the next 7 + the first 20 imported into > > the database...then have it do this for the next 7 + the first 20...so > > on and so forth until hits the end of the line. > > I'm not sure I understand. It sounds like you have a very long line of > data from the csv file and you want to split it into groups of 7, after > taking the first 20 items. If that is correct, something like this might > work: > > row = ... # your long row > prefix = row[:20] # the twenty items that repeat > for i in range(20, len(row), 7): > next = prefix + row[i:i+7] > # Handle 'next' - add it to the database or whateve > > Kent > -- Spencer Parker _______________________________________________________ "if you can't go to heaven, may you at least die in Ireland." _______________________________________________________ -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080321/b3ccec0f/attachment.htm From kent37 at tds.net Fri Mar 21 18:54:31 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 21 Mar 2008 13:54:31 -0400 Subject: [Tutor] CSV file processing... In-Reply-To: References: <47E2F664.3030907@tds.net> Message-ID: <47E3F657.9050706@tds.net> Spencer Parker wrote: > So if my long row is row two...how do I tell it to use row 2? csv_data = csv.reader(file('output.txt','r')) headers = csv_data.next() # Skip header row row = csv_data.next() # The row with data Kent From inthefridge at gmail.com Fri Mar 21 19:59:44 2008 From: inthefridge at gmail.com (Spencer Parker) Date: Fri, 21 Mar 2008 12:59:44 -0600 Subject: [Tutor] CSV file processing... In-Reply-To: <47E3F657.9050706@tds.net> References: <47E2F664.3030907@tds.net> <47E3F657.9050706@tds.net> Message-ID: Okay...so I got it mostly working...it now dies with this trackback: Traceback (most recent call last): File "./loadcsv.py", line 23, in ? co.execute(""" File "/usr/lib64/python2.4/site-packages/MySQLdb/cursors.py", line 148, in execute query = query % db.literal(args) On Fri, Mar 21, 2008 at 11:54 AM, Kent Johnson wrote: > Spencer Parker wrote: > > So if my long row is row two...how do I tell it to use row 2? > > csv_data = csv.reader(file('output.txt','r')) > headers = csv_data.next() # Skip header row > row = csv_data.next() # The row with data > > Kent > -- Spencer Parker _______________________________________________________ "if you can't go to heaven, may you at least die in Ireland." _______________________________________________________ -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080321/1b8a9310/attachment.htm From wackedd at mac.com Fri Mar 21 20:03:36 2008 From: wackedd at mac.com (wackedd at mac.com) Date: Fri, 21 Mar 2008 12:03:36 -0700 Subject: [Tutor] More Converter Message-ID: <245E2DCC-0118-1000-A22A-BD839F694284-Webmail-10021@mac.com> I am still in need of more help. Currently I am just trying to get one conversion down, as then I can duplicate it. However I am not sure how to make it Convert. Currently I am working with: # Converter Original = raw_input("Insert inches, feet ") To = raw_input("Insert inches, feet ") Variable = int(raw_input("Insert Amount to Convert ")) if Original == raw_input(feet) and To == raw_input(inches): print Variable*12 I want it so that if the raw_input from Original is feet, and the raw_input from To is inches it will print the raw_input from Variable*12. I always get this error message though Traceback (most recent call last): File "/Users/donaldlucas/Documents/Python Scripts/Converter.py", line 5, in if Original == raw_input(feet) and To == raw_input(inches): NameError: name 'feet' is not defined I would assume that this is because I am not doing the if Orignal== part correctly. Help me? Thanks From kent37 at tds.net Fri Mar 21 20:18:53 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 21 Mar 2008 15:18:53 -0400 Subject: [Tutor] CSV file processing... In-Reply-To: References: <47E2F664.3030907@tds.net> <47E3F657.9050706@tds.net> Message-ID: <47E40A1D.2060602@tds.net> Spencer Parker wrote: > Okay...so I got it mostly working...it now dies with this trackback: It would be helpful to see what 'it' is (i.e. your code), and also to see the actual error message as well as the traceback. We try to read minds on this group but we aren't really very good at it. Kent > > Traceback (most recent call last): > File "./loadcsv.py", line 23, in ? > co.execute(""" > File "/usr/lib64/python2.4/site-packages/MySQLdb/cursors.py", line > 148, in execute > query = query % db.literal(args) From inthefridge at gmail.com Fri Mar 21 20:24:30 2008 From: inthefridge at gmail.com (Spencer Parker) Date: Fri, 21 Mar 2008 13:24:30 -0600 Subject: [Tutor] CSV file processing... In-Reply-To: <47E40A1D.2060602@tds.net> References: <47E2F664.3030907@tds.net> <47E3F657.9050706@tds.net> <47E40A1D.2060602@tds.net> Message-ID: I posted it in a previous message on the list...but here it is... #!/usr/bin/python import MySQLdb import csv import sys try: db = MySQLdb.connect (host = "localhost",user = "root",passwd = "Ch33s3Monk3y",db = "xenstats") except MySQLdb.Error, e: print "Error %d: %s" % (e.args[0], e.args[1]) sys.exit (1) try: co = db.cursor() csv_data = csv.reader(file('output.txt','r')) headers = csv_data.next() row = csv_data.next() prefix = row[:20] for i in range(20, len(row), 7): next = prefix + row[i:i+7] for row in csv_data: print next co.execute(""" INSERT INTO stats VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s); """,row) co.close() except MySQLdb.Error, e: print "Error %d: %s" % (e.args[0], e.args[1]) sys.exit (1) db.commit() db.close() On Fri, Mar 21, 2008 at 1:18 PM, Kent Johnson wrote: > Spencer Parker wrote: > > Okay...so I got it mostly working...it now dies with this trackback: > > It would be helpful to see what 'it' is (i.e. your code), and also to > see the actual error message as well as the traceback. We try to read > minds on this group but we aren't really very good at it. > > Kent > > > > > Traceback (most recent call last): > > File "./loadcsv.py", line 23, in ? > > co.execute(""" > > File "/usr/lib64/python2.4/site-packages/MySQLdb/cursors.py", line > > 148, in execute > > query = query % db.literal(args) > -- Spencer Parker _______________________________________________________ "if you can't go to heaven, may you at least die in Ireland." _______________________________________________________ -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080321/48788fb8/attachment.htm From kent37 at tds.net Fri Mar 21 20:34:14 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 21 Mar 2008 15:34:14 -0400 Subject: [Tutor] CSV file processing... In-Reply-To: References: <47E2F664.3030907@tds.net> <47E3F657.9050706@tds.net> <47E40A1D.2060602@tds.net> Message-ID: <47E40DB6.8090603@tds.net> Spencer Parker wrote: > I posted it in a previous message on the list...but here it is... Looks new to me... > > #!/usr/bin/python > > import MySQLdb > import csv > import sys > > try: > db = MySQLdb.connect (host = "localhost",user = "root",passwd = > "Ch33s3Monk3y",db = "xenstats") > except MySQLdb.Error, e: > print "Error %d: %s" % (e.args[0], e.args[1]) > sys.exit (1) > > try: > co = db.cursor() > csv_data = csv.reader(file('output.txt','r')) > headers = csv_data.next() > row = csv_data.next() > prefix = row[:20] > for i in range(20, len(row), 7): > next = prefix + row[i:i+7] > > for row in csv_data: print next Why do you have this loop? You only want to process one row, right? > co.execute(""" > INSERT INTO stats VALUES > (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s); > """,row) Should be next - the processed data - not row - the raw data. You still didn't show the actual error message. After the traceback there should be an error. Kent From inthefridge at gmail.com Fri Mar 21 20:42:33 2008 From: inthefridge at gmail.com (Spencer Parker) Date: Fri, 21 Mar 2008 13:42:33 -0600 Subject: [Tutor] CSV file processing... In-Reply-To: <47E40DB6.8090603@tds.net> References: <47E2F664.3030907@tds.net> <47E3F657.9050706@tds.net> <47E40A1D.2060602@tds.net> <47E40DB6.8090603@tds.net> Message-ID: This is all that I get when I run it... Traceback (most recent call last): File "./loadcsv.py", line 23, in ? co.execute(""" File "/usr/lib64/python2.4/site-packages/MySQLdb/cursors.py", line 148, in execute query = query % db.literal(args) TypeError: not all arguments converted during string formatting On Fri, Mar 21, 2008 at 1:34 PM, Kent Johnson wrote: > Spencer Parker wrote: > > I posted it in a previous message on the list...but here it is... > > Looks new to me... > > > > #!/usr/bin/python > > > > import MySQLdb > > import csv > > import sys > > > > try: > > db = MySQLdb.connect (host = "localhost",user = "root",passwd = > > "Ch33s3Monk3y",db = "xenstats") > > except MySQLdb.Error, e: > > print "Error %d: %s" % (e.args[0], e.args[1]) > > sys.exit (1) > > > > try: > > co = db.cursor() > > csv_data = csv.reader(file('output.txt','r')) > > headers = csv_data.next() > > row = csv_data.next() > > prefix = row[:20] > > for i in range(20, len(row), 7): > > next = prefix + row[i:i+7] > > > > for row in csv_data: print next > > Why do you have this loop? You only want to process one row, right? > > > co.execute(""" > > INSERT INTO stats VALUES > > > (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s); > > """,row) > > Should be next - the processed data - not row - the raw data. > > You still didn't show the actual error message. After the traceback > there should be an error. > > Kent > -- Spencer Parker _______________________________________________________ "if you can't go to heaven, may you at least die in Ireland." _______________________________________________________ -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080321/5c57e73c/attachment.htm From inthefridge at gmail.com Fri Mar 21 20:44:32 2008 From: inthefridge at gmail.com (Spencer Parker) Date: Fri, 21 Mar 2008 13:44:32 -0600 Subject: [Tutor] CSV file processing... In-Reply-To: References: <47E2F664.3030907@tds.net> <47E3F657.9050706@tds.net> <47E40A1D.2060602@tds.net> <47E40DB6.8090603@tds.net> Message-ID: That loop was some weird indentation that was caused when I pasted it...it wasn't suppose to be indented like that... On Fri, Mar 21, 2008 at 1:42 PM, Spencer Parker wrote: > This is all that I get when I run it... > > Traceback (most recent call last): > File "./loadcsv.py", line 23, in ? > co.execute(""" > File "/usr/lib64/python2.4/site-packages/MySQLdb/cursors.py", line 148, > in execute > query = query % db.literal(args) > TypeError: not all arguments converted during string formatting > > > > On Fri, Mar 21, 2008 at 1:34 PM, Kent Johnson wrote: > > > Spencer Parker wrote: > > > I posted it in a previous message on the list...but here it is... > > > > Looks new to me... > > > > > > #!/usr/bin/python > > > > > > import MySQLdb > > > import csv > > > import sys > > > > > > try: > > > db = MySQLdb.connect (host = "localhost",user = "root",passwd = > > > "Ch33s3Monk3y",db = "xenstats") > > > except MySQLdb.Error, e: > > > print "Error %d: %s" % (e.args[0], e.args[1]) > > > sys.exit (1) > > > > > > try: > > > co = db.cursor() > > > csv_data = csv.reader(file('output.txt','r')) > > > headers = csv_data.next() > > > row = csv_data.next() > > > prefix = row[:20] > > > for i in range(20, len(row), 7): > > > next = prefix + row[i:i+7] > > > > > > for row in csv_data: print next > > > > Why do you have this loop? You only want to process one row, right? > > > > > co.execute(""" > > > INSERT INTO stats VALUES > > > > > (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s); > > > """,row) > > > > Should be next - the processed data - not row - the raw data. > > > > You still didn't show the actual error message. After the traceback > > there should be an error. > > > > Kent > > > > > > -- > Spencer Parker > _______________________________________________________ > > "if you can't go to heaven, may you at least die in Ireland." > > _______________________________________________________ > -- Spencer Parker _______________________________________________________ "if you can't go to heaven, may you at least die in Ireland." _______________________________________________________ -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080321/1b090191/attachment.htm From inthefridge at gmail.com Fri Mar 21 20:50:37 2008 From: inthefridge at gmail.com (Spencer Parker) Date: Fri, 21 Mar 2008 13:50:37 -0600 Subject: [Tutor] CSV file processing... In-Reply-To: References: <47E2F664.3030907@tds.net> <47E3F657.9050706@tds.net> <47E40A1D.2060602@tds.net> <47E40DB6.8090603@tds.net> Message-ID: I took that loop out...I had that in from something else and forgot to take it out...I took it out and it still does the same error. On Fri, Mar 21, 2008 at 1:44 PM, Spencer Parker wrote: > That loop was some weird indentation that was caused when I pasted it...it > wasn't suppose to be indented like that... > > > On Fri, Mar 21, 2008 at 1:42 PM, Spencer Parker > wrote: > > > This is all that I get when I run it... > > > > Traceback (most recent call last): > > File "./loadcsv.py", line 23, in ? > > co.execute(""" > > File "/usr/lib64/python2.4/site-packages/MySQLdb/cursors.py", line > > 148, in execute > > query = query % db.literal(args) > > TypeError: not all arguments converted during string formatting > > > > > > > > On Fri, Mar 21, 2008 at 1:34 PM, Kent Johnson wrote: > > > > > Spencer Parker wrote: > > > > I posted it in a previous message on the list...but here it is... > > > > > > Looks new to me... > > > > > > > > #!/usr/bin/python > > > > > > > > import MySQLdb > > > > import csv > > > > import sys > > > > > > > > try: > > > > db = MySQLdb.connect (host = "localhost",user = "root",passwd = > > > > "Ch33s3Monk3y",db = "xenstats") > > > > except MySQLdb.Error, e: > > > > print "Error %d: %s" % (e.args[0], e.args[1]) > > > > sys.exit (1) > > > > > > > > try: > > > > co = db.cursor() > > > > csv_data = csv.reader(file('output.txt','r')) > > > > headers = csv_data.next() > > > > row = csv_data.next() > > > > prefix = row[:20] > > > > for i in range(20, len(row), 7): > > > > next = prefix + row[i:i+7] > > > > > > > > for row in csv_data: print next > > > > > > Why do you have this loop? You only want to process one row, right? > > > > > > > co.execute(""" > > > > INSERT INTO stats VALUES > > > > > > > (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s); > > > > """,row) > > > > > > Should be next - the processed data - not row - the raw data. > > > > > > You still didn't show the actual error message. After the traceback > > > there should be an error. > > > > > > Kent > > > > > > > > > > > -- > > Spencer Parker > > _______________________________________________________ > > > > "if you can't go to heaven, may you at least die in Ireland." > > > > _______________________________________________________ > > > > > > -- > Spencer Parker > _______________________________________________________ > > "if you can't go to heaven, may you at least die in Ireland." > > _______________________________________________________ > -- Spencer Parker _______________________________________________________ "if you can't go to heaven, may you at least die in Ireland." _______________________________________________________ -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080321/755c10bc/attachment.htm From marc.tompkins at gmail.com Fri Mar 21 20:55:36 2008 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Fri, 21 Mar 2008 12:55:36 -0700 Subject: [Tutor] CSV file processing... In-Reply-To: References: <47E2F664.3030907@tds.net> <47E3F657.9050706@tds.net> <47E40A1D.2060602@tds.net> <47E40DB6.8090603@tds.net> Message-ID: <40af687b0803211255g4e9a9637u11d38900b0cab406@mail.gmail.com> On Fri, Mar 21, 2008 at 12:42 PM, Spencer Parker wrote: > This is all that I get when I run it... > > Traceback (most recent call last): > File "./loadcsv.py", line 23, in ? > co.execute(""" > File "/usr/lib64/python2.4/site-packages/MySQLdb/cursors.py", line 148, > in execute > query = query % db.literal(args) > TypeError: not all arguments converted during string formatting > > co.execute(""" > > > INSERT INTO stats VALUES > > > > > (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s); > > > """,row) > > > You have triple quotes around your SQL. That means that "implied" line breaks become real. It won't look as nice, but take the line breaks out and I think it ought to work. Just my $.02... -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080321/8b0ee68b/attachment.htm From kent37 at tds.net Fri Mar 21 20:55:45 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 21 Mar 2008 15:55:45 -0400 Subject: [Tutor] CSV file processing... In-Reply-To: References: <47E2F664.3030907@tds.net> <47E3F657.9050706@tds.net> <47E40A1D.2060602@tds.net> <47E40DB6.8090603@tds.net> Message-ID: <47E412C1.9020108@tds.net> Spencer Parker wrote: > That loop was some weird indentation that was caused when I pasted > it...it wasn't suppose to be indented like that... Why is it there at all? The loop with range() is the one that is generating the data you want to store. > This is all that I get when I run it... > TypeError: not all arguments converted during string formatting You didn't include that line before. That means you have more arguments (the length of row) than you have %s placeholders. Kent From marc.tompkins at gmail.com Fri Mar 21 20:58:43 2008 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Fri, 21 Mar 2008 12:58:43 -0700 Subject: [Tutor] CSV file processing... In-Reply-To: <40af687b0803211255g4e9a9637u11d38900b0cab406@mail.gmail.com> References: <47E2F664.3030907@tds.net> <47E3F657.9050706@tds.net> <47E40A1D.2060602@tds.net> <47E40DB6.8090603@tds.net> <40af687b0803211255g4e9a9637u11d38900b0cab406@mail.gmail.com> Message-ID: <40af687b0803211258h37a17c73g830fcd4d4d670cbf@mail.gmail.com> Sorry... no, it still shouldn't work... maybe like so: co.execute('''INSERT INTO stats VALUES("%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s" % row''') > You have triple quotes around your SQL. That means that "implied" line > breaks become real. It won't look as nice, but take the line breaks out and > I think it ought to work. > > Just my $.02... > > -- > www.fsrtechnologies.com -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080321/970ec258/attachment.htm From inthefridge at gmail.com Fri Mar 21 21:37:26 2008 From: inthefridge at gmail.com (Spencer Parker) Date: Fri, 21 Mar 2008 14:37:26 -0600 Subject: [Tutor] CSV file processing... In-Reply-To: <40af687b0803211258h37a17c73g830fcd4d4d670cbf@mail.gmail.com> References: <47E3F657.9050706@tds.net> <47E40A1D.2060602@tds.net> <47E40DB6.8090603@tds.net> <40af687b0803211255g4e9a9637u11d38900b0cab406@mail.gmail.com> <40af687b0803211258h37a17c73g830fcd4d4d670cbf@mail.gmail.com> Message-ID: Okay...so this is what I have now.. co.execute(""" File "/usr/lib64/python2.4/site-packages/MySQLdb/cursors.py", line 148, in execute query = query % db.literal(args) TypeError: not enough arguments for format string [sjpark at pxe ~]$ vim loadcsv.py [sjpark at pxe ~]$ vim output.txt [sjpark at pxe ~]$ ./loadcsv.py Traceback (most recent call last): File "./loadcsv.py", line 22, in ? co.execute(""" File "/usr/lib64/python2.4/site-packages/MySQLdb/cursors.py", line 148, in execute query = query % db.literal(args) TypeError: not enough arguments for format string [sjpark at pxe ~]$ vim output.txt [sjpark at pxe ~]$ ./loadcsv.py Traceback (most recent call last): File "./loadcsv.py", line 22, in ? co.execute(""" File "/usr/lib64/python2.4/site-packages/MySQLdb/cursors.py", line 148, in execute query = query % db.literal(args) TypeError: not enough arguments for format string [sjpark at pxe ~]$ vim loadcsv.py [sjpark at pxe ~]$ ./loadcsv.py Traceback (most recent call last): File "./loadcsv.py", line 22, in ? co.execute(""" File "/usr/lib64/python2.4/site-packages/MySQLdb/cursors.py", line 148, in execute query = query % db.literal(args) TypeError: not enough arguments for format string [sjpark at pxe ~]$ vim loadcsv.py [sjpark at pxe ~]$ ./loadcsv.py Traceback (most recent call last): File "./loadcsv.py", line 22, in ? co.execute(""" File "/usr/lib64/python2.4/site-packages/MySQLdb/cursors.py", line 148, in execute query = query % db.literal(args) TypeError: not enough arguments for format string [sjpark at pxe ~]$ vim loadcsv.py [sjpark at pxe ~]$ ./loadcsv.py Traceback (most recent call last): File "./loadcsv.py", line 22, in ? co.execute(""" File "/usr/lib64/python2.4/site-packages/MySQLdb/cursors.py", line 148, in execute query = query % db.literal(args) TypeError: not enough arguments for format string [sjpark at pxe ~]$ vim loadcsv.py [sjpark at pxe ~]$ ./loadcsv.py Traceback (most recent call last): File "./loadcsv.py", line 22, in ? co.execute(""" File "/usr/lib64/python2.4/site-packages/MySQLdb/cursors.py", line 163, in execute self.errorhandler(self, exc, value) File "/usr/lib64/python2.4/site-packages/MySQLdb/connections.py", line 35, in defaulterrorhandler raise errorclass, errorvalue _mysql_exceptions.OperationalError: (1136, "Column count doesn't match value count at row 1") [sjpark at pxe ~]$ vim loadcsv.py [sjpark at pxe ~]$ ./loadcsv.py Traceback (most recent call last): File "./loadcsv.py", line 22, in ? co.execute(""" File "/usr/lib64/python2.4/site-packages/MySQLdb/cursors.py", line 163, in execute self.errorhandler(self, exc, value) File "/usr/lib64/python2.4/site-packages/MySQLdb/connections.py", line 35, in defaulterrorhandler raise errorclass, errorvalue _mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ')' at line 1") [sjpark at pxe ~]$ vim output.txt [sjpark at pxe ~]$ ./loadcsv.py Traceback (most recent call last): File "./loadcsv.py", line 22, in ? co.execute(""" File "/usr/lib64/python2.4/site-packages/MySQLdb/cursors.py", line 163, in execute self.errorhandler(self, exc, value) File "/usr/lib64/python2.4/site-packages/MySQLdb/connections.py", line 35, in defaulterrorhandler raise errorclass, errorvalue _mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ')' at line 1") [sjpark at pxe ~]$ vim output.txt [sjpark at pxe ~]$ vim loadcsv.py [sjpark at pxe ~]$ ./loadcsv.py Traceback (most recent call last): File "./loadcsv.py", line 22, in ? co.execute(""" File "/usr/lib64/python2.4/site-packages/MySQLdb/cursors.py", line 163, in execute self.errorhandler(self, exc, value) File "/usr/lib64/python2.4/site-packages/MySQLdb/connections.py", line 35, in defaulterrorhandler raise errorclass, errorvalue _mysql_exceptions.OperationalError: (1136, "Column count doesn't match value count at row 1") [sjpark at pxe ~]$ vim loadcsv.py [sjpark at pxe ~]$ ./loadcsv.py Traceback (most recent call last): File "./loadcsv.py", line 22, in ? co.execute(""" File "/usr/lib64/python2.4/site-packages/MySQLdb/cursors.py", line 148, in execute query = query % db.literal(args) TypeError: not enough arguments for format string [sjpark at pxe ~]$ vim loadcsv.py [sjpark at pxe ~]$ ./loadcsv.py File "./loadcsv.py", line 30 co.close() ^ SyntaxError: invalid syntax [sjpark at pxe ~]$ vim loadcsv.py [sjpark at pxe ~]$ ./loadcsv.py Traceback (most recent call last): File "./loadcsv.py", line 25, in ? co.execute(''' File "/usr/lib64/python2.4/site-packages/MySQLdb/cursors.py", line 163, in execute self.errorhandler(self, exc, value) File "/usr/lib64/python2.4/site-packages/MySQLdb/connections.py", line 35, in defaulterrorhandler raise errorclass, errorvalue _mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1") [sjpark at pxe ~]$ vim loadcsv.py [sjpark at pxe ~]$ ./loadcsv.py Traceback (most recent call last): File "./loadcsv.py", line 25, in ? co.execute(""" File "/usr/lib64/python2.4/site-packages/MySQLdb/cursors.py", line 163, in execute self.errorhandler(self, exc, value) File "/usr/lib64/python2.4/site-packages/MySQLdb/connections.py", line 35, in defaulterrorhandler raise errorclass, errorvalue _mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1") [sjpark at pxe ~]$ vim loadcsv.py [sjpark at pxe ~]$ ./loadcsv.py Traceback (most recent call last): File "./loadcsv.py", line 25, in ? co.execute(""" File "/usr/lib64/python2.4/site-packages/MySQLdb/cursors.py", line 163, in execute self.errorhandler(self, exc, value) File "/usr/lib64/python2.4/site-packages/MySQLdb/connections.py", line 35, in defaulterrorhandler raise errorclass, errorvalue _mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1") [sjpark at pxe ~]$ vim loadcsv.py [sjpark at pxe ~]$ ./loadcsv.py Traceback (most recent call last): File "./loadcsv.py", line 25, in ? co.execute(""" File "/usr/lib64/python2.4/site-packages/MySQLdb/cursors.py", line 163, in execute self.errorhandler(self, exc, value) File "/usr/lib64/python2.4/site-packages/MySQLdb/connections.py", line 35, in defaulterrorhandler raise errorclass, errorvalue _mysql_exceptions.OperationalError: (1136, "Column count doesn't match value count at row 1") [sjpark at pxe ~]$ vim loadcsv.py [sjpark at pxe ~]$ ./loadcsv.py Traceback (most recent call last): File "./loadcsv.py", line 25, in ? co.execute(""" File "/usr/lib64/python2.4/site-packages/MySQLdb/cursors.py", line 148, in execute query = query % db.literal(args) TypeError: not enough arguments for format string [sjpark at pxe ~]$ vim loadcsv.py [sjpark at pxe ~]$ ./loadcsv.py Traceback (most recent call last): File "./loadcsv.py", line 25, in ? co.execute(""" File "/usr/lib64/python2.4/site-packages/MySQLdb/cursors.py", line 148, in execute query = query % db.literal(args) TypeError: not enough arguments for format string [sjpark at pxe ~]$ python Python 2.4.3 (#1, Mar 14 2007, 19:01:42) [GCC 4.1.1 20070105 (Red Hat 4.1.1-52)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> 17 +8 25 >>> [sjpark at pxe ~]$ vim loadcsv.py [sjpark at pxe ~]$ python Python 2.4.3 (#1, Mar 14 2007, 19:01:42) [GCC 4.1.1 20070105 (Red Hat 4.1.1-52)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> [sjpark at pxe ~]$ ./loadcsv.py Traceback (most recent call last): File "./loadcsv.py", line 25, in ? co.execute(""" File "/usr/lib64/python2.4/site-packages/MySQLdb/cursors.py", line 163, in execute self.errorhandler(self, exc, value) File "/usr/lib64/python2.4/site-packages/MySQLdb/connections.py", line 35, in defaulterrorhandler raise errorclass, errorvalue _mysql_exceptions.OperationalError: (1136, "Column count doesn't match value count at row 1") [sjpark at pxe ~]$ vim loadcsv.py [sjpark at pxe ~]$ ./loadcsv.py Traceback (most recent call last): File "./loadcsv.py", line 25, in ? co.execute(""" File "/usr/lib64/python2.4/site-packages/MySQLdb/cursors.py", line 163, in execute self.errorhandler(self, exc, value) File "/usr/lib64/python2.4/site-packages/MySQLdb/connections.py", line 35, in defaulterrorhandler raise errorclass, errorvalue _mysql_exceptions.OperationalError: (1136, "Column count doesn't match value count at row 1") [sjpark at pxe ~]$ vim loadcsv.py [sjpark at pxe ~]$ ./loadcsv.py Traceback (most recent call last): File "./loadcsv.py", line 25, in ? co.execute(""" File "/usr/lib64/python2.4/site-packages/MySQLdb/cursors.py", line 163, in execute self.errorhandler(self, exc, value) File "/usr/lib64/python2.4/site-packages/MySQLdb/connections.py", line 35, in defaulterrorhandler raise errorclass, errorvalue _mysql_exceptions.OperationalError: (1136, "Column count doesn't match value count at row 1") [sjpark at pxe ~]$ vim loadcsv.py [sjpark at pxe ~]$ ./loadcsv.py Traceback (most recent call last): File "./loadcsv.py", line 25, in ? co.execute(''' File "/usr/lib64/python2.4/site-packages/MySQLdb/cursors.py", line 163, in execute self.errorhandler(self, exc, value) File "/usr/lib64/python2.4/site-packages/MySQLdb/connections.py", line 35, in defaulterrorhandler raise errorclass, errorvalue _mysql_exceptions.OperationalError: (1136, "Column count doesn't match value count at row 1") [sjpark at pxe ~]$ vim loadcsv.py [sjpark at pxe ~]$ ./loadcsv.py Traceback (most recent call last): File "./loadcsv.py", line 25, in ? co.execute(''' File "/usr/lib64/python2.4/site-packages/MySQLdb/cursors.py", line 163, in execute self.errorhandler(self, exc, value) File "/usr/lib64/python2.4/site-packages/MySQLdb/connections.py", line 35, in defaulterrorhandler raise errorclass, errorvalue _mysql_exceptions.OperationalError: (1136, "Column count doesn't match value count at row 1") [sjpark at pxe ~]$ vim loadcsv.py [sjpark at pxe ~]$ ./loadcsv.py Traceback (most recent call last): File "./loadcsv.py", line 25, in ? co.execute(''' File "/usr/lib64/python2.4/site-packages/MySQLdb/cursors.py", line 163, in execute self.errorhandler(self, exc, value) File "/usr/lib64/python2.4/site-packages/MySQLdb/connections.py", line 35, in defaulterrorhandler raise errorclass, errorvalue _mysql_exceptions.OperationalError: (1136, "Column count doesn't match value count at row 1") [sjpark at pxe ~]$ vim loadcsv.py [sjpark at pxe ~]$ ./loadcsv.py Traceback (most recent call last): File "./loadcsv.py", line 25, in ? co.execute(''' File "/usr/lib64/python2.4/site-packages/MySQLdb/cursors.py", line 163, in execute self.errorhandler(self, exc, value) File "/usr/lib64/python2.4/site-packages/MySQLdb/connections.py", line 35, in defaulterrorhandler raise errorclass, errorvalue _mysql_exceptions.OperationalError: (1136, "Column count doesn't match value count at row 1") [sjpark at pxe ~]$ vim loadcsv.py [sjpark at pxe ~]$ vim loadcsv.py #!/usr/bin/python import MySQLdb import csv import sys try: db = MySQLdb.connect (host = "localhost",user = "root",passwd = "Ch33s3Monk3y",db = "xenstats") except MySQLdb.Error, e: print "Error %d: %s" % (e.args[0], e.args[1]) sys.exit (1) co = db.cursor() csv_data = csv.reader(file('output.txt','r')) headers = csv_data.next() row = csv_data.next() prefix = row[:17] for i in range(17, len(row), 8): next = prefix + row[i:i+8] co.execute(''' INSERT INTO stats VALUES("%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s"); % row''') co.close() db.commit() db.close() Now I get this error: File "./loadcsv.py", line 25, in ? co.execute(''' File "/usr/lib64/python2.4/site-packages/MySQLdb/cursors.py", line 163, in execute self.errorhandler(self, exc, value) File "/usr/lib64/python2.4/site-packages/MySQLdb/connections.py", line 35, in defaulterrorhandler raise errorclass, errorvalue _mysql_exceptions.OperationalError: (1136, "Column count doesn't match value count at row 1") I have a database that has 26 columns in it...MySQL...my data should only be 25. I have one that auto increments a unique ID for. On Fri, Mar 21, 2008 at 1:58 PM, Marc Tompkins wrote: > Sorry... no, it still shouldn't work... > maybe like so: > > co.execute('''INSERT INTO stats > VALUES("%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s" > % row''') > > > > You have triple quotes around your SQL. That means that "implied" line > > breaks become real. It won't look as nice, but take the line breaks out and > > I think it ought to work. > > > > Just my $.02... > > > > -- > > www.fsrtechnologies.com > > > > > -- > www.fsrtechnologies.com -- Spencer Parker _______________________________________________________ "if you can't go to heaven, may you at least die in Ireland." _______________________________________________________ -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080321/0901c26a/attachment-0001.htm From sli1que at yahoo.com Fri Mar 21 21:49:54 2008 From: sli1que at yahoo.com (Eric Walker) Date: Fri, 21 Mar 2008 13:49:54 -0700 (PDT) Subject: [Tutor] Python Grammer Message-ID: <259434.32432.qm@web65401.mail.ac4.yahoo.com> Did anyone respond to my Python Grammer Question? Thanks Eric.... ____________________________________________________________________________________ Be a better friend, newshound, and know-it-all with Yahoo! Mobile. Try it now. http://mobile.yahoo.com/;_ylt=Ahu06i62sR8HDtDypao8Wcj9tAcJ From kent37 at tds.net Fri Mar 21 22:44:33 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 21 Mar 2008 17:44:33 -0400 Subject: [Tutor] CSV file processing... In-Reply-To: References: <47E3F657.9050706@tds.net> <47E40A1D.2060602@tds.net> <47E40DB6.8090603@tds.net> <40af687b0803211255g4e9a9637u11d38900b0cab406@mail.gmail.com> <40af687b0803211258h37a17c73g830fcd4d4d670cbf@mail.gmail.com> Message-ID: <47E42C41.6050903@tds.net> Spencer Parker wrote: > Okay...so this is what I have now.. Do you really expect us to read through this? If you can't be bothered to compose a decent question and read the answers then neither can I. Kent From kent37 at tds.net Fri Mar 21 23:06:03 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 21 Mar 2008 18:06:03 -0400 Subject: [Tutor] CSV file processing... In-Reply-To: <40af687b0803211258h37a17c73g830fcd4d4d670cbf@mail.gmail.com> References: <47E2F664.3030907@tds.net> <47E3F657.9050706@tds.net> <47E40A1D.2060602@tds.net> <47E40DB6.8090603@tds.net> <40af687b0803211255g4e9a9637u11d38900b0cab406@mail.gmail.com> <40af687b0803211258h37a17c73g830fcd4d4d670cbf@mail.gmail.com> Message-ID: <47E4314B.7070203@tds.net> Marc Tompkins wrote: > Sorry... no, it still shouldn't work... > maybe like so: > co.execute('''INSERT INTO stats > VALUES("%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s" > % row''') > > > You have triple quotes around your SQL. That means that "implied" > line breaks become real. It won't look as nice, but take the line > breaks out and I think it ought to work. Wrong on both counts. The triple quotes and line breaks are fine and row should be passed as a separate argument as it was. Kent From dineshbvadhia at hotmail.com Fri Mar 21 23:37:17 2008 From: dineshbvadhia at hotmail.com (Dinesh B Vadhia) Date: Fri, 21 Mar 2008 15:37:17 -0700 Subject: [Tutor] Python to C++ Message-ID: Thank-you for all the suggestions for converting to C/C++ which will be followed up. Can we interface Python to a C++ library and if so how? Dinesh ................................................................................ Date: Thu, 20 Mar 2008 17:21:52 -0000 From: "Alan Gauld" Subject: Re: [Tutor] Python to C++ To: tutor at python.org Message-ID: Content-Type: text/plain; format=flowed; charset="iso-8859-1"; reply-type=original "Dinesh B Vadhia" wrote > Say because of performance, you might want to re-write/convert > Python code to C++. What is the best way (or best practice) > to do this wrt the tools available? It may be obvious but its worth noting that optimised Python may be faster than a badly written C port. So first make sure you have squeezed the best performance out of Python. Secondly only rewrite the bits that need it so use the profiler to identify the bottlenecks in your Python code and move those to a separate module to reduce conversion effort. After that the advice already given re pyrex/psycho etc is all good. You might also find SWIG a useful alternative if you decide to rewrite the slow functions by hand. SWIG will help wrap those functions so that the remaining Python code can access them. Alan G. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080321/96bf0732/attachment.htm From sli1que at yahoo.com Fri Mar 21 23:40:02 2008 From: sli1que at yahoo.com (Eric Walker) Date: Fri, 21 Mar 2008 15:40:02 -0700 (PDT) Subject: [Tutor] Python Grammer Message-ID: <351585.89547.qm@web65416.mail.ac4.yahoo.com> Ok, I found the responses, sorry.. I have been reading the book "Text Processing in PYTHON" by David Mertz. I have some text that I have to parse. I want to use grammers. I can't seem to understand how the syntax works. something like: hello := Thanks in Advance Eric ____________________________________________________________________________________ Be a better friend, newshound, and know-it-all with Yahoo! Mobile. Try it now. http://mobile.yahoo.com/;_ylt=Ahu06i62sR8HDtDypao8Wcj9tAcJ _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor ____________________________________________________________________________________ Never miss a thing. Make Yahoo your home page. http://www.yahoo.com/r/hs From alan.gauld at btinternet.com Sat Mar 22 00:24:56 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 21 Mar 2008 23:24:56 -0000 Subject: [Tutor] More Converter References: <245E2DCC-0118-1000-A22A-BD839F694284-Webmail-10021@mac.com> Message-ID: wrote > Original = raw_input("Insert inches, feet ") > To = raw_input("Insert inches, feet ") > Variable = int(raw_input("Insert Amount to Convert ")) Up to here is OK. > if Original == raw_input(feet) and To == raw_input(inches): But here you get a bit confused. raw_input is used to get input from the user as a string. You have already stored the input so now you want to compare that input to a literal value so you don't need to use raw_input here, just compare to the actual string: if Original == "feet" and To == "inches": print Variable*12 And that will work. However to make your program easier for the user - less typing and less chance of error you might like to present a menu so that the user only has to type one number or letter Unit_Menu = """ 1) Yards 2) Feet 3) Inches Select a unit(1-3)""" >From = raw_input(Unit_Menu) To = raw_input(Unit_Menu) if From == "2" and To == "3": print From * 12 > I always get this error message though > > Traceback (most recent call last): > File "/Users/donaldlucas/Documents/Python Scripts/Converter.py", > line 5, in > if Original == raw_input(feet) and To == raw_input(inches): > NameError: name 'feet' is not defined raw_input expects a string or a string variable. Without quotes Python expects feet to be a variable name but no suh variable has been defined. But as above you don;t need raw_input, just compare to the literal string "feet". HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Sat Mar 22 00:27:59 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 21 Mar 2008 23:27:59 -0000 Subject: [Tutor] Python Grammer References: <351585.89547.qm@web65416.mail.ac4.yahoo.com> Message-ID: "Eric Walker" wrote . > I have some text that I have to parse. I want to use grammers. > I can't seem to understand how the syntax works. > something like: > hello := OK, Thats somethjing called Backaus Naur Format (or BNF), try Googling for it - or Wikipedia - and you will get lots of examples. It's a format for defining grammars (such as programming languages.) ISTR it was invented to describe Algol which was the great grand-daddy of C/C++/Java etc. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From hunter92383 at gmail.com Sat Mar 22 01:01:23 2008 From: hunter92383 at gmail.com (elis aeris) Date: Fri, 21 Mar 2008 17:01:23 -0700 Subject: [Tutor] returning two values Message-ID: <674d5ce60803211701h57ae5954lac043bdbec931ca5@mail.gmail.com> is it possible to return two values? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080321/efd4955b/attachment.htm From hunter92383 at gmail.com Sat Mar 22 01:03:46 2008 From: hunter92383 at gmail.com (elis aeris) Date: Fri, 21 Mar 2008 17:03:46 -0700 Subject: [Tutor] list Message-ID: <674d5ce60803211703t322b8c13wa2f3488c273bf91e@mail.gmail.com> how do I create an empy int array of 10? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080321/91f763d7/attachment.htm From hunter92383 at gmail.com Sat Mar 22 01:04:21 2008 From: hunter92383 at gmail.com (elis aeris) Date: Fri, 21 Mar 2008 17:04:21 -0700 Subject: [Tutor] append string Message-ID: <674d5ce60803211704q3e86d2aakcdc85ba7e0c53ced@mail.gmail.com> how do I append to the end of strings? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080321/2e5d6aeb/attachment-0001.htm From hunter92383 at gmail.com Sat Mar 22 01:05:10 2008 From: hunter92383 at gmail.com (elis aeris) Date: Fri, 21 Mar 2008 17:05:10 -0700 Subject: [Tutor] int to string Message-ID: <674d5ce60803211705q1ef85b0en6529e10d7b80493@mail.gmail.com> how do I convert int to string? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080321/d08dda0b/attachment.htm From gregor.lingl at aon.at Sat Mar 22 01:11:02 2008 From: gregor.lingl at aon.at (Gregor Lingl) Date: Sat, 22 Mar 2008 01:11:02 +0100 Subject: [Tutor] returning two values In-Reply-To: <674d5ce60803211701h57ae5954lac043bdbec931ca5@mail.gmail.com> References: <674d5ce60803211701h57ae5954lac043bdbec931ca5@mail.gmail.com> Message-ID: <47E44E96.4020803@aon.at> elis aeris schrieb: > is it possible to return two values? > Yes: >>> def return2(): return "this", "that" >>> return2() ('this', 'that') >>> a,b=return2() >>> a 'this' >>> b 'that' >>> Regards, Gregor > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080322/f82b3df7/attachment.htm From steve at alchemy.com Sat Mar 22 01:11:33 2008 From: steve at alchemy.com (Steve Willoughby) Date: Fri, 21 Mar 2008 17:11:33 -0700 Subject: [Tutor] returning two values In-Reply-To: <674d5ce60803211701h57ae5954lac043bdbec931ca5@mail.gmail.com> References: <674d5ce60803211701h57ae5954lac043bdbec931ca5@mail.gmail.com> Message-ID: <47E44EB5.9050107@alchemy.com> elis aeris wrote: > is it possible to return two values? Yes and no. You can return "a" value, but that value may itself be a tuple of values. Or a list, dictionary or other kind of object. > how do I create an empy int array of 10? If an int array has 10 things in it, it's not empty. You don't need to pre-declare the size of arrays (actually we call them tuples and lists) in Python at all. To make an empty list, just use [] like this: a = [] You can then fill it with whatever you like. Also there is no notion of "int array". Each element may be of a different type. > how do I append to the end of strings? a = "Hello" a += " world" a now contains "Hello world" > how do I convert int to string? You could use the str() constructor: str(12) --> "12" Or you could use string formatting: "%d" % 12 --> "12" > > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From hunter92383 at gmail.com Sat Mar 22 01:11:50 2008 From: hunter92383 at gmail.com (elis aeris) Date: Fri, 21 Mar 2008 17:11:50 -0700 Subject: [Tutor] returning two values In-Reply-To: <47E44E96.4020803@aon.at> References: <674d5ce60803211701h57ae5954lac043bdbec931ca5@mail.gmail.com> <47E44E96.4020803@aon.at> Message-ID: <674d5ce60803211711q72b52e2aw68d97aa48d65efe8@mail.gmail.com> oh this is brillant, i LOVE python thank for replying On Fri, Mar 21, 2008 at 5:11 PM, Gregor Lingl wrote: > elis aeris schrieb: > > is it possible to return two values? > > Yes: > >>> def return2(): > return "this", "that" > > >>> return2() > ('this', 'that') > >>> a,b=return2() > >>> a > 'this' > >>> b > 'that' > >>> > Regards, > Gregor > > ------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.orghttp://mail.python.org/mailman/listinfo/tutor > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080321/a2bee429/attachment.htm From hunter92383 at gmail.com Sat Mar 22 01:12:41 2008 From: hunter92383 at gmail.com (elis aeris) Date: Fri, 21 Mar 2008 17:12:41 -0700 Subject: [Tutor] returning two values In-Reply-To: <674d5ce60803211711q72b52e2aw68d97aa48d65efe8@mail.gmail.com> References: <674d5ce60803211701h57ae5954lac043bdbec931ca5@mail.gmail.com> <47E44E96.4020803@aon.at> <674d5ce60803211711q72b52e2aw68d97aa48d65efe8@mail.gmail.com> Message-ID: <674d5ce60803211712l4b41ad97l616b6c18a948c7c5@mail.gmail.com> so just str(int) got it, thanks ! On Fri, Mar 21, 2008 at 5:11 PM, elis aeris wrote: > > oh this is brillant, i LOVE python > > thank for replying > > > On Fri, Mar 21, 2008 at 5:11 PM, Gregor Lingl wrote: > > > elis aeris schrieb: > > > > is it possible to return two values? > > > > Yes: > > >>> def return2(): > > return "this", "that" > > > > >>> return2() > > ('this', 'that') > > >>> a,b=return2() > > >>> a > > 'this' > > >>> b > > 'that' > > >>> > > Regards, > > Gregor > > > > ------------------------------ > > > > _______________________________________________ > > Tutor maillist - Tutor at python.orghttp://mail.python.org/mailman/listinfo/tutor > > > > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080321/be65f1de/attachment.htm From andreas at kostyrka.org Sat Mar 22 01:29:01 2008 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Sat, 22 Mar 2008 01:29:01 +0100 Subject: [Tutor] list In-Reply-To: <674d5ce60803211703t322b8c13wa2f3488c273bf91e@mail.gmail.com> References: <674d5ce60803211703t322b8c13wa2f3488c273bf91e@mail.gmail.com> Message-ID: <1206145741.11011.6.camel@localhost> Empty? array = [] If you want to assign 10 "None", that would be: array = [None] * 10 Andreas Am Freitag, den 21.03.2008, 17:03 -0700 schrieb elis aeris: > how do I create an empy int array of 10? > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Dies ist ein digital signierter Nachrichtenteil Url : http://mail.python.org/pipermail/tutor/attachments/20080322/b658df4a/attachment.pgp From hunter92383 at gmail.com Sat Mar 22 01:29:46 2008 From: hunter92383 at gmail.com (elis aeris) Date: Fri, 21 Mar 2008 17:29:46 -0700 Subject: [Tutor] list In-Reply-To: <1206145741.11011.6.camel@localhost> References: <674d5ce60803211703t322b8c13wa2f3488c273bf91e@mail.gmail.com> <1206145741.11011.6.camel@localhost> Message-ID: <674d5ce60803211729l6e0deb90m7510ee2be779d439@mail.gmail.com> arra = [0] * 10 ? On Fri, Mar 21, 2008 at 5:29 PM, Andreas Kostyrka wrote: > Empty? > > array = [] > > If you want to assign 10 "None", that would be: > > array = [None] * 10 > > Andreas > > Am Freitag, den 21.03.2008, 17:03 -0700 schrieb elis aeris: > > how do I create an empy int array of 10? > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080321/934ea92f/attachment.htm From steve at alchemy.com Sat Mar 22 01:41:46 2008 From: steve at alchemy.com (Steve Willoughby) Date: Fri, 21 Mar 2008 17:41:46 -0700 Subject: [Tutor] list In-Reply-To: <674d5ce60803211729l6e0deb90m7510ee2be779d439@mail.gmail.com> References: <674d5ce60803211703t322b8c13wa2f3488c273bf91e@mail.gmail.com> <1206145741.11011.6.camel@localhost> <674d5ce60803211729l6e0deb90m7510ee2be779d439@mail.gmail.com> Message-ID: <47E455CA.5020109@alchemy.com> elis aeris wrote: > arra = [0] * 10 ? If you want a list of ten zeroes, yes. A couple of suggestions: Find a tutorial introduction to Python such as those on python.org, or google for "dive into python", and go through the examples in there. Also, use the interactive Python interpreter to try out things like this. You'll probably make much faster progress that way compared to asking such fine-grained questions here. This is not really a forum for a long conversational sort of interaction or complete step-by-step tutorials on Python. > > On Fri, Mar 21, 2008 at 5:29 PM, Andreas Kostyrka > wrote: > >> Empty? >> >> array = [] >> >> If you want to assign 10 "None", that would be: >> >> array = [None] * 10 >> >> Andreas >> >> Am Freitag, den 21.03.2008, 17:03 -0700 schrieb elis aeris: >>> how do I create an empy int array of 10? >>> _______________________________________________ >>> Tutor maillist - Tutor at python.org >>> http://mail.python.org/mailman/listinfo/tutor > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From tktucker at gmail.com Sat Mar 22 02:39:58 2008 From: tktucker at gmail.com (Tom Tucker) Date: Fri, 21 Mar 2008 21:39:58 -0400 Subject: [Tutor] int to string In-Reply-To: <674d5ce60803211705q1ef85b0en6529e10d7b80493@mail.gmail.com> References: <674d5ce60803211705q1ef85b0en6529e10d7b80493@mail.gmail.com> Message-ID: <2a278ffe0803211839o6099930cm12d62f0fa4e67c4f@mail.gmail.com> >>> y = 3 >>> type(y) >>> x = str(y) >>> type(x) On Fri, Mar 21, 2008 at 8:05 PM, elis aeris wrote: > how do I convert int to string? > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080321/5a1d481a/attachment-0001.htm From tktucker at gmail.com Sat Mar 22 02:44:23 2008 From: tktucker at gmail.com (Tom Tucker) Date: Fri, 21 Mar 2008 21:44:23 -0400 Subject: [Tutor] append string In-Reply-To: <674d5ce60803211704q3e86d2aakcdc85ba7e0c53ced@mail.gmail.com> References: <674d5ce60803211704q3e86d2aakcdc85ba7e0c53ced@mail.gmail.com> Message-ID: <2a278ffe0803211844t79df367fp118aa84981415027@mail.gmail.com> Strings are immutable, you can't append to them. How about this.... >>> mystring = 'Elis' >>> mystring.append('Aeris') Traceback (most recent call last): File "", line 1, in AttributeError: 'str' object has no attribute 'append' >>> mystring + ' Aeris' 'Elis Aeris' >>> x = mystring + ' Aeris' >>> print x Elis Aeris On Fri, Mar 21, 2008 at 8:04 PM, elis aeris wrote: > how do I append to the end of strings? > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080321/9e02710b/attachment.htm From eike.welk at gmx.net Sat Mar 22 02:44:54 2008 From: eike.welk at gmx.net (Eike Welk) Date: Sat, 22 Mar 2008 02:44:54 +0100 Subject: [Tutor] Python to C++ In-Reply-To: References: Message-ID: <200803220244.54377.eike.welk@gmx.net> On Friday 21 March 2008 23:37, Dinesh B Vadhia wrote: > Thank-you for all the suggestions for converting to C/C++ which > will be followed up. > > Can we interface Python to a C++ library and if so how? > > Dinesh > If you have only few classes / member functions Boost-Python is a good solution. http://www.boost.org/libs/python/doc/ I heard that SWIG can also generate glue code for C++. http://www.swig.org/Doc1.3/SWIGPlus.html You could also look at Py-QT they have a tool like SWIG (SIP I think), which they use to generate the glue code for the fairly big QT library. Maybe you like it better. http://www.riverbankcomputing.co.uk/pyqt/ From technorapture at gmail.com Sat Mar 22 03:01:12 2008 From: technorapture at gmail.com (Shrutarshi Basu) Date: Fri, 21 Mar 2008 22:01:12 -0400 Subject: [Tutor] Pseudo-functions and dicts Message-ID: <376fbdcf0803211901ubc91bdds35942775aee9d3c6@mail.gmail.com> I have a dictionary (in a module) which contains values of various sensors. I would like a user to be able use to a function syntax to get the sensor values, both as a whole and individually. Currently I have a function for each value who's sole purpose is to look up the corresponding dict value and return. But I don't think this is an elegant way to solve the problem. Is there someway I could define a single function that responds to all of possible function calls? Eg. My dict : sensor = {'sens1': 200, 'sens2': 300} etc my functions: def sens1(): return sensor['sens1'] same for sens2. There are two solutions I've thought about: Have a function that takes in the sensor's name as a string and responds accordingly. (which might be what I'll end up using) I could let the user directly access the dict, but I'm not sure if that is a good idea. My project requires that the user of my module should not have to know about Python's data structures to use the values my module returns. If there is some sort of non-functional dot-separated syntax that I could use, that would be good too. Thanks, Basu -- Embedded Architectures, Systems programming and outrageous ideas -- http://xcomputers.wordpress.com From maseriyer at yahoo.com Sat Mar 22 04:08:32 2008 From: maseriyer at yahoo.com (maser) Date: Fri, 21 Mar 2008 20:08:32 -0700 (PDT) Subject: [Tutor] what is @classmethod and @staticmethod ?? Message-ID: <66208.9916.qm@web50708.mail.re2.yahoo.com> Hi I couldn't find a good resource explaining what @classmethod and @staticmethod are in python and when, how these could be used. If someone could explain what these are, or point me to resources that may help, it is appreciated. Thanks iyer ____________________________________________________________________________________ Be a better friend, newshound, and know-it-all with Yahoo! Mobile. Try it now. http://mobile.yahoo.com/;_ylt=Ahu06i62sR8HDtDypao8Wcj9tAcJ From wackedd at mac.com Sat Mar 22 05:49:18 2008 From: wackedd at mac.com (wackedd at mac.com) Date: Fri, 21 Mar 2008 21:49:18 -0700 Subject: [Tutor] Even More Converter! Message-ID: <34ACA2C9-0118-1000-B5E9-5B67AAE91AB3-Webmail-10010@mac.com> After my last Email received I have been able to successfully create a Converter, currently it only has 6 units, but I will be adding more. My current code is # Converter Unit_Menu=""" 1) Centimeters 2) Inches 3) Feet 4) Yards 5) Miles 6) Millimeter Select a unit(1-6) """ >From = raw_input(Unit_Menu) To = raw_input(Unit_Menu) Variable = int(raw_input("Insert Amount to Convert ")) And then of course I have multiple followings after this, one example of is this. # Centimeters to Inches if From == "1" and To == "2": if Variable < 2: print Variable, "Centimeter is", Variable/2.5, "Inches" else: print Variable, "Centimeters is", Variable/2.5, "Inches" It works perfectly, so I am sure my question will not be hard to answer. When Python gives me the answer to my conversion, is there a way to create it so every 3 numbers a comma is inserted? Such as: 1 mile is 5,280 feet. Instead of 1 mile is 5280 feet. Yes a simple thing, but something which I believe will make it look better. Also is there a way to make this so I don't have to go through every individual line of code and add *insert comma* or something to it, simply at the top like how the Unit Menu is placed only once there, and yet applies to the whole document. Thank you From andreas at kostyrka.org Sat Mar 22 09:46:58 2008 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Sat, 22 Mar 2008 09:46:58 +0100 Subject: [Tutor] append string In-Reply-To: <674d5ce60803211704q3e86d2aakcdc85ba7e0c53ced@mail.gmail.com> References: <674d5ce60803211704q3e86d2aakcdc85ba7e0c53ced@mail.gmail.com> Message-ID: <1206175618.11011.11.camel@localhost> somestring = "ABC" somestring2 = somestring + "D" somestring2 += "EF" assert somestring2 == "ABCDEF" assert somestring == "ABC" assert id(somestring) != id(somestring2) Basically, strings are immutable. If you need to append something to a string, you need to construct a new string object with the new value. Now if you are using this to collect huge outputfiles in pieces, one of the common idioms in Python is collecting it in a list, and converting to string at the end: collector = [] for i in xrange(100000): collector.append((str(i) * 80)[0:80]) string = "".join(collector) assert len(string) == 8000000 # ~8MB Andreas Am Freitag, den 21.03.2008, 17:04 -0700 schrieb elis aeris: > how do I append to the end of strings? > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Dies ist ein digital signierter Nachrichtenteil Url : http://mail.python.org/pipermail/tutor/attachments/20080322/65f38dcb/attachment.pgp From andreas at kostyrka.org Sat Mar 22 09:49:02 2008 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Sat, 22 Mar 2008 09:49:02 +0100 Subject: [Tutor] int to string In-Reply-To: <674d5ce60803211705q1ef85b0en6529e10d7b80493@mail.gmail.com> References: <674d5ce60803211705q1ef85b0en6529e10d7b80493@mail.gmail.com> Message-ID: <1206175742.11011.14.camel@localhost> Beside casting it with str(), you can also use a format string: assert "%d" % 10 == "10" assert "%5d" % 10 == " 10" assert "%05d" % 10 == "00010" In practice % supports a superset of what printf in C provides. Andreas Am Freitag, den 21.03.2008, 17:05 -0700 schrieb elis aeris: > how do I convert int to string? > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Dies ist ein digital signierter Nachrichtenteil Url : http://mail.python.org/pipermail/tutor/attachments/20080322/005a0d90/attachment.pgp From andreas at kostyrka.org Sat Mar 22 09:57:32 2008 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Sat, 22 Mar 2008 09:57:32 +0100 Subject: [Tutor] Pseudo-functions and dicts In-Reply-To: <376fbdcf0803211901ubc91bdds35942775aee9d3c6@mail.gmail.com> References: <376fbdcf0803211901ubc91bdds35942775aee9d3c6@mail.gmail.com> Message-ID: <1206176252.11011.20.camel@localhost> Well, there are basically two ways to go at it. If you want it at module level, you need to generate the functions: sensor = {'sens1': 200, 'sens2': 300} for key in sensor.keys(): def helper(keytofetch=key): return sensor[keytofetch] globals()[key] = helper print sens1() print sens2() Alternatively, if you want to stuff into a class, you can do: class X: def __init__(self): self.sensor = {} def __getattr__(self, key): return lambda : self.sensor[key] x=X() x.sensor = {'sens1': 200, 'sens2': 300} print x.sens1() print x.sens2() print x.test() # => raises KeyError Andreas Am Freitag, den 21.03.2008, 22:01 -0400 schrieb Shrutarshi Basu: > I have a dictionary (in a module) which contains values of various > sensors. I would like a user to be able use to a function syntax to > get the sensor values, both as a whole and individually. Currently I > have a function for each value who's sole purpose is to look up the > corresponding dict value and return. But I don't think this is an > elegant way to solve the problem. Is there someway I could define a > single function that responds to all of possible function calls? > > Eg. > My dict : sensor = {'sens1': 200, 'sens2': 300} etc > my functions: > def sens1(): > return sensor['sens1'] > same for sens2. > > There are two solutions I've thought about: > Have a function that takes in the sensor's name as a string and > responds accordingly. (which might be what I'll end up using) > I could let the user directly access the dict, but I'm not sure if > that is a good idea. My project requires that the user of my module > should not have to know about Python's data structures to use the > values my module returns. If there is some sort of non-functional > dot-separated syntax that I could use, that would be good too. > Thanks, > Basu > -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Dies ist ein digital signierter Nachrichtenteil Url : http://mail.python.org/pipermail/tutor/attachments/20080322/01225fbe/attachment.pgp From andreas at kostyrka.org Sat Mar 22 10:08:43 2008 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Sat, 22 Mar 2008 10:08:43 +0100 Subject: [Tutor] what is @classmethod and @staticmethod ?? In-Reply-To: <66208.9916.qm@web50708.mail.re2.yahoo.com> References: <66208.9916.qm@web50708.mail.re2.yahoo.com> Message-ID: <1206176923.11011.28.camel@localhost> Well, it's classmethod/staticmethod in truth, @ is the decorator operator: def testdec(func): return {"funcobj": func} class Abc(object): @testdec def method(): pass assert isinstance(Abc.method, dict) Basically as you can see above, @X before a function definition takes the function, applies X, and use the result instead. Now, naive Python level implementations of classmethod and staticmethod would be (untested, all typed in the mailer): def classmethod(func): def wrapper(self, *args, **kw): return func(self.__class__, *args, **kw) return wrapper def staticmethod(func): def wrapper(self, *args, **kw): return func(*args, **kw) return wrapper Andreas Am Freitag, den 21.03.2008, 20:08 -0700 schrieb maser: > Hi > > I couldn't find a good resource explaining what > @classmethod and @staticmethod are in python and when, > how these could be used. > > If someone could explain what these are, or point me > to resources that may help, it is appreciated. > > Thanks > iyer > > > ____________________________________________________________________________________ > Be a better friend, newshound, and > know-it-all with Yahoo! Mobile. Try it now. http://mobile.yahoo.com/;_ylt=Ahu06i62sR8HDtDypao8Wcj9tAcJ > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Dies ist ein digital signierter Nachrichtenteil Url : http://mail.python.org/pipermail/tutor/attachments/20080322/b6c9def3/attachment-0001.pgp From kepalapening at gmail.com Sat Mar 22 11:17:25 2008 From: kepalapening at gmail.com (Kepala Pening) Date: Sat, 22 Mar 2008 18:17:25 +0800 Subject: [Tutor] Even More Converter! Message-ID: <20080322.101725.000.1@SELINAPPORTABLE> import re num = 123456789 print ','.join(re.findall("\d{3}", str(num))) output: 123,456,789 ----- Original Message ----- From: wackedd at mac.com To: tutor at python.org Date: Fri, 21 Mar 2008 21:49:18 -0700 Subject: [Tutor] Even More Converter! It works perfectly, so I am sure my question will not be hard to answer. When Python gives me the answer to my conversion, is there a way to create it so every 3 numbers a comma is inserted? Such as: 1 mile is 5,280 feet. Instead of 1 mile is 5280 feet. Yes a simple thing, but something which I believe will make it look better. Also is there a way to make this so I don't have to go through every individual line of code and add *insert comma* or something to it, simply at the top like how the Unit Menu is placed only once there, and yet applies to the whole document. Thank you From norman at khine.net Sat Mar 22 12:31:09 2008 From: norman at khine.net (Norman Khine) Date: Sat, 22 Mar 2008 12:31:09 +0100 Subject: [Tutor] suggestion on improving script Message-ID: <47E4EDFD.9080201@khine.net> Hello, Please excuse me in advance if this post is long winded. I have the following nagging issue for which I have found a work around, but wanted a better solution. I am using jQuery to populate tabs with some data, such as news and jobs posts, as can be seen at http://uk.expert.travel In my application, I have the following structure (only partially listed): $ tree -L 2 . |-- expert_travel.py |-- ui | `-- ui.tabs.js ... `-- utils.py #expert_travel.py from utils import t1, t2, t3, t4 ... #################################################################### # News - List #################################################################### def list_news(self, context): namespace = {} namespace['batch'] = '' #Search the catalogue, list all news items in company ... # Set batch informations [t1] batch_start = int(context.get_form_value('t1', default=0)) batch_size = 5 batch_total = len(news_items) batch_fin = batch_start + batch_size if batch_fin > batch_total: batch_fin = batch_total news_items = news_items[batch_start:batch_fin] # Namespace if news_items: msgs = (u'There is one news item.', u'There are ${n} news items.') [t1] news_batch = t1(context.uri, batch_start, batch_size, batch_total, msgs=msgs) msg = None else: news_batch = None msg = u'Currently there is no news.' #################################################################### # List jobs list_jobs__label__ = u'List jobs' list_jobs__access__ = True def list_jobs(self, context): ... # Set batch informations [t2] batch_start = int(context.get_form_value('t2', default=0)) batch_size = 5 batch_total = len(jobs) batch_fin = batch_start + batch_size if batch_fin > batch_total: batch_fin = batch_total jobs = jobs[batch_start:batch_fin] # Namespace if jobs: msgs = (u'There is one job.', u'There are ${n} jobs.') [t2] job_batch = t2(context.uri, batch_start, batch_size, batch_total, msgs=msgs) msg = None else: job_table = None job_batch = None msg = u'Sorry but there are no jobs' ... #### #utils.py def t1(uri, start, size, total, gettext=Handler.gettext, msgs=(u"There is 1 object.", u"There are ${n} objects.")): # Plural forms if total == 1: msg1 = gettext(msgs[0]) else: msg1 = gettext(msgs[1]) msg1 = Template(msg1).substitute(n=total) msg1 = msg1.encode('utf-8') # Calculate end end = min(start + size, total) # Previous previous = None if start > 0: previous = max(start - size, 0) previous = str(previous) [t1] previous = uri.replace(t1=previous) previous = str(previous) previous = XMLAttribute.encode(previous) previous = '<<' \ % (previous, gettext(u'Previous')) # Next next = None if end < total: next = str(end) [t1] next = uri.replace(t1=next) next = str(next) next = XMLAttribute.encode(next) next = '>>' \ % (next, gettext(u'Next')) # Output if previous is None and next is None: msg = msg1 else: # View more if previous is None: link = next elif next is None: link = previous else: link = '%s %s' % (previous, next) msg2 = gettext(u"View from ${start} to ${end} (${link}):") msg2 = Template(msg2) msg2 = msg2.substitute(start=(start+1), end=end, link=link) msg2 = msg2.encode('utf-8') msg = '%s %s' % (msg1, msg2) # Wrap around a paragraph return Parser('

%s

' % msg, namespaces) #Second TAB def t2(uri, start, size, total, gettext=Handler.gettext, msgs=(u"There is 1 object.", u"There are ${n} objects.")): # Plural forms ... ### I would like to alter this batch control so that I don't have to create a new method everytime I need a new tab. For example, I would like to change t1, t2 ... t[n] depending on the tab I am at. You can see it in action at http://uk.expert.travel/;view If you click on the [Jobs] tab, there are 6 jobs, if you then click on the 'There are 6 jobs. View from 1 to 5 (>>):' you will get a list of the last post. Note the URI http://uk.expert.travel/;view?t2=5 If I only use one global method, the problem would be that when I clicked on the News tab, I will get no items displayed as can be seen here: http://uk.expert.travel/companies/abakuc/;view I hope this makes sense ;) Any advice would be much appreciated. Cheers Norman From kent37 at tds.net Sat Mar 22 13:38:02 2008 From: kent37 at tds.net (Kent Johnson) Date: Sat, 22 Mar 2008 08:38:02 -0400 Subject: [Tutor] Pseudo-functions and dicts In-Reply-To: <376fbdcf0803211901ubc91bdds35942775aee9d3c6@mail.gmail.com> References: <376fbdcf0803211901ubc91bdds35942775aee9d3c6@mail.gmail.com> Message-ID: <47E4FDAA.30700@tds.net> Shrutarshi Basu wrote: > There are two solutions I've thought about: > Have a function that takes in the sensor's name as a string and > responds accordingly. (which might be what I'll end up using) That is almost the same as using ordinary dict access, with slightly different syntax, e.g. sensor('sens1') vs sensor['sens1']. There is actually a function to do this, it is called sensor.__getitem__. You can give it a new name if you like: In [1]: sensor = {'sens1': 200, 'sens2': 300} In [2]: get_value = sensor.__getitem__ # Note no parentheses here In [3]: get_value('sens1') Out[3]: 200 > I could let the user directly access the dict, but I'm not sure if > that is a good idea. Why not? > My project requires that the user of my module > should not have to know about Python's data structures to use the > values my module returns. This seems a strange requirement! > If there is some sort of non-functional > dot-separated syntax that I could use, that would be good too. You could make a class whose attributes are the dict keys, then use attribute access syntax. The Bunch class is handy for this: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52308 In [5]: values = Bunch(**sensor) # use sensor as keyword arguments In [6]: values.sens1 Out[6]: 200 Kent From bhaaluu at gmail.com Sat Mar 22 14:02:40 2008 From: bhaaluu at gmail.com (bhaaluu) Date: Sat, 22 Mar 2008 09:02:40 -0400 Subject: [Tutor] Even More Converter! In-Reply-To: <20080322.101725.000.1@SELINAPPORTABLE> References: <20080322.101725.000.1@SELINAPPORTABLE> Message-ID: import re num = 12345678 print ','.join(re.findall("\d{3}", str(num))) output: 123,456 Where is the '78'? It looks like that solution inserts comma's from left to right instead of from right to left. -- b h a a l u u at g m a i l dot c o m "You assist an evil system most effectively by obeying its orders and decrees. An evil system never deserves such allegiance. Allegiance to it means partaking of the evil. A good person will resist an evil system with his or her whole soul." [Mahatma Gandhi] On Sat, Mar 22, 2008 at 6:17 AM, Kepala Pening wrote: > > import re > > num = 123456789 > > print ','.join(re.findall("\d{3}", str(num))) > > output: > 123,456,789 > > > > > ----- Original Message ----- > From: wackedd at mac.com > To: tutor at python.org > Date: Fri, 21 Mar 2008 21:49:18 -0700 > Subject: [Tutor] Even More Converter! > > It works perfectly, so I am sure my question will not be hard to answer. > When Python gives me the answer to my conversion, is there a way to create it > so every 3 numbers a comma is inserted? > Such as: 1 mile is 5,280 feet. Instead of 1 mile is 5280 feet. Yes a simple > thing, but something which I believe will make it look better. > Also is there a way to make this so I don't have to go through every > individual line of code and add *insert comma* or something to it, simply > at the top like how the Unit Menu is placed only once there, and yet > applies to the whole document. Thank you > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From finalyugi at sapo.pt Sat Mar 22 14:00:20 2008 From: finalyugi at sapo.pt (Rolando Pereira) Date: Sat, 22 Mar 2008 13:00:20 +0000 Subject: [Tutor] Even More Converter! In-Reply-To: <20080322.101725.000.1@SELINAPPORTABLE> References: <20080322.101725.000.1@SELINAPPORTABLE> Message-ID: <47E502E4.3000805@sapo.pt> Kepala Pening wrote: > import re > > num = 123456789 > > print ','.join(re.findall("\d{3}", str(num))) > > output: > 123,456,789 > [snip] The problem with that is that it cuts the digits in the end of the number, if they can't form a 3 digit value. Example: import re n = 1234 print ",".join(re.findall("\d{3}", str(n))) Output: 123, instead of 1,234 I think the use of a function would be better. def convert_num(num): num = map(lambda x: int(x), str(num)) num.reverse() k=0 tmp_number = [] for i in range(len(num)): if k == 2 and i != range(len(num))[-1]: tmp_number.append(num[i]) tmp_number.append(",") k = 0 else: tmp_number.append(num[i]) k += 1 num = map(lambda n: str(n), tmp_number) num.reverse() num = "".join(num) return num First it converts the number into a list in which each digit is a separate member. Then it reverses that list (because when we want to add the commas, we start to count from the right and not from the left, that is, it's 1,234 and not 123,4). Next a few loop variables (k and tmp_number), and we loop through the "num" list, appending it's reversed digits into "tmp_number", except when we have added 2 numbers without adding a comma, so we append the next number AND a comma. When the cycle ends, tmp_number is a list of ints with "," string separating groups of 3 numbers. In the end, it make "num" the same as "tmp_number", with all it's members turned to strings (didn't knew that join() only worked with strings in a list), reverse it (so it returns the same number that was in the beginning, and joins everything into a string. Example: n = 1234 convert_num(n) Output: 1,234 -- _ ASCII ribbon campaign ( ) - against HTML email X & vCards / \ From kent37 at tds.net Sat Mar 22 14:41:34 2008 From: kent37 at tds.net (Kent Johnson) Date: Sat, 22 Mar 2008 09:41:34 -0400 Subject: [Tutor] Even More Converter! In-Reply-To: <34ACA2C9-0118-1000-B5E9-5B67AAE91AB3-Webmail-10010@mac.com> References: <34ACA2C9-0118-1000-B5E9-5B67AAE91AB3-Webmail-10010@mac.com> Message-ID: <47E50C8E.3070202@tds.net> wackedd at mac.com wrote: > When Python gives me the answer to my conversion, is there a way to create it so every 3 numbers a comma is inserted? Django uses this function: def intcomma(value): """ Converts an integer to a string containing commas every three digits. For example, 3000 becomes '3,000' and 45000 becomes '45,000'. """ orig = str(value) new = re.sub("^(-?\d+)(\d{3})", '\g<1>,\g<2>', str(value)) if orig == new: return new else: return intcomma(new) > Also is there a way to make this so I don't have to go through every individual line of code and add *insert comma* or something to it, simply at the top like how the Unit Menu is placed only once there, and yet applies to the whole document. Thank you No. The way to do this is to learn how to use functions to consolidate all the prints into one place. Kent From alan.gauld at btinternet.com Sat Mar 22 15:07:11 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 22 Mar 2008 14:07:11 -0000 Subject: [Tutor] what is @classmethod and @staticmethod ?? References: <66208.9916.qm@web50708.mail.re2.yahoo.com> Message-ID: "maser" wrote > I couldn't find a good resource explaining what > @classmethod and @staticmethod are in python and when, > how these could be used. I'm not sure which aspect of this is the problem Andreas has explained the strange @ syntax for a decorator however if its the concepts of class method and static method that confuss then that probably didn't help :-) So first I ask do you know what a class method (or static method) is? (Unless you are a language lawyer you can almost consider them as synonyms). If not the simple answer is that a class method is one which acts on the class itself rather than on instances of the class (I'll assume you understand the difference between classes and instances (or objects)). This if you have a Circle class for example there might be a class method to return the count of how many Circle instances exist. It might look like this: class Circle(object): count = 0 # a class variable def __init__(self, radius=10): Circle.count += 1 self.radius = radius def __del__(self): Circle.count -= 1 @classmethod def circles(this): return Circle.count c1 = Circle() c2 = Circle(5) c3 = Circle(42) print Circle.circles() Does that help? -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From rdm at rcblue.com Sat Mar 22 15:27:59 2008 From: rdm at rcblue.com (Dick Moores) Date: Sat, 22 Mar 2008 07:27:59 -0700 Subject: [Tutor] Even More Converter! In-Reply-To: <47E502E4.3000805@sapo.pt> References: <20080322.101725.000.1@SELINAPPORTABLE> <47E502E4.3000805@sapo.pt> Message-ID: <20080322142813.95FD11E4018@bag.python.org> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080322/23cc3ab4/attachment.htm From kepalapening at gmail.com Sat Mar 22 17:43:08 2008 From: kepalapening at gmail.com (Kepala Pening) Date: Sun, 23 Mar 2008 00:43:08 +0800 Subject: [Tutor] Even More Converter! Message-ID: <20080322.164308.625.1@SELINAPPORTABLE> sorry, I forgot that re search from the front of the string. import re putComma = lambda x: (','.join(re.findall("\d{1,3}", str(x)[::-1])))[::-1] print putComma(1234567) # 1,234,567 print putComma(12345678) # 12,345,678 print putComma(123456789) # 123,456,789 ----- Original Message ----- From: bhaaluu To: "Kepala Pening" Cc: tutor at python.org Date: Sat, 22 Mar 2008 09:02:40 -0400 Subject: Re: [Tutor] Even More Converter! > import re > num = 12345678 > print ','.join(re.findall("\d{3}", str(num))) > > output: > 123,456 > > Where is the '78'? > > It looks like that solution inserts comma's from left to right > instead of from right to left. > -- > b h a a l u u at g m a i l dot c o m > "You assist an evil system most effectively by obeying its > orders and decrees. An evil system never deserves such > allegiance. Allegiance to it means partaking of the evil. > A good person will resist an evil system with his or her > whole soul." [Mahatma Gandhi] > > On Sat, Mar 22, 2008 at 6:17 AM, Kepala Pening wrote: > > > > import re > > > > num = 123456789 > > > > print ','.join(re.findall("\d{3}", str(num))) > > > > output: > > 123,456,789 > > > > > > > > > > ----- Original Message ----- > > From: wackedd at mac.com > > To: tutor at python.org > > Date: Fri, 21 Mar 2008 21:49:18 -0700 > > Subject: [Tutor] Even More Converter! > > > > It works perfectly, so I am sure my question will not be hard to answer. > > When Python gives me the answer to my conversion, is there a way to create it > > so every 3 numbers a comma is inserted? > > Such as: 1 mile is 5,280 feet. Instead of 1 mile is 5280 feet. Yes a simple > > thing, but something which I believe will make it look better. > > Also is there a way to make this so I don't have to go through every > > individual line of code and add *insert comma* or something to it, simply > > at the top like how the Unit Menu is placed only once there, and yet > > applies to the whole document. Thank you > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > From alan.gauld at btinternet.com Sat Mar 22 18:30:09 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 22 Mar 2008 17:30:09 -0000 Subject: [Tutor] Even More Converter! References: <34ACA2C9-0118-1000-B5E9-5B67AAE91AB3-Webmail-10010@mac.com> Message-ID: wrote > When Python gives me the answer to my conversion, > is there a way to create it so every 3 numbers a > comma is inserted? Bear in mind that the use of commas is very much a local thing. In some parts of the world periods are used and a comma indicates a decimal point so 123,456 could be 123 thousand 456 or 123 point 456 depending on where the reader is from. If that is important you might need to investigate a locale specific way of defining the seperator. I know Windows has hooks to get it from the local settings but I'm not sure about *nix and I don't know if Python has a generic way. This might not matter to you in practice , but I thought I'd mention it just in case... -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From finalyugi at sapo.pt Sat Mar 22 19:11:18 2008 From: finalyugi at sapo.pt (Rolando Pereira) Date: Sat, 22 Mar 2008 18:11:18 +0000 Subject: [Tutor] Even More Converter! In-Reply-To: References: <34ACA2C9-0118-1000-B5E9-5B67AAE91AB3-Webmail-10010@mac.com> Message-ID: <47E54BC6.20208@sapo.pt> Alan Gauld wrote: > > If that is important you might need to investigate a locale specific > way of defining the seperator. I know Windows has hooks to get > it from the local settings but I'm not sure about *nix and I don't > know if Python has a generic way. > > This might not matter to you in practice , but I thought I'd > mention it just in case... > There is always the shell command "locale". ___________________________ import subprocess output = subprocess.Popen("locale | grep NUMERIC", shell=True, \ stdout=subprocess.PIPE) print output.communicate()[0] LC_NUMERIC="pt_PT.UTF-8" (In my case) ___________________________ The problem with this is that it assumes the default shell is properly setted up (which may not be the case, for example this output happens in Bash, but in ZSH it gives en_US.UTF-8), which may not be the case. -- _ ASCII ribbon campaign ( ) - against HTML email X & vCards / \ From kent37 at tds.net Sat Mar 22 19:19:19 2008 From: kent37 at tds.net (Kent Johnson) Date: Sat, 22 Mar 2008 14:19:19 -0400 Subject: [Tutor] Even More Converter! In-Reply-To: References: <34ACA2C9-0118-1000-B5E9-5B67AAE91AB3-Webmail-10010@mac.com> Message-ID: <47E54DA7.2060403@tds.net> Alan Gauld wrote: > Bear in mind that the use of commas is very much a > local thing. In some parts of the world periods are used > and a comma indicates a decimal point so > > 123,456 > > could be 123 thousand 456 or 123 point 456 depending > on where the reader is from. > > If that is important you might need to investigate a locale specific > way of defining the seperator. In [7]: import locale In [9]: locale.setlocale(locale.LC_ALL, '') Out[9]: 'en_US.UTF-8' In [10]: locale.localeconv()['thousands_sep'] Out[10]: ',' Kent From hunter92383 at gmail.com Sat Mar 22 22:35:50 2008 From: hunter92383 at gmail.com (elis aeris) Date: Sat, 22 Mar 2008 14:35:50 -0700 Subject: [Tutor] windows: pop up window Message-ID: <674d5ce60803221435x2db92ca9qe3b70d931c044c71@mail.gmail.com> how do I pop up a window to ask user's input? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080322/2f30f5c8/attachment.htm From hunter92383 at gmail.com Sat Mar 22 22:43:51 2008 From: hunter92383 at gmail.com (elis aeris) Date: Sat, 22 Mar 2008 14:43:51 -0700 Subject: [Tutor] add to list Message-ID: <674d5ce60803221443o6d20c66ey79aff13adde868ac@mail.gmail.com> chat_window_char_definition = { "2.7.1." : "1", "2.3.3.3.3." : "2", "2.2.3.3.4." : "3", "2.2.2.7.1." : "4", "4.3.3.3.4." : "5", } how do I automatically add to this list without doing it by hand? Also, the list is of tuples of 2, how ever, I need to have a tuple of 3, is that possible? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080322/6fb0dd6e/attachment.htm From kent37 at tds.net Sat Mar 22 22:59:24 2008 From: kent37 at tds.net (Kent Johnson) Date: Sat, 22 Mar 2008 17:59:24 -0400 Subject: [Tutor] add to list In-Reply-To: <674d5ce60803221443o6d20c66ey79aff13adde868ac@mail.gmail.com> References: <674d5ce60803221443o6d20c66ey79aff13adde868ac@mail.gmail.com> Message-ID: <47E5813C.20205@tds.net> elis aeris wrote: > chat_window_char_definition = { "2.7.1." : "1", > "2.3.3.3.3." : "2", > "2.2.3.3.4." : "3", > "2.2.2.7.1." : "4", > "4.3.3.3.4." : "5", > } > > how do I automatically add to this list without doing it by hand? Is there some pattern to the values? I can't see it. > > Also, the list is of tuples of 2, how ever, I need to have a tuple of 3, > is that possible? Tuples can be whatever length you want. But what you have is not a list of tuples, it is a dict mapping keys to values. You could make the keys or the values be tuples of strings rather than strings. Some context would probably help us give you a better answer. Kent From hunter92383 at gmail.com Sat Mar 22 23:02:14 2008 From: hunter92383 at gmail.com (elis aeris) Date: Sat, 22 Mar 2008 15:02:14 -0700 Subject: [Tutor] add to list In-Reply-To: <47E5813C.20205@tds.net> References: <674d5ce60803221443o6d20c66ey79aff13adde868ac@mail.gmail.com> <47E5813C.20205@tds.net> Message-ID: <674d5ce60803221502h34472683wbe971acf6146a225@mail.gmail.com> there is no pattern in the numbers. but don't worry about it, because all i am doing is this: two strings that look like "2.3.3.3.3.", youknow, str(int) + "." + str(int) + "." and so forth are presented and they equal to a value, which is the third string. in short, given the first two strings, return the third string from the list. it's a dictionary. On Sat, Mar 22, 2008 at 2:59 PM, Kent Johnson wrote: > elis aeris wrote: > > chat_window_char_definition = { "2.7.1." : "1", > > "2.3.3.3.3." : "2", > > "2.2.3.3.4." : "3", > > "2.2.2.7.1." : "4", > > "4.3.3.3.4." : "5", > > } > > > > how do I automatically add to this list without doing it by hand? > > Is there some pattern to the values? I can't see it. > > > > Also, the list is of tuples of 2, how ever, I need to have a tuple of 3, > > is that possible? > > Tuples can be whatever length you want. But what you have is not a list > of tuples, it is a dict mapping keys to values. You could make the keys > or the values be tuples of strings rather than strings. > > Some context would probably help us give you a better answer. > > Kent > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080322/4cfbb102/attachment.htm From kent37 at tds.net Sat Mar 22 23:02:11 2008 From: kent37 at tds.net (Kent Johnson) Date: Sat, 22 Mar 2008 18:02:11 -0400 Subject: [Tutor] windows: pop up window In-Reply-To: <674d5ce60803221435x2db92ca9qe3b70d931c044c71@mail.gmail.com> References: <674d5ce60803221435x2db92ca9qe3b70d931c044c71@mail.gmail.com> Message-ID: <47E581E3.4040207@tds.net> elis aeris wrote: > how do I pop up a window to ask user's input? Take a look at http://www.ferg.org/easygui/ Kent From hunter92383 at gmail.com Sat Mar 22 23:02:48 2008 From: hunter92383 at gmail.com (elis aeris) Date: Sat, 22 Mar 2008 15:02:48 -0700 Subject: [Tutor] windows: pop up window In-Reply-To: <47E581E3.4040207@tds.net> References: <674d5ce60803221435x2db92ca9qe3b70d931c044c71@mail.gmail.com> <47E581E3.4040207@tds.net> Message-ID: <674d5ce60803221502i510b3e89if51a70feaffeedc9@mail.gmail.com> how about console window input? On Sat, Mar 22, 2008 at 3:02 PM, Kent Johnson wrote: > elis aeris wrote: > > how do I pop up a window to ask user's input? > > Take a look at > http://www.ferg.org/easygui/ > > Kent > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080322/c55434f5/attachment.htm From kent37 at tds.net Sat Mar 22 23:07:52 2008 From: kent37 at tds.net (Kent Johnson) Date: Sat, 22 Mar 2008 18:07:52 -0400 Subject: [Tutor] suggestion on improving script In-Reply-To: <47E4EDFD.9080201@khine.net> References: <47E4EDFD.9080201@khine.net> Message-ID: <47E58338.90309@tds.net> Norman Khine wrote: > I would like to alter this batch control so that I don't have to create > a new method everytime I need a new tab. > > For example, I would like to change t1, t2 ... t[n] depending on the tab > I am at. I don't really understand the question but I think maybe the tabs should be represented by instances of some class rather than functions. Kent From kent37 at tds.net Sat Mar 22 23:09:08 2008 From: kent37 at tds.net (Kent Johnson) Date: Sat, 22 Mar 2008 18:09:08 -0400 Subject: [Tutor] windows: pop up window In-Reply-To: <674d5ce60803221502i510b3e89if51a70feaffeedc9@mail.gmail.com> References: <674d5ce60803221435x2db92ca9qe3b70d931c044c71@mail.gmail.com> <47E581E3.4040207@tds.net> <674d5ce60803221502i510b3e89if51a70feaffeedc9@mail.gmail.com> Message-ID: <47E58384.6090306@tds.net> elis aeris wrote: > how about console window input? You want to "pop up" a console window? Usually if your program is running in a console you have a window already. Use raw_input() to get user input in the console. Kent > > On Sat, Mar 22, 2008 at 3:02 PM, Kent Johnson > wrote: > > elis aeris wrote: > > how do I pop up a window to ask user's input? > > Take a look at > http://www.ferg.org/easygui/ > > Kent > > From hunter92383 at gmail.com Sat Mar 22 23:10:03 2008 From: hunter92383 at gmail.com (elis aeris) Date: Sat, 22 Mar 2008 15:10:03 -0700 Subject: [Tutor] windows: pop up window In-Reply-To: <47E58384.6090306@tds.net> References: <674d5ce60803221435x2db92ca9qe3b70d931c044c71@mail.gmail.com> <47E581E3.4040207@tds.net> <674d5ce60803221502i510b3e89if51a70feaffeedc9@mail.gmail.com> <47E58384.6090306@tds.net> Message-ID: <674d5ce60803221510j403248adg24d7042bab73e4f2@mail.gmail.com> oh sorry, I should have been clear: how about just popping a prompt in the same window that is running the script? On Sat, Mar 22, 2008 at 3:09 PM, Kent Johnson wrote: > elis aeris wrote: > > how about console window input? > > You want to "pop up" a console window? Usually if your program is > running in a console you have a window already. Use raw_input() to get > user input in the console. > > Kent > > > > On Sat, Mar 22, 2008 at 3:02 PM, Kent Johnson > > wrote: > > > > elis aeris wrote: > > > how do I pop up a window to ask user's input? > > > > Take a look at > > http://www.ferg.org/easygui/ > > > > Kent > > > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080322/9e11949e/attachment.htm From kent37 at tds.net Sat Mar 22 23:12:20 2008 From: kent37 at tds.net (Kent Johnson) Date: Sat, 22 Mar 2008 18:12:20 -0400 Subject: [Tutor] add to list In-Reply-To: <674d5ce60803221502h34472683wbe971acf6146a225@mail.gmail.com> References: <674d5ce60803221443o6d20c66ey79aff13adde868ac@mail.gmail.com> <47E5813C.20205@tds.net> <674d5ce60803221502h34472683wbe971acf6146a225@mail.gmail.com> Message-ID: <47E58444.9020406@tds.net> elis aeris wrote: > there is no pattern in the numbers. Then how do you expect to create them automatically? I don't understand that part of the question. > two strings that look like "2.3.3.3.3.", youknow, str(int) + "." + > str(int) + "." and so forth > are presented and they equal to a value, which is the third string. > > in short, given the first two strings, return the third string from the > list. That sounds like you want a dict whose key is a tuple of the first two strings, and the value is the third string. For example, In [11]: d = { ('a', 'b'): '1', ....: ('c', 'd'): '2' } In [12]: In [12]: d['a', 'b'] Out[12]: '1' Kent From hunter92383 at gmail.com Sat Mar 22 23:12:31 2008 From: hunter92383 at gmail.com (elis aeris) Date: Sat, 22 Mar 2008 15:12:31 -0700 Subject: [Tutor] x and y Message-ID: <674d5ce60803221512w182694fbta97f443f5c39e908@mail.gmail.com> on a different note, also on lists, I need to save two values, x and y. list = { int, int int, int int, int but i am not sure of the syntax, is it possible to just read both values from the same entry in the list ? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080322/4dc92a2d/attachment.htm From hunter92383 at gmail.com Sat Mar 22 23:14:55 2008 From: hunter92383 at gmail.com (elis aeris) Date: Sat, 22 Mar 2008 15:14:55 -0700 Subject: [Tutor] add to list In-Reply-To: <47E58444.9020406@tds.net> References: <674d5ce60803221443o6d20c66ey79aff13adde868ac@mail.gmail.com> <47E5813C.20205@tds.net> <674d5ce60803221502h34472683wbe971acf6146a225@mail.gmail.com> <47E58444.9020406@tds.net> Message-ID: <674d5ce60803221514td13ae5ema4642d7bd00abea6@mail.gmail.com> Another part of program takes care of that patternless stuff, only saving and retrieving for comparison is concerned for this part of the code. In [11]: d = { ('a', 'b'): '1', ....: ('c', 'd'): '2' } In [12]: In [12]: d['a', 'b'] Out[12]: '1' that does look like what I looking for, how does it work? On Sat, Mar 22, 2008 at 3:12 PM, Kent Johnson wrote: > elis aeris wrote: > > there is no pattern in the numbers. > > Then how do you expect to create them automatically? I don't understand > that part of the question. > > > two strings that look like "2.3.3.3.3.", youknow, str(int) + "." + > > str(int) + "." and so forth > > are presented and they equal to a value, which is the third string. > > > > in short, given the first two strings, return the third string from the > > list. > > That sounds like you want a dict whose key is a tuple of the first two > strings, and the value is the third string. For example, > In [11]: d = { ('a', 'b'): '1', > ....: ('c', 'd'): '2' } > In [12]: > In [12]: d['a', 'b'] > Out[12]: '1' > > Kent > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080322/7f7f417a/attachment.htm From kent37 at tds.net Sat Mar 22 23:15:12 2008 From: kent37 at tds.net (Kent Johnson) Date: Sat, 22 Mar 2008 18:15:12 -0400 Subject: [Tutor] windows: pop up window In-Reply-To: <674d5ce60803221510j403248adg24d7042bab73e4f2@mail.gmail.com> References: <674d5ce60803221435x2db92ca9qe3b70d931c044c71@mail.gmail.com> <47E581E3.4040207@tds.net> <674d5ce60803221502i510b3e89if51a70feaffeedc9@mail.gmail.com> <47E58384.6090306@tds.net> <674d5ce60803221510j403248adg24d7042bab73e4f2@mail.gmail.com> Message-ID: <47E584F0.5070207@tds.net> elis aeris wrote: > oh sorry, I should have been clear: > > how about just popping a prompt in the same window that is running the > script? Sounds like you want raw_input(): http://docs.python.org/lib/built-in-funcs.html#l2h-59 Kent From hunter92383 at gmail.com Sat Mar 22 23:17:54 2008 From: hunter92383 at gmail.com (elis aeris) Date: Sat, 22 Mar 2008 15:17:54 -0700 Subject: [Tutor] windows: pop up window In-Reply-To: <47E584F0.5070207@tds.net> References: <674d5ce60803221435x2db92ca9qe3b70d931c044c71@mail.gmail.com> <47E581E3.4040207@tds.net> <674d5ce60803221502i510b3e89if51a70feaffeedc9@mail.gmail.com> <47E58384.6090306@tds.net> <674d5ce60803221510j403248adg24d7042bab73e4f2@mail.gmail.com> <47E584F0.5070207@tds.net> Message-ID: <674d5ce60803221517l64982544sf8f13af121e04f65@mail.gmail.com> sweet, I love built in functions. thanks ! On Sat, Mar 22, 2008 at 3:15 PM, Kent Johnson wrote: > elis aeris wrote: > > oh sorry, I should have been clear: > > > > how about just popping a prompt in the same window that is running the > > script? > > Sounds like you want raw_input(): > http://docs.python.org/lib/built-in-funcs.html#l2h-59 > > Kent > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080322/ada7c85b/attachment.htm From alan.gauld at btinternet.com Sat Mar 22 23:48:40 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 22 Mar 2008 22:48:40 -0000 Subject: [Tutor] x and y References: <674d5ce60803221512w182694fbta97f443f5c39e908@mail.gmail.com> Message-ID: "elis aeris" wrote > on a different note, also on lists, I need to save two values, x > and y. > > list = { int, int > int, int > int, int > > but i am not sure of the syntax, is it possible to just read both > values > from the same entry in the list ? I have no idea what you mean by that, can you give a more specific example? Are you trying to extract 2 values out of a list into variables? Are you trying to save two variable values into a list? And what kind of list is your example? It uses a built in function(list) to refer to something that looks like a cross between a dictionary and an open list but filled with the same value (or another built in function?) Can you try using a Python example with real values and tell us what you want to dowith them. (And try it at the >>> prompt first, since the most obvious solution is often the right one in Python!) HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From hunter92383 at gmail.com Sat Mar 22 23:50:56 2008 From: hunter92383 at gmail.com (elis aeris) Date: Sat, 22 Mar 2008 15:50:56 -0700 Subject: [Tutor] x and y In-Reply-To: References: <674d5ce60803221512w182694fbta97f443f5c39e908@mail.gmail.com> Message-ID: <674d5ce60803221550v100a5e41kd68c4fdb4caef604@mail.gmail.com> I just need a way to key a list of tuples of 2 for referencing. On Sat, Mar 22, 2008 at 3:48 PM, Alan Gauld wrote: > > "elis aeris" wrote > > > on a different note, also on lists, I need to save two values, x > > and y. > > > > list = { int, int > > int, int > > int, int > > > > but i am not sure of the syntax, is it possible to just read both > > values > > from the same entry in the list ? > > I have no idea what you mean by that, can you give a more > specific example? > > Are you trying to extract 2 values out of a list into variables? > Are you trying to save two variable values into a list? > > And what kind of list is your example? > It uses a built in function(list) to refer to something that looks > like a cross between a dictionary and an open list but filled > with the same value (or another built in function?) > > Can you try using a Python example with real values and tell > us what you want to dowith them. (And try it at the >>> prompt > first, since the most obvious solution is often the right one in > Python!) > > HTH, > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.freenetpages.co.uk/hp/alan.gauld > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080322/6f80970b/attachment-0001.htm From alan.gauld at btinternet.com Sun Mar 23 01:28:38 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 23 Mar 2008 00:28:38 -0000 Subject: [Tutor] x and y References: <674d5ce60803221512w182694fbta97f443f5c39e908@mail.gmail.com> <674d5ce60803221550v100a5e41kd68c4fdb4caef604@mail.gmail.com> Message-ID: "elis aeris" wrote >I just need a way to key a list of tuples of 2 for referencing. > >> I have no idea what you mean by that, can you give a more >> specific example? OK, I have now read your discussion with Kent. Can i ask, have you tried going through any of the basic tutorials? They all cover this kind of stuff, especially dictionaries and raw input and string concatenation etc. It will be much more effective to work through a tutorial than to keep coming back here with every little question. Try the Raw Materials topic of my tutorial for starters. It gives an example of a phone book comprised of a list stored in a dictionary keyed by name... However as to this question, you can store any Python object as the value of a dictionary (even another dictionary), and you can use any *immutable* object as a key. So if I want to store two numbers as a value against another two numbers you can just do this: mapping = { (1,2):(10,20), (3,4): (30,40) } print mapping[(1,2)] #-> (10,20) mapping[(5,6)] = (50,60) # assign new value HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From dkuhlman at rexx.com Sun Mar 23 01:46:23 2008 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Sat, 22 Mar 2008 17:46:23 -0700 Subject: [Tutor] append string In-Reply-To: <1206175618.11011.11.camel@localhost> References: <674d5ce60803211704q3e86d2aakcdc85ba7e0c53ced@mail.gmail.com> <1206175618.11011.11.camel@localhost> Message-ID: <20080323004623.GA93543@cutter.rexx.com> On Sat, Mar 22, 2008 at 09:46:58AM +0100, Andreas Kostyrka wrote: > > Basically, strings are immutable. If you need to append something to a > string, you need to construct a new string object with the new value. > > Now if you are using this to collect huge outputfiles in pieces, one of > the common idioms in Python is collecting it in a list, and converting > to string at the end: > > collector = [] > for i in xrange(100000): > collector.append((str(i) * 80)[0:80]) > > string = "".join(collector) > assert len(string) == 8000000 # ~8MB That was formerly good advice for sure, and it probably still is good advice. But, read the following note from http://docs.python.org/lib/typesseq.html: (6) If s and t are both strings, some Python implementations such as CPython can usually perform an in-place optimization for assignments of the form s=s+t or s+=t. When applicable, this optimization makes quadratic run-time much less likely. This optimization is both version and implementation dependent. For performance sensitive code, it is preferable to use the str.join() method which assures consistent linear concatenation performance across versions and implementations. Changed in version 2.4: Formerly, string concatenation never occurred in-place. As the above note says, this optimization is implementation dependent. In particular, if you plan on moving your code to Jython, then follow Andreas's suggestion to use list append followed by string join. - Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman From rmd103 at psu.edu Sun Mar 23 01:54:11 2008 From: rmd103 at psu.edu (r dascenzo) Date: Sat, 22 Mar 2008 20:54:11 -0400 Subject: [Tutor] Libraries/Modules and how well you know them? Message-ID: <84816351-31CD-4563-B824-C2632E0186AC@psu.edu> Hello, As someone relatively new to programming, I've a few questions related to the Global Module Index: http://docs.python.org/modindex.html What are the distinctions between a library and a module? Do people frequently use the terms interchangeably in conversations, mailng lists, and around the web? Looking at the index, there are hundreds of modules. Do "good" programmers know the contents of all the modules and functions without having to look them up? Are there any suggestions on which might be the most useful to become familiar with at first? Thanks. From kent37 at tds.net Sun Mar 23 03:24:34 2008 From: kent37 at tds.net (Kent Johnson) Date: Sat, 22 Mar 2008 22:24:34 -0400 Subject: [Tutor] Libraries/Modules and how well you know them? In-Reply-To: <84816351-31CD-4563-B824-C2632E0186AC@psu.edu> References: <84816351-31CD-4563-B824-C2632E0186AC@psu.edu> Message-ID: <47E5BF62.6080501@tds.net> r dascenzo wrote: > What are the distinctions between a library and a module? Do people > frequently use the terms interchangeably in conversations, mailng > lists, and around the web? "module" is very specific, it is a single Python source file. A library is a collection of useful modules. > Looking at the index, there are hundreds of modules. Do "good" > programmers know the contents of all the modules and functions without > having to look them up? No. > Are there any suggestions on which might be > the most useful to become familiar with at first? Um, the ones that do things that you want to do? The table of contents for the library docs gives a more useful organization: http://docs.python.org/lib/lib.html I strongly recommend chapters 2 and 3 to every Python programmer - they include docs for all the built-in functions and data types. Experienced Python programmers do know much of this without having to look it up. Other than that... os and os.path have many useful functions for working with files and file paths. re is extremely useful but difficult to learn. datetime has lots of useful date handling stuff. sys, csv, itertools, collections, urllib2, logging, unittest are some of the modules I use regularly. But your needs may be different. Browse the table of contents and take a closer look at the ones that look useful to you. Kent From bgailer at alum.rpi.edu Sun Mar 23 03:42:10 2008 From: bgailer at alum.rpi.edu (bob gailer) Date: Sat, 22 Mar 2008 22:42:10 -0400 Subject: [Tutor] More Converter In-Reply-To: <245E2DCC-0118-1000-A22A-BD839F694284-Webmail-10021@mac.com> References: <245E2DCC-0118-1000-A22A-BD839F694284-Webmail-10021@mac.com> Message-ID: <47E5C382.3050103@alum.rpi.edu> wackedd at mac.com wrote: > I am still in need of more help. Currently I am just trying to get one conversion down, as then I can duplicate it. However I am not sure how to make it Convert. Currently I am working with: > > # Converter > Original = raw_input("Insert inches, feet ") > There is a convention in Python to name variables starting with lower case and reserve initial caps for class names. Thus original = raw_input("Insert inches, feet ") > To = raw_input("Insert inches, feet ") > Variable = int(raw_input("Insert Amount to Convert ")) > if Original == raw_input(feet) and To == raw_input(inches): > print Variable*12 > This might be premature for you, but it is useful to separate data from logic. If this were my program I'd create a dictionary of conversion factors thus: factors = {("feet", "inches") : 12.0, ("yards", "inches") : 36.0, ...} then look up the user's desire thus: factor = factors[(original, to)] print variable * factor I hope you (1) can understand this and (2) see that it makes program maintenance and expansion a lot easier. Once you get the value of a dictionary then there are more steps you could take: e.g. you only need entries for going "up". If the user requested "inches", "feet" the dictionary lookup would fail, then you'd try again with: factor = factors[(to, original)] print variable / factor Adding key testing: if (original, to) in factors: factor = factors[(original, to)] print variable * factor elif (to, original): factor = factors[(to, original)] print variable / factor else: print "no conversion available for %s to %s" % (original, to) [snip] -- Bob Gailer 919-636-4239 Chapel Hill, NC From nomb85 at comcast.net Sun Mar 23 06:22:45 2008 From: nomb85 at comcast.net (Nathan McBride) Date: Sun, 23 Mar 2008 01:22:45 -0400 Subject: [Tutor] Maybe advanced pexpect question? In-Reply-To: <5e58f2e40802132027w4432d9e0n3847f28fbc48794@mail.gmail.com> References: <3576e740802131857u44da9f5coa07656c1f97f5d91@mail.gmail.com> <5e58f2e40802132027w4432d9e0n3847f28fbc48794@mail.gmail.com> Message-ID: <1206249765.27498.2.camel@localhost.localdomain> I've used pexpect for a few projects and love it. Basically pexpect lets you spawn a program and interact with it from code like you yourself were running it in a console. How would you send the ctrl key? nomb From rabidpoobear at gmail.com Sun Mar 23 08:41:08 2008 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sun, 23 Mar 2008 02:41:08 -0500 Subject: [Tutor] windows: pop up window In-Reply-To: <674d5ce60803221517l64982544sf8f13af121e04f65@mail.gmail.com> References: <674d5ce60803221435x2db92ca9qe3b70d931c044c71@mail.gmail.com> <47E581E3.4040207@tds.net> <674d5ce60803221502i510b3e89if51a70feaffeedc9@mail.gmail.com> <47E58384.6090306@tds.net> <674d5ce60803221510j403248adg24d7042bab73e4f2@mail.gmail.com> <47E584F0.5070207@tds.net> <674d5ce60803221517l64982544sf8f13af121e04f65@mail.gmail.com> Message-ID: On Sat, Mar 22, 2008 at 5:17 PM, elis aeris wrote: > sweet, I love built in functions. thanks ! Seriously, Elis. You would have learned raw_input in *any* Python tutorial. You need to read some tutorials. Seriously. -Luke -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080323/a4125d7d/attachment.htm From alan.gauld at btinternet.com Sun Mar 23 10:16:13 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 23 Mar 2008 09:16:13 -0000 Subject: [Tutor] More Converter References: <245E2DCC-0118-1000-A22A-BD839F694284-Webmail-10021@mac.com> <47E5C382.3050103@alum.rpi.edu> Message-ID: "bob gailer" wrote> Adding key testing: > > if (original, to) in factors: > factor = factors[(original, to)] > print variable * factor > elif (to, original): probably meant to be elif (to,original) in factors: > factor = factors[(to, original)] > print variable / factor > else: > print "no conversion available for %s to %s" % (original, to) Alan G From kent37 at tds.net Sun Mar 23 12:58:19 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 23 Mar 2008 07:58:19 -0400 Subject: [Tutor] Maybe advanced pexpect question? In-Reply-To: <1206249765.27498.2.camel@localhost.localdomain> References: <3576e740802131857u44da9f5coa07656c1f97f5d91@mail.gmail.com> <5e58f2e40802132027w4432d9e0n3847f28fbc48794@mail.gmail.com> <1206249765.27498.2.camel@localhost.localdomain> Message-ID: <47E645DB.8080309@tds.net> Nathan McBride wrote: > I've used pexpect for a few projects and love it. Basically pexpect > lets you spawn a program and interact with it from code like you > yourself were running it in a console. How would you send the ctrl key? I don't use pexpect, so I am guessing... The ctrl key by itself is not a character so you can't send that. ctrl-C is a character that is represented in a string as \x03. I expect you would send a control character with sendline(), for example to sent ctrl-C try child.sendline ('\x03') Kent From kent37 at tds.net Sun Mar 23 13:05:13 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 23 Mar 2008 08:05:13 -0400 Subject: [Tutor] Python Grammer In-Reply-To: <351585.89547.qm@web65416.mail.ac4.yahoo.com> References: <351585.89547.qm@web65416.mail.ac4.yahoo.com> Message-ID: <47E64779.6000702@tds.net> Eric Walker wrote: > Ok, I found the responses, sorry.. > I have been reading the book "Text Processing in PYTHON" by David Mertz. > I have some text that I have to parse. I want to use grammers. It's grammAr. A grammar is a formal description of the structure of a language. It is not a parser; rather it is a specification of what the parser needs to do. Perhaps if you describe your actual problem and say why you want to use a grammar we can be of more help, either pointing you to a parsing solution or helping to solve the problem without a formal parser. (Most Python text processing problems can be solved with simple string processing or regular expressions.) Kent From tayeb.meftah at gmail.com Sun Mar 23 13:44:51 2008 From: tayeb.meftah at gmail.com (Meftah Tayeb) Date: Sun, 23 Mar 2008 13:44:51 +0100 Subject: [Tutor] unsubscription References: <674d5ce60803221443o6d20c66ey79aff13adde868ac@mail.gmail.com><47E5813C.20205@tds.net> <674d5ce60803221502h34472683wbe971acf6146a225@mail.gmail.com> Message-ID: <004701c88ce3$b378c380$0201a8c0@tayeb87b48071c> hi, please ho to Unsubscrib from this mailing list ? thanks... -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080323/946fdefd/attachment.htm From cfuller084 at thinkingplanet.net Sun Mar 23 14:31:41 2008 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Sun, 23 Mar 2008 08:31:41 -0500 Subject: [Tutor] Maybe advanced pexpect question? In-Reply-To: <47E645DB.8080309@tds.net> References: <3576e740802131857u44da9f5coa07656c1f97f5d91@mail.gmail.com> <1206249765.27498.2.camel@localhost.localdomain> <47E645DB.8080309@tds.net> Message-ID: <200803230831.41976.cfuller084@thinkingplanet.net> What about Alt keys? ?I was thinking terminal control voodoo. ?But I don't know any. ?man 5 termcap might be a start, though. Cheers On Sunday 23 March 2008 06:58, Kent Johnson wrote: > Nathan McBride wrote: > > I've used pexpect for a few projects and love it. Basically pexpect > > lets you spawn a program and interact with it from code like you > > yourself were running it in a console. How would you send the ctrl key? > > I don't use pexpect, so I am guessing... > > The ctrl key by itself is not a character so you can't send that. ctrl-C > is a character that is represented in a string as \x03. I expect you > would send a control character with sendline(), for example to sent > ctrl-C try > child.sendline ('\x03') > > Kent > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From cfuller at thinkingplanet.net Sun Mar 23 14:30:30 2008 From: cfuller at thinkingplanet.net (Chris Fuller) Date: Sun, 23 Mar 2008 08:30:30 -0500 Subject: [Tutor] Maybe advanced pexpect question? In-Reply-To: <47E645DB.8080309@tds.net> References: <3576e740802131857u44da9f5coa07656c1f97f5d91@mail.gmail.com> <1206249765.27498.2.camel@localhost.localdomain> <47E645DB.8080309@tds.net> Message-ID: <200803230830.31080.cfuller@thinkingplanet.net> What about Alt keys? I was thinking terminal control voodoo. But I don't know any. man 5 termcap might be a start, though. Cheers On Sunday 23 March 2008 06:58, Kent Johnson wrote: > Nathan McBride wrote: > > I've used pexpect for a few projects and love it. Basically pexpect > > lets you spawn a program and interact with it from code like you > > yourself were running it in a console. How would you send the ctrl key? > > I don't use pexpect, so I am guessing... > > The ctrl key by itself is not a character so you can't send that. ctrl-C > is a character that is represented in a string as \x03. I expect you > would send a control character with sendline(), for example to sent > ctrl-C try > child.sendline ('\x03') > > Kent > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From bgailer at alum.rpi.edu Sun Mar 23 17:20:42 2008 From: bgailer at alum.rpi.edu (bob gailer) Date: Sun, 23 Mar 2008 12:20:42 -0400 Subject: [Tutor] suggestion on improving script In-Reply-To: <47E4EDFD.9080201@khine.net> References: <47E4EDFD.9080201@khine.net> Message-ID: <47E6835A.8010803@alum.rpi.edu> Norman Khine wrote: > Hello, > > Please excuse me in advance if this post is long winded. I have the > following nagging issue for which I have found a work around, but wanted > a better solution. > The reason http://uk.expert.travel/companies/abakuc/;view?batchstart=5 fails while http://uk.expert.travel/;view?t2=5 succeeds does not have to do with using a global method. t2=5 tells the CGI program which tab was clicked, whereas batchstart=5 does not. You only need one "t" function as long as you use the t2=5 approach (or some other way to communicate WHICH tab and WHERE to start (e.g. ?tab=2,batchstart=5. Also - 99% of list_news, list_jobs, et. al. can be factored out into common code. Does this make sense? Would you like more help or can you start figuring it out yourself? > I am using jQuery to populate tabs with some data, such as news and jobs > posts, as can be seen at http://uk.expert.travel > > In my application, I have the following structure (only partially listed): > > $ tree -L 2 > . > |-- expert_travel.py > |-- ui > | `-- ui.tabs.js > ... > `-- utils.py > > > > #expert_travel.py > > from utils import t1, t2, t3, t4 > > ... > > #################################################################### > # News - List > #################################################################### > > def list_news(self, context): > namespace = {} > namespace['batch'] = '' > #Search the catalogue, list all news items in company > > ... > > # Set batch informations > > [t1] batch_start = int(context.get_form_value('t1', default=0)) > > batch_size = 5 > batch_total = len(news_items) > batch_fin = batch_start + batch_size > if batch_fin > batch_total: > batch_fin = batch_total > news_items = news_items[batch_start:batch_fin] > # Namespace > if news_items: > msgs = (u'There is one news item.', > u'There are ${n} news items.') > > [t1] news_batch = t1(context.uri, batch_start, batch_size, > batch_total, msgs=msgs) > > msg = None > else: > news_batch = None > msg = u'Currently there is no news.' > > > #################################################################### > # List jobs > list_jobs__label__ = u'List jobs' > list_jobs__access__ = True > def list_jobs(self, context): > ... > > # Set batch informations > > [t2] batch_start = int(context.get_form_value('t2', default=0)) > > batch_size = 5 > batch_total = len(jobs) > batch_fin = batch_start + batch_size > if batch_fin > batch_total: > batch_fin = batch_total > jobs = jobs[batch_start:batch_fin] > # Namespace > if jobs: > msgs = (u'There is one job.', > u'There are ${n} jobs.') > > [t2] job_batch = t2(context.uri, batch_start, batch_size, > batch_total, msgs=msgs) > > msg = None > else: > job_table = None > job_batch = None > msg = u'Sorry but there are no jobs' > ... > > > > #### > > #utils.py > > def t1(uri, start, size, total, gettext=Handler.gettext, > msgs=(u"There is 1 object.", u"There are ${n} objects.")): > > # Plural forms > if total == 1: > msg1 = gettext(msgs[0]) > else: > msg1 = gettext(msgs[1]) > msg1 = Template(msg1).substitute(n=total) > msg1 = msg1.encode('utf-8') > > # Calculate end > end = min(start + size, total) > > # Previous > previous = None > if start > 0: > previous = max(start - size, 0) > previous = str(previous) > > [t1] previous = uri.replace(t1=previous) > > previous = str(previous) > previous = XMLAttribute.encode(previous) > previous = '<<' \ > % (previous, gettext(u'Previous')) > # Next > next = None > if end < total: > next = str(end) > > [t1] next = uri.replace(t1=next) > > next = str(next) > next = XMLAttribute.encode(next) > next = '>>' \ > % (next, gettext(u'Next')) > > # Output > if previous is None and next is None: > msg = msg1 > else: > # View more > if previous is None: > link = next > elif next is None: > link = previous > else: > link = '%s %s' % (previous, next) > > msg2 = gettext(u"View from ${start} to ${end} (${link}):") > msg2 = Template(msg2) > msg2 = msg2.substitute(start=(start+1), end=end, link=link) > msg2 = msg2.encode('utf-8') > > msg = '%s %s' % (msg1, msg2) > > # Wrap around a paragraph > return Parser('

%s

' % msg, namespaces) > > > #Second TAB > > def t2(uri, start, size, total, gettext=Handler.gettext, > msgs=(u"There is 1 object.", u"There are ${n} objects.")): > # Plural forms > ... > > > ### > > I would like to alter this batch control so that I don't have to create > a new method everytime I need a new tab. > > For example, I would like to change t1, t2 ... t[n] depending on the tab > I am at. > > You can see it in action at http://uk.expert.travel/;view > > If you click on the [Jobs] tab, there are 6 jobs, if you then click on > the 'There are 6 jobs. View from 1 to 5 (>>):' > > you will get a list of the last post. > > Note the URI http://uk.expert.travel/;view?t2=5 > > > If I only use one global method, the problem would be that when I > clicked on the News tab, I will get no items displayed as can be seen here: > > http://uk.expert.travel/companies/abakuc/;view > > I hope this makes sense ;) > > Any advice would be much appreciated. > > Cheers > > Norman > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Bob Gailer 919-636-4239 Chapel Hill, NC From ricaraoz at gmail.com Wed Mar 19 14:36:29 2008 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Wed, 19 Mar 2008 10:36:29 -0300 Subject: [Tutor] Calling super classs __init__? In-Reply-To: <4331ad810803182045v237d226by23361bf4587de965@mail.gmail.com> References: <931023.43222.qm@web45611.mail.sp1.yahoo.com> <5e58f2e40803181737u5101ab5bw861e3e8d2100e014@mail.gmail.com> <4331ad810803182045v237d226by23361bf4587de965@mail.gmail.com> Message-ID: <47E116DD.1070805@bigfoot.com> Luciano Ramalho wrote: > Nowadays the best practice for invoking a method from all superclasses > (yes, multiple inheritance) is this: > > class SubClass(BaseClass): > def __init__(self, t, *args, **kw): > super(SubClass, self).__init__(*args, **kw) > # do something with t > > That way you let Python decide which superclasses your SubClass has, > instead of hard-coding it in several places. > You are actually hard-coding it here too, "class SubClass(BaseClass):" has "BaseClass" hard-coded. All you do here is hard-code it once instead of twice. > Cheers, > > Luciano > > > On Tue, Mar 18, 2008 at 9:37 PM, John Fouhy wrote: >> On 19/03/2008, Allen Fowler wrote: >> > I have a super class that accepts many arguments to it's constructor, and a subclass that should define one additional argument. >> > >> > What's the most "pythonic" way to make this work? >> >> class BaseClass(object): >> def __init__(self, x, y, z, foo='foo'): # whatever >> # etc >> >> class SubClass(BaseClass): >> def __init__(self, t, *args, **kw): >> BaseClass.__init__(self, *args, **kw) >> # do something with t >> >> This does mean that the special sub class argument has to come before >> the base class arguments when you create instances. >> >> Whether you call BaseClass.__init__ early or late in the subclass init >> method could depend on what your classes are doing. Remember, in >> Python, __init__ only initializes objects, it doesn't create them. >> It's just another bit of code that you can call whenever you want. >> >> -- >> John. >> >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld at btinternet.com Sun Mar 23 18:38:05 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 23 Mar 2008 17:38:05 -0000 Subject: [Tutor] unsubscription References: <674d5ce60803221443o6d20c66ey79aff13adde868ac@mail.gmail.com><47E5813C.20205@tds.net><674d5ce60803221502h34472683wbe971acf6146a225@mail.gmail.com> <004701c88ce3$b378c380$0201a8c0@tayeb87b48071c> Message-ID: "Meftah Tayeb" wrote > please ho to Unsubscrib from this mailing list ? Go to the mailing list page on python.org and unsubscribe there. http://mail.python.org/mailman/listinfo/tutor HTH Alan g From maseriyer at yahoo.com Sun Mar 23 18:49:41 2008 From: maseriyer at yahoo.com (maser) Date: Sun, 23 Mar 2008 10:49:41 -0700 (PDT) Subject: [Tutor] what is @classmethod and @staticmethod ?? In-Reply-To: <1206176923.11011.28.camel@localhost> Message-ID: <154961.17428.qm@web50705.mail.re2.yahoo.com> Thanks, Andreas. Why do we need to use classmethod/ staticmethod and where do we need to use them ? thanks iyer --- Andreas Kostyrka wrote: > Well, it's classmethod/staticmethod in truth, @ is > the decorator > operator: > > def testdec(func): > return {"funcobj": func} > > class Abc(object): > @testdec > def method(): > pass > > assert isinstance(Abc.method, dict) > > Basically as you can see above, @X before a function > definition takes > the function, applies X, and use the result instead. > > Now, naive Python level implementations of > classmethod and staticmethod > would be (untested, all typed in the mailer): > > def classmethod(func): > def wrapper(self, *args, **kw): > return func(self.__class__, *args, **kw) > return wrapper > > def staticmethod(func): > def wrapper(self, *args, **kw): > return func(*args, **kw) > return wrapper > > Andreas > > Am Freitag, den 21.03.2008, 20:08 -0700 schrieb > maser: > > Hi > > > > I couldn't find a good resource explaining what > > @classmethod and @staticmethod are in python and > when, > > how these could be used. > > > > If someone could explain what these are, or point > me > > to resources that may help, it is appreciated. > > > > Thanks > > iyer > > > > > > > ____________________________________________________________________________________ > > Be a better friend, newshound, and > > know-it-all with Yahoo! Mobile. Try it now. > http://mobile.yahoo.com/;_ylt=Ahu06i62sR8HDtDypao8Wcj9tAcJ > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > ____________________________________________________________________________________ Be a better friend, newshound, and know-it-all with Yahoo! Mobile. Try it now. http://mobile.yahoo.com/;_ylt=Ahu06i62sR8HDtDypao8Wcj9tAcJ From dineshbvadhia at hotmail.com Sun Mar 23 12:15:03 2008 From: dineshbvadhia at hotmail.com (Dinesh B Vadhia) Date: Sun, 23 Mar 2008 04:15:03 -0700 Subject: [Tutor] from __future__ import division Message-ID: I spent fruitless hours trying to get a (normal) division x/y to work and then saw that you have to declare: > from __future__ import division .. at the top of a module file. What is this all about? Dinesh -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080323/15ca9c6f/attachment.htm From steve at alchemy.com Sun Mar 23 19:51:38 2008 From: steve at alchemy.com (Steve Willoughby) Date: Sun, 23 Mar 2008 11:51:38 -0700 Subject: [Tutor] from __future__ import division In-Reply-To: References: Message-ID: <47E6A6BA.7070303@alchemy.com> Dinesh B Vadhia wrote: > I spent fruitless hours trying to get a (normal) division x/y to work and then saw that you have to declare: normal division x/y works just as expected, with one caveat: remember that if you divide two *integer* values, you will get an *integer* division operation yielding an *integer* result. So: 1.0 / 2.0 --> 0.5 1.0 / 2 --> 0.5 1 / 2.0 --> 0.5 1 / 2 --> 0 So if you make sure at least one operand is a real number you'll get a real result. This is now division works in many programming languages including C and C++. In the future, Python will switch to always yielding a real result, and to force an integer division operation you use the special "//" integer division operator. If you want that behavior now, just import that "from the future": from __future__ import division now: 1 / 2 --> 0.5 4 / 2 --> 2.0 1 // 2 --> 0 4 // 2 --> 2 HTH HAND >> from __future__ import division > > .. at the top of a module file. What is this all about? > > Dinesh > > > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From andreas at kostyrka.org Sun Mar 23 21:20:04 2008 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Sun, 23 Mar 2008 21:20:04 +0100 Subject: [Tutor] Calling super classs __init__? In-Reply-To: <47E116DD.1070805@bigfoot.com> References: <931023.43222.qm@web45611.mail.sp1.yahoo.com> <5e58f2e40803181737u5101ab5bw861e3e8d2100e014@mail.gmail.com> <4331ad810803182045v237d226by23361bf4587de965@mail.gmail.com> <47E116DD.1070805@bigfoot.com> Message-ID: <1206303604.11011.36.camel@localhost> Am Mittwoch, den 19.03.2008, 10:36 -0300 schrieb Ricardo Ar?oz: > Luciano Ramalho wrote: > > Nowadays the best practice for invoking a method from all superclasses > > (yes, multiple inheritance) is this: > > > > class SubClass(BaseClass): > > def __init__(self, t, *args, **kw): > > super(SubClass, self).__init__(*args, **kw) > > # do something with t > > > > That way you let Python decide which superclasses your SubClass has, > > instead of hard-coding it in several places. > > > > You are actually hard-coding it here too, "class SubClass(BaseClass):" > has "BaseClass" hard-coded. All you do here is hard-code it once instead > of twice. Yes and no. Yes a human has specified the relationships. But you do not have to specify what other baseclasses your class has. This is relevant for multiple inheritence, like: D => B => A D => C => A The problem is mostly hiding implementation details. Using super, you just let Python pick the "next" class to give control. Using B.__init__ and C.__init__, A.__init__ would be called twice. Andreas > > > Cheers, > > > > Luciano > > > > > > On Tue, Mar 18, 2008 at 9:37 PM, John Fouhy wrote: > >> On 19/03/2008, Allen Fowler wrote: > >> > I have a super class that accepts many arguments to it's constructor, and a subclass that should define one additional argument. > >> > > >> > What's the most "pythonic" way to make this work? > >> > >> class BaseClass(object): > >> def __init__(self, x, y, z, foo='foo'): # whatever > >> # etc > >> > >> class SubClass(BaseClass): > >> def __init__(self, t, *args, **kw): > >> BaseClass.__init__(self, *args, **kw) > >> # do something with t > >> > >> This does mean that the special sub class argument has to come before > >> the base class arguments when you create instances. > >> > >> Whether you call BaseClass.__init__ early or late in the subclass init > >> method could depend on what your classes are doing. Remember, in > >> Python, __init__ only initializes objects, it doesn't create them. > >> It's just another bit of code that you can call whenever you want. > >> > >> -- > >> John. > >> > >> > >> _______________________________________________ > >> Tutor maillist - Tutor at python.org > >> http://mail.python.org/mailman/listinfo/tutor > >> > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Dies ist ein digital signierter Nachrichtenteil Url : http://mail.python.org/pipermail/tutor/attachments/20080323/75d5d979/attachment.pgp From andreas at kostyrka.org Sun Mar 23 21:25:06 2008 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Sun, 23 Mar 2008 21:25:06 +0100 Subject: [Tutor] what is @classmethod and @staticmethod ?? In-Reply-To: <154961.17428.qm@web50705.mail.re2.yahoo.com> References: <154961.17428.qm@web50705.mail.re2.yahoo.com> Message-ID: <1206303906.11011.40.camel@localhost> One usual usage for classmethods are "alternate" constructors. Andreas Am Sonntag, den 23.03.2008, 10:49 -0700 schrieb maser: > Thanks, Andreas. Why do we need to use classmethod/ > staticmethod and where do we need to use them ? > > thanks > iyer > > --- Andreas Kostyrka wrote: > > > Well, it's classmethod/staticmethod in truth, @ is > > the decorator > > operator: > > > > def testdec(func): > > return {"funcobj": func} > > > > class Abc(object): > > @testdec > > def method(): > > pass > > > > assert isinstance(Abc.method, dict) > > > > Basically as you can see above, @X before a function > > definition takes > > the function, applies X, and use the result instead. > > > > Now, naive Python level implementations of > > classmethod and staticmethod > > would be (untested, all typed in the mailer): > > > > def classmethod(func): > > def wrapper(self, *args, **kw): > > return func(self.__class__, *args, **kw) > > return wrapper > > > > def staticmethod(func): > > def wrapper(self, *args, **kw): > > return func(*args, **kw) > > return wrapper > > > > Andreas > > > > Am Freitag, den 21.03.2008, 20:08 -0700 schrieb > > maser: > > > Hi > > > > > > I couldn't find a good resource explaining what > > > @classmethod and @staticmethod are in python and > > when, > > > how these could be used. > > > > > > If someone could explain what these are, or point > > me > > > to resources that may help, it is appreciated. > > > > > > Thanks > > > iyer > > > > > > > > > > > > ____________________________________________________________________________________ > > > Be a better friend, newshound, and > > > know-it-all with Yahoo! Mobile. Try it now. > > > http://mobile.yahoo.com/;_ylt=Ahu06i62sR8HDtDypao8Wcj9tAcJ > > > _______________________________________________ > > > Tutor maillist - Tutor at python.org > > > http://mail.python.org/mailman/listinfo/tutor > > > > > > ____________________________________________________________________________________ > Be a better friend, newshound, and > know-it-all with Yahoo! Mobile. Try it now. http://mobile.yahoo.com/;_ylt=Ahu06i62sR8HDtDypao8Wcj9tAcJ -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Dies ist ein digital signierter Nachrichtenteil Url : http://mail.python.org/pipermail/tutor/attachments/20080323/73725862/attachment.pgp From dreamweaver.gr at gmail.com Sun Mar 23 22:44:28 2008 From: dreamweaver.gr at gmail.com (Konstantinos Rousis) Date: Sun, 23 Mar 2008 23:44:28 +0200 Subject: [Tutor] Handling XMLHTTPRequests In-Reply-To: References: Message-ID: Dear all, I am trying to build an extension for the Firefox that will automatically authorize users through KeyNote system. My components are the following: 1. Python implementation of KeyNote. Stand-alone, given some information makes the authorization decision. 2. Firefox Extension: When some events are triggered, an XMLHTTPRequest (XHR) should be sent to the server. 3. *(?)A python script that should handle the XHRs.* 1 and 2 are ready and my difficulties are in 3. I need some conceptual help on the following: - Is it possible a Python script hosted on Apache, accept the XHRs made from Firefox extension's JavaScript? - Can data sent (e.g. XML files) along with the XHR be extracted from my python script and be redirected to the stand-alone Python KeyNote application, as well as getting the result back (i.e. authorization decision)? - Can I define the HTTP response that will be sent back to the browser/client? The important thing is this script to be hosted on an Apache server and not be a stand-alone server. Moreover I would like to avoid the use of CGI and rather use the mod_python. Any help would be really appreciated. -- Regards, Konstantinos -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080323/06a10120/attachment.htm From kent37 at tds.net Sun Mar 23 23:26:26 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 23 Mar 2008 18:26:26 -0400 Subject: [Tutor] what is @classmethod and @staticmethod ?? In-Reply-To: <154961.17428.qm@web50705.mail.re2.yahoo.com> References: <154961.17428.qm@web50705.mail.re2.yahoo.com> Message-ID: <47E6D912.1050801@tds.net> maser wrote: > Thanks, Andreas. Why do we need to use classmethod/ > staticmethod and where do we need to use them ? I use staticmethods as a convenience to put related functions in the namespace of a class. Perhaps foo.py contains class Foo with staticmethod bar(). In client code I can say from foo import Foo Foo.bar() If bar was a module method it would be from foo import Foo, bar bar() I prefer the former in cases where bar is related to Foo. Kent From mwalsh at mwalsh.org Sun Mar 23 20:00:53 2008 From: mwalsh at mwalsh.org (mwalsh) Date: Sun, 23 Mar 2008 14:00:53 -0500 Subject: [Tutor] Maybe advanced pexpect question? In-Reply-To: <47E645DB.8080309@tds.net> References: <3576e740802131857u44da9f5coa07656c1f97f5d91@mail.gmail.com> <5e58f2e40802132027w4432d9e0n3847f28fbc48794@mail.gmail.com> <1206249765.27498.2.camel@localhost.localdomain> <47E645DB.8080309@tds.net> Message-ID: <47E6A8E5.80507@mwalsh.org> Kent Johnson wrote: > Nathan McBride wrote: >> I've used pexpect for a few projects and love it. Basically pexpect >> lets you spawn a program and interact with it from code like you >> yourself were running it in a console. How would you send the ctrl key? > > I don't use pexpect, so I am guessing... > > The ctrl key by itself is not a character so you can't send that. ctrl-C > is a character that is represented in a string as \x03. I expect you > would send a control character with sendline(), for example to sent > ctrl-C try > child.sendline ('\x03') In recent versions of pexpect (I'm looking at 2.3), 'spawn' objects include a sendcontrol method which does almost exactly that for cntl-c, with send instead of sendline. > Kent > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From hunter92383 at gmail.com Sun Mar 23 23:42:04 2008 From: hunter92383 at gmail.com (elis aeris) Date: Sun, 23 Mar 2008 15:42:04 -0700 Subject: [Tutor] I am reading the tutorial alright? Message-ID: <674d5ce60803231542m66714edcpf6d4ae9b47b80e23@mail.gmail.com> t = 12345, 54321, "hello!" print t[0] the way the 3 items are saved and access fits my need, now how do I make t have more than one entry so effectively I get this? t[n][n] ? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080323/c9bf6b15/attachment.htm From cappy2112 at gmail.com Mon Mar 24 00:11:33 2008 From: cappy2112 at gmail.com (Tony Cappellini) Date: Sun, 23 Mar 2008 16:11:33 -0700 Subject: [Tutor] what is @classmethod and @staticmethod ?? Message-ID: <8249c4ac0803231611v40eb8b9cw75813cf75c2dd698@mail.gmail.com> Kent Would you show the examples which show where staticmethod & classmethod are used? I've often wondered about the usefulness of these myself. Having read many of the popular books on python, none provide a good clear explanation of why or where these should be used, and what the alternatives are (if any). They typically show an extremely terse example of the syntax with little explanation. Message: 7 Date: Sun, 23 Mar 2008 18:26:26 -0400 From: Kent Johnson Subject: Re: [Tutor] what is @classmethod and @staticmethod ?? To: maser Cc: tutor at python.org Message-ID: <47E6D912.1050801 at tds.net> Content-Type: text/plain; charset=ISO-8859-1; format=flowed maser wrote: > Thanks, Andreas. Why do we need to use classmethod/ > staticmethod and where do we need to use them ? I use staticmethods as a convenience to put related functions in the namespace of a class. Perhaps foo.py contains class Foo with staticmethod bar(). In client code I can say from foo import Foo Foo.bar() If bar was a module method it would be from foo import Foo, bar bar() I prefer the former in cases where bar is related to Foo. Kent From bgailer at alum.rpi.edu Mon Mar 24 00:13:47 2008 From: bgailer at alum.rpi.edu (bob gailer) Date: Sun, 23 Mar 2008 19:13:47 -0400 Subject: [Tutor] I am reading the tutorial alright? In-Reply-To: <674d5ce60803231542m66714edcpf6d4ae9b47b80e23@mail.gmail.com> References: <674d5ce60803231542m66714edcpf6d4ae9b47b80e23@mail.gmail.com> Message-ID: <47E6E42B.6020808@alum.rpi.edu> elis aeris wrote: > t = 12345, 54321, "hello!" > print t[0] > > the way the 3 items are saved and access fits my need, now how do I > make t have more than one entry so effectively I get this? > > t[n][n] > (1) are you going through the tutorials as requested? (2) please learn how to ask meaningful questions For example t[n][n] does not communicate the outcome you desire. In Python t[n][n] would get you the nth element of the nth element of t. For example if n were 2 you'd get 3. If that is what you want you just answered your own question, as a simple test in the Python interactive window would reveal. Otherwise we can only guess as to what you want and that wastes all of our time! It would be far more effective to show us what the result would look like based on the data you entered into t. PLEASE do as much as you can to solve problems yourself and express questions CLEARLY! -- Bob Gailer 919-636-4239 Chapel Hill, NC From hunter92383 at gmail.com Mon Mar 24 00:16:29 2008 From: hunter92383 at gmail.com (elis aeris) Date: Sun, 23 Mar 2008 16:16:29 -0700 Subject: [Tutor] I am reading the tutorial alright? In-Reply-To: <47E6E42B.6020808@alum.rpi.edu> References: <674d5ce60803231542m66714edcpf6d4ae9b47b80e23@mail.gmail.com> <47E6E42B.6020808@alum.rpi.edu> Message-ID: <674d5ce60803231616s65e85704kd52107e3411a457d@mail.gmail.com> in c++ i use array[n][n] to store things. how do i create an array like that? On Sun, Mar 23, 2008 at 4:13 PM, bob gailer wrote: > elis aeris wrote: > > t = 12345, 54321, "hello!" > > print t[0] > > > > the way the 3 items are saved and access fits my need, now how do I > > make t have more than one entry so effectively I get this? > > > > t[n][n] > > > (1) are you going through the tutorials as requested? > (2) please learn how to ask meaningful questions > For example t[n][n] does not communicate the outcome you desire. > In Python t[n][n] would get you the nth element of the nth element of t. > For example if n were 2 you'd get 3. If that is what you want you just > answered your own question, as a simple test in the Python interactive > window would reveal. > > Otherwise we can only guess as to what you want and that wastes all of > our time! > > It would be far more effective to show us what the result would look > like based on the data you entered into t. > > PLEASE do as much as you can to solve problems yourself and express > questions CLEARLY! > > -- > Bob Gailer > 919-636-4239 Chapel Hill, NC > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080323/0f6cbcb6/attachment.htm From marc.tompkins at gmail.com Mon Mar 24 00:22:07 2008 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Sun, 23 Mar 2008 16:22:07 -0700 Subject: [Tutor] I am reading the tutorial alright? In-Reply-To: <674d5ce60803231616s65e85704kd52107e3411a457d@mail.gmail.com> References: <674d5ce60803231542m66714edcpf6d4ae9b47b80e23@mail.gmail.com> <47E6E42B.6020808@alum.rpi.edu> <674d5ce60803231616s65e85704kd52107e3411a457d@mail.gmail.com> Message-ID: <40af687b0803231622y49ba72e1m89780fc14d3463ca@mail.gmail.com> On Sun, Mar 23, 2008 at 4:16 PM, elis aeris wrote: > in c++ i use array[n][n] to store things. > > how do i create an array like that? > Python doesn't have "arrays". It has tuples, lists, and dictionaries. A quick Google will tell you the distinctions between them. It looks to me like you want to create a list of lists.... t =[ ["item1", "item2", "item3"], ["itemA", "itemB", "itemC"], ["itemI", "itemII", "itemIII"] ] t[0][0] == "item1" t[1][1] == "itemB" t[2][2] == "itemIII" > > > > > > On Sun, Mar 23, 2008 at 4:13 PM, bob gailer wrote: > > > elis aeris wrote: > > > t = 12345, 54321, "hello!" > > > print t[0] > > > > > > the way the 3 items are saved and access fits my need, now how do I > > > make t have more than one entry so effectively I get this? > > > > > > t[n][n] > > > > > (1) are you going through the tutorials as requested? > > (2) please learn how to ask meaningful questions > > For example t[n][n] does not communicate the outcome you desire. > > In Python t[n][n] would get you the nth element of the nth element of t. > > For example if n were 2 you'd get 3. If that is what you want you just > > answered your own question, as a simple test in the Python interactive > > window would reveal. > > > > Otherwise we can only guess as to what you want and that wastes all of > > our time! > > > > It would be far more effective to show us what the result would look > > like based on the data you entered into t. > > > > PLEASE do as much as you can to solve problems yourself and express > > questions CLEARLY! > > > > -- > > Bob Gailer > > 919-636-4239 Chapel Hill, NC > > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080323/21573f21/attachment.htm From hunter92383 at gmail.com Mon Mar 24 00:24:25 2008 From: hunter92383 at gmail.com (elis aeris) Date: Sun, 23 Mar 2008 16:24:25 -0700 Subject: [Tutor] I am reading the tutorial alright? In-Reply-To: <40af687b0803231622y49ba72e1m89780fc14d3463ca@mail.gmail.com> References: <674d5ce60803231542m66714edcpf6d4ae9b47b80e23@mail.gmail.com> <47E6E42B.6020808@alum.rpi.edu> <674d5ce60803231616s65e85704kd52107e3411a457d@mail.gmail.com> <40af687b0803231622y49ba72e1m89780fc14d3463ca@mail.gmail.com> Message-ID: <674d5ce60803231624v5cf4ff66n36837d6943fa488a@mail.gmail.com> t =[ ["item1", "item2", "item3"], ["itemA", "itemB", "itemC"], ["itemI", "itemII", "itemIII"] ] yes this is what I am looking for. Now I want to talk about this: how should I have asked my Q to let everyone know what I was looking for? looking back to my first post, it seems to be a little weak. Can you suggest something that I could have said? On Sun, Mar 23, 2008 at 4:22 PM, Marc Tompkins wrote: > On Sun, Mar 23, 2008 at 4:16 PM, elis aeris wrote: > > > in c++ i use array[n][n] to store things. > > > > how do i create an array like that? > > > > Python doesn't have "arrays". It has tuples, lists, and dictionaries. A > quick Google will tell you the distinctions between them. > > It looks to me like you want to create a list of lists.... > > > t =[ ["item1", "item2", "item3"], ["itemA", "itemB", "itemC"], ["itemI", > "itemII", "itemIII"] ] > > t[0][0] == "item1" > t[1][1] == "itemB" > t[2][2] == "itemIII" > > > > > > > > > > > > > > > > > On Sun, Mar 23, 2008 at 4:13 PM, bob gailer > > wrote: > > > > > elis aeris wrote: > > > > t = 12345, 54321, "hello!" > > > > print t[0] > > > > > > > > the way the 3 items are saved and access fits my need, now how do I > > > > make t have more than one entry so effectively I get this? > > > > > > > > t[n][n] > > > > > > > (1) are you going through the tutorials as requested? > > > (2) please learn how to ask meaningful questions > > > For example t[n][n] does not communicate the outcome you desire. > > > In Python t[n][n] would get you the nth element of the nth element of > > > t. > > > For example if n were 2 you'd get 3. If that is what you want you just > > > answered your own question, as a simple test in the Python interactive > > > window would reveal. > > > > > > Otherwise we can only guess as to what you want and that wastes all of > > > our time! > > > > > > It would be far more effective to show us what the result would look > > > like based on the data you entered into t. > > > > > > PLEASE do as much as you can to solve problems yourself and express > > > questions CLEARLY! > > > > > > -- > > > Bob Gailer > > > 919-636-4239 Chapel Hill, NC > > > > > > > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > -- > www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080323/fe5657ce/attachment.htm From hunter92383 at gmail.com Mon Mar 24 00:24:40 2008 From: hunter92383 at gmail.com (elis aeris) Date: Sun, 23 Mar 2008 16:24:40 -0700 Subject: [Tutor] I am reading the tutorial alright? In-Reply-To: <40af687b0803231622y49ba72e1m89780fc14d3463ca@mail.gmail.com> References: <674d5ce60803231542m66714edcpf6d4ae9b47b80e23@mail.gmail.com> <47E6E42B.6020808@alum.rpi.edu> <674d5ce60803231616s65e85704kd52107e3411a457d@mail.gmail.com> <40af687b0803231622y49ba72e1m89780fc14d3463ca@mail.gmail.com> Message-ID: <674d5ce60803231624j3fd23169qba5edd12207a4376@mail.gmail.com> thanks for the reply, btw. On Sun, Mar 23, 2008 at 4:22 PM, Marc Tompkins wrote: > On Sun, Mar 23, 2008 at 4:16 PM, elis aeris wrote: > > > in c++ i use array[n][n] to store things. > > > > how do i create an array like that? > > > > Python doesn't have "arrays". It has tuples, lists, and dictionaries. A > quick Google will tell you the distinctions between them. > > It looks to me like you want to create a list of lists.... > > > t =[ ["item1", "item2", "item3"], ["itemA", "itemB", "itemC"], ["itemI", > "itemII", "itemIII"] ] > > t[0][0] == "item1" > t[1][1] == "itemB" > t[2][2] == "itemIII" > > > > > > > > > > > > > > > > > On Sun, Mar 23, 2008 at 4:13 PM, bob gailer > > wrote: > > > > > elis aeris wrote: > > > > t = 12345, 54321, "hello!" > > > > print t[0] > > > > > > > > the way the 3 items are saved and access fits my need, now how do I > > > > make t have more than one entry so effectively I get this? > > > > > > > > t[n][n] > > > > > > > (1) are you going through the tutorials as requested? > > > (2) please learn how to ask meaningful questions > > > For example t[n][n] does not communicate the outcome you desire. > > > In Python t[n][n] would get you the nth element of the nth element of > > > t. > > > For example if n were 2 you'd get 3. If that is what you want you just > > > answered your own question, as a simple test in the Python interactive > > > window would reveal. > > > > > > Otherwise we can only guess as to what you want and that wastes all of > > > our time! > > > > > > It would be far more effective to show us what the result would look > > > like based on the data you entered into t. > > > > > > PLEASE do as much as you can to solve problems yourself and express > > > questions CLEARLY! > > > > > > -- > > > Bob Gailer > > > 919-636-4239 Chapel Hill, NC > > > > > > > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > -- > www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080323/965f05c9/attachment-0001.htm From kent37 at tds.net Mon Mar 24 00:34:34 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 23 Mar 2008 19:34:34 -0400 Subject: [Tutor] what is @classmethod and @staticmethod ?? In-Reply-To: <8249c4ac0803231611v40eb8b9cw75813cf75c2dd698@mail.gmail.com> References: <8249c4ac0803231611v40eb8b9cw75813cf75c2dd698@mail.gmail.com> Message-ID: <47E6E90A.1060001@tds.net> Tony Cappellini wrote: > Kent > > Would you show the examples which show where staticmethod & > classmethod are used? Some good discussion here: http://groups.google.com/group/comp.lang.python/browse_thread/thread/56ee49c203fd72e2/922f84d9d26662fc?hl=en&lnk=gst& I don't use classmethods so I can't discuss that. For staticmethods, suppose I have in foo.py class Foo(object): # Lots of useful stuff In client.py I have from foo import Foo # Do interesting things with Foo Now perhaps I need a function doSomethingRelatedToFoo() that belongs in foo.py but doesn't have to be an instance method - it is just a related function. I could make this a module function and change client.py to read from foo import Foo, doSomethingRelatedToFoo doSomethingRelatedToFoo() or I could make doSomethingRelatedToFoo a staticmethod, then I don't have to change the import statement, I can access doSomethingRelatedToFoo() through the already-imported Foo class: Foo.doSomethingRelatedToFoo() It's a pretty small difference but I like keeping the import simple and not having to change it when I add doSomethingRelatedToFoo() to foo.py. Kent From hunter92383 at gmail.com Mon Mar 24 00:41:21 2008 From: hunter92383 at gmail.com (elis aeris) Date: Sun, 23 Mar 2008 16:41:21 -0700 Subject: [Tutor] returning two values continued Message-ID: <674d5ce60803231641k6d3ecf93t589b9abafdc0a9a7@mail.gmail.com> def returning (): a = 1 b = 2 return a, b ab = returning() does this work? if it does, is ab a tuple of 2 and [0] being a and [1] being b? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080323/48df6bf3/attachment.htm From cappy2112 at gmail.com Mon Mar 24 01:07:55 2008 From: cappy2112 at gmail.com (Tony Cappellini) Date: Sun, 23 Mar 2008 17:07:55 -0700 Subject: [Tutor] what is @classmethod and @staticmethod ?? In-Reply-To: <47E6E90A.1060001@tds.net> References: <8249c4ac0803231611v40eb8b9cw75813cf75c2dd698@mail.gmail.com> <47E6E90A.1060001@tds.net> Message-ID: <8249c4ac0803231707m1d7d0102i5ff976a4cb090f10@mail.gmail.com> > I don't use classmethods so I can't discuss that. For staticmethods, > suppose I have in foo.py Where is the word "staticmethod" in the example below? Where is it used? This is what I was hoping to see. > > class Foo(object): > # Lots of useful stuff > > > In client.py I have > > from foo import Foo > > # Do interesting things with Foo > > > Now perhaps I need a function > doSomethingRelatedToFoo() > that belongs in foo.py but doesn't have to be an instance method - it is > just a related function. I could make this a module function and change > client.py to read > > from foo import Foo, doSomethingRelatedToFoo > > doSomethingRelatedToFoo() > > > or I could make doSomethingRelatedToFoo a staticmethod, then I don't > have to change the import statement, I can access > doSomethingRelatedToFoo() through the already-imported Foo class: > > Foo.doSomethingRelatedToFoo() > > It's a pretty small difference but I like keeping the import simple and > not having to change it when I add doSomethingRelatedToFoo() to foo.py. > > Kent > From marc.tompkins at gmail.com Mon Mar 24 01:11:10 2008 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Sun, 23 Mar 2008 17:11:10 -0700 Subject: [Tutor] I am reading the tutorial alright? In-Reply-To: <674d5ce60803231624v5cf4ff66n36837d6943fa488a@mail.gmail.com> References: <674d5ce60803231542m66714edcpf6d4ae9b47b80e23@mail.gmail.com> <47E6E42B.6020808@alum.rpi.edu> <674d5ce60803231616s65e85704kd52107e3411a457d@mail.gmail.com> <40af687b0803231622y49ba72e1m89780fc14d3463ca@mail.gmail.com> <674d5ce60803231624v5cf4ff66n36837d6943fa488a@mail.gmail.com> Message-ID: <40af687b0803231711g379b06d4o2c77c37d96d50c30@mail.gmail.com> On Sun, Mar 23, 2008 at 4:24 PM, elis aeris wrote: > Now I want to talk about this: how should I have asked my Q to let > everyone know what I was looking for? > > looking back to my first post, it seems to be a little weak. Can you > suggest something that I could have said? > Offhand, how about "What's the Python equivalent of a multi-dimensional array?" Speaking only for myself, what bugs me about most of your questions so far is that you don't seem to do any thinking before you hit Send. For a few of your questions, it would have taken you less time/effort to do a three-word Google search than to ask the list; for this one, this list was probably the right place - but thirty seconds of thought about what you really wanted to ask would have made the difference. If you don't know the technical terms( e.g. "array" versus "list", "dictionary", "tuple"), I for one will not bite your head off for it - as long as you make a good-faith effort to express yourself. Most of us who read and answer questions are going to spend at least a couple of minutes, and some thought, on our reply. If it seems that you spent less than that on your question, it can be irritating. Some of us can be downright cranky, but nobody likes to feel disrespected. Just take a minute and think. -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080323/16efae04/attachment.htm From alan.gauld at btinternet.com Mon Mar 24 01:22:01 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 24 Mar 2008 00:22:01 -0000 Subject: [Tutor] what is @classmethod and @staticmethod ?? References: <1206176923.11011.28.camel@localhost> <154961.17428.qm@web50705.mail.re2.yahoo.com> Message-ID: "maser" wrote > Thanks, Andreas. Why do we need to use classmethod/ > staticmethod and where do we need to use them ? Although there are minor technical details where they differ static methods and class methods are nearly identical. The names come from two programming traditions with different names for the same thing. Smalltalk and Lisp etc use class method. Delphi, C++ and Javba use static method. In terms of usage they are both the same and have two basic purposes: 1) As per my earlier response and example to do something to the entire class of objects, either select one instance using some kind of search mechanism - database queries are often coded in class methods, or a count of all instances (perhaps with filters which is similar to a database sel;ect) or it can be conversions of one type/class to another. And this can in turn be a kind of factory method or pseudo constructor. 2) class methods can also be used to provide generic collections of functions, perhaps with some shared data/variables. Booch called these "Class Utilities" in his book. They could for example provide a pseudo object interface to legacy code or provide namespace protection for a commonly used data name. The second form can usually be provided with functions in a module in Python but thats not the case in some other languages. As a practical example of the former consider a client/server application where the client sends requests to the server specifying the class and instance and method of the target object. The interprocess message handler can delegate the message to a class method to look up the instance and in turn call the actual method of the returned instance. This is much lighter weight than using a full blown Object Request Broker but provides a simar level of decoupling and ease of use in the client code. I've built several systems using this pattern and the RPC code hardly changes. Another example is where you need to produce highly dynamic object systems with lots of introspection and varying object structures. This is rarely needed in Python because the built in introspection is so good but in languages like C++ it may be the easiest way of creating new "classes" (not objects) in real time (although in truth these "classes" are restricted to new data members and accessor methods) One practical case using this was a hospital diagniosis system where doctors needed to be able to introduce new subclasses of disease/diagnosis and have these classes merge seamlessly with the base hard coded disease classes. Static methods were used to maintain dictionaries of dictionaries representing the sub classes and their features. These could then be passed to the instances as required and the instances performed a similar kind of attribute access to that used by Python. Its probably worth saying that these kinds of uses are powerful when needed but they are not by any means needed in every program. Although once you use them you tend to find more uses for them than you previously expected! :-) HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From marc.tompkins at gmail.com Mon Mar 24 01:26:08 2008 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Sun, 23 Mar 2008 17:26:08 -0700 Subject: [Tutor] returning two values continued In-Reply-To: <674d5ce60803231641k6d3ecf93t589b9abafdc0a9a7@mail.gmail.com> References: <674d5ce60803231641k6d3ecf93t589b9abafdc0a9a7@mail.gmail.com> Message-ID: <40af687b0803231726j36d2de40m99eedb3e9ceda31f@mail.gmail.com> On Sun, Mar 23, 2008 at 4:41 PM, elis aeris wrote: > def returning (): > a = 1 > b = 2 > return a, b > > > ab = returning() > > > does this work? > I cut and pasted into an interactive Python session: >>> def returning (): ... a = 1 ... b = 2 ... return a, b ... >>> >>> ab = returning() >>> print ab (1, 2) if it does, is ab a tuple of 2 and [0] being a and [1] being b? > >>> print type(ab) >>> print ab[0] 1 >>> print ab[1] 2 I don't know what environment you're using - I use Windows XP. 1 - Start/Run, 'cmd', OK gets me a command prompt. 2 - I type "python" and hit Enter - I have a Python interactive session. 3 - I highlight your code snippet, hit Ctrl-Ins to copy it, then right-click in the Python session and select Paste. Ten seconds down, and there's your answer. Your question was reasonably well thought-out and phrased - you're halfway there. Go the other half - try it yourself as I did, and if there's still something (like an error message) you don't understand, post the code AND the result when you tried it. It only takes an extra minute, and it gets you a LOT more credit here. Cut, Copy, and Paste are your friends. -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080323/a4212d36/attachment.htm From alan.gauld at btinternet.com Mon Mar 24 01:25:36 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 24 Mar 2008 00:25:36 -0000 Subject: [Tutor] from __future__ import division References: <47E6A6BA.7070303@alchemy.com> Message-ID: "Steve Willoughby" wrote > normal division x/y works just as expected, with one caveat: > remember > that if you divide two *integer* values, you will get an *integer* > division operation yielding an *integer* result. So: It's worth pointing out that although beginners tend to find this behaviour odd it is actually very useful for many types of programming problem(*). That's why the future mechanism includes a new operator to do the older style integer division (*)Some examples include manipulating indices into lists, selecting from limited ranges, dealing with cyclic lists etc. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Mon Mar 24 01:31:22 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 24 Mar 2008 00:31:22 -0000 Subject: [Tutor] I am reading the tutorial alright? References: <674d5ce60803231542m66714edcpf6d4ae9b47b80e23@mail.gmail.com><47E6E42B.6020808@alum.rpi.edu> <674d5ce60803231616s65e85704kd52107e3411a457d@mail.gmail.com> Message-ID: "elis aeris" wrote > in c++ i use array[n][n] to store things. > > how do i create an array like that? Please read any tutorial they nearly all cover multi dimensional lists. It is also easy to experiment at the >>> prompt. Just try the obvious thing - create a list of lists. It works as you wouyld expect from C++. People spend a lot of time writing tutorials so that beginners don't need to ask questions like this. And so the tutors don't need to spend a lot of their time answering the same things for every beginner! We are trying to be helpful but you need to help yourself too. It is far quicker to spend some time on a tutorial than to post questions here thenm wait for a reply that answers it. Try building a list of lists. If you have problems come back and show us what you did and what went wrong. Then we can offer specific help. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Mon Mar 24 01:37:47 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 24 Mar 2008 00:37:47 -0000 Subject: [Tutor] returning two values continued References: <674d5ce60803231641k6d3ecf93t589b9abafdc0a9a7@mail.gmail.com> Message-ID: "elis aeris" wrote > def returning (): > a = 1 > b = 2 > return a, b > > > ab = returning() > > > does this work? > > if it does, is ab a tuple of 2 and [0] being a and [1] being b? Try it in the >>> prompt, thats what its there for and will give you an instant answer: >>> def returning(): ... a = 1 ... b = 2 ... return a,b ... >>> ab = returning() >>> print ab (1, 2) >>> print ab[0] 1 >>> print ab[1] 2 >>> Does that answer your question? -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld Give a man a fish and feed him for a day Teach him to fish and you feed him for life From alan.gauld at btinternet.com Mon Mar 24 01:34:42 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 24 Mar 2008 00:34:42 -0000 Subject: [Tutor] I am reading the tutorial alright? References: <674d5ce60803231542m66714edcpf6d4ae9b47b80e23@mail.gmail.com><47E6E42B.6020808@alum.rpi.edu><674d5ce60803231616s65e85704kd52107e3411a457d@mail.gmail.com><40af687b0803231622y49ba72e1m89780fc14d3463ca@mail.gmail.com> <674d5ce60803231624v5cf4ff66n36837d6943fa488a@mail.gmail.com> Message-ID: "elis aeris" wrote > looking back to my first post, it seems to be a little weak. Can you > suggest > something that I could have said? Your first post was downright confusing. Your second post was better because it described what you wanted. You did that by drawing comparison with C++ arrays. In general describe the problem you are trying to solve and show what you think the code might look like and the output you would expect. or like to see. And before posting try a search on google, always including the work Python in the search string. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Mon Mar 24 01:56:36 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 23 Mar 2008 20:56:36 -0400 Subject: [Tutor] what is @classmethod and @staticmethod ?? In-Reply-To: <8249c4ac0803231707m1d7d0102i5ff976a4cb090f10@mail.gmail.com> References: <8249c4ac0803231611v40eb8b9cw75813cf75c2dd698@mail.gmail.com> <47E6E90A.1060001@tds.net> <8249c4ac0803231707m1d7d0102i5ff976a4cb090f10@mail.gmail.com> Message-ID: <47E6FC44.9010006@tds.net> Tony Cappellini wrote: >> I don't use classmethods so I can't discuss that. For staticmethods, >> suppose I have in foo.py > > Where is the word "staticmethod" in the example below? Where is it used? > This is what I was hoping to see. It would be class Foo(object): @staticmethod def doSomethingRelatedToFoo(): # whatever Kent From hunter92383 at gmail.com Mon Mar 24 02:25:00 2008 From: hunter92383 at gmail.com (elis aeris) Date: Sun, 23 Mar 2008 18:25:00 -0700 Subject: [Tutor] def_a Message-ID: <674d5ce60803231825u35a737b8i10c126bb1731b126@mail.gmail.com> def_a =[ ["3.2.2.2.2.2.3.", "0.0.3.2.2.2.2.2.3.0.0.0.", "O"], ["8.1.1.4.", "0.0.2.2.2.2.3.1.1.1.0.0.", "h"], ["1.2.", "0.1.1.1.0.0.0.0.0.0.0.0.", ","], ["2.7.2.", "0.0.3.1.1.1.1.1.3.0.0.0.", "I"], ["5.1.1.4.1.1.4.", "0.0.3.3.3.3.5.0.0.0.0.0.", "m"], ["3.3.3.3.", "0.0.3.1.4.2.2.0.0.0.0.0.", "e"], ["1.3.3.4.", "0.0.3.2.3.1.2.0.0.0.0.0.", "a"], ["5.1.1.4.", "0.0.2.2.2.2.3.0.0.0.0.0.", "n"], ["2.", "0.0.1.1.0.0.0.0.0.0.0.0.", "."], ["7.1.1.1.1.", "0.0.5.1.1.1.1.1.1.0.0.0.", "L"], ["1.5.2.2.", "0.0.2.1.1.1.4.1.0.0.0.0.", "t"], ["3.", "0.0.0.0.0.0.0.1.1.1.0.0.", "'"], ["2.3.3.2.", "0.0.3.1.2.1.3.0.0.0.0.0.", "s"], ["3.3.3.6.", "2.1.3.2.2.2.3.0.0.0.0.0.", "g"], ["3.2.2.3.", "0.0.2.2.2.2.2.0.0.0.0.0.", "o"], ["8.2.2.3.", "0.0.3.2.2.2.3.1.1.1.0.0.", "b"], ["4.1.1.5.", "0.0.3.2.2.2.2.0.0.0.0.0.", "u"], ["6.", "0.0.1.1.1.1.1.0.1.0.0.0.", "i"], ["6.", "0.0.1.0.1.1.1.1.1.0.0.0.", "!"] , ] def returnzero: return def_a[2] this is a simple version of the function i use, and of course in the real version [0] and [1] is used as well. what I am trying to do is to write a generic function like this def returnzero (def_a): return def_a in other words, a generic function that is able to use any list assigned to it, so that i don't have to write 8 functions just to use 8 list,because that would be dumb, right? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080323/f6a943c1/attachment.htm From alan.gauld at btinternet.com Mon Mar 24 02:40:03 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 24 Mar 2008 01:40:03 -0000 Subject: [Tutor] def_a References: <674d5ce60803231825u35a737b8i10c126bb1731b126@mail.gmail.com> Message-ID: "elis aeris" wrote > def_a =[ > ["3.2.2.2.2.2.3.", "0.0.3.2.2.2.2.2.3.0.0.0.", "O"], > .... > ["6.", "0.0.1.1.1.1.1.0.1.0.0.0.", "i"], > ["6.", "0.0.1.0.1.1.1.1.1.0.0.0.", "!"] > ] > > def returnzero: > return def_a[2] > > what I am trying to do is to write a generic function like this > > def returnzero (def_a): > return def_a > > in other words, a generic function that is able to use any list > assigned to > it, so that i don't have to write 8 functions just to use 8 > list,because > that would be dumb, right? Yes it would be dumb. Do you have any other questions? Have you tried the code? Did it work as expected? Alan G. From hunter92383 at gmail.com Mon Mar 24 05:03:35 2008 From: hunter92383 at gmail.com (elis aeris) Date: Sun, 23 Mar 2008 21:03:35 -0700 Subject: [Tutor] def_a In-Reply-To: References: <674d5ce60803231825u35a737b8i10c126bb1731b126@mail.gmail.com> Message-ID: <674d5ce60803232103j740561bdp55fd61b181f47cd@mail.gmail.com> it works :D On Sun, Mar 23, 2008 at 6:40 PM, Alan Gauld wrote: > > "elis aeris" wrote > > > def_a =[ > > ["3.2.2.2.2.2.3.", "0.0.3.2.2.2.2.2.3.0.0.0.", "O"], > > .... > > ["6.", "0.0.1.1.1.1.1.0.1.0.0.0.", "i"], > > ["6.", "0.0.1.0.1.1.1.1.1.0.0.0.", "!"] > > ] > > > > def returnzero: > > return def_a[2] > > > > what I am trying to do is to write a generic function like this > > > > def returnzero (def_a): > > return def_a > > > > in other words, a generic function that is able to use any list > > assigned to > > it, so that i don't have to write 8 functions just to use 8 > > list,because > > that would be dumb, right? > > Yes it would be dumb. > > Do you have any other questions? > Have you tried the code? Did it work as expected? > > Alan G. > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080323/77203c8a/attachment.htm From trey at opmstech.org Mon Mar 24 06:04:44 2008 From: trey at opmstech.org (Trey Keown) Date: Mon, 24 Mar 2008 00:04:44 -0500 (CDT) Subject: [Tutor] cross-compile python? Message-ID: <62127.68.190.0.209.1206335084.squirrel@webmail.opmstech.org> Hey all, I've started trying to make homebrew programs for my wii the past couple of days, and have found that programming it in c is quite hard. I was wondering how I would go about compiling python for something like this. The wii has a ppc processor, and runs homebrew in the native .elf format. Thanks From Pamela.J.Bartruff at supervalu.com Mon Mar 24 13:07:50 2008 From: Pamela.J.Bartruff at supervalu.com (Bartruff, Pamela J.) Date: Mon, 24 Mar 2008 07:07:50 -0500 Subject: [Tutor] how to write a function Message-ID: Hello Python users, I am very new to Python, how do I program that converts 24 hour time to 12 hour time? The program should have three functions(input, conversion and output function) Thanks for any help Pamela Bartruff -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080324/32992e2e/attachment.htm From kent37 at tds.net Mon Mar 24 14:07:29 2008 From: kent37 at tds.net (Kent Johnson) Date: Mon, 24 Mar 2008 09:07:29 -0400 Subject: [Tutor] how to write a function In-Reply-To: References: Message-ID: <47E7A791.8080509@tds.net> Bartruff, Pamela J. wrote: > Hello Python users, > > I am very new to Python, how do I program that converts 24 hour time to > 12 hour time? The program should have three functions(input, conversion > and output function) This sounds like a homework assignment. We will help with homework but we won't do it for you. Do you know how to write a function? What is the time format? Where does the input come from? What have you tried so far? Kent From Pamela.J.Bartruff at supervalu.com Mon Mar 24 14:28:13 2008 From: Pamela.J.Bartruff at supervalu.com (Bartruff, Pamela J.) Date: Mon, 24 Mar 2008 08:28:13 -0500 Subject: [Tutor] how to write a function In-Reply-To: <47E7A791.8080509@tds.net> References: <47E7A791.8080509@tds.net> Message-ID: Def convert_time(time): """split hours from minutes" Time = raw_input("enter a time, in military: ") If hours > 12 Hours = hours - 12 Am_or_pm = "p.m." Output_hours = hours Output_minutes = minutes Output_hours = "" Else: Am_or_pm = "a.m." -----Original Message----- From: Kent Johnson [mailto:kent37 at tds.net] Sent: Monday, March 24, 2008 8:07 AM To: Bartruff, Pamela J. Cc: tutor at python.org Subject: Re: [Tutor] how to write a function Bartruff, Pamela J. wrote: > Hello Python users, > > I am very new to Python, how do I program that converts 24 hour time to > 12 hour time? The program should have three functions(input, conversion > and output function) This sounds like a homework assignment. We will help with homework but we won't do it for you. Do you know how to write a function? What is the time format? Where does the input come from? What have you tried so far? Kent From bhaaluu at gmail.com Mon Mar 24 15:16:49 2008 From: bhaaluu at gmail.com (bhaaluu) Date: Mon, 24 Mar 2008 10:16:49 -0400 Subject: [Tutor] how to write a function In-Reply-To: References: Message-ID: On Mon, Mar 24, 2008 at 8:07 AM, Bartruff, Pamela J. wrote: > > Hello Python users, > > I am very new to Python, how do I program that converts 24 hour time to 12 > hour time? The program should have three functions(input, conversion and > output function) > > Thanks for any help > > Pamela Bartruff > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor You define a function with: def functionName(): The body of the function should be indented (4 spaces is good). So here are examples of 3 'stub' functions that don't do anything (yet): def input(): # comments go after a hash # this is the input function varName = raw_input("Enter input: ") return varName def conversion(varName): # this is the conversion function # do something here int(varName) return varName def output(varName): # this is the output function print ("You input %s" % varName) def main(): varName = input() conversion(varName) output(varName) if __name__ == "__main__": main() You'll have to fill in the parts specific to your problem. The best way to start is to work the problem out on paper first: ie. you should already know how to do the math to convert from 24 hour time, to 12 hour time. If you can't do it on paper yet, you need to start by learning how to do it on paper before you can teach the computer how to do it. Happy Programming! -- b h a a l u u at g m a i l dot c o m "You assist an evil system most effectively by obeying its orders and decrees. An evil system never deserves such allegiance. Allegiance to it means partaking of the evil. A good person will resist an evil system with his or her whole soul." [Mahatma Gandhi] From inthefridge at gmail.com Mon Mar 24 15:51:25 2008 From: inthefridge at gmail.com (Spencer Parker) Date: Mon, 24 Mar 2008 08:51:25 -0600 Subject: [Tutor] CSV file processing... In-Reply-To: <40af687b0803211255g4e9a9637u11d38900b0cab406@mail.gmail.com> References: <47E2F664.3030907@tds.net> <47E3F657.9050706@tds.net> <47E40A1D.2060602@tds.net> <47E40DB6.8090603@tds.net> <40af687b0803211255g4e9a9637u11d38900b0cab406@mail.gmail.com> Message-ID: I am at a loss as to why this isn't working properly: #!/usr/bin/python import MySQLdb import csv import sys try: db = MySQLdb.connect (host = "localhost",user = "root",passwd = "########",db = "stats") except MySQLdb.Error, e: print "Error %d: %s" % (e.args[0], e.args[1]) sys.exit (1) co = db.cursor() csv_data = csv.reader(file('output.txt','r')) headers = csv_data.next() row = csv_data.next() prefix = row[:17] for i in range(17, len(row),8): next = prefix + row[i:i+8] print next co.execute(""" INSERT INTO stats(Hostname, Time, Arch, PhysicalCPU, Count, Running, Blocked, Paused, Shutdown, Shutoff, Crashed, Active, Inactive, PCPU, TotalMemory, Totalguestmemory, TotalCPUtime, DomainID, Domainname, CPUTime, PGCPU, RDRQ, WRRQ, RXBY, TXBY) VALUES("%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s"); """, row) co.close() db.commit() db.close() It pulls all of the data correctly and it is the correct of items that it is grabbing. I get this traceback: Traceback (most recent call last): File "./loadcsv.py", line 21, in ? co.execute(""" File "/usr/lib64/python2.4/site-packages/MySQLdb/cursors.py", line 148, in execute query = query % db.literal(args) TypeError: not all arguments converted during string formatting If I have it print out the next variable...the data is correct that it is pulling out... ['test.test.net', '15:33:59', 'x86_64', '8', '9', '1', '4', '0', '0', '0', '0', '5', '4', '0.0', '12495360', '818688', '0', '1', 'beta', '0.', '0.', '', '', '', ''] Maybe fresh eyes could pull out my mistake? Thanks again for everything! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080324/747080e3/attachment.htm From Pamela.J.Bartruff at supervalu.com Mon Mar 24 16:17:01 2008 From: Pamela.J.Bartruff at supervalu.com (Bartruff, Pamela J.) Date: Mon, 24 Mar 2008 10:17:01 -0500 Subject: [Tutor] how to write a function In-Reply-To: References: Message-ID: Thank you so much. I appreciate the help, I am very new to Python, but I would very much like to learn more... -----Original Message----- From: bhaaluu [mailto:bhaaluu at gmail.com] Sent: Monday, March 24, 2008 9:17 AM To: Bartruff, Pamela J. Cc: tutor at python.org Subject: Re: [Tutor] how to write a function On Mon, Mar 24, 2008 at 8:07 AM, Bartruff, Pamela J. wrote: > > Hello Python users, > > I am very new to Python, how do I program that converts 24 hour time to 12 > hour time? The program should have three functions(input, conversion and > output function) > > Thanks for any help > > Pamela Bartruff > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor You define a function with: def functionName(): The body of the function should be indented (4 spaces is good). So here are examples of 3 'stub' functions that don't do anything (yet): def input(): # comments go after a hash # this is the input function varName = raw_input("Enter input: ") return varName def conversion(varName): # this is the conversion function # do something here int(varName) return varName def output(varName): # this is the output function print ("You input %s" % varName) def main(): varName = input() conversion(varName) output(varName) if __name__ == "__main__": main() You'll have to fill in the parts specific to your problem. The best way to start is to work the problem out on paper first: ie. you should already know how to do the math to convert from 24 hour time, to 12 hour time. If you can't do it on paper yet, you need to start by learning how to do it on paper before you can teach the computer how to do it. Happy Programming! -- b h a a l u u at g m a i l dot c o m "You assist an evil system most effectively by obeying its orders and decrees. An evil system never deserves such allegiance. Allegiance to it means partaking of the evil. A good person will resist an evil system with his or her whole soul." [Mahatma Gandhi] From kent37 at tds.net Mon Mar 24 16:27:37 2008 From: kent37 at tds.net (Kent Johnson) Date: Mon, 24 Mar 2008 11:27:37 -0400 Subject: [Tutor] CSV file processing... In-Reply-To: References: <47E2F664.3030907@tds.net> <47E3F657.9050706@tds.net> <47E40A1D.2060602@tds.net> <47E40DB6.8090603@tds.net> <40af687b0803211255g4e9a9637u11d38900b0cab406@mail.gmail.com> Message-ID: <47E7C869.6070602@tds.net> Spencer Parker wrote: > I am at a loss as to why this isn't working properly: > > #!/usr/bin/python > > import MySQLdb > import csv > import sys > > try: > db = MySQLdb.connect (host = "localhost",user = "root",passwd = > "########",db = "stats") > except MySQLdb.Error, e: > print "Error %d: %s" % (e.args[0], e.args[1]) > sys.exit (1) > > co = db.cursor() > csv_data = csv.reader(file('output.txt','r')) > headers = csv_data.next() > row = csv_data.next() > prefix = row[:17] > for i in range(17, len(row),8): > next = prefix + row[i:i+8] > print next > co.execute(""" > INSERT INTO stats(Hostname, Time, Arch, PhysicalCPU, Count, Running, > Blocked, Paused, Shutdown, Shutoff, Crashed, Active, Inactive, PCPU, > TotalMemory, Totalguestmemory, TotalCPUtime, DomainID, Domainname, > CPUTime, PGCPU, RDRQ, WRRQ, RXBY, TXBY) > > VALUES("%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s"); > """, row) You want 'next', not 'row' Kent > co.close() > db.commit() > db.close() > > It pulls all of the data correctly and it is the correct of items that > it is grabbing. I get this traceback: > > Traceback (most recent call last): > File "./loadcsv.py", line 21, in ? > co.execute(""" > File "/usr/lib64/python2.4/site-packages/MySQLdb/cursors.py", line > 148, in execute > query = query % db.literal(args) > TypeError: not all arguments converted during string formatting > > If I have it print out the next variable...the data is correct that it > is pulling out... > > ['test.test.net ', '15:33:59', 'x86_64', '8', '9', > '1', '4', '0', '0', '0', '0', '5', '4', '0.0', '12495360', '818688', > '0', '1', 'beta', '0.', '0.', '', '', '', ''] > > Maybe fresh eyes could pull out my mistake? > > Thanks again for everything! > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From inthefridge at gmail.com Mon Mar 24 16:38:09 2008 From: inthefridge at gmail.com (Spencer Parker) Date: Mon, 24 Mar 2008 09:38:09 -0600 Subject: [Tutor] CSV file processing... In-Reply-To: <47E7C869.6070602@tds.net> References: <47E3F657.9050706@tds.net> <47E40A1D.2060602@tds.net> <47E40DB6.8090603@tds.net> <40af687b0803211255g4e9a9637u11d38900b0cab406@mail.gmail.com> <47E7C869.6070602@tds.net> Message-ID: Okay...that got me a different error: Traceback (most recent call last): File "./loadcsv.py", line 21, in ? co.execute(""" File "/usr/lib64/python2.4/site-packages/MySQLdb/cursors.py", line 163, in execute self.errorhandler(self, exc, value) File "/usr/lib64/python2.4/site-packages/MySQLdb/connections.py", line 35, in defaulterrorhandler raise errorclass, errorvalue _mysql_exceptions.OperationalError: (1136, "Column count doesn't match value count at row 1") Thanks for getting me past that part...once this is error is resolved...then it should be done. The good thing is I think I could actually do this again and understand what I am doing...I guess there is progress there. On Mon, Mar 24, 2008 at 9:27 AM, Kent Johnson wrote: > Spencer Parker wrote: > > I am at a loss as to why this isn't working properly: > > > > #!/usr/bin/python > > > > import MySQLdb > > import csv > > import sys > > > > try: > > db = MySQLdb.connect (host = "localhost",user = "root",passwd = > > "########",db = "stats") > > except MySQLdb.Error, e: > > print "Error %d: %s" % (e.args[0], e.args[1]) > > sys.exit (1) > > > > co = db.cursor() > > csv_data = csv.reader(file('output.txt','r')) > > headers = csv_data.next() > > row = csv_data.next() > > prefix = row[:17] > > for i in range(17, len(row),8): > > next = prefix + row[i:i+8] > > print next > > co.execute(""" > > INSERT INTO stats(Hostname, Time, Arch, PhysicalCPU, Count, Running, > > Blocked, Paused, Shutdown, Shutoff, Crashed, Active, Inactive, PCPU, > > TotalMemory, Totalguestmemory, TotalCPUtime, DomainID, Domainname, > > CPUTime, PGCPU, RDRQ, WRRQ, RXBY, TXBY) > > > > > VALUES("%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s"); > > """, row) > > You want 'next', not 'row' > > Kent > > > co.close() > > db.commit() > > db.close() > > > > It pulls all of the data correctly and it is the correct of items that > > it is grabbing. I get this traceback: > > > > Traceback (most recent call last): > > File "./loadcsv.py", line 21, in ? > > co.execute(""" > > File "/usr/lib64/python2.4/site-packages/MySQLdb/cursors.py", line > > 148, in execute > > query = query % db.literal(args) > > TypeError: not all arguments converted during string formatting > > > > If I have it print out the next variable...the data is correct that it > > is pulling out... > > > > ['test.test.net ', '15:33:59', 'x86_64', '8', '9', > > '1', '4', '0', '0', '0', '0', '5', '4', '0.0', '12495360', '818688', > > '0', '1', 'beta', '0.', '0.', '', '', '', ''] > > > > Maybe fresh eyes could pull out my mistake? > > > > Thanks again for everything! > > > > > > ------------------------------------------------------------------------ > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > -- Spencer Parker _______________________________________________________ "if you can't go to heaven, may you at least die in Ireland." _______________________________________________________ -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080324/e2458817/attachment-0001.htm From kent37 at tds.net Mon Mar 24 16:46:14 2008 From: kent37 at tds.net (Kent Johnson) Date: Mon, 24 Mar 2008 11:46:14 -0400 Subject: [Tutor] CSV file processing... In-Reply-To: References: <47E3F657.9050706@tds.net> <47E40A1D.2060602@tds.net> <47E40DB6.8090603@tds.net> <40af687b0803211255g4e9a9637u11d38900b0cab406@mail.gmail.com> <47E7C869.6070602@tds.net> Message-ID: <47E7CCC6.8030608@tds.net> Spencer Parker wrote: > Okay...that got me a different error: > _mysql_exceptions.OperationalError: (1136, "Column count doesn't match > value count at row 1") So, what do you think that error might be trying to tell you? What output do you get from the 'print next' statement? Kent From inthefridge at gmail.com Mon Mar 24 17:01:47 2008 From: inthefridge at gmail.com (Spencer Parker) Date: Mon, 24 Mar 2008 10:01:47 -0600 Subject: [Tutor] CSV file processing... In-Reply-To: <47E7CCC6.8030608@tds.net> References: <47E40A1D.2060602@tds.net> <47E40DB6.8090603@tds.net> <40af687b0803211255g4e9a9637u11d38900b0cab406@mail.gmail.com> <47E7C869.6070602@tds.net> <47E7CCC6.8030608@tds.net> Message-ID: I am pretty sure it is trying to tell me that the data I have is not matching up with the columns I have in mysql. The output I get from the print next is this: ['test.test.net', '15:33:59', 'x86_64', '8', '9', '1', '4', '0', '0', '0', '0', '5', '4', '0.0', '12495360', '818688', '0', '36', 'core.none.com', '0.', '0.', '', '', '', ''] I have 25 columns in my MySQL database and it appears to be grabbing 25 items. On Mon, Mar 24, 2008 at 9:46 AM, Kent Johnson wrote: > Spencer Parker wrote: > > Okay...that got me a different error: > > > _mysql_exceptions.OperationalError: (1136, "Column count doesn't match > > value count at row 1") > > So, what do you think that error might be trying to tell you? What > output do you get from the 'print next' statement? > > Kent > > -- Spencer Parker _______________________________________________________ "if you can't go to heaven, may you at least die in Ireland." _______________________________________________________ -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080324/39f784d8/attachment.htm From kent37 at tds.net Mon Mar 24 17:30:40 2008 From: kent37 at tds.net (Kent Johnson) Date: Mon, 24 Mar 2008 12:30:40 -0400 Subject: [Tutor] CSV file processing... In-Reply-To: References: <47E40A1D.2060602@tds.net> <47E40DB6.8090603@tds.net> <40af687b0803211255g4e9a9637u11d38900b0cab406@mail.gmail.com> <47E7C869.6070602@tds.net> <47E7CCC6.8030608@tds.net> Message-ID: <47E7D730.9000301@tds.net> Spencer Parker wrote: > I am pretty sure it is trying to tell me that the data I have is not > matching up with the columns I have in mysql. Yes, I think so. > > The output I get from the print next is this: > > ['test.test.net ', '15:33:59', 'x86_64', '8', '9', > '1', '4', '0', '0', '0', '0', '5', '4', '0.0', '12495360', '818688', > '0', '36', 'core.none.com ', '0.', '0.', '', '', > '', ''] > > I have 25 columns in my MySQL database and it appears to be grabbing 25 > items. Does it print any more lines, for example a line with no data that would look like [] ? How many values are in the row of input? What is your current code? The last one you posted seems to have an incorrect indent, the co.execute() doesn't look like it is inside the loop. Kent From inthefridge at gmail.com Mon Mar 24 17:49:46 2008 From: inthefridge at gmail.com (Spencer Parker) Date: Mon, 24 Mar 2008 10:49:46 -0600 Subject: [Tutor] CSV file processing... In-Reply-To: <47E7D730.9000301@tds.net> References: <47E40DB6.8090603@tds.net> <40af687b0803211255g4e9a9637u11d38900b0cab406@mail.gmail.com> <47E7C869.6070602@tds.net> <47E7CCC6.8030608@tds.net> <47E7D730.9000301@tds.net> Message-ID: Okay...so I don't know what I was missing...but I copied the code from a file I had without the loop in it...now it works just fine...I'm going through to see what changed right now...thanks for the help...it is appreciated... On Mon, Mar 24, 2008 at 10:30 AM, Kent Johnson wrote: > Spencer Parker wrote: > > I am pretty sure it is trying to tell me that the data I have is not > > matching up with the columns I have in mysql. > > Yes, I think so. > > > > The output I get from the print next is this: > > > > ['test.test.net ', '15:33:59', 'x86_64', '8', '9', > > '1', '4', '0', '0', '0', '0', '5', '4', '0.0', '12495360', '818688', > > '0', '36', 'core.none.com ', '0.', '0.', '', '', > > '', ''] > > > > I have 25 columns in my MySQL database and it appears to be grabbing 25 > > items. > > Does it print any more lines, for example a line with no data that would > look like > [] > ? > > How many values are in the row of input? What is your current code? The > last one you posted seems to have an incorrect indent, the co.execute() > doesn't look like it is inside the loop. > > Kent > -- Spencer Parker _______________________________________________________ "if you can't go to heaven, may you at least die in Ireland." _______________________________________________________ -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080324/c3d60227/attachment.htm From inthefridge at gmail.com Mon Mar 24 17:54:17 2008 From: inthefridge at gmail.com (Spencer Parker) Date: Mon, 24 Mar 2008 10:54:17 -0600 Subject: [Tutor] CSV file processing... In-Reply-To: References: <40af687b0803211255g4e9a9637u11d38900b0cab406@mail.gmail.com> <47E7C869.6070602@tds.net> <47E7CCC6.8030608@tds.net> <47E7D730.9000301@tds.net> Message-ID: I took out the quotes around the second part of the INSERT statement and that made it work fine. On Mon, Mar 24, 2008 at 10:49 AM, Spencer Parker wrote: > Okay...so I don't know what I was missing...but I copied the code from a > file I had without the loop in it...now it works just fine...I'm going > through to see what changed right now...thanks for the help...it is > appreciated... > > > On Mon, Mar 24, 2008 at 10:30 AM, Kent Johnson wrote: > > > Spencer Parker wrote: > > > I am pretty sure it is trying to tell me that the data I have is not > > > matching up with the columns I have in mysql. > > > > Yes, I think so. > > > > > > The output I get from the print next is this: > > > > > > ['test.test.net ', '15:33:59', 'x86_64', '8', > > '9', > > > '1', '4', '0', '0', '0', '0', '5', '4', '0.0', '12495360', '818688', > > > '0', '36', 'core.none.com ', '0.', '0.', '', '', > > > '', ''] > > > > > > I have 25 columns in my MySQL database and it appears to be grabbing > > 25 > > > items. > > > > Does it print any more lines, for example a line with no data that would > > look like > > [] > > ? > > > > How many values are in the row of input? What is your current code? The > > last one you posted seems to have an incorrect indent, the co.execute() > > doesn't look like it is inside the loop. > > > > Kent > > > > > > -- > Spencer Parker > _______________________________________________________ > > "if you can't go to heaven, may you at least die in Ireland." > > _______________________________________________________ > -- Spencer Parker _______________________________________________________ "if you can't go to heaven, may you at least die in Ireland." _______________________________________________________ -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080324/4cda9a59/attachment.htm From marc.tompkins at gmail.com Mon Mar 24 18:20:23 2008 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Mon, 24 Mar 2008 10:20:23 -0700 Subject: [Tutor] how to write a function In-Reply-To: References: <47E7A791.8080509@tds.net> Message-ID: <40af687b0803241020k46752bfal86162e44bd93a42c@mail.gmail.com> On Mon, Mar 24, 2008 at 6:28 AM, Bartruff, Pamela J. < Pamela.J.Bartruff at supervalu.com> wrote: > Def convert_time(time): > """split hours from minutes" > Time = raw_input("enter a time, in military: ") > At this point, Time is a string, not a number. (At this point, we also have to _assume_ that the user entered a valid date string, but you can worry about validation a little later...) hours = Time.split(':')[0] minutes = Time.split(':')[1] The "split" method returns a list of strings. I've told it to use a colon (':') as the separator. "hours" takes the first item in the list - remember that we start from 0, not from 1 - and "minutes" takes the second item. At this point you still have two strings, not numbers - convert them to integers like so: hours = int(Time.split(':')[0]) minutes = int(Time.split(':')[1]) (note - these lines replace what we did above) And now you can move on to the rest of your logic... If hours > 12 > Hours = hours - 12 > Am_or_pm = "p.m." > Output_hours = hours > Output_minutes = minutes > Output_hours = "" > Else: > Am_or_pm = "a.m." > -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080324/5033ccd7/attachment-0001.htm From mlangford.cs03 at gtalumni.org Mon Mar 24 22:51:02 2008 From: mlangford.cs03 at gtalumni.org (Michael Langford) Date: Mon, 24 Mar 2008 17:51:02 -0400 Subject: [Tutor] cross-compile python? In-Reply-To: <62127.68.190.0.209.1206335084.squirrel@webmail.opmstech.org> References: <62127.68.190.0.209.1206335084.squirrel@webmail.opmstech.org> Message-ID: <82b4f5810803241451r1ab7ehecb80e17577a04a6@mail.gmail.com> Cross compiling python isn't easy. Follow what this blogger did to get started, then ask when you get stuck. http://whatschrisdoing.com/blog/2006/10/06/howto-cross-compile-python-25/ --Michael On Mon, Mar 24, 2008 at 1:04 AM, Trey Keown wrote: > Hey all, > I've started trying to make homebrew programs for my wii the past couple > of days, and have found that programming it in c is quite hard. I was > wondering how I would go about compiling python for something like this. > The wii has a ppc processor, and runs homebrew in the native .elf format. > > Thanks > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Michael Langford Phone: 404-386-0495 Consulting: http://www.RowdyLabs.com From andreas at kostyrka.org Mon Mar 24 23:51:12 2008 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Mon, 24 Mar 2008 23:51:12 +0100 Subject: [Tutor] what is @classmethod and @staticmethod ?? In-Reply-To: <8249c4ac0803231611v40eb8b9cw75813cf75c2dd698@mail.gmail.com> References: <8249c4ac0803231611v40eb8b9cw75813cf75c2dd698@mail.gmail.com> Message-ID: <1206399073.11011.46.camel@localhost> A classical example is a class that can be constructed from different values. Ok, let's implement a special integer class: class MyOwnInteger(object): def __init__(self, value): self.value = value Now, let's say we want to add the possibility to create MyOwnInteger instances from strings. We can accomplish this by checking the type of value inside of __init__, but this does not scale if there might be different interpretations for a string: class MyOwnInteger(object): def __init__(self, value): self.value = value @classmethod def fromString(cls, value): return cls(int(value)) @classmethod def fromFiledata(cls, filename): fp = file(filename) data = fp.read() fp.close() return cls(int(data.strip())) Andreas Am Sonntag, den 23.03.2008, 16:11 -0700 schrieb Tony Cappellini: > Kent > > Would you show the examples which show where staticmethod & > classmethod are used? > > I've often wondered about the usefulness of these myself. Having read > many of the popular books on python, none provide a good clear > explanation > of why or where these should be used, and what the alternatives are > (if any). They typically show an extremely terse example of the syntax > with little explanation. > > > Message: 7 > Date: Sun, 23 Mar 2008 18:26:26 -0400 > From: Kent Johnson > Subject: Re: [Tutor] what is @classmethod and @staticmethod ?? > To: maser > Cc: tutor at python.org > Message-ID: <47E6D912.1050801 at tds.net> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > maser wrote: > > Thanks, Andreas. Why do we need to use classmethod/ > > staticmethod and where do we need to use them ? > > I use staticmethods as a convenience to put related functions in the > namespace of a class. Perhaps foo.py contains class Foo with > staticmethod bar(). In client code I can say > > from foo import Foo > Foo.bar() > > If bar was a module method it would be > > from foo import Foo, bar > bar() > > > I prefer the former in cases where bar is related to Foo. > > Kent > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Dies ist ein digital signierter Nachrichtenteil Url : http://mail.python.org/pipermail/tutor/attachments/20080324/f7583512/attachment.pgp From technorapture at gmail.com Tue Mar 25 03:12:41 2008 From: technorapture at gmail.com (Shrutarshi Basu) Date: Mon, 24 Mar 2008 22:12:41 -0400 Subject: [Tutor] Let imported module access calling program Message-ID: <376fbdcf0803241912lc985f0fk79c5ee0f6e78937@mail.gmail.com> I'm working on a module-based robot interface, but I've hit a bit of a roadblock. I would like the user's script to be able to simply import modules and drive the robot. I want the users code to be executed once every few seconds, but I don't want the timing system to be part of the users code: the user should just define the robot's behavior which is executed in a cyclic manner. I would like to make the timing and repeating system a part of the module the user imports in their code, but that means that the module has to be able to access functions inside the calling program. Is there an easy way to do this? Or is there a completely different solution that I'm not seeing? (I would like to avoid something object-oriented, because that's a personal challenge for me for this project: to explore new ways of problem-solving) Thanks, Basu -- Embedded Architectures, Systems programming and outrageous ideas -- http://bytebaker.com From kent37 at tds.net Tue Mar 25 03:30:31 2008 From: kent37 at tds.net (Kent Johnson) Date: Mon, 24 Mar 2008 22:30:31 -0400 Subject: [Tutor] Let imported module access calling program In-Reply-To: <376fbdcf0803241912lc985f0fk79c5ee0f6e78937@mail.gmail.com> References: <376fbdcf0803241912lc985f0fk79c5ee0f6e78937@mail.gmail.com> Message-ID: <47E863C7.8030601@tds.net> Shrutarshi Basu wrote: > I'm working on a module-based robot interface, but I've hit a bit of a > roadblock. I would like the user's script to be able to simply import > modules and drive the robot. I want the users code to be executed once > every few seconds, but I don't want the timing system to be part of > the users code This seems kind of strange to me. You want the entire user module to be re-run? Why don't you want looping and timing to be under the user's control? Can you show a short example of what the user code might look like? Kent From technorapture at gmail.com Tue Mar 25 03:43:51 2008 From: technorapture at gmail.com (Shrutarshi Basu) Date: Mon, 24 Mar 2008 22:43:51 -0400 Subject: [Tutor] Let imported module access calling program In-Reply-To: <47E863C7.8030601@tds.net> References: <376fbdcf0803241912lc985f0fk79c5ee0f6e78937@mail.gmail.com> <47E863C7.8030601@tds.net> Message-ID: <376fbdcf0803241943v55350408l3022cd5c1db3d37d@mail.gmail.com> > This seems kind of strange to me. You want the entire user module to be > re-run? Why don't you want looping and timing to be under the user's > control? Can you show a short example of what the user code might look like? > > Kent > Well perhaps not the entire module, but probably most of it. Here's an example. Suppose you want to define a simple obstacle avoidance behavior, the script should be something similar to: import robot if robot.sensor('front') > 100: robot.left_turn() Defining the sensor() and left_turn() functions is no problem, but this should be a continuous behavior, hence the need to run it over and over at certain time intervals. I already have a config.py (accessed by robot.py and a few other modules) which the user can modify to set the intervals (and other details). i've also been thinking about creating a controller.py which handles the repetition and imports the user's code and runs its functions, but i would still like to explore this method. Thanks again, Basu From cappy2112 at gmail.com Tue Mar 25 07:39:18 2008 From: cappy2112 at gmail.com (Tony Cappellini) Date: Mon, 24 Mar 2008 23:39:18 -0700 Subject: [Tutor] Python to C++ Message-ID: <8249c4ac0803242339m5c0df142ue0263b18babc1ddd@mail.gmail.com> Another alternative is Weave http://www.scipy.org/Weave But mixing C/C++ with Python sort of defeats the reasons for using Python to begin with Message: 2 Date: Sat, 22 Mar 2008 02:44:54 +0100 From: Eike Welk Subject: Re: [Tutor] Python to C++ To: tutor at python.org Message-ID: <200803220244.54377.eike.welk at gmx.net> Content-Type: text/plain; charset=utf-8 On Friday 21 March 2008 23:37, Dinesh B Vadhia wrote: > Thank-you for all the suggestions for converting to C/C++ which > will be followed up. > > Can we interface Python to a C++ library and if so how? > > Dinesh > If you have only few classes / member functions Boost-Python is a good solution. http://www.boost.org/libs/python/doc/ I heard that SWIG can also generate glue code for C++. http://www.swig.org/Doc1.3/SWIGPlus.html You could also look at Py-QT they have a tool like SWIG (SIP I think), which they use to generate the glue code for the fairly big QT library. Maybe you like it better. http://www.riverbankcomputing.co.uk/pyqt/ From andreas at kostyrka.org Tue Mar 25 10:46:36 2008 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Tue, 25 Mar 2008 10:46:36 +0100 Subject: [Tutor] Python to C++ In-Reply-To: <8249c4ac0803242339m5c0df142ue0263b18babc1ddd@mail.gmail.com> References: <8249c4ac0803242339m5c0df142ue0263b18babc1ddd@mail.gmail.com> Message-ID: <1206438396.11011.58.camel@localhost> Well, not exactly. Mixing Python with C/C++ extends the "coverage" that you can do with Python. Andreas Am Montag, den 24.03.2008, 23:39 -0700 schrieb Tony Cappellini: > Another alternative is Weave > http://www.scipy.org/Weave > > But mixing C/C++ with Python sort of defeats the reasons for using > Python to begin with > > Message: 2 > Date: Sat, 22 Mar 2008 02:44:54 +0100 > From: Eike Welk > Subject: Re: [Tutor] Python to C++ > To: tutor at python.org > Message-ID: <200803220244.54377.eike.welk at gmx.net> > Content-Type: text/plain; charset=utf-8 > > On Friday 21 March 2008 23:37, Dinesh B Vadhia wrote: > > Thank-you for all the suggestions for converting to C/C++ which > > will be followed up. > > > > Can we interface Python to a C++ library and if so how? > > > > Dinesh > > > > If you have only few classes / member functions Boost-Python is a good > solution. > http://www.boost.org/libs/python/doc/ > > I heard that SWIG can also generate glue code for C++. > http://www.swig.org/Doc1.3/SWIGPlus.html > > You could also look at Py-QT they have a tool like SWIG (SIP I think), > which they use to generate the glue code for the fairly big QT > library. Maybe you like it better. > http://www.riverbankcomputing.co.uk/pyqt/ > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Dies ist ein digital signierter Nachrichtenteil Url : http://mail.python.org/pipermail/tutor/attachments/20080325/32ffe39f/attachment.pgp From kent37 at tds.net Tue Mar 25 03:16:09 2008 From: kent37 at tds.net (Kent Johnson) Date: Mon, 24 Mar 2008 22:16:09 -0400 Subject: [Tutor] New Kent's Korner: urllib2 cookbook Message-ID: <47E86069.8070406@tds.net> Draft notes for the next Kent's Korner presentation are available at http://personalpages.tds.net/~kent37/kk/00010.html Comments welcome. Kent From kent37 at tds.net Tue Mar 25 12:22:19 2008 From: kent37 at tds.net (Kent Johnson) Date: Tue, 25 Mar 2008 07:22:19 -0400 Subject: [Tutor] Let imported module access calling program In-Reply-To: <376fbdcf0803241943v55350408l3022cd5c1db3d37d@mail.gmail.com> References: <376fbdcf0803241912lc985f0fk79c5ee0f6e78937@mail.gmail.com> <47E863C7.8030601@tds.net> <376fbdcf0803241943v55350408l3022cd5c1db3d37d@mail.gmail.com> Message-ID: <47E8E06B.3030808@tds.net> Shrutarshi Basu wrote: >> This seems kind of strange to me. You want the entire user module to be >> re-run? > > Well perhaps not the entire module, but probably most of it. How will you know how much to re-run? Reloading a module re-runs *all* of it, including reinitializing any global variables... > Here's an > example. Suppose you want to define a simple obstacle avoidance > behavior, the script should be something similar to: > > import robot > if robot.sensor('front') > 100: > robot.left_turn() A few ideas: - put all the code that should be repeated into a single function and pass that function to a run() function: def actions(): if robot.sensor('front') > 100: robot.left_turn() robot.run(actions) - Give the user direct control of the timing: while robot.is_running(): if robot.sensor('front') > 100: robot.left_turn() time.sleep(1) # or robot.wait() - register event handlers for specific events. This is more complex but it is also a more flexible execution model than polling at timed intervals: def handle_sensor_front(): robot.left_turn() robot.register('sensor', 'front', handle_sensor_front) - have the user subclass robot and implement handler methods: class MyRobot(robot): def handle_sensor_front(self): self.left_turn() You might want to look at Pyro (Python Robotics) to see how others have solved this problem: http://pyrorobotics.org/?page=Pyro Kent > > Defining the sensor() and left_turn() functions is no problem, but > this should be a continuous behavior, hence the need to run it over > and over at certain time intervals. I already have a config.py > (accessed by robot.py and a few other modules) which the user can > modify to set the intervals (and other details). i've also been > thinking about creating a controller.py which handles the repetition > and imports the user's code and runs its functions, but i would still > like to explore this method. > Thanks again, > Basu > From hunter92383 at gmail.com Tue Mar 25 13:00:01 2008 From: hunter92383 at gmail.com (elis aeris) Date: Tue, 25 Mar 2008 05:00:01 -0700 Subject: [Tutor] Python to C++ In-Reply-To: <1206438396.11011.58.camel@localhost> References: <8249c4ac0803242339m5c0df142ue0263b18babc1ddd@mail.gmail.com> <1206438396.11011.58.camel@localhost> Message-ID: <674d5ce60803250500o7b3c9a9dg24577e1dd4c5a62e@mail.gmail.com> i personally write my python code with c++ in mind because i knew i am going to rewrite it over. so it's very easy to do that. it's fun to find out how many more lines of c++ is required for something done with 2 lines in python. On Tue, Mar 25, 2008 at 2:46 AM, Andreas Kostyrka wrote: > Well, not exactly. Mixing Python with C/C++ extends the "coverage" that > you can do with Python. > > Andreas > > > Am Montag, den 24.03.2008, 23:39 -0700 schrieb Tony Cappellini: > > Another alternative is Weave > > http://www.scipy.org/Weave > > > > But mixing C/C++ with Python sort of defeats the reasons for using > > Python to begin with > > > > Message: 2 > > Date: Sat, 22 Mar 2008 02:44:54 +0100 > > From: Eike Welk > > Subject: Re: [Tutor] Python to C++ > > To: tutor at python.org > > Message-ID: <200803220244.54377.eike.welk at gmx.net> > > Content-Type: text/plain; charset=utf-8 > > > > On Friday 21 March 2008 23:37, Dinesh B Vadhia wrote: > > > Thank-you for all the suggestions for converting to C/C++ which > > > will be followed up. > > > > > > Can we interface Python to a C++ library and if so how? > > > > > > Dinesh > > > > > > > If you have only few classes / member functions Boost-Python is a good > > solution. > > http://www.boost.org/libs/python/doc/ > > > > I heard that SWIG can also generate glue code for C++. > > http://www.swig.org/Doc1.3/SWIGPlus.html > > > > You could also look at Py-QT they have a tool like SWIG (SIP I think), > > which they use to generate the glue code for the fairly big QT > > library. Maybe you like it better. > > http://www.riverbankcomputing.co.uk/pyqt/ > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080325/4a8d49a7/attachment.htm From technorapture at gmail.com Tue Mar 25 13:46:17 2008 From: technorapture at gmail.com (Shrutarshi Basu) Date: Tue, 25 Mar 2008 08:46:17 -0400 Subject: [Tutor] Let imported module access calling program In-Reply-To: <47E8E06B.3030808@tds.net> References: <376fbdcf0803241912lc985f0fk79c5ee0f6e78937@mail.gmail.com> <47E863C7.8030601@tds.net> <376fbdcf0803241943v55350408l3022cd5c1db3d37d@mail.gmail.com> <47E8E06B.3030808@tds.net> Message-ID: <376fbdcf0803250546y53bf4ffckd703b7b92ba4a83c@mail.gmail.com> The event handling approach looks interesting and isn't something that I haven't encountered before. Could you to point me somewhere I could learn more about it? I've already read the papers published by the Pyro group and looked at some of their sample programs. I am trying to give the user a similar experience, but using an modular instead of class-based architecture. But I think I will go look into some of the source to get an idea for what they have done (though in the end i will probably implement a different system). Thanks again for all your help, Basu From kent37 at tds.net Tue Mar 25 14:01:12 2008 From: kent37 at tds.net (Kent Johnson) Date: Tue, 25 Mar 2008 09:01:12 -0400 Subject: [Tutor] Let imported module access calling program In-Reply-To: <376fbdcf0803250546y53bf4ffckd703b7b92ba4a83c@mail.gmail.com> References: <376fbdcf0803241912lc985f0fk79c5ee0f6e78937@mail.gmail.com> <47E863C7.8030601@tds.net> <376fbdcf0803241943v55350408l3022cd5c1db3d37d@mail.gmail.com> <47E8E06B.3030808@tds.net> <376fbdcf0803250546y53bf4ffckd703b7b92ba4a83c@mail.gmail.com> Message-ID: <47E8F798.20804@tds.net> Shrutarshi Basu wrote: > The event handling approach looks interesting and isn't something that > I haven't encountered before. Could you to point me somewhere I could > learn more about it? Not really...this is commonly used by GUI frameworks. For example in Tkinter you can register a mouse-button callback on a widget by calling widget.bind('', callback) where callback is the event handler. http://www.pythonware.com/library/tkinter/introduction/events-and-bindings.htm In your case, you would define the possible events and make a registry. For example, the registry could be a dict mapping event name to a list of handlers: from collections import defaultdict event_registry = defaultdict(list) def register(event, handler): # Should check that event is a real event name event_registry[event].append(handler) A client might call register('sensor_front', handle_sensor_front) Then in your main loop you check for the various events and call the callbacks. Perhaps you have a dict mapping event names to functions that query a condition: events = dict(sensor_front = lambda: robot.sensor('front') for event, query in events.items(): if query(): for handler in event_registry[event]: handler() This is simplistic - it needs error handling, a way to remove event handlers and probably much more - but perhaps it will give you enough to evaluate the idea. Kent From hunter92383 at gmail.com Tue Mar 25 14:19:03 2008 From: hunter92383 at gmail.com (elis aeris) Date: Tue, 25 Mar 2008 06:19:03 -0700 Subject: [Tutor] decimal precision Message-ID: <674d5ce60803250619v7e020400y7ea959b4ab7750ac@mail.gmail.com> x = 53 w = 192 for a in range ( x, (x+192) ): print (a-x)/w the problem is at (a-x)/w it's supposed to return a ratio between x and w, yet it 0 all the time. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080325/b7ae0f7b/attachment.htm From connorsml at gmail.com Tue Mar 25 14:31:52 2008 From: connorsml at gmail.com (Michael Connors) Date: Tue, 25 Mar 2008 14:31:52 +0100 Subject: [Tutor] decimal precision In-Reply-To: <674d5ce60803250619v7e020400y7ea959b4ab7750ac@mail.gmail.com> References: <674d5ce60803250619v7e020400y7ea959b4ab7750ac@mail.gmail.com> Message-ID: On 25/03/2008, elis aeris wrote: > > x = 53 > w = 192 > for a in range ( x, (x+192) ): > print (a-x)/w > > > the problem is at (a-x)/w > > it's supposed to return a ratio between x and w, yet it 0 all the time. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > I think to do float division the operands should be floats. So if you do: print float(a-x) / float(w) It should produce a floating point result. -- Michael Connors -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080325/9f1f8d96/attachment.htm From connorsml at gmail.com Tue Mar 25 14:30:55 2008 From: connorsml at gmail.com (Michael Connors) Date: Tue, 25 Mar 2008 14:30:55 +0100 Subject: [Tutor] decimal precision In-Reply-To: <674d5ce60803250619v7e020400y7ea959b4ab7750ac@mail.gmail.com> References: <674d5ce60803250619v7e020400y7ea959b4ab7750ac@mail.gmail.com> Message-ID: On 25/03/2008, elis aeris wrote: > > x = 53 > w = 192 > for a in range ( x, (x+192) ): > print (a-x)/w > > > the problem is at (a-x)/w > > it's supposed to return a ratio between x and w, yet it 0 all the time. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > I think to do float division the operands should be floats. So if you do: print float(a-x) / float(w) It should produce a floating point result. -- Michael Connors -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080325/049bfc22/attachment.htm From hunter92383 at gmail.com Tue Mar 25 14:55:46 2008 From: hunter92383 at gmail.com (elis aeris) Date: Tue, 25 Mar 2008 06:55:46 -0700 Subject: [Tutor] decimal precision In-Reply-To: References: <674d5ce60803250619v7e020400y7ea959b4ab7750ac@mail.gmail.com> Message-ID: <674d5ce60803250655v6a7fd9f2m3d7dce2f31f07558@mail.gmail.com> what if i want it only to 2nd decimal? what if i want to cut off everything behind decimal? On Tue, Mar 25, 2008 at 6:30 AM, Michael Connors wrote: > > On 25/03/2008, elis aeris wrote: > > > x = 53 > > w = 192 > > for a in range ( x, (x+192) ): > > print (a-x)/w > > > > > > the problem is at (a-x)/w > > > > it's supposed to return a ratio between x and w, yet it 0 all the time. > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > > I think to do float division the operands should be floats. > So if you do: > > print float(a-x) / float(w) > > It should produce a floating point result. > > -- > Michael Connors > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080325/65e07108/attachment-0001.htm From connorsml at gmail.com Tue Mar 25 15:05:07 2008 From: connorsml at gmail.com (Michael Connors) Date: Tue, 25 Mar 2008 15:05:07 +0100 Subject: [Tutor] decimal precision In-Reply-To: <674d5ce60803250655v6a7fd9f2m3d7dce2f31f07558@mail.gmail.com> References: <674d5ce60803250619v7e020400y7ea959b4ab7750ac@mail.gmail.com> <674d5ce60803250655v6a7fd9f2m3d7dce2f31f07558@mail.gmail.com> Message-ID: On 25/03/2008, elis aeris wrote: > > what if i want it only to 2nd decimal? > > what if i want to cut off everything behind decimal? > In: print "%.2f" % (0.999999) Out: 0.99 http://docs.python.org/lib/typesseq-strings.html -- Michael Connors -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080325/ab5d4893/attachment.htm From cappy2112 at gmail.com Tue Mar 25 15:21:38 2008 From: cappy2112 at gmail.com (Tony Cappellini) Date: Tue, 25 Mar 2008 07:21:38 -0700 Subject: [Tutor] Python to C++ In-Reply-To: <1206438396.11011.58.camel@localhost> References: <8249c4ac0803242339m5c0df142ue0263b18babc1ddd@mail.gmail.com> <1206438396.11011.58.camel@localhost> Message-ID: <8249c4ac0803250721p4e98d94ci6fc03c40efc1486@mail.gmail.com> Yes, but then you loose the clean Python readability, which is one of the strong points for using Python On Tue, Mar 25, 2008 at 2:46 AM, Andreas Kostyrka wrote: > Well, not exactly. Mixing Python with C/C++ extends the "coverage" that > you can do with Python. > > Andreas > > > Am Montag, den 24.03.2008, 23:39 -0700 schrieb Tony Cappellini: > > > > Another alternative is Weave > > http://www.scipy.org/Weave > > > > But mixing C/C++ with Python sort of defeats the reasons for using > > Python to begin with > > > > Message: 2 > > Date: Sat, 22 Mar 2008 02:44:54 +0100 > > From: Eike Welk > > Subject: Re: [Tutor] Python to C++ > > To: tutor at python.org > > Message-ID: <200803220244.54377.eike.welk at gmx.net> > > Content-Type: text/plain; charset=utf-8 > > > > On Friday 21 March 2008 23:37, Dinesh B Vadhia wrote: > > > Thank-you for all the suggestions for converting to C/C++ which > > > will be followed up. > > > > > > Can we interface Python to a C++ library and if so how? > > > > > > Dinesh > > > > > > > If you have only few classes / member functions Boost-Python is a good > > solution. > > http://www.boost.org/libs/python/doc/ > > > > I heard that SWIG can also generate glue code for C++. > > http://www.swig.org/Doc1.3/SWIGPlus.html > > > > You could also look at Py-QT they have a tool like SWIG (SIP I think), > > which they use to generate the glue code for the fairly big QT > > library. Maybe you like it better. > > http://www.riverbankcomputing.co.uk/pyqt/ > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > From rdm at rcblue.com Tue Mar 25 15:28:20 2008 From: rdm at rcblue.com (Dick Moores) Date: Tue, 25 Mar 2008 07:28:20 -0700 Subject: [Tutor] decimal precision In-Reply-To: <674d5ce60803250655v6a7fd9f2m3d7dce2f31f07558@mail.gmail.co m> References: <674d5ce60803250619v7e020400y7ea959b4ab7750ac@mail.gmail.com> <674d5ce60803250655v6a7fd9f2m3d7dce2f31f07558@mail.gmail.com> Message-ID: <20080325142834.4EAF31E401F@bag.python.org> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080325/7576bccf/attachment.htm From andreas at kostyrka.org Tue Mar 25 16:33:21 2008 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Tue, 25 Mar 2008 16:33:21 +0100 Subject: [Tutor] Python to C++ In-Reply-To: <8249c4ac0803250721p4e98d94ci6fc03c40efc1486@mail.gmail.com> References: <8249c4ac0803242339m5c0df142ue0263b18babc1ddd@mail.gmail.com> <1206438396.11011.58.camel@localhost> <8249c4ac0803250721p4e98d94ci6fc03c40efc1486@mail.gmail.com> Message-ID: <1206459201.11011.92.camel@localhost> Check out Cython or Pyrex. For a number of applications (performance speedup, C interfacing) they provide a quite Pythonic experience. Andreas Am Dienstag, den 25.03.2008, 07:21 -0700 schrieb Tony Cappellini: > Yes, but then you loose the clean Python readability, which is one of > the strong points for using Python > > > On Tue, Mar 25, 2008 at 2:46 AM, Andreas Kostyrka wrote: > > Well, not exactly. Mixing Python with C/C++ extends the "coverage" that > > you can do with Python. > > > > Andreas > > > > > > Am Montag, den 24.03.2008, 23:39 -0700 schrieb Tony Cappellini: > > > > > > > Another alternative is Weave > > > http://www.scipy.org/Weave > > > > > > But mixing C/C++ with Python sort of defeats the reasons for using > > > Python to begin with > > > > > > Message: 2 > > > Date: Sat, 22 Mar 2008 02:44:54 +0100 > > > From: Eike Welk > > > Subject: Re: [Tutor] Python to C++ > > > To: tutor at python.org > > > Message-ID: <200803220244.54377.eike.welk at gmx.net> > > > Content-Type: text/plain; charset=utf-8 > > > > > > On Friday 21 March 2008 23:37, Dinesh B Vadhia wrote: > > > > Thank-you for all the suggestions for converting to C/C++ which > > > > will be followed up. > > > > > > > > Can we interface Python to a C++ library and if so how? > > > > > > > > Dinesh > > > > > > > > > > If you have only few classes / member functions Boost-Python is a good > > > solution. > > > http://www.boost.org/libs/python/doc/ > > > > > > I heard that SWIG can also generate glue code for C++. > > > http://www.swig.org/Doc1.3/SWIGPlus.html > > > > > > You could also look at Py-QT they have a tool like SWIG (SIP I think), > > > which they use to generate the glue code for the fairly big QT > > > library. Maybe you like it better. > > > http://www.riverbankcomputing.co.uk/pyqt/ > > > _______________________________________________ > > > Tutor maillist - Tutor at python.org > > > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Dies ist ein digital signierter Nachrichtenteil Url : http://mail.python.org/pipermail/tutor/attachments/20080325/bf10611b/attachment.pgp From bryan.fodness at gmail.com Tue Mar 25 16:59:54 2008 From: bryan.fodness at gmail.com (Bryan Fodness) Date: Tue, 25 Mar 2008 11:59:54 -0400 Subject: [Tutor] Problem with logic while extracting data from binary file Message-ID: Here is my program. I am trying to extract values from a binary file for use in a calculation. I am having trouble with the logic. Everything goes well until I use the parseSequence function. If there is only one sequence I seem fine, but if there is a sequence within a sequence everything seems to fall apart. I don' t know if I have just looked at this so long that I am not seeing the obvious fix. Any help would be appreciated. I have attached the input file that I am using for a test. Also, here is one of the strings that enters the parseSequence function, broken up to make it more readable. I would like to get parseDICOM(rawData)['\n0\x82']. ----------------------------------------- ('\n0', 'p\x00', 544, '\xfe\xff\x00\xe0\x18\x02\x00\x00 \n0q\x00\x02\x00\x00\x001 \n0x\x00\x02\x00\x00\x0010 \n0\x80\x00\x02\x00\x00\x004 \n0\xa0\x00\x02\x00\x00\x000 \x0c0\x04\x00\xe8\x01\x00\x00 \xfe\xff\x00\xe0p\x00\x00\x00 *\n0\x82*\x002\x00\x00\x0042.9068704277562\\- 392.3545926477\\189.182112099444 \n0\x84\x00\x0c\x00\x00\x008.9617062e-1 \n0\x86\x00\x10\x00\x00\x00127.378510918301 \x0c0\x06\x00\x02\x00\x00\x001 \xfe\xff\x00\xe0p\x00\x00\x00 *\n0\x82*\x002\x00\x00\x0042.9068704277562\\- 392.3545926477\\189.182112099444 \n0\x84\x00\x0c\x00\x00\x001.629998e-1 \n0\x86\x00\x10\x00\x00\x0023.159729257873 \x0c0\x06\x00\x02\x00\x00\x004 \xfe\xff\x00\xe0t\x00\x00\x00 *\n0\x82*\x002\x00\x00\x0042.9068704277562\\- 392.3545926477\\189.182112099444 \n0\x84\x00\x10\x00\x00\x001.26285318894435 \n0\x86\x00\x10\x00\x00\x00227.690980638769 \x0c0\x06\x00\x02\x00\x00\x003 \xfe\xff\x00\xe0t\x00\x00\x00 \n0\x82\x002\x00\x00\x0042.9068704277562\\- 392.3545926477\\189.182112099444 \n0\x84\x00\x10\x00\x00\x001.52797639111557 \n0\x86\x00\x10\x00\x00\x00263.433384670643 \x0c0\x06\x00\x02\x00\x00\x002 ') import struct from time import * print "Creating Variables...\n" start=clock() rawData = open('file.dcm', 'rb').read() # Need to get Transfer Syntax UID (0002,0010) for encoding type def parsePreamble(data): preamble = data[:128] dicm = data[128:132] if dicm == 'DICM': return preamble, 132 else: raise NotAPreambleException def parseMetaElementGL(data): vl_field = data[138:140] length = struct.unpack('h', vl_field)[0] value = struct.unpack('hh',data[140:(140+length)])[0] return value def parseDataElement(data, start): if start < (144+parseMetaElementGL(rawData)): group_num = data[start:start+2] element_num = data[start+2:start+4] vr_field = data[start+4:start+6] if vr_field == 'UN' or vr_field == 'SQ' or vr_field == 'OB' or vr_field == 'OW': unused = data[start+6:start+8] vl_field = data[start+8:start+12] length = struct.unpack('hh', vl_field)[0] # 4-byte value = data[start+12:(start+12+length)] pos = start+12+length element = (group_num+element_num) return element, pos, value, length else: vl_field = data[start+6:start+8] length = struct.unpack('h', vl_field)[0] # 2-byte value = data[start+8:(start+8+length)] pos = start+8+length element = (group_num+element_num) return element, pos, value, length else: while start < len(data): group_num = data[start:start+2] element_num = data[start+2:start+4] vl_field = data[start+4:start+8] length = struct.unpack('hh', vl_field)[0] value = data[start+8:(start+8+length)] pos = start+8+length element = (group_num+element_num) return element, pos, value, length else: print "End of File" def parseSequence(data, start): group_num = data[start:start+2] element_num = data[start+2:start+4] vl_field = data[start+4:start+8] length = struct.unpack('hh', vl_field)[0] value = data[start+8:(start+8+length)] pos = start+8+length element = (group_num+element_num) if element == '\xfe\xff\x00\xe0': start = start+8 group_num = data[start:start+2] element_num = data[start+2:start+4] vl_field = data[start+4:start+8] length = struct.unpack('hh', vl_field)[0] value = data[start+8:(start+8+length)] pos = start+8+length element = (group_num+element_num) if element == '\xfe\xff\x00\xe0': start = start+8 group_num = data[start:start+2] element_num = data[start+2:start+4] vl_field = data[start+4:start+8] length = struct.unpack('hh', vl_field)[0] value = data[start+8:(start+8+length)] pos = start+8+length element = (group_num+element_num) return element, pos, value else: return element, pos, value else: return element, pos, value def parseDICOM(data): elements = [] values = [] try: preamble, next = parsePreamble(data) except NotAPreambleException: preamble, next = None, 0 while next < len(data): element, next, value, length = parseDataElement(data, next) if element == '\n0\x10\x00' or element == '\n0@\x00' or element == '\n0p\x00' or element == '\n0\xb0\x00': start = 0 while start < length: element, start, svalue = parseSequence(value, start) elements.append(element) values.append(svalue) else: elements.append(element) values.append(value) paired = zip(elements, values) search = dict(paired) return search # Access variables for use in calculation InstanceCreationDate = parseDICOM(rawData)['\x08\x00\x12\x00'] InstanceCreationTime = parseDICOM(rawData)['\x08\x00\x13\x00'] PatientsName = parseDICOM(rawData)['\x10\x00\x10\x00'] RTPlanLabel = parseDICOM(rawData)['\n0\x02\x00'] DoseReferenceDescription = parseDICOM(rawData)['\n0\x16\x00'] ToleranceTableLabel = parseDICOM(rawData)['\n0C\x00'] NumberOfBeams = int(parseDICOM(rawData)['\n0\x80\x00']) BeamDoseSpecificationPoint = parseDICOM(rawData)['\n0\x82'] print "Instance Creation Date\t\t\t=\t%s" %InstanceCreationDate print "Instance Creation Time\t\t\t=\t%s" %InstanceCreationTime print "Patients Name\t\t\t\t=\t%s" %PatientsName print "RT Plan Label\t\t\t\t=\t%s" %RTPlanLabel print "DoseReference Description\t\t=\t%s" %DoseReferenceDescription print "Tolerance Table Label\t\t\t=\t%s" %ToleranceTableLabel print "Number Of Beams\t\t\t\t=\t%i" %NumberOfBeams print "Beam Dose Specification Point\t\t=\t%s" %LeafJawPostions end=clock() time=end-start print "\nVariables created in %.3f seconds\n" %time -- "The game of science can accurately be described as a never-ending insult to human intelligence." - Jo?o Magueijo -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080325/d0dacd8b/attachment-0001.htm -------------- next part -------------- A non-text attachment was scrubbed... Name: file.dcm Type: application/octet-stream Size: 13138 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20080325/d0dacd8b/attachment-0001.obj From olexander.dubrovsky at viart.com.ua Tue Mar 25 17:13:24 2008 From: olexander.dubrovsky at viart.com.ua (Olexander) Date: Tue, 25 Mar 2008 18:13:24 +0200 Subject: [Tutor] Help with input/output Message-ID: <427247286.20080325181324@viart.com.ua> Hello, please could you help me with input processing for olympiad problems. For example, what would be the code for input and output of this problem: Input The input file contains several test cases. The first line of each test case contains two integers A and D separated by a single space indicating, respectively, the number of attacking and defending players involved in the play (2 <= A,D <= 11). The next line contains A integers Bi separated by single spaces, indicating the distances of the attacking players to the goal line (1 <= Bi <= 104). The next line contains D integers Cj separated by single spaces, indicating the distances of the defending players to the goal line (1 <= Cj <= 104). The end of input is indicated by A = D = 0. Output For each test case in the input print a line containing a single character: ?Y? (uppercase) if there is an attacking player offside, and ?N? (uppercase) otherwise. Example Input: 2 3 500 700 700 500 500 2 2 200 400 200 1000 3 4 530 510 490 480 470 50 310 0 0 Output: N Y N I also wonder how to output several integers in one line. Thank you. From bgailer at alum.rpi.edu Tue Mar 25 19:53:13 2008 From: bgailer at alum.rpi.edu (bob gailer) Date: Tue, 25 Mar 2008 14:53:13 -0400 Subject: [Tutor] decimal precision In-Reply-To: <674d5ce60803250619v7e020400y7ea959b4ab7750ac@mail.gmail.com> References: <674d5ce60803250619v7e020400y7ea959b4ab7750ac@mail.gmail.com> Message-ID: <47E94A19.5020701@alum.rpi.edu> elis aeris wrote: [snip] I echo Dick Moore. Several of us have requested that you study the tutorials. We continue to see no evidence that you are doing that, nor have you told us you are reading them or why not. Please respond by telling us you are reading the tutorials or if not why not. If you are, help us understand why the tutorials fail to answer many of these basic questions. I will not respond to any more of your posts until I have a sense that you are doing your best to learn by yourself. There are some who intentionally "abuse" forums like this. It is starting to look like you are one of those. -- Bob Gailer 919-636-4239 Chapel Hill, NC From bgailer at alum.rpi.edu Tue Mar 25 20:05:35 2008 From: bgailer at alum.rpi.edu (bob gailer) Date: Tue, 25 Mar 2008 15:05:35 -0400 Subject: [Tutor] Problem with logic while extracting data from binary file In-Reply-To: References: Message-ID: <47E94CFF.1020102@alum.rpi.edu> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080325/e8f2027a/attachment.htm From kent37 at tds.net Tue Mar 25 20:17:10 2008 From: kent37 at tds.net (Kent Johnson) Date: Tue, 25 Mar 2008 15:17:10 -0400 Subject: [Tutor] Help with input/output In-Reply-To: <427247286.20080325181324@viart.com.ua> References: <427247286.20080325181324@viart.com.ua> Message-ID: <47E94FB6.4010701@tds.net> Olexander wrote: > Hello, > > please could you help me with input processing for olympiad problems. Do you know how to read and write files? This is covered in every Python book and tutorial. What have you tried? What problems are you having? > I also wonder how to output several integers in one line. Again, this should be covered in a tutorial, but for example print 1, 2, 3 outputs three integers. Kent From levity at gmail.com Tue Mar 25 22:17:09 2008 From: levity at gmail.com (Lawrence Wang) Date: Tue, 25 Mar 2008 17:17:09 -0400 Subject: [Tutor] struct.calcsize curiosity... Message-ID: <22e13a220803251417w48e8cb63ha318bc633d60bc6b@mail.gmail.com> >>> struct.calcsize('hq') 12 >>> struct.calcsize('qh') 10 why is this? is it platform-dependent? i'm on mac os x. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080325/ec65a758/attachment.htm From GGraham at cistercian.org Tue Mar 25 22:49:03 2008 From: GGraham at cistercian.org (Greg Graham) Date: Tue, 25 Mar 2008 16:49:03 -0500 Subject: [Tutor] struct.calcsize curiosity... In-Reply-To: <22e13a220803251417w48e8cb63ha318bc633d60bc6b@mail.gmail.com> References: <22e13a220803251417w48e8cb63ha318bc633d60bc6b@mail.gmail.com> Message-ID: <4B07785C52C78449A6C036FB2F69BEBD0320B3CA@server1.cistercian.com> Lawrence Wang wrote: > >>> struct.calcsize('hq') > 12 > >>> struct.calcsize('qh') > 10 > > why is this? is it platform-dependent? i'm on mac os x. This has to do with data alignment and is platform-dependent. Are you on a PowerPC Macintosh? On my Intel Windows XP box, I get the following: In [3]: struct.calcsize('hq') Out[3]: 16 In [4]: struct.calcsize('qh') Out[4]: 10 I suspect on your computer, the elements of the struct have to be aligned on a 4 byte boundary. In the case of 'hq', the h takes 2 bytes, and the q takes 8 bytes. However, the q must start on a 4 byte boundary, so 2 bytes are wasted as padding between the h and the q. In the second example, because the q is first and takes 8 bytes, the h begins on a 4 byte boundary, so no padding is used. Note however if you had an array of 'qh' structs, I would expect there to still be 2 bytes of padding between each array member. On my machine, it seems to align on 8 byte boundaries, so in the 'hq' case, I'm wasting 6 bytes for padding between the h and the q. Greg From maozbay at gmail.com Tue Mar 25 23:57:38 2008 From: maozbay at gmail.com (Mali Ozbay) Date: Tue, 25 Mar 2008 17:57:38 -0500 Subject: [Tutor] Google Summer of Code 2008 - Student looking for Python Zope ZODB Grok Project / Mentor Message-ID: Hi there: I would love to see if there is anyone looking for a student to mentor to do some hacking in fields such as Python Zope ZODB Grok etc., during this summer, in the Google Summer of Code 2008. If you are interested in learning more about my background and experiences please see my resume on : http://denali.cs.uh.edu:9080/mali/re/Mehmet_Ozbay_Resume-3-25-08.htm You can also view my profile on Google Summer of Code 2008 web space ( http://code.google.com/soc/2008/) in the applicant students list. Sincerely Mali Ozbay University Of Houston - Computer Science -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080325/d1d7c039/attachment.htm From mlangford.cs03 at gtalumni.org Wed Mar 26 00:41:29 2008 From: mlangford.cs03 at gtalumni.org (Michael Langford) Date: Tue, 25 Mar 2008 19:41:29 -0400 Subject: [Tutor] Let imported module access calling program In-Reply-To: <376fbdcf0803241912lc985f0fk79c5ee0f6e78937@mail.gmail.com> References: <376fbdcf0803241912lc985f0fk79c5ee0f6e78937@mail.gmail.com> Message-ID: <82b4f5810803251641u7c7022cajba71bd41967f67d6@mail.gmail.com> The following is a pretty normal control loop for robot control (or other embedded devices). There are probably some syntactical errors as I'm writing this without a working python interpreter available at this second, but it should give you the correct gist to do what you said you were trying to do. You may want something like: #robotcontrol.py import time class OperationalStep(object): def __init__(self,func,interval=0): self.func = func self.interval = interval self.lastRun = getTime() def run(): """If the step hasn't been run recently enough, do so""" if self.interval + self.lastRun < getTime(): self.func() self.lastRun = getTime() def unknownEvent(): print( "This is an undefined event code" ) events = collections.defaultdict(unknownEvent) def getTime(): """returns time""" return time.clock() def registerEventHandler(eventCode,handler): """When event eventCode is seen, run handler""" global events events[eventCode] = handler def registerOperationalStep(step,delayAtLeast=0): """Registers a step that will be taken in the program no more often than delayAtLeast often""" global tasks t = OperationalStep(step,delayAtLeast) tasks.append(t) eventQueue = [] def addEvent(ev): global eventQueue eventQueue.append(ev) def robotLoop(): """runs each task, handling events as possible""" global eventQueue,tasks while True: for task in tasks: #process events for ev in eventQueue: events[ev]() #run next task task.run() All of this would be put in its own module, say robotcontrol, that would then be used thusly in a complete separate file: #myrobot.py import robotcontrol from madeupRobotApi import * from time import sleep def checkBump(): """Checks to see if the robot bump bar is pushed in""" if bump.pressed(): robotcontrol.addEvent(BUMP_EVENT) def handleSonarData(): """gets data from the sonar""" data = sonar.read() print (data) def handleCoreMeltdown(): """turns off the core""" powercore.off() def turnLeft(): ""turns the robot 90 degrees left" lwheels.run(-10) rwheels.run(10) sleep(10) lwheels.run(0) rwheels.run(0) checkBump() def turnRight(): ""turns the robot 90 degrees right" lwheels.run(10) rwheels.run(-10) sleep(10) lwheels.run(0) rwheels.run(0) checkBump() def goForward(speed=10,t=10): """goes forward at speed for time t""" lwheels.run(speed) rwheels.run(speed) sleep(t) lwheels.run(0) rwheels.run(0) checkBump() def goForwardALittle() goForward(10,1) checkBump() def checkSensors() if sonar.ready(): robotcontrol.addEvent(SONAR_EVENT) if core.tooHot(): robotcontrol.addEvent(OHNO_EVENT) direction = "RIGHT" def decideNewDirection(): global direction if sonar.data == "heavy": direction = "LEFT" else: direction = "RIGHT" def handleBump() """back up upon bump""" if bump.pressed(): goForward(speed=-10,t=10) def turn(): """turns the direction specified in direction""" global direction if direction == "LEFT": turnLeft() else: turnRight() def robotSetup(): """sets all the event handlers and defines the operational program""" #these will happen as things generate events registerEventHandler(SONAR_EVENT,handleSonarData) registerEventHandler(OHNO_EVENT,handleCoreMeltdown) registerEventHandler(BUMP_EVENT,handleBump) #robot control scheme registerOperationalStep(checkSensors,10) registerOperationalStep(decideNewDirection) registerOperationalStep(turn) registerOperationalStep(goForwardALittle) registerOperationalStep(decideNewDirection) registerOperationalStep(turn) if "__name__"==__main__: robotSetup() robotcontrol.robotLoop() -- Michael Langford 404-386-0495 http://www.RowdyLabs.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080325/464e8477/attachment.htm From nomb85 at comcast.net Wed Mar 26 03:01:23 2008 From: nomb85 at comcast.net (Nathan McBride) Date: Tue, 25 Mar 2008 22:01:23 -0400 Subject: [Tutor] Maybe advanced pexpect question? In-Reply-To: <47E6A8E5.80507@mwalsh.org> References: <3576e740802131857u44da9f5coa07656c1f97f5d91@mail.gmail.com> <5e58f2e40802132027w4432d9e0n3847f28fbc48794@mail.gmail.com> <1206249765.27498.2.camel@localhost.localdomain> <47E645DB.8080309@tds.net> <47E6A8E5.80507@mwalsh.org> Message-ID: <1206496883.8110.0.camel@localhost.localdomain> I'm thinking more along the lines as of running a program, sending tab to get to the field send text to put on the field, tab, send text ? On Sun, 2008-03-23 at 14:00 -0500, mwalsh wrote: > Kent Johnson wrote: > > Nathan McBride wrote: > >> I've used pexpect for a few projects and love it. Basically pexpect > >> lets you spawn a program and interact with it from code like you > >> yourself were running it in a console. How would you send the ctrl key? > > > > I don't use pexpect, so I am guessing... > > > > The ctrl key by itself is not a character so you can't send that. ctrl-C > > is a character that is represented in a string as \x03. I expect you > > would send a control character with sendline(), for example to sent > > ctrl-C try > > child.sendline ('\x03') > > In recent versions of pexpect (I'm looking at 2.3), 'spawn' objects > include a sendcontrol method which does almost exactly that for cntl-c, > with send instead of sendline. > > > Kent > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From technorapture at gmail.com Wed Mar 26 04:30:19 2008 From: technorapture at gmail.com (Shrutarshi Basu) Date: Tue, 25 Mar 2008 23:30:19 -0400 Subject: [Tutor] Let imported module access calling program In-Reply-To: <82b4f5810803251641u7c7022cajba71bd41967f67d6@mail.gmail.com> References: <376fbdcf0803241912lc985f0fk79c5ee0f6e78937@mail.gmail.com> <82b4f5810803251641u7c7022cajba71bd41967f67d6@mail.gmail.com> Message-ID: <376fbdcf0803252030p2990bb1el6d4eb1d30370fb4b@mail.gmail.com> Wow...I never expected to get so much help. Thanks for all of it...it's much appreciated. I'm not quite sure which approach I'm going to use (have quite some thinking to do), but I'll certainly consider all of them. And I've certainly learned a lot. Thanks again, Basu -- The ByteBaker : http://www.bytebaker.com From gloomdemon at gmail.com Wed Mar 26 09:47:23 2008 From: gloomdemon at gmail.com (Gloom Demon) Date: Wed, 26 Mar 2008 10:47:23 +0200 Subject: [Tutor] Table like array in Python Message-ID: <38446940803260147q4d90b23eo39eb7cc3b442e2b6@mail.gmail.com> Hello :-) I am reading Ivan van Leiningem "Learn Python in 24 hours" and I am having problems understanding the way arrays work in Python. I used to know Pascal and arrays there were tablelike. Example (cost of something in different countries by different years) Record1 US 2006 22.10 Record2 US 2007 23.45 Record3 UK 2007 22.90 .................................. RecordN .................... So I could read the record, see if the name of the country in the first cell was what I was looking for and either continue working with the record or resume searching. However in Python, if I understand correctly this example would look like this: US 2006 22.10 US 2007 23.45 UK 2007 22.90 ........................ This means that I have to keep a lot of unnesessary information in RAM, not to mention that I would have to scan through the whole array instead of scanning just the required cell. Could anyone please direct me to a good description of working with arrays in Python? And I have problems understanding what dictionaries are for :-( Thank You! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080326/e1236fd1/attachment.htm From connorsml at gmail.com Wed Mar 26 10:56:25 2008 From: connorsml at gmail.com (Michael Connors) Date: Wed, 26 Mar 2008 10:56:25 +0100 Subject: [Tutor] Table like array in Python In-Reply-To: <38446940803260147q4d90b23eo39eb7cc3b442e2b6@mail.gmail.com> References: <38446940803260147q4d90b23eo39eb7cc3b442e2b6@mail.gmail.com> Message-ID: On 26/03/2008, Gloom Demon wrote: > > Hello :-) > > Example (cost of something in different countries by different years) > > Record1 US 2006 22.10 > Record2 US 2007 23.45 > Record3 UK 2007 22.90 > .................................. > > > In Python a list is similiar to an array in Pascal. You define a list like this: my_list = [1, 2, 3, 4] However I dont think you want an array here, if I was doing something like this I would use a dictionary. A dictionary stores keys and values. So you could do something like this: records = {'US': {'2007': 22.5, '2008': 44.8}, 'UK': {'2008': 3.4, '2007': 2.6}} You can now access a particular record as follows: In: print records['UK']['2007'] Out: 2.6 Regards, -- Michael Connors -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080326/c9fe40eb/attachment-0001.htm From kent37 at tds.net Wed Mar 26 11:41:20 2008 From: kent37 at tds.net (Kent Johnson) Date: Wed, 26 Mar 2008 06:41:20 -0400 Subject: [Tutor] Table like array in Python In-Reply-To: <38446940803260147q4d90b23eo39eb7cc3b442e2b6@mail.gmail.com> References: <38446940803260147q4d90b23eo39eb7cc3b442e2b6@mail.gmail.com> Message-ID: <47EA2850.7090107@tds.net> Gloom Demon wrote: > Example (cost of something in different countries by different years) > > Record1 US 2006 22.10 > Record2 US 2007 23.45 > Record3 UK 2007 22.90 > .................................. > RecordN .................... > > So I could read the record, see if the name of the country in the first > cell was what I was looking for and either continue working with the > record or resume searching. Where are the records coming from? A file or database? > > However in Python, if I understand correctly this example would look > like this: > > US 2006 22.10 US 2007 23.45 UK 2007 22.90 ........................ If the data is in a file, and you read the file using file.read(), then you will get the full contents in memory in a single string. > > This means that I have to keep a lot of unnesessary information in RAM, > not to mention that I would have to scan through the whole array instead > of scanning just the required cell. > > Could anyone please direct me to a good description of working with > arrays in Python? Arrays are called lists in Python, they are covered in every tutorial. But I think maybe it is files that you need help with. You can read files line by line. One way is to use a for loop, for example, f = open('records.txt') for line in f: # the contents of each line in turn will be put in 'line' data = line.split() # split the line at spaces if data[1] == 'US': # process line for US Kent From rschroev_nospam_ml at fastmail.fm Wed Mar 26 12:03:06 2008 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Wed, 26 Mar 2008 12:03:06 +0100 Subject: [Tutor] Table like array in Python In-Reply-To: <38446940803260147q4d90b23eo39eb7cc3b442e2b6@mail.gmail.com> References: <38446940803260147q4d90b23eo39eb7cc3b442e2b6@mail.gmail.com> Message-ID: Gloom Demon schreef: > Hello :-) > > I am reading Ivan van Leiningem "Learn Python in 24 hours" and I am > having problems understanding the way arrays work in Python. I used to > know Pascal and arrays there were tablelike. > > Example (cost of something in different countries by different years) > > Record1 US 2006 22.10 > Record2 US 2007 23.45 > Record3 UK 2007 22.90 > .................................. > RecordN .................... That is an array of records. In Pascal you can also have e.g. an array of integers, and it is a sequential list just as in Python. What makes it table-like is that you have an array not of scalars but of records. > However in Python, if I understand correctly this example would look > like this: > > US 2006 22.10 US 2007 23.45 UK 2007 22.90 ........................ You could do it like that, but there are better ways. You could make a list of tuples, which would be more or less equivalent to your Pascal array of records. A simple example, presuming you read the values from a file: lst = [] for line in countryfile: country, year, amount = line.split() year = int(year) amount = float(amount) lst.append((country, year, amount)) That would look like: [ ('US', 2006, 22.10), ('US', 2007, 23.45) ... ] Then you could scan through it like this: for record in lst: if record[0] == 'US': ... -- The saddest aspect of life right now is that science gathers knowledge faster than society gathers wisdom. -- Isaac Asimov Roel Schroeven From tktucker at gmail.com Wed Mar 26 15:11:33 2008 From: tktucker at gmail.com (Tom Tucker) Date: Wed, 26 Mar 2008 10:11:33 -0400 Subject: [Tutor] Library for Disk Usage (UNIX) Message-ID: <2a278ffe0803260711pd4930f9gd04c8c45fe5fd5ca@mail.gmail.com> Hello all. I'm looking for a builtin Python library capable of providing similar output to what the unix df command provides. Obviously, I'm trying to avoid a system call if possible. I'm looking for the following fields at a mimimum, total size, used, and /path. Suggestions? I was looking at os.stat(/path)[WXYZ}, and os.path.getsize, but they are lacking. Thanks for the help, Tom -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080326/7f01cace/attachment.htm From cfuller084 at thinkingplanet.net Wed Mar 26 17:11:48 2008 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Wed, 26 Mar 2008 11:11:48 -0500 Subject: [Tutor] Library for Disk Usage (UNIX) In-Reply-To: <2a278ffe0803260711pd4930f9gd04c8c45fe5fd5ca@mail.gmail.com> References: <2a278ffe0803260711pd4930f9gd04c8c45fe5fd5ca@mail.gmail.com> Message-ID: <200803261111.48488.cfuller084@thinkingplanet.net> On Wednesday 26 March 2008 09:11, Tom Tucker wrote: > Hello all. I'm looking for a builtin Python library capable of providing > similar output to what the unix df command provides. Obviously, I'm trying > to avoid a system call if possible. I'm looking for the following fields > at a mimimum, total size, used, and /path. Suggestions? I was looking at > os.stat(/path)[WXYZ}, and os.path.getsize, but they are lacking. > > Thanks for the help, > > Tom You need to know the size of the blocks that the filesystem uses. Use the statvfs module and the os.statvfs function. Cheers From bgailer at alum.rpi.edu Wed Mar 26 20:01:17 2008 From: bgailer at alum.rpi.edu (bob gailer) Date: Wed, 26 Mar 2008 15:01:17 -0400 Subject: [Tutor] Problem with logic while extracting data from binary file In-Reply-To: References: <47E94CFF.1020102@alum.rpi.edu> <47E9900C.6080200@alum.rpi.edu> Message-ID: <47EA9D7D.7070008@alum.rpi.edu> Please always reply to the list not just me. Bryan Fodness wrote: > > Thanks Bob, > > I was having trouble with that loop from the start. Could you tell me > what a=3 is doing, I cannot seem to figure it out. I accidentally left that in. It was a place for me to set a breakpoint in the debugger. I also failed to point out that I made the creation of the dictionary "search" straightforward rather than collecting all the keys and values. However neither your code or mine handles the multi-value cases (e.g. \n0\x82). To solve that I changed search to be of type defaultdict so each new element is a list and we can use append() to add values to the lists. The printed output now looks like lists but that is easy to alter. In this version I also "import time", and changed the names start and time so as not to conflict (even in appearance) with other names. Also in this version I modified parseDataElement to be a generator (the quickest way I could think of to solve the while loop problem) and added a for loop in parseDICOM to access the generator. This also required adding "start = pos" at the end of the while loop. BUT ... on further inspection of your program and data I note that there is NOTHING that looks for \n0\x82. It sits in the middle of a block of data of length 544. There needs to be some code to examine the contents of that block and look for \n0\x82. Also discovered and fixed "name 'LeafJawPostions' is not defined". Code follows ------------------------------------------------------------------ import struct import time import collections print "Creating Variables...\n" startTime = time.clock() rawData = open('file.dcm', 'rb').read() # Need to get Transfer Syntax UID (0002,0010) for encoding type def parseDICOM(data): search = collections.defaultdict(list) try: preamble, next = parsePreamble(data) except NotAPreambleException: preamble, next = None, 0 while next < len(data): for element, next, value, length in parseDataElement(data, next): if element.startswith('\n0') and element.endswith('\x00') and element[2] in ('\x10', '@', 'p', '\xb0'): start = 0 while start < length: element, start, svalue = parseSequence(value, start) search[element].append(svalue) else: search[element].append(value) return search def parsePreamble(data): preamble = data[:128] dicm = data[128:132] if dicm == 'DICM': return preamble, 132 else: raise NotAPreambleException def parseMetaElementGL(data): vl_field = data[138:140] length = struct.unpack('h', vl_field)[0] value = struct.unpack('hh',data[140:(140+length)])[0] return value def parseDataElement(data, start): if start < (144 + parseMetaElementGL(rawData)): group_num = data[start:start+2] element_num = data[start+2:start+4] vr_field = data[start+4:start+6] if vr_field in ('UN', 'SQ', 'OB','OW'): unused = data[start+6:start+8] vl_field = data[start+8:start+12] length = struct.unpack('hh', vl_field)[0] # 4-byte value = data[start+12:(start+12+length)] pos = start+12+length element = (group_num+element_num) yield element, pos, value, length else: vl_field = data[start+6:start+8] length = struct.unpack('h', vl_field)[0] # 2-byte value = data[start+8:(start+8+length)] pos = start+8+length element = (group_num+element_num) yield element, pos, value, length else: while start < len(data): group_num = data[start:start+2] element_num = data[start+2:start+4] vl_field = data[start+4:start+8] length = struct.unpack('hh', vl_field)[0] value = data[start+8:(start+8+length)] pos = start+8+length element = (group_num+element_num) yield element, pos, value, length start = pos else: print "End of File" def parseSequence(data, start): group_num = data[start:start+2] element_num = data[start+2:start+4] vl_field = data[start+4:start+8] length = struct.unpack('hh', vl_field)[0] value = data[start+8:(start+8+length)] pos = start+8+length element = (group_num+element_num) if element == '\xfe\xff\x00\xe0': start = start+8 group_num = data[start:start+2] element_num = data[start+2:start+4] vl_field = data[start+4:start+8] length = struct.unpack('hh', vl_field)[0] value = data[start+8:(start+8+length)] pos = start+8+length element = (group_num+element_num) if element == '\xfe\xff\x00\xe0': start = start+8 group_num = data[start:start+2] element_num = data[start+2:start+4] vl_field = data[start+4:start+8] length = struct.unpack('hh', vl_field)[0] value = data[start+8:(start+8+length)] pos = start+8+length element = (group_num+element_num) return element, pos, value else: return element, pos, value else: return element, pos, value # Access variables for use in calculation parsedData = parseDICOM(rawData) InstanceCreationDate = parsedData['\x08\x00\x12\x00'] InstanceCreationTime = parsedData['\x08\x00\x13\x00'] PatientsName = parsedData['\x10\x00\x10\x00'] RTPlanLabel = parsedData['\n0\x02\x00'] DoseReferenceDescription = parsedData['\n0\x16\x00'] ToleranceTableLabel = parsedData['\n0C\x00'] NumberOfBeams = int(parsedData['\n0\x80\x00'][0]) BeamDoseSpecificationPoint = parsedData['\n0\x82'] print "Instance Creation Date\t\t\t=\t%s" %InstanceCreationDate print "Instance Creation Time\t\t\t=\t%s" %InstanceCreationTime print "Patients Name\t\t\t\t=\t%s" %PatientsName print "RT Plan Label\t\t\t\t=\t%s" %RTPlanLabel print "DoseReference Description\t\t=\t%s" %DoseReferenceDescription print "Tolerance Table Label\t\t\t=\t%s" %ToleranceTableLabel print "Number Of Beams\t\t\t\t=\t%i" %NumberOfBeams print "Beam Dose Specification Point\t\t=\t%s" % BeamDoseSpecificationPoint end = time.clock() runTime = end - startTime print "\nVariables created in %.3f seconds\n" % runTime -- Bob Gailer 919-636-4239 Chapel Hill, NC From danpaquin at yahoo.com Wed Mar 26 21:30:27 2008 From: danpaquin at yahoo.com (Dan Thomas-Paquin) Date: Wed, 26 Mar 2008 13:30:27 -0700 (PDT) Subject: [Tutor] SOAPpy and ZSI Message-ID: <777156.47055.qm@web50807.mail.re2.yahoo.com> Hi, I've been tasked with setting up a basic SOAP client and I'm its been the most frustrating python experience. Here's the code: from LoginService_services import * import sys from SOAPpy import SOAPProxy # get a port proxy instance loc = LoginServiceLocator() port = loc.getLogin(in0='pbs_uen', in1='TDapi', in2='3dcarapi') # create a new request req = LoginRequest() # call the remote method resp = port.Login(req) lr = resp.LoginReturn lri0 = lr.get_element_items()[0] service_url = lri0.Value n = 'http://DefaultNamespace' server = SOAPProxy(service_url, namespace=n) server.config.dumpSOAPOut = 1 server.config.dumpSOAPIn = 1 server.config.dumpHeadersOut = 1 server.config.dumpHeadersIn = 1 test = server.greeting() Notice I use ZSI (LoginService_services) for the Login and then SOAPpy for the post log-in stuff (ZSI's wsdl2py script broke on the post log-in WSDL). The login part works fine. It returns a URL with a session id appended. server.greeting() creates this envelope which I can see because of the dumps: but then this error follows right after: File "generic_usage.py", line 34, in test = server.greeting() File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/SOAPpy/Client.py", line 470, in __call__ return self.__r_call(*args, **kw) File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/SOAPpy/Client.py", line 492, in __r_call self.__hd, self.__ma) File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/SOAPpy/Client.py", line 363, in __call config = self.config) File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/SOAPpy/Client.py", line 252, in call raise HTTPError(code, msg) SOAPpy.Errors.HTTPError: line 252 of Client.py is: if code == 500 and not \ ( startswith(content_type, "text/xml") and message_len > 0 ): raise HTTPError(code, msg) I can't tell if the server is returning the 500 error or if the transport is. I honestly don't know where to go from here. I wouldn't doubt that the envelope isn't correct for the service but I don't have access to any more info on that. Help much appreciated. Dan "All men dream: but not equally. Those who dream by night in the dusty recesses of their minds wake in the day to find that it was vanity: but the dreamers of the day are dangerous men, for they may act their dreams with open eyes, to make it possible." -T. E. Lawrence - From cappy2112 at gmail.com Thu Mar 27 00:28:52 2008 From: cappy2112 at gmail.com (Tony Cappellini) Date: Wed, 26 Mar 2008 16:28:52 -0700 Subject: [Tutor] Tutor Digest, Vol 49, Issue 78 In-Reply-To: References: Message-ID: <8249c4ac0803261628v3d0f0ac9qa5c48f26e2aa519@mail.gmail.com> >>Draft notes for the next Kent's Korner presentation are available at >>http://personalpages.tds.net/~kent37/kk/00010.html >>Comments welcome. I vote Kent move out of the korner and into the front of the classroom! Nice color scheme, easy to look at, good layout, font, size, and small chunks (paragraphs?) of info to digest without getting overwhelmed by a page of content. The page looks great. From o.lenstra at gmail.com Thu Mar 27 11:15:59 2008 From: o.lenstra at gmail.com (Olrik Lenstra) Date: Thu, 27 Mar 2008 11:15:59 +0100 Subject: [Tutor] Tutor support request. Message-ID: <3c8f6fd70803270315l79d71eb7t297734a6c025911e@mail.gmail.com> Hi There: I am Olrik. 17 year old student that is practicing IT. I recently began learning Python and it's going quite fine. I'm following a tutorial at http://www.freenetpages.co.uk/hp/alan.gauld/ I just finished the branching tab to the left. And i'm about to start Modules & Functions. However, I've reached a point where I'd like some support from someone that is willing to tutor me and maybe give me some little assignments that I can practice on. I'm really willing to learn how to program Python and generally a fast learner. Hope to hear from you soon, Regards, Olrik From bhaaluu at gmail.com Thu Mar 27 13:51:44 2008 From: bhaaluu at gmail.com (bhaaluu) Date: Thu, 27 Mar 2008 08:51:44 -0400 Subject: [Tutor] Tutor support request. In-Reply-To: <3c8f6fd70803270315l79d71eb7t297734a6c025911e@mail.gmail.com> References: <3c8f6fd70803270315l79d71eb7t297734a6c025911e@mail.gmail.com> Message-ID: Hello Olrik, You can post your questions to this list and have access to many tutors. Generally speaking, if you'll post a code snippet with your question, it makes replying with a helpful answer much easier. Happy Programming! -- b h a a l u u at g m a i l dot c o m "You assist an evil system most effectively by obeying its orders and decrees. An evil system never deserves such allegiance. Allegiance to it means partaking of the evil. A good person will resist an evil system with his or her whole soul." [Mahatma Gandhi] On Thu, Mar 27, 2008 at 6:15 AM, Olrik Lenstra wrote: > Hi There: > > I am Olrik. 17 year old student that is practicing IT. > I recently began learning Python and it's going quite fine. > I'm following a tutorial at http://www.freenetpages.co.uk/hp/alan.gauld/ > I just finished the branching tab to the left. And i'm about to start > Modules & Functions. > However, I've reached a point where I'd like some support from someone > that is willing to tutor me > and maybe give me some little assignments that I can practice on. > I'm really willing to learn how to program Python and generally a fast learner. > > Hope to hear from you soon, > Regards, > Olrik > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From justin.cardinal at exbsolutions.com Thu Mar 27 16:50:41 2008 From: justin.cardinal at exbsolutions.com (Justin Cardinal) Date: Thu, 27 Mar 2008 10:50:41 -0500 Subject: [Tutor] Scripting Outlook Message-ID: <023501c89022$4fd24fd0$de91a8c0@exbspider> Can anyone direct me to some examples/documentation for using python to work with Outlook? So far, the most useful thing I've come across is a post from someone with problems adding an attachment: http://mail.python.org/pipermail/python-list/2002-August/160894.html That actually got me far enough to create a basic message and send it with "To" recipients, subject and body filled out. I get a warning that a program is trying to access Outlook, which I then have to manually allow, and I think I've seen it suggested that this can be worked around. Also, I'd like to learn more, like how to use signatures and encryption, adding recipients to the "Cc" and "Bcc" fields, etc. Any suggestions would be much appreciated. Thanks! Justin Cardinal | EXB Solutions, Inc -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080327/ca598605/attachment.htm From mail at timgolden.me.uk Thu Mar 27 16:58:28 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 27 Mar 2008 15:58:28 +0000 Subject: [Tutor] Scripting Outlook In-Reply-To: <023501c89022$4fd24fd0$de91a8c0@exbspider> References: <023501c89022$4fd24fd0$de91a8c0@exbspider> Message-ID: <47EBC424.2020008@timgolden.me.uk> Justin Cardinal wrote: > Can anyone direct me to some examples/documentation for using python to work > with Outlook? So far, the most useful thing I've come across is a post from > someone with problems adding an attachment: > http://mail.python.org/pipermail/python-list/2002-August/160894.html > > That actually got me far enough to create a basic message and send it with > "To" recipients, subject and body filled out. I get a warning that a program > is trying to access Outlook, which I then have to manually allow, and I > think I've seen it suggested that this can be worked around. Also, I'd like > to learn more, like how to use signatures and encryption, adding recipients > to the "Cc" and "Bcc" fields, etc. Any suggestions would be much > appreciated. Thanks! I have some (very few) examples here: http://timgolden.me.uk/python/win32_how_do_i/read-my-outlook-inbox.html http://timgolden.me.uk/python/win32_how_do_i/replace-outlook-attachments-with-links.html and for moderately advanced stuff you can always try try the SpamBayes source: http://spambayes.sourceforge.net/ but as far as I know no-one's produced a Pythonic wrapper for Outlook so you're basically using standard CDO or Outlook automation. Which means that any of the samples around the Web should be applicable and fairly easily translated. I'll try to rustle up some more examples from my own stash, but the nature of my how-do-i pages is that they're small, self-contained examples rather than extensive docs. TJG From mail at timgolden.me.uk Thu Mar 27 17:05:15 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 27 Mar 2008 16:05:15 +0000 Subject: [Tutor] Scripting Outlook In-Reply-To: <023501c89022$4fd24fd0$de91a8c0@exbspider> References: <023501c89022$4fd24fd0$de91a8c0@exbspider> Message-ID: <47EBC5BB.4000207@timgolden.me.uk> Justin Cardinal wrote: > Can anyone direct me to some examples/documentation for using python to work > with Outlook? So far, the most useful thing I've come across is a post from > someone with problems adding an attachment: and just for another example, here's some older code which I post untested (altho' it certainly worked once upon a time). If I get a chance I'll work it into a how-do-i. TJG import os from win32com.client import Dispatch, constants, gencache outlook = gencache.EnsureDispatch ("Outlook.Application") def send (self, to_people, cc_people=[], subject="", text="", attachments=[]): msg = outlook.CreateItem (constants.olMailItem) msg.Subject = subject msg.Body = text if type (to_people) == type (""): to_people = (to_people,) if type (cc_people) == type (""): cc_people = (cc_people,) recipients = [] for person in to_people: recipient = msg.Recipients.Add (person) recipient.Type = constants.olTo recipients.append (recipient) for person in cc_people: recipient = msg.Recipients.Add (person) recipient.Type = constants.olCC recipients.append (recipient) if type (attachments) == type (""): attachments = (attachments,) for attachment in attachments: if os.path.isfile (attachment): msg.Attachments.Add (attachment) else: print "attachment %s skipped" % attachment all_resolved = 1 for recipient in recipients: if not recipient.Resolve (): print "Unable to resolve " + recipient.Name all_resolved = 0 if all_resolved: msg.Send () print "Message sent" else: print "Message not sent" From tucalipe at gmail.com Thu Mar 27 19:34:02 2008 From: tucalipe at gmail.com (Artur Sousa) Date: Thu, 27 Mar 2008 15:34:02 -0300 Subject: [Tutor] Creating Standalone Executables Message-ID: <29c144020803271134j418d415dx4f4cea25c059ab8b@mail.gmail.com> Hi. Is there a way to create a user friendly, with a simple GUI, *.py executable? The packages I've been trying create executables for doscmd that doesn't wait for the user to input the required values. Let me explain: What I'm trying to publish is one single script with various subscripts defined by functions, so I would end with one single py file, and when the user opens it, it has to enter a command to acess one of its features. However, The doscmd version of python doesn't waits for the users' response, it just terminates the script. So, I'd like some information on how to create a simple executable that allows the user to choose the subscripts he/she wants to run. It doesn't really need to have a GUI, but something rather than doscmd, if possible... Thanks in advance. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080327/478d558f/attachment.htm From bryan.fodness at gmail.com Thu Mar 27 22:42:34 2008 From: bryan.fodness at gmail.com (Bryan Fodness) Date: Thu, 27 Mar 2008 17:42:34 -0400 Subject: [Tutor] Problem with logic while extracting data from binary file In-Reply-To: <47EA9D7D.7070008@alum.rpi.edu> References: <47E94CFF.1020102@alum.rpi.edu> <47E9900C.6080200@alum.rpi.edu> <47EA9D7D.7070008@alum.rpi.edu> Message-ID: Thanks again, I can't seem to keep track of my start values when I break up the value variable into svalues. Do you think I should do this, or should I have a running count from the beginning of the file and keep track until the end? I am trying to find \n0\x82\x00 and \n0\x84\x00 within the block. I've added the if statement, and it seems to enter the parseSequence function the way I would expect, but it does not seem to populate the dictionary. Sorry for so many questions about this, but I feel like I am so close. while next < len(data): for element, next, value, length in parseDataElement(data, next): ## if element in ('\n0\x10\x00', '\n0@\x00', '\n0p\x00', ## '\n0\xb0\x00', '\n0\x80\x01'): if element == '\n0p\x00': start = 0 while start < length: element, start, svalue = parseSequence(value, start) if svalue.startswith('\xfe\xff\x00\xe0'): start_2 = 0 element, start_2, svalue = parseSequence(svalue, start) search[element].append(svalue) search[element].append(svalue) else: search[element].append(value) return search -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080327/d705feca/attachment.htm From bryan.fodness at gmail.com Thu Mar 27 22:45:03 2008 From: bryan.fodness at gmail.com (Bryan Fodness) Date: Thu, 27 Mar 2008 17:45:03 -0400 Subject: [Tutor] Problem with logic while extracting data from binary file In-Reply-To: References: <47E94CFF.1020102@alum.rpi.edu> <47E9900C.6080200@alum.rpi.edu> <47EA9D7D.7070008@alum.rpi.edu> Message-ID: the start_2 is supposed to be start On Thu, Mar 27, 2008 at 5:42 PM, Bryan Fodness wrote: > Thanks again, > > I can't seem to keep track of my start values when I break up the value > variable into svalues. Do you think I should do this, or should I have a > running count from the beginning of the file and keep track until the end? > > I am trying to find \n0\x82\x00 and \n0\x84\x00 within the block. I've > added the if statement, and it seems to enter the parseSequence function the > way I would expect, but it does not seem to populate the dictionary. > > Sorry for so many questions about this, but I feel like I am so close. > > > while next < len(data): > for element, next, value, length in parseDataElement(data, next): > ## if element in ('\n0\x10\x00', '\n0@\x00', '\n0p\x00', > ## '\n0\xb0\x00', '\n0\x80\x01'): > if element == '\n0p\x00': > start = 0 > while start < length: > element, start, svalue = parseSequence(value, start) > if svalue.startswith('\xfe\xff\x00\xe0'): > start_2 = 0 > element, start_2, svalue = parseSequence(svalue, > start) > search[element].append(svalue) > search[element].append(svalue) > else: > search[element].append(value) > return search > -- "The game of science can accurately be described as a never-ending insult to human intelligence." - Jo?o Magueijo -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080327/b91a833a/attachment-0001.htm From dperlman at wisc.edu Thu Mar 27 23:54:49 2008 From: dperlman at wisc.edu (David Perlman) Date: Thu, 27 Mar 2008 17:54:49 -0500 Subject: [Tutor] Interactive plots... Message-ID: I am thinking about writing a program which will involve, among other things, displaying a plot of a series of numbers. The idea is that you could click on the points and move them to change the numbers. Reverse-plotting, I suppose. It need not be complex; the numbers will all be zero or one, and it's only necessary to flip the bits, so click-and-drag is seriously overkill. Really it would be better to just double-click on a point to switch it from one value to the other. Can anyone point me in the right direction? I have written some programs in python before, including TKinter, but this new project is beyond the point that I know where to even start looking. :) In case you care, the application is in functional brain imaging; the brain scans generate a certain number of time points (say 500) and then the motion of the subject is also calculated. Standard practice is to generate a "censor" file composed of zeros and ones, where zero indicates that that time point had excessive motion and must be disregarded. I want to display a graph of the motion over time, and allow quick and easy interactive editing of the censor time series in visual parallel to the motion graph. This would save a lot of time; at present everyone does this in Excel, which being a horrible Windows program can't be integrated into the predominantly UNIX-based processing pipeline. And in any case, it requires manually typing all the zeros, looking back and forth between the graph of motion and the list of numbers. I have already written a program to algorithmically generate the censor time series from the motion data, but it is absolutely essential to be able to manually double-check and if necessary make minor edits. I'd like to be able to keep that functionality in Python rather than sending everyone back to Excel... if possible! Thanks very much for any help. -- -dave---------------------------------------------------------------- "Pseudo-colored pictures of a person's brain lighting up are undoubtedly more persuasive than a pattern of squiggles produced by a polygraph. That could be a big problem if the goal is to get to the truth." -Dr. Steven Hyman, Harvard From wescpy at gmail.com Fri Mar 28 00:01:46 2008 From: wescpy at gmail.com (wesley chun) Date: Thu, 27 Mar 2008 16:01:46 -0700 Subject: [Tutor] Scripting Outlook In-Reply-To: <47EBC5BB.4000207@timgolden.me.uk> References: <023501c89022$4fd24fd0$de91a8c0@exbspider> <47EBC5BB.4000207@timgolden.me.uk> Message-ID: <78b3a9580803271601w698f831kf3552a1f06006603@mail.gmail.com> > > Can anyone direct me to some examples/documentation for using python to work > > with Outlook? > > and just for another example, here's some older code > which I post untested (altho' it certainly worked > once upon a time). If I get a chance I'll work it > into a how-do-i. i began to write a chapter on Win32/Microsoft Office programming and put this preliminary work in the 2nd edition of Core Python with the intention on completing it for some future edition. there is one code snippet in the book for Outlook (Example 23.5, olook.pyw). you don't have to buy the book and can just download that file from the book's website below (click "Source Code" on the left and go to chapter 23). i plan to have more examples in future editions of the book. hope this helps! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From bryan.fodness at gmail.com Fri Mar 28 00:03:31 2008 From: bryan.fodness at gmail.com (Bryan Fodness) Date: Thu, 27 Mar 2008 19:03:31 -0400 Subject: [Tutor] Problem with logic while extracting data from binary file In-Reply-To: <47EC22F4.8030105@alum.rpi.edu> References: <47E94CFF.1020102@alum.rpi.edu> <47E9900C.6080200@alum.rpi.edu> <47EA9D7D.7070008@alum.rpi.edu> <47EC22F4.8030105@alum.rpi.edu> Message-ID: On Thu, Mar 27, 2008 at 6:43 PM, bob gailer wrote: > Bryan Fodness wrote: > > Thanks again, > > The problem is that parseSequence gets the length of the block, then, in > effect, skips to the next block. That bypasses the sub-sequences you want. > > parseSquence needs to examine the block for the sub-blocks beginning > with \n0\x84\x00. This will probably require another while loop. I will try that. > > > Do you use a debugger? It has been very helpful to me in tracking down > the problem. What operating system are you running? What IDE or > development tool are you using? I have not used a debugger yet, I was getting ready to try that. I am using IDLE on Windows Vista. > > > [snip] > > -- > Bob Gailer > 919-636-4239 Chapel Hill, NC > > -- "The game of science can accurately be described as a never-ending insult to human intelligence." - Jo?o Magueijo -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080327/ff3e9802/attachment.htm From john at fouhy.net Fri Mar 28 00:07:02 2008 From: john at fouhy.net (John Fouhy) Date: Fri, 28 Mar 2008 12:07:02 +1300 Subject: [Tutor] Interactive plots... In-Reply-To: References: Message-ID: <5e58f2e40803271607y518bbda5la12539e5cc7398e7@mail.gmail.com> On 28/03/2008, David Perlman wrote: > I am thinking about writing a program which will involve, among other > things, displaying a plot of a series of numbers. The idea is that > you could click on the points and move them to change the numbers. > Reverse-plotting, I suppose. It need not be complex; the numbers > will all be zero or one, and it's only necessary to flip the bits, so > click-and-drag is seriously overkill. Really it would be better to > just double-click on a point to switch it from one value to the other. > > Can anyone point me in the right direction? I have written some > programs in python before, including TKinter, but this new project is > beyond the point that I know where to even start looking. :) You could probably do it with Tkinter -- use a Canvas widget to draw your points. Each point could just be an oval, and you can bind events to canvas items in a similar fashion to binding to buttons. So you would bind on click (or double-click) an event to move the point and recalculate. If you want to drag points around, it's possible too, the bindings just become a bit more complex. I think there are recipes or examples around on the net that you can probably find. -- John. From rdm at rcblue.com Fri Mar 28 00:26:25 2008 From: rdm at rcblue.com (Dick Moores) Date: Thu, 27 Mar 2008 16:26:25 -0700 Subject: [Tutor] Tutor support request. In-Reply-To: <3c8f6fd70803270315l79d71eb7t297734a6c025911e@mail.gmail.co m> References: <3c8f6fd70803270315l79d71eb7t297734a6c025911e@mail.gmail.com> Message-ID: <20080327232727.2B0961E4012@bag.python.org> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080327/df4f38d6/attachment.htm From bgailer at alum.rpi.edu Thu Mar 27 23:43:00 2008 From: bgailer at alum.rpi.edu (bob gailer) Date: Thu, 27 Mar 2008 18:43:00 -0400 Subject: [Tutor] Problem with logic while extracting data from binary file In-Reply-To: References: <47E94CFF.1020102@alum.rpi.edu> <47E9900C.6080200@alum.rpi.edu> <47EA9D7D.7070008@alum.rpi.edu> Message-ID: <47EC22F4.8030105@alum.rpi.edu> Bryan Fodness wrote: > Thanks again, The problem is that parseSequence gets the length of the block, then, in effect, skips to the next block. That bypasses the sub-sequences you want. parseSquence needs to examine the block for the sub-blocks beginning with \n0\x84\x00. This will probably require another while loop. Do you use a debugger? It has been very helpful to me in tracking down the problem. What operating system are you running? What IDE or development tool are you using? [snip] -- Bob Gailer 919-636-4239 Chapel Hill, NC From kepalapening at gmail.com Fri Mar 28 01:47:46 2008 From: kepalapening at gmail.com (Rizauddin Saian) Date: Fri, 28 Mar 2008 08:47:46 +0800 Subject: [Tutor] Creating Standalone Executables Message-ID: <20080328.004746.750.1@SELINAPPORTABLE> Just put an extra raw_input() at the end of the python script. It will wait for your input, instead of closing the command prompt. BTW, easygui (http://www.ferg.org/easygui/) is a very simple gui. If you use wxPython, you can use wxGlade as the gui editor. ----- Original Message ----- From: "Artur Sousa" To: tutor at python.org Date: Thu, 27 Mar 2008 15:34:02 -0300 Subject: [Tutor] Creating Standalone Executables Hi. Is there a way to create a user friendly, with a simple GUI, *.py executable? The packages I've been trying create executables for doscmd that doesn't wait for the user to input the required values. Let me explain: What I'm trying to publish is one single script with various subscripts defined by functions, so I would end with one single py file, and when the user opens it, it has to enter a command to acess one of its features. However, The doscmd version of python doesn't waits for the users' response, it just terminates the script. So, I'd like some information on how to create a simple executable that allows the user to choose the subscripts he/she wants to run. It doesn't really need to have a GUI, but something rather than doscmd, if possible... Thanks in advance. From bgailer at alum.rpi.edu Fri Mar 28 02:46:49 2008 From: bgailer at alum.rpi.edu (bob gailer) Date: Thu, 27 Mar 2008 21:46:49 -0400 Subject: [Tutor] Problem with logic while extracting data from binary file In-Reply-To: References: <47E94CFF.1020102@alum.rpi.edu> <47E9900C.6080200@alum.rpi.edu> <47EA9D7D.7070008@alum.rpi.edu> <47EC22F4.8030105@alum.rpi.edu> Message-ID: <47EC4E09.5030407@alum.rpi.edu> Bryan Fodness wrote: > > I have not used a debugger yet, I was getting ready to try that. I am > using IDLE on Windows Vista. > Ah. May I recommend Python for Windows. The debugging support is excellent. I prefer it to IDLE. http://sourceforge.net/projects/pywin32/ -- Bob Gailer 919-636-4239 Chapel Hill, NC From pylinuxian at gmail.com Fri Mar 28 09:14:58 2008 From: pylinuxian at gmail.com (linuxian iandsd) Date: Fri, 28 Mar 2008 08:14:58 +0000 Subject: [Tutor] parse emails as they come in Message-ID: good morning everybody ! I have scripted a small program to parse a 5 lines email message as it comes in to my inbox (this is handled by procmail & here is a wonderful intro to it : http://linuxfocus.org/English/November1997/article8.html) so every email is being parsed & information is extracted from it. but sometimes two or more emails come in at once so the input file that my python script has to parse is more than five lines !! my question is how do i effeciently manage this from within my original script. thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080328/806f5368/attachment-0001.htm From amints7 at gmail.com Fri Mar 28 05:50:23 2008 From: amints7 at gmail.com (Amin Han) Date: Fri, 28 Mar 2008 00:50:23 -0400 Subject: [Tutor] Help Writing a Bill Calculating Program Message-ID: Hi, I'm currently a novice at Python, and I need help creating the following program... # Write a program that asks the user to enter a package number and the total number of hours spent online that month (you may assume that the user will enter an integer number of hours). Using the information below, calculate and print the user's bill for that month. # Modify your program so that it first asks for the total number of bills to generate. Your program should use a loop to calculate that many customer bills. #If possible, modify your program so that it also calculates and prints what the user would have spent if he had one of the other two packages. If the user would have saved money using a different package, print out an appropriate message (e.g., "Package 3 would have been cheaper"). * Package 1: For $9.95 per month, up to 10 hours of access are provided. Each additional hour costs $2.00. * Package 2: For $13.95 per month, up to 20 hours of access are provided. Each additional hour costs $1.00. * Package 3: For 19.95 per month, a customer receives an unlimited number of hours of access. If you could help, that would be much appreciated. Thanks so much. -- "After three days without reading, talk becomes flavorless." From andreas at kostyrka.org Fri Mar 28 11:48:47 2008 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Fri, 28 Mar 2008 11:48:47 +0100 Subject: [Tutor] Help Writing a Bill Calculating Program In-Reply-To: References: Message-ID: <1206701327.11011.141.camel@localhost> Hint: When you want help with your homework, you should first try to program something. Pasting the requirements to this mailing list will not help you. Homeworks are there so that YOU learn something. Not that you can prove that you are capable to find someone that does it for you. Andreas Am Freitag, den 28.03.2008, 00:50 -0400 schrieb Amin Han: > Hi, I'm currently a novice at Python, and I need help creating the > following program... > > # Write a program that asks the user to enter a package number and the > total number of hours spent online that month (you may assume that the > user will enter an integer number of hours). Using the information > below, calculate and print the user's bill for that month. > # Modify your program so that it first asks for the total number of > bills to generate. Your program should use a loop to calculate that > many customer bills. > #If possible, modify your program so that it also calculates and > prints what the user would have spent if he had one of the other two > packages. If the user would have saved money using a different > package, print out an appropriate message (e.g., "Package 3 would have > been cheaper"). > > * Package 1: For $9.95 per month, up to 10 hours of access are > provided. Each additional hour costs $2.00. > * Package 2: For $13.95 per month, up to 20 hours of access are > provided. Each additional hour costs $1.00. > * Package 3: For 19.95 per month, a customer receives an unlimited > number of hours of access. > > If you could help, that would be much appreciated. Thanks so much. > -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Dies ist ein digital signierter Nachrichtenteil Url : http://mail.python.org/pipermail/tutor/attachments/20080328/a5f8b30b/attachment.pgp From bhaaluu at gmail.com Fri Mar 28 12:32:04 2008 From: bhaaluu at gmail.com (bhaaluu) Date: Fri, 28 Mar 2008 07:32:04 -0400 Subject: [Tutor] Help Writing a Bill Calculating Program In-Reply-To: References: Message-ID: On Fri, Mar 28, 2008 at 12:50 AM, Amin Han wrote: > Hi, I'm currently a novice at Python, and I need help creating the > following program... > > # Write a program that asks the user to enter a package number and the > total number of hours spent online that month (you may assume that the > user will enter an integer number of hours). Using the information > below, calculate and print the user's bill for that month. First of all, carefully read the problem that you have been given. Most computer programs solve a problem. At a minimum, a program may ask for INPUT, then do a COMPUTATION of some sort, and finally OUTPUT an answer or solution. After you've read the problem, get a pencil and a piece of paper and write down everything you've learned by reading the problem. At a minimum, you should write down what the INPUT is, what needs to be COMPUTED, and what the output is. Things called variables hold input values, and be used in COMPUTATIONS, and also used to provide output. It is usually helpful to have meaningful variable names. At this point, you should have enough information to write a simple program using pseudocode. Now work through the pseudocode and desk-check it to see if it will do what you want it to do. Good. At this point, translating the pseudocode to Python should be rather straightforward. > # Modify your program so that it first asks for the total number of > bills to generate. Your program should use a loop to calculate that > many customer bills. In order to modify a program, you need to have a working program. So, if you don't have a working program yet, go back and work some more. Once you have a working program, you'll need to review what you know about loops. Apply that knowledge, using the same steps as before, to this problem. INPUT->COMPUTATION->OUTPUT > #If possible, modify your program so that it also calculates and > prints what the user would have spent if he had one of the other two > packages. If the user would have saved money using a different > package, print out an appropriate message (e.g., "Package 3 would have > been cheaper"). Here again, use the same approach as you've already done for this problem. > * Package 1: For $9.95 per month, up to 10 hours of access are > provided. Each additional hour costs $2.00. > * Package 2: For $13.95 per month, up to 20 hours of access are > provided. Each additional hour costs $1.00. > * Package 3: For 19.95 per month, a customer receives an unlimited > number of hours of access. The data is very clear. What is package 1? Package 2? Package 3? Read it and write it down until you understand each one. > > If you could help, that would be much appreciated. Thanks so much. > I hope this helps you get started. Once you have some Python code written, and you still have problems, write back and ask for help with your code. Please include your platform, Python version, and the code you're having problems with in your post. Happy Programming! -- b h a a l u u at g m a i l dot c o m "You assist an evil system most effectively by obeying its orders and decrees. An evil system never deserves such allegiance. Allegiance to it means partaking of the evil. A good person will resist an evil system with his or her whole soul." [Mahatma Gandhi] From kent37 at tds.net Fri Mar 28 13:16:02 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 28 Mar 2008 08:16:02 -0400 Subject: [Tutor] parse emails as they come in In-Reply-To: References: Message-ID: <47ECE182.1040704@tds.net> linuxian iandsd wrote: > but sometimes two or more emails come in at once so the input file that > my python script has to parse is more than five lines !! my question is > how do i effeciently manage this from within my original script. I guess you need to put your processing into a loop? Kent From cfuller084 at thinkingplanet.net Fri Mar 28 14:08:20 2008 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Fri, 28 Mar 2008 08:08:20 -0500 Subject: [Tutor] parse emails as they come in In-Reply-To: References: Message-ID: <200803280808.20625.cfuller084@thinkingplanet.net> The email and mailbox modules might help you out. Multiple email messages will probably parse as an mbox format mailbox. http://docs.python.org/lib/module-email.html http://docs.python.org/lib/module-mailbox.html Cheers On Friday 28 March 2008 03:14, linuxian iandsd wrote: > good morning everybody ! > > I have scripted a small program to parse a 5 lines email message as it > comes in to my inbox (this is handled by procmail & here is a wonderful > intro to it : http://linuxfocus.org/English/November1997/article8.html) > > so every email is being parsed & information is extracted from it. > > but sometimes two or more emails come in at once so the input file that my > python script has to parse is more than five lines !! my question is how do > i effeciently manage this from within my original script. > > thanks From bryan.fodness at gmail.com Fri Mar 28 21:24:10 2008 From: bryan.fodness at gmail.com (Bryan Fodness) Date: Fri, 28 Mar 2008 16:24:10 -0400 Subject: [Tutor] Problem with logic while extracting data from binary file In-Reply-To: <47EC4E09.5030407@alum.rpi.edu> References: <47E94CFF.1020102@alum.rpi.edu> <47E9900C.6080200@alum.rpi.edu> <47EA9D7D.7070008@alum.rpi.edu> <47EC22F4.8030105@alum.rpi.edu> <47EC4E09.5030407@alum.rpi.edu> Message-ID: Thanks again, Still lost, even with watching the variables. I see that it kicks out of the loop, but don't understand what I have done to cause this. I'm sorry for repeated emails, but I have spent multiple days on this. I have added another while loop that I think should work, but I can't seem to keep it in the while loop. I feel like I am getting close. It seems like it gets everything at the first level , but not the way I expected. It seems to get the first value inside the first while loop, and then goes outside the loop to get the next three. I would have expected it to return the values as it goes through the first while loop (since they are at the same level), then when it sees the nested identifier, go into the second while loop and return values. Any insight would be wonderful. def parseSequence(data, start): group_num = data[start:start+2] element_num = data[start+2:start+4] vl_field = data[start+4:start+8] length = struct.unpack('hh', vl_field)[0] value = data[start+8:(start+8+length)] pos = start+8+length element = (group_num+element_num) if element == '\xfe\xff\x00\xe0': data = value while start < 536: #length: # 536 group_num = data[start:start+2] element_num = data[start+2:start+4] vl_field = data[start+4:start+8] length = struct.unpack('hh', vl_field)[0] value = data[start+8:(start+8+length)] start = start+8+length element = (group_num+element_num) if element == '\xfe\xff\x00\xe0': data = value while start < 112: #length: # 112, 112, 116, 116 group_num = data[start:start+2] element_num = data[start+2:start+4] vl_field = data[start+4:start+8] length = struct.unpack('hh', vl_field)[0] value = data[start+8:(start+8+length)] start = start+8+length element = (group_num+element_num) return element, start, value else: return element, start, value else: return element, pos, value -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080328/e298e103/attachment.htm From sierra_mtnview at sbcglobal.net Sat Mar 29 13:27:36 2008 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sat, 29 Mar 2008 05:27:36 -0700 Subject: [Tutor] Saving an Image in a Given Format Message-ID: <47EE35B8.6010304@sbcglobal.net> I'm pretty new to Python and libraries. I'm actually trying to modify some code someone else wrote. There are two ways images are saved. One is for the user to select a "Save as GIF" menu item, or save as tiff, or others. The other way is that the user wants a collected image from a camera saved every, say, 10 minutes. The "save" process is different for some reason. Here are the two code segments involved (NOTE my comments and questions below B.): A. Save every 10 minutes t = time.localtime(now_time) s = "a%4d%02d%02d_%02d%02d%02d.tif" % ( t.tm_year, t.tm_mon, t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec ) s = os.path.join("Exposures",s) <========== auto-exposures if not os.path.exists("Exposures"): os.mkdir("Exposures") self.current_image.save(s) <============ save image if self.trigger_mode: self.Trigger() self.CheckEvent() contrast this with where the user specifically wants the image he sees saved as a gif: B. From menu option def SaveGIF(self): if self.current_path: default_path = splitext(basename(self.current_path))[0] + ".gif" path = asksaveasfilename(defaultextension=".gif", title="Save as GIF", initialfile=default_path, filetypes=GIF_FILE_TYPES) else: path = asksaveasfilename(defaultextension=".gif", title="Save as GIF", filetypes=GIF_FILE_TYPES) if not path: return gif = self.current_image.convert("RGB") gif.save(path) <===========Save as gif. The programmer told me if I change the tif in A. to gif, jpg or whatever, it would work. Instead I get a file the of zero length when I use jpg. Can anyone explain why this wouldn't work? I see that current_image.convert is involved in one place and current_image.save in the first. What module owns these "current" methods? Hmmm, maybe I needed to use jpeg? -- Wayne Watson (Watson Adventures, Prop., Nevada City, CA) (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet "The only laws of matter are those which our minds must fabricate, and the only laws of mind are fabricated for it by matter." -- James Clerk Maxwell Web Page: From kveretennicov at gmail.com Sat Mar 29 23:12:52 2008 From: kveretennicov at gmail.com (Konstantin Veretennicov) Date: Sun, 30 Mar 2008 00:12:52 +0200 Subject: [Tutor] Python and xml In-Reply-To: <2323A6D37908A847A7C32F1E3662C80EB5E7FA@dc1ex01.air.org> References: <2323A6D37908A847A7C32F1E3662C80EB5E7FA@dc1ex01.air.org> Message-ID: <4660fe300803291512n5f5255e5v564f6bef2ac0f71d@mail.gmail.com> On Sat, Mar 29, 2008 at 3:57 PM, Doran, Harold wrote: > I am a python neophyte who has used python to parse through text files > using basic functions and no OOP experience. I have a need to process some > xml files and from what I am now reading python is the exact tool I need to > work through this issue. > > However, as I read online docs and peruse which books to buy, I am quickly > becoming overwhelmed with the topic and could use some guidance on how to > best tackle my task. > > You can start with this basic example (requires Python 2.5): spam.xml: Dinsdale (Face the Press) The Spanish Inquisition Deja vu The Buzz Aldrin Show Live From the Grill-O-Mat Snack Bar It's a Living The Attila the Hun Show Archaeology Today How to Recognize Different Parts of the Body Scott of the Antarctic How Not to Be Seen Spam Royal Episode 13 spam.py: from xml.etree.ElementTree import ElementTree as ET et = ET(file='spam.xml') for episode in et.findall('episode'): print episode.attrib['number'] + ':', '"' + episode.text + '"' Use standard csv module if you want to produce csv ouput ( http://docs.python.org/lib/module-csv.html). -- kv -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080330/d1142f55/attachment.htm From sierra_mtnview at sbcglobal.net Sun Mar 30 04:15:01 2008 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sat, 29 Mar 2008 19:15:01 -0700 Subject: [Tutor] Saving an Image in a Given Format In-Reply-To: <47EE35B8.6010304@sbcglobal.net> References: <47EE35B8.6010304@sbcglobal.net> Message-ID: <47EEF7A5.8010104@sbcglobal.net> I see that I misunderstood the syntax of Python for: current_image.convert current_image.save current_image is a "pointer" whose type is some class, so convert() and save() must be methods in that class. The question is what class/module? PIL? Wayne Watson wrote: > I'm pretty new to Python and libraries. I'm actually trying to modify > some code someone else wrote. There are two ways images are saved. One > is for the user to select a "Save as GIF" menu item, or save as tiff, or > others. The other way is that the user wants a collected image from a > camera saved every, say, 10 minutes. The "save" process is different for > some reason. Here are the two code segments involved (NOTE my comments > and questions below B.): > > A. Save every 10 minutes > t = time.localtime(now_time) > s = "a%4d%02d%02d_%02d%02d%02d.tif" % ( > t.tm_year, t.tm_mon, t.tm_mday, > t.tm_hour, t.tm_min, t.tm_sec ) > s = os.path.join("Exposures",s) <========== auto-exposures > if not os.path.exists("Exposures"): > os.mkdir("Exposures") > self.current_image.save(s) <============ save image > if self.trigger_mode: > self.Trigger() > self.CheckEvent() > > > contrast this with where the user specifically wants the image he sees > saved as a gif: > > B. From menu option > > def SaveGIF(self): > if self.current_path: > default_path = splitext(basename(self.current_path))[0] + > ".gif" > path = asksaveasfilename(defaultextension=".gif", > title="Save as GIF", > initialfile=default_path, > filetypes=GIF_FILE_TYPES) > else: > path = asksaveasfilename(defaultextension=".gif", > title="Save as GIF", > filetypes=GIF_FILE_TYPES) > if not path: > return > gif = self.current_image.convert("RGB") > gif.save(path) <===========Save as gif. > > The programmer told me if I change the tif in A. to gif, jpg or > whatever, it would work. Instead I get a file the of zero length when I > use jpg. Can anyone explain why this wouldn't work? I see that > current_image.convert is involved in one place and current_image.save in > the first. What module owns these "current" methods? > > Hmmm, maybe I needed to use jpeg? > > -- Wayne Watson (Watson Adventures, Prop., Nevada City, CA) (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet "The only laws of matter are those which our minds must fabricate, and the only laws of mind are fabricated for it by matter." -- James Clerk Maxwell Web Page: From rabidpoobear at gmail.com Sun Mar 30 04:47:28 2008 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sat, 29 Mar 2008 20:47:28 -0600 Subject: [Tutor] Saving an Image in a Given Format In-Reply-To: <47EEF7A5.8010104@sbcglobal.net> References: <47EE35B8.6010304@sbcglobal.net> <47EEF7A5.8010104@sbcglobal.net> Message-ID: On Sat, Mar 29, 2008 at 8:15 PM, Wayne Watson wrote: > I see that I misunderstood the syntax of Python for: > > current_image.convert > current_image.save > > current_image is a "pointer" whose type is some class, so convert() and > save() must be methods in that class. Yes, they are methods of a class. self.current_image is just a normal python variable that stores a reference to a class instance. You can call it a 'pointer' because it's probably similar to that internally, but it's easier just to think about it as a label for a specific calss instance. > The question is what class/module? > PIL? You need to give us the full code. There will be an import statement at the top, and you can figure out where current_image is created. These clues will lead you to the library that they're using. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080329/da8ec8d0/attachment.htm From pine508 at hotmail.com Sun Mar 30 05:23:08 2008 From: pine508 at hotmail.com (Che M) Date: Sat, 29 Mar 2008 23:23:08 -0400 Subject: [Tutor] Interactive plots... In-Reply-To: References: Message-ID: > I am thinking about writing a program which will involve, among other > things, displaying a plot of a series of numbers. The idea is that > you could click on the points and move them to change the numbers. > Reverse-plotting, I suppose. It need not be complex; the numbers > will all be zero or one, and it's only necessary to flip the bits, so > click-and-drag is seriously overkill. Really it would be better to > just double-click on a point to switch it from one value to the other. > > Can anyone point me in the right direction? I have written some > programs in python before, including TKinter, but this new project is > beyond the point that I know where to even start looking. :) > > In case you care, the application is in functional brain imaging; the > brain scans generate a certain number of time points (say 500) and > then the motion of the subject is also calculated. Standard practice > is to generate a "censor" file composed of zeros and ones, where zero > indicates that that time point had excessive motion and must be > disregarded. I want to display a graph of the motion over time, and > allow quick and easy interactive editing of the censor time series in > visual parallel to the motion graph. This would save a lot of time; > at present everyone does this in Excel, which being a horrible > Windows program can't be integrated into the predominantly UNIX-based > processing pipeline. And in any case, it requires manually typing > all the zeros, looking back and forth between the graph of motion and > the list of numbers. > > I have already written a program to algorithmically generate the > censor time series from the motion data, but it is absolutely > essential to be able to manually double-check and if necessary make > minor edits. I'd like to be able to keep that functionality in > Python rather than sending everyone back to Excel... if possible! > > Thanks very much for any help. > > -- > -dave- Without knowing more, it seems that this is going to be a lot of work, but if it will be used for years, probably worth it. For graphing: in the wxPython widget toolkit there is a PyPlot widget which does plotting, or you could use Matplotlib, a Python plotting library (with similarities to Matlab) with lots of functions. In either case you can catch mouse events on the plot and connect those events to changing the display of which parts of the motion graph are "censored" (might not be possible with PyPlot; definitely with Matplotlib). That way you could censor (or uncensor) sections of the trace right on the graph, and the censor time series would be updated from that. I'd also say about Excel ("being a horrible Windows program") that it is not horrible, unless you meant that all Windows-only programs were horrible by virtue of running on Windows? Excel is a good program, in my opinion. But if you want to keep it all under Linux and sort of all of a piece, I get that. _________________________________________________________________ How well do you know your celebrity gossip? http://originals.msn.com/thebigdebate?ocid=T002MSN03N0707A -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080329/f4ed1c7f/attachment.htm From kent37 at tds.net Sun Mar 30 14:57:32 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 30 Mar 2008 08:57:32 -0400 Subject: [Tutor] Saving an Image in a Given Format In-Reply-To: <47EEF7A5.8010104@sbcglobal.net> References: <47EE35B8.6010304@sbcglobal.net> <47EEF7A5.8010104@sbcglobal.net> Message-ID: <47EF8E3C.3010806@tds.net> Wayne Watson wrote: > I see that I misunderstood the syntax of Python for: > > current_image.convert > current_image.save > > current_image is a "pointer" whose type is some class, so convert() and > save() must be methods in that class. Yes. > The question is what class/module? > PIL? That is a likely candidate, especially if you know the program uses PIL. But it could be another image class, or a custom wrapper around PIL... You should look for the place where the images are created. Or in your code below you could put print self.current_image.__class__ before the save() statements and see what it tells you. It's curious that saveGIF() needs the convert() call. Maybe that is what you need in the save every 10 minutes call? What format is the original data? What is the format of the tiff files saved every 10 minutes? You have to do a bit of detective work to sort this out. Kent > > Wayne Watson wrote: >> I'm pretty new to Python and libraries. I'm actually trying to modify >> some code someone else wrote. There are two ways images are saved. One >> is for the user to select a "Save as GIF" menu item, or save as tiff, or >> others. The other way is that the user wants a collected image from a >> camera saved every, say, 10 minutes. The "save" process is different for >> some reason. Here are the two code segments involved (NOTE my comments >> and questions below B.): >> >> A. Save every 10 minutes >> t = time.localtime(now_time) >> s = "a%4d%02d%02d_%02d%02d%02d.tif" % ( >> t.tm_year, t.tm_mon, t.tm_mday, >> t.tm_hour, t.tm_min, t.tm_sec ) >> s = os.path.join("Exposures",s) <========== auto-exposures >> if not os.path.exists("Exposures"): >> os.mkdir("Exposures") >> self.current_image.save(s) <============ save image >> if self.trigger_mode: >> self.Trigger() >> self.CheckEvent() >> >> >> contrast this with where the user specifically wants the image he sees >> saved as a gif: >> >> B. From menu option >> >> def SaveGIF(self): >> if self.current_path: >> default_path = splitext(basename(self.current_path))[0] + >> ".gif" >> path = asksaveasfilename(defaultextension=".gif", >> title="Save as GIF", >> initialfile=default_path, >> filetypes=GIF_FILE_TYPES) >> else: >> path = asksaveasfilename(defaultextension=".gif", >> title="Save as GIF", >> filetypes=GIF_FILE_TYPES) >> if not path: >> return >> gif = self.current_image.convert("RGB") >> gif.save(path) <===========Save as gif. >> >> The programmer told me if I change the tif in A. to gif, jpg or >> whatever, it would work. Instead I get a file the of zero length when I >> use jpg. Can anyone explain why this wouldn't work? I see that >> current_image.convert is involved in one place and current_image.save in >> the first. What module owns these "current" methods? >> >> Hmmm, maybe I needed to use jpeg? >> >> > From eric at ericwalstad.com Mon Mar 31 17:37:10 2008 From: eric at ericwalstad.com (Eric Walstad) Date: Mon, 31 Mar 2008 08:37:10 -0700 Subject: [Tutor] Saving an Image in a Given Format In-Reply-To: <47EEF7A5.8010104@sbcglobal.net> References: <47EE35B8.6010304@sbcglobal.net> <47EEF7A5.8010104@sbcglobal.net> Message-ID: <47F10526.4040109@ericwalstad.com> Wayne Watson wrote: > current_image ... convert() and > save() must be methods in that class. The question is what class/module? > PIL? I don't know, but you could try the following from the python command line, which might give you some hints: dir(current_image) current_image.foobarfizzbang >>> import Image # PIL Image class >>> im = Image.open('/path/to/foo.jpg') >>> dir(im) # Gives you a list of the object's attribute names ['_Image__transformer', '__doc__', '__getattr__', '__init__', '__module__', '_copy', '_dump', '_expand', '_getexif', '_makeself', '_new', '_open', 'app', 'applist', 'bits', 'category', 'convert', 'copy', 'crop', 'decoderconfig', 'decodermaxblock', 'draft', 'filename', 'filter', 'format', 'format_description', 'fp', 'fromstring', 'getbands', 'getbbox', 'getcolors', 'getdata', 'getextrema', 'getim', 'getpalette', 'getpixel', 'getprojection', 'histogram', 'huffman_ac', 'huffman_dc', 'im', 'info', 'layer', 'layers', 'load', 'load_djpeg', 'load_end', 'load_prepare', 'mode', 'offset', 'palette', 'paste', 'point', 'putalpha', 'putdata', 'putpalette', 'putpixel', 'quantization', 'quantize', 'readonly', 'resize', 'rotate', 'save', 'seek', 'show', 'size', 'split', 'tell', 'thumbnail', 'tile', 'tobitmap', 'tostring', 'transform', 'transpose', 'verify'] The following error message tells me the object came from PIL.Image, a good hint. >>> im.just_throw_me_an_error Traceback (most recent call last): File "/home/ewalstad/var/tmp/", line 1, in File "/usr/lib/python2.5/site-packages/PIL/Image.py", line 493, in __getattr__ raise AttributeError(name) AttributeError: just_throw_me_an_error