From highprimate@howlermonkey.net Tue Jan 1 02:35:24 2002 From: highprimate@howlermonkey.net (Kirk Bailey) Date: Mon, 31 Dec 2001 21:35:24 -0500 Subject: [Tutor] It works Message-ID: <200201010235.g012ZRM13923@ns.howlermonkey.net> And thank you Sean for some good tips off list, and to Danny. First and second modules now work. Initialmenu: http://www.howlermonkey.net/cgi-bin/TLwebmgr.py - feel free to click and take a look. info/command form: http://www.howlermonkey.net/cgi-bin/TLwebform2.py (BUT DO NOT GO THERE DIRECTLY! IT DEPENDS ON INPUT FROM PAGE 1!!!) Visit the menu above (TLwebmgr.py), click a list name. This will bring up page 2, customized for THAT list. THE NEXT MODULE IS TLcommander.py AND IS NOT EVEN HALF BUILT YET. CLicking will only result in errors and confusion. But it's getting there. end In total confusion, Kirk D Bailey |----------------------------------------------------| | Consulting Agent Provecateur | | Webmaster, Howlermonkey Email services Co. | | Please visit us at http://www.howlermonkey.net/ | |----------------------------------------------------| From kev@sat.net Tue Jan 1 02:51:23 2002 From: kev@sat.net (Kevin McCormick) Date: Mon, 31 Dec 2001 20:51:23 -0600 Subject: [Tutor] exception classes References: <3C30B950.6040101@sat.net> <20011231222755.GC6385@localhost> Message-ID: <3C31242B.1010202@sat.net> dman wrote: > On Mon, Dec 31, 2001 at 01:15:28PM -0600, Kevin McCormick wrote: > | I am trying to figure out how to design an exception class > > What does your exception need to be able to do and what info does it > need to store? The following is a minimal example : > > # first define the class > class MyException( Exception ) : > pass > I have seen this where a block goes something like: try: except: raise MyException( 'error in some operation' ) For example: class MyException( Exception ): pass def f1(a, b, *var, **kw): print a, b, var, kw try: f1(1, 2, 34, 45, c=4, d=5, b=6) except: raise MyException('you made a boo-boo') Gives result: Traceback (most recent call last): File "", line 10, in ? __main__.MyException: you made a boo-boo Now, what do you do with it? I am writing a calendar type module of spreadsheet like functions, and I want to return -1 for calls made with bad arguments, but give some feedback, like -> error variable: x could not be processed, perhaps to a log file or something. Also, as in my example, the Syntax Error was assigning 6 to b, where 2 was in the b slot. How can information of this type be preserved? Thanks Kevin From highprimate@howlermonkey.net Tue Jan 1 03:03:25 2002 From: highprimate@howlermonkey.net (Kirk Bailey) Date: Mon, 31 Dec 2001 22:3:25 -0500 Subject: [Tutor] Security Message-ID: <200201010303.g0133UM14089@ns.howlermonkey.net> OK, now comes an intresting task. ACTUALLY Adding them to the list, or removing them. At this point there are security issues. Is this REALLY sistermaryjoe@ourladyofendlessblessing.org signing up for the 'evil-humor' list? Or someone looking to annoy sister mary Joe? We can send them a letter, and have it come back with a secret code. Something along these lines is a commonly used ploy. We can just sign them up at this point; it's been done. We already have unsubscribe information in the footer, so they can go to the site and unsub if they want to, but this means other people can annoy them with unwanted subs, and we really want to prevent this, would'nt you? We could do something else, but bless me if I know what that something else is! So I guess that we will do a simple email process here, and a random number generation, and send that to them in the subject, and let them reply to it. the subject would be in the form of: command listname randomnumber If they give us a good random number, the file maintainer puts their email address in that list. Bad address, bad listname, or bad random number and it barks. Comments or discussion? end In total confusion, Kirk D Bailey |----------------------------------------------------| | Consulting Agent Provecateur | | Webmaster, Howlermonkey Email services Co. | | Please visit us at http://www.howlermonkey.net/ | |----------------------------------------------------| From grimmtoothtoo@yahoo.com Tue Jan 1 04:24:53 2002 From: grimmtoothtoo@yahoo.com (Grimmtooth) Date: Mon, 31 Dec 2001 23:24:53 -0500 Subject: [Tutor] Security In-Reply-To: <200201010303.g0133UM14089@ns.howlermonkey.net> Message-ID: > We can send them a letter, and have it come back with a secret > code. Something along these lines is a commonly > used ploy. I think this is the best method, myself. First of all, the most used implementation of this method requires NO action on the part of the recipient if they do NOT want on the list -- it should time out after some interval. > We can just sign them up at this point; it's been done. Yeah, in the good old days. > We already have unsubscribe information in the footer, so they > can go to the site and unsub if they want to, > but this means other people can annoy them with unwanted subs, > and we really want to prevent this, would'nt > you? Absolutely. Make it opt-in. > We could do something else, but bless me if I know what that > something else is! How about require them to telnet to a secret server which address is encoded into a limrick included in the subscribe letter, enter a special pass phrase that is encoded in a BCD string? Nah, scratch that. > So I guess that we will do a simple email process here, and a > random number generation, and send that to them > in the subject, and let them reply to it. the subject would be in > the form of: > > command listname randomnumber > > If they give us a good random number, the file maintainer puts > their email address in that list. Bad address, > bad listname, or bad random number and it barks. A bit too easy to mess up. I suggest this: go ahead with the random number, if you want, but also add a checksum of the addresss and list name to that number, in some form or another. Keep a local database tying the number to the email address and list name. Require them to reply with the number in either the subject OR as the first line of the message (this allows for services like Yahoo that append stuff to any message). Require ONLY the number, you already have the address and list name. You aren't gaining much by allowing them to meet all three requirements in a complex system that could have any number of routing wierdness and/or multiple email addresses per person. Sure, it MIGHT be possible to spoof this, but the number of cases is so miniscule compared to the amount of work required by the end user as to make it counterproductive. Remember, you asked :-) _________________________________________________________ Do You Yahoo!? Get your free @yahoo.com address at http://mail.yahoo.com From dsh8290@rit.edu Tue Jan 1 06:07:07 2002 From: dsh8290@rit.edu (dman) Date: Tue, 1 Jan 2002 01:07:07 -0500 Subject: [Tutor] exception classes In-Reply-To: <3C31242B.1010202@sat.net> References: <3C30B950.6040101@sat.net> <20011231222755.GC6385@localhost> <3C31242B.1010202@sat.net> Message-ID: <20020101060707.GB8481@localhost> On Mon, Dec 31, 2001 at 08:51:23PM -0600, Kevin McCormick wrote: | dman wrote: | | >On Mon, Dec 31, 2001 at 01:15:28PM -0600, Kevin McCormick wrote: | >| I am trying to figure out how to design an exception class | > | >What does your exception need to be able to do and what info does it | >need to store? The following is a minimal example : | > | ># first define the class | >class MyException( Exception ) : | > pass | | I have seen this where a block goes something like: | | try: | | except: This line means to catch all exceptions, regardless of type, but don't assign that object to a name | raise MyException( 'error in some operation' ) then raise another exception. The new exception contains some data, which may (or, as in this case, may not) relate to the previous exception. | For example: | | class MyException( Exception ): | pass | | def f1(a, b, *var, **kw): | print a, b, var, kw | | try: | f1(1, 2, 34, 45, c=4, d=5, b=6) | except: | raise MyException('you made a boo-boo') | | Gives result: | Traceback (most recent call last): | File "", line 10, in ? | __main__.MyException: you made a boo-boo | | Now, what do you do with it? You have to catch it and do what you want with it. If you are making an application you need to determine what the proper response it -- it may be to stop prematurely or it may be to report it to the user and keep going. Typically when creating a library you raise exceptions to provide (error) information back to the client code (application) so that it can properly handle the situations. | I am writing a calendar type module of spreadsheet like functions, and I | want to return -1 for calls made with bad arguments, but give some | feedback, like -> error variable: x could not be processed, perhaps to a | log file or something. In a language like C that lacks exceptions, returning -1 to indicate failure is an acceptable practice. It is bad practice in python. In python (or java or c++) you should raise (throw) an exception if an error occures. I don't remember the python name, but java has IllegalArgumentException built-in that you can raise if the arguments are bad. | Also, as in my example, the Syntax Error was assigning 6 to b, where 2 | was in the b slot. How can information of this type be preserved? Catch that SyntaxError exception and extract the message data from it, than pack that data into the exception you subsequently raised. -D -- If any of you lacks wisdom, he should ask God, who gives generously to all without finding fault, and it will be given to him. But when he asks he must believe and not doubt, because he who doubts is like a wave of the sea, blown and tossed by the wind. James 1:5-6 From r.b.rigilink@chello.nl Tue Jan 1 10:53:26 2002 From: r.b.rigilink@chello.nl (Roeland Rengelink) Date: Tue, 01 Jan 2002 11:53:26 +0100 Subject: [Tutor] Code critique please (OOP strategy) References: Message-ID: <3C319526.983BEFD5@chello.nl> Hi Timothy, You have a working program and a feeling that it could be improved. This is what refactoring is all about. A great page giving a detailed example in Python (translated from the example in Java from the Refactoring book by M. Fowler) can be found at: http://www.hiper.com.br/python/refactor/ I'm sure you'll recognize several points from your own code. Hope this helps, Roeland Timothy Wilson wrote: > > Hi everyone, > > I've done an object-oriented version of the stock portfolio tracking > program I assigned to my students > (http://www.isd197.org/sibley/cs/icp/assignments/portfolio_html). I plan > to use this for comparison when we introduce OOP after the Winter Break. > > My version is available at http://www.qwerk.org/tim/ > > I'd like to get some feedback on the code. I've created two classes > here, Portfolio and Stock. I'm specifically interested in the way the > main() function interacts with the class methods. I've got a strange mix > of program logic stuck in a series of elif statements and in the class > methods themselves. Something doesn't seem right about it. > > Is there a way to create a Menu class that would help? > > -Tim > > -- > Tim Wilson | Visit Sibley online: | Check out: > Henry Sibley HS | http://www.isd197.org | http://www.zope.com > W. St. Paul, MN | | http://slashdot.org > wilson@visi.com | | http://linux.com > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- r.b.rigilink@chello.nl "Half of what I say is nonsense. Unfortunately I don't know which half" From moreno.rivilla@gmx.net Tue Jan 1 11:56:34 2002 From: moreno.rivilla@gmx.net (Francisco Moreno Rivilla) Date: Tue, 01 Jan 2002 12:56:34 +0100 Subject: [Tutor] Re: ERROR using "BuildApplication": Some modules could not be found In-Reply-To: Message-ID: A peaceful and happy NEW YEAR to all! > Since you're getting a memory error, my guess is you need to increase > the amount of memory in Finder that you've allocated to > BuildApplication. That's just a guess, though. > thnx a lot Dan, I did already so; first time the app crashed, but now it works (I had to increase the min. memory allocated too). Now I got a new ERROR: BuildApplication cant find some modules... the little script I try to compile is: ##### import W w = W.Window( (200, 100), "Hello MacPython!") def buttonCallback(): w.close() w.button = W.Button( (50, 30, 100, 30), "Good Bye!", buttonCallback) w.open() ##### the ERROR-MESSAGE is: Some modules could not be found; continue anyway? (SOCKS, W, msvcrt, rourl2path, terminos) ##### any idea? _____________________________________________ Francisco Barcelona Spain _____________________________________________ i-MAC G3/233 160MB RAM, OS 8.6 and PYTHON 2.2 From r.b.rigilink@chello.nl Tue Jan 1 12:52:36 2002 From: r.b.rigilink@chello.nl (Roeland Rengelink) Date: Tue, 01 Jan 2002 13:52:36 +0100 Subject: [Tutor] Code critique please (OOP strategy) References: Message-ID: <3C31B113.EEB8B38E@chello.nl> Timothy Wilson wrote: > > On Mon, 31 Dec 2001, Sean 'Shaleh' Perry wrote: [snip] > > I am also curious as to why the prices are * 100 every time. There is no > > comment in the code for this. > > All the prices are stored in cents. My understanding is that a lot of > software that works with financial data keeps track of everything in > cents and converts to dollars when necessary. This should help eliminate > rounding errors. > Be very carefull here, What you do is take a price expressed as 'xxxx.xx', convert it to float and multiply it by 100, expecting that the resulting floating point value (the price in cents), doesn't contain rounding errors. However, on my machine I find: >>> for i in '0123456789': ... for j in '0123456789': ... f, g = float('0.'+i+j)*100, float(i+j) ... if f != g: ... print f, g, repr(f), repr(g) ... 7.0 7.0 7.0000000000000009 7.0 14.0 14.0 14.000000000000002 14.0 28.0 28.0 28.000000000000004 28.0 29.0 29.0 28.999999999999996 29.0 55.0 55.0 55.000000000000007 55.0 56.0 56.0 56.000000000000007 56.0 57.0 57.0 56.999999999999993 57.0 58.0 58.0 57.999999999999993 58.0 where f is the value in dollars*100, and g is the value in cents, and the above snippet lists the cases for which these values are unequal (Tim Peters would also give a real explanation about the pitfalls of FP math, which I will not do for fear of making an ass of myself) However, I don't think you're solving the problem from financial software here. IIRC that problem is related to the financial rounding rules. Consider a VAT of 15% on a purchase of 2 items of 97 cents. The VAT on one of these items is 15 cents. So the VAT on the puchase should be 30 cents. Contrast this with the VAT on the purchase of one item of 1.94, which is 29 cents. Since the rounding rules work on the cents level, it is easier in financial software to express prices in cents. But, more importantly, financial software has to be very carefull not to take shortcuts like: price1*frac+price2*frac --> (price1+price2)*frac Hope this helps, Roeland -- r.b.rigilink@chello.nl "Half of what I say is nonsense. Unfortunately I don't know which half" From pythontutor@venix.com Tue Jan 1 15:13:12 2002 From: pythontutor@venix.com (Lloyd Kvam) Date: Tue, 01 Jan 2002 10:13:12 -0500 Subject: [Tutor] Code critique please (OOP strategy) References: <20011231130438.B922@speakeasy.net> Message-ID: <3C31D208.2080701@venix.com> Yet another python module I hadn't noticed, cmd. Suggestions: self.purchasePrice = int(purchasePrice*100) # Amount in cents (and elsewhere) Presumably you are trying to avoid rounding problems from floats. I did not trace everything through, but I think you will need to explicitly convert to integers to be safe. You want to avoid mixing user interface concerns into your data processing classes (Portfolio, Stock). You already did that by putting the UI into main. I believe modifying this suggestion to create a PortfolioCMD class that chooses or creates a portfolio for StockCmd. In general, your UI "knows" about the classes that do the work, but does not inherit from them. This way alternative interfaces (HTML, SOAP, etc.) can be provided without changing the underlying classes. Michael P. Reilly wrote: > On Mon, Dec 31, 2001 at 08:46:48AM -0600, Timothy Wilson wrote: > [rest snipped] > >>>you could make a menu class or function, but all that would do is move the >>>code out of main. >>> >>Here's an example: >> >>The main() function contains the following code to delete a stock: >> >>elif choice.upper() == 'D': >> ticker = raw_input("Delete which stock (type a ticker symbol): ") >> for stock in p.contents: >> if stock.ticker == ticker.upper(): >> p.delStock(stock) >> print "Removed %s" % stock.ticker >> >>The delStock method is: >> >>def delStock(self, stock): >> self.contents.remove(stock) >> self.modified = 1 >> >>Is is correct to ask for the ticker symbol in the 'elif' or should I do >>that in 'delStock'? My reason for doing it the way I did was to make the >>code as reusable as possible. That may or may not be a valid reason in >>this case. I'd appreciate feedback on this point. >> > > You might want to look at the cmd module; it's design is meant for > user keyboard input. > > import cmd > > class Portfolio(cmd.Cmd): > prompt = '(O)pen existing portfolio or (M)ake a new one? ' > > def __init__(self): > cmd.Cmd.__init__(self) > self.portfolio = None > > def do_M(self, args): > self.portfolio = Portfolio() > > def do_O(self, args): > file = raw_input("filename: ") > self.portfolio = Portfolio(file) > > class StockCmd(cmd.Cmd): > prompt = '(A)dd/(D)elete stocks, (S)ave file, (U)pdate, ' \ > '(R)eport, or (Q)uit? ' > > def __init__(self, portfolio): > cmd.Cmd.__init__(self) > self.portfolio = portfolio > > def do_A(self, args): > ticker = raw_input("Ticket symbol: ") > companyname = raw_input("Company name: ") > ... > p.addStock(s) > > def do_D(self, args): > > ... > > then you create new instances of these classes: > > cmd = PortfolioCmd() > cmd.onecmd() # only one prompt and return > if cmd.portfolio is not None: > StockCmd(cmd.portfolio).cmdloop() > > This makes things a bit more extensible and teaches your students to > reuse library classes. > > -Arcege > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From alan.gauld@bt.com Tue Jan 1 18:51:28 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Tue, 1 Jan 2002 18:51:28 -0000 Subject: [Tutor] overloaded methods Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C21F@mbtlipnt02.btlabs.bt.co.uk> > just to confirm. Overloading method names > (with parameters belonging to different types) > is not possible in python. Thats right. The parameter is a name which could refer to any object. > class Currency: > pass > class Dollar(Currency): > pass > class Euro(Currency): > pass > > class CalculateRupeeEquivalent: > def calculate(currency): > //type checking of curency here? > //i don't like it with lots of ifs and else. Neither do I, dictionary lookups are much nicer and faster. > class CalculateRupeeEquivalentForDollar(CalculateRupeeEquivalent): > def calculate(currency): > //return equivalent Still not reliable since you can't guarantee that currency is a dollar... Better(IMHO) to stick to the original plan and create conversion methods per currency. Then you can check the type by using the type itself as a key into a dictionary which points to the conversion functions, something like this: currencyType == type(currency) if convert.haskey(currencyType): convert[currencyType]() I suspect that only works in V2.2 If you prefer create a currencyType method in each currency class that returns a constant. (DOLLAR, EURO, RUPEE) = (1,2,3) class Dollar(Currency): # ... def currencyType(): return DOLLAR class RupeeConvertor: def dollarToRupee(self,currency): # do it here def euroToRupee(self, currency): # and here too def __init__(self): self.convertor = {DOLLAR:self.dollarToRupee, EURO:self.euroToRupee } def convert(self, currency): if self.convertor.haskey(currency.currencyType): return self.convertor[currency.currencyType](currency) Err, something like that anyway... OTOH surely most currency conversions involve a single conversion value(the exchange rate) so couldn't you just get the currencyType dictionary populated with the rates? Then only one convertion function is needed. Alan G From alan.gauld@bt.com Tue Jan 1 19:00:09 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Tue, 1 Jan 2002 19:00:09 -0000 Subject: [Tutor] need a little help Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C220@mbtlipnt02.btlabs.bt.co.uk> > had no succes. i know there is a way for the program to > cycle back to where > my user = input() statement is. i apreshiate your help and > time. thank you. Take a look at my web tutor under looping. In particular you want to look closely at the "while" loop. Alan g. Author of the 'Learning to Program' web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld@bt.com Tue Jan 1 19:06:15 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Tue, 1 Jan 2002 19:06:15 -0000 Subject: [Tutor] wxPython? (fwd) Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C221@mbtlipnt02.btlabs.bt.co.uk> > Let me forward this to the rest of Tutor. I hate saying this, but I > can't reproduce the wackiness. Its standard integer division - the kind thats going away post V2.2 > def divide(x,y): > return x/y > > for y in range(-10,10,1): > x=2 > try: > print divide(x,y), y 2/-10 all the way to 2/-3 gives a negative fraction which is rounded down to -1 2/-2 = -1 2/-1 = -2 2/0 = exception 2/1 = 2 2/2 = 1 2/3 to 2/10 gives a fraction which is rounded down to 0. > -1 -10 > -1 -9 > -1 -8 > -1 -7 > -1 -6 > -1 -5 > -1 -4 > -1 -3 > -1 -2 > -2 -1 > You are trying to divide by zero > 2 1 > 1 2 > 0 3 > 0 4 > 0 5 > 0 6 > 0 7 > 0 8 > 0 9 QED. Alan G. From alan.gauld@bt.com Tue Jan 1 19:17:34 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Tue, 1 Jan 2002 19:17:34 -0000 Subject: [Tutor] exception classes Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C222@mbtlipnt02.btlabs.bt.co.uk> > I have seen this where a block goes something like: > > try: > > except: > raise MyException( 'error in some operation' ) Thats kind of uncommon. Norally you raise exceptions in your code and somebody else catches them. So: class BadArg(Exception): pass def MyFunct(arg): if not arg: raise BadArg('fooey!') else: # do the deed Now in a program a client goes: try: MyFunc(None) except BadArg: print 'oops!' > Now, what do you do with it? Apart from Exception classes(as opposed to strings) I explain exception handling in my web tutor. Have a look and see if it helps. Alan g. Author of the 'Learning to Program' web site http://www.freenetpages.co.uk/hp/alan.gauld From dsh8290@rit.edu Tue Jan 1 19:39:27 2002 From: dsh8290@rit.edu (dman) Date: Tue, 1 Jan 2002 14:39:27 -0500 Subject: [Tutor] wxPython? (fwd) In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66C221@mbtlipnt02.btlabs.bt.co.uk> References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C221@mbtlipnt02.btlabs.bt.co.uk> Message-ID: <20020101193927.GA11389@localhost> On Tue, Jan 01, 2002 at 07:06:15PM +0000, alan.gauld@bt.com wrote: | > Let me forward this to the rest of Tutor. I hate saying this, but I | > can't reproduce the wackiness. | | Its standard integer division - the kind thats going away post V2.2 It's not going away, it is just changing to the "//" operator instead of an overloaded "/" operator. -D -- Microsoft is to operating systems & security .... .... what McDonald's is to gourmet cooking From glingl@aon.at Tue Jan 1 22:06:14 2002 From: glingl@aon.at (Gregor Lingl) Date: Tue, 1 Jan 2002 23:06:14 +0100 Subject: [Tutor] And now for something completely different Message-ID: <000f01c19310$87ba7c30$1664a8c0@mega> This is a multi-part message in MIME format. ------=_NextPart_000_000C_01C19318.E941B420 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable If you don't like to be distracted from Python: return else: In a book (incidentally in Michalewicz/Fogel : How To Solve It) i read the following remark: " ... this problem was selected from a math text for fifth graders in the United States" I'm not sure, what means fifth graders in US? For what type of school is the expression =20 "fifth graders" in use? What age have students, who are fifth graders? Sorry for the distraction=20 Gregor =20 =20 ------=_NextPart_000_000C_01C19318.E941B420 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
If you don't like to be distracted from = Python:
    return
else:
 
    In a book
    (incidentally in = Michalewicz/Fogel : How To=20 Solve It)
    i read the following = remark:
 
       " ... this = problem=20 was selected from a math text
       for fifth = graders in the=20 United States"
 
    I'm not sure, what means fifth = graders in=20 US?
    For what type of school is the=20 expression  
    "fifth graders" in  use?
    What age have students, who are = fifth=20 graders?
 
    Sorry for the distraction =
    Gregor
 
   
   
------=_NextPart_000_000C_01C19318.E941B420-- From dsh8290@rit.edu Tue Jan 1 22:20:42 2002 From: dsh8290@rit.edu (dman) Date: Tue, 1 Jan 2002 17:20:42 -0500 Subject: [Tutor] And now for something completely different In-Reply-To: <000f01c19310$87ba7c30$1664a8c0@mega> References: <000f01c19310$87ba7c30$1664a8c0@mega> Message-ID: <20020101222042.GA12217@localhost> On Tue, Jan 01, 2002 at 11:06:14PM +0100, Gregor Lingl wrote: | In a book | (incidentally in Michalewicz/Fogel : How To Solve It) | i read the following remark: | | " ... this problem was selected from a math text | for fifth graders in the United States" | | I'm not sure, what means fifth graders in US? | For what type of school is the expression | "fifth graders" in use? (public) school starts at age 4 or 5 (depending on birthday and parental decisions) with "preschool". Preschool is optional, but regardless, the following year children enter "kindergarten" (age 5 or 6). Following that is "first grade". The sequence progresses to "12th grade" (senior year of high school). In many areas fifth grade is the last grade of Elementary School (aka Primary School) and sixth grade begins "Middle School". In some areas 6th grade is part of Elementary school and Middle School starts at 7th grade. Regardless, High School is 9th through 12th grade (inclusive). | What age have students, who are fifth graders? (FYI) A more natural/common was to ask this question is "What age are fifth graders?". Fifth graders will usually be 10 or 11 years old. -D -- Pleasant words are a honeycomb, sweet to the soul and healing to the bones. Proverbs 16:24 From info007@netzero.net Tue Jan 1 13:14:50 2002 From: info007@netzero.net (info007) Date: Tue, 1 Jan 2002 05:14:50 -0800 Subject: [Tutor] what small microcontroller chips can I controll with small basic python codes. Message-ID: <000801c192c6$4ff7bbe0$030ad2d2@koni> This is a multi-part message in MIME format. ------=_NextPart_000_0005_01C19283.3D26AB40 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable what small microcontroller chips can I controll with small basic python = codes.=20 Example--- Atmel........ etc.......... And where can I find the work sheet and schematics to do this... Thank you !!!!! ------=_NextPart_000_0005_01C19283.3D26AB40 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable

what small microcontroller chips can I controll with = small basic=20 python codes.

Example--- Atmel........  = etc..........

And where can I find the work sheet and = schematics to=20 do this...

Thank you !!!!!

 

------=_NextPart_000_0005_01C19283.3D26AB40-- ---------------------------------------------------- Sign Up for NetZero Platinum Today Only $9.95 per month! http://my.netzero.net/s/signup?r=platinum&refcd=PT97 From highprimate@howlermonkey.net Wed Jan 2 01:00:27 2002 From: highprimate@howlermonkey.net (Kirk D Bailey) Date: Tue, 1 Jan 20:00:27 2002 -0500 Subject: [Tutor] usenet Message-ID: <200201020100.g0210RM18868@ns.howlermonkey.net> gang, is there any python software to receive usenet and port it to email messages? Got the TinyList menu sustem half done, looks up all lists and displays name and BREIF description; click the name and it displays the page with membership for for that list and the full description. TLpost.py is rock solid and is routinely handling list traffic. I have it with manual in a zip file for anyone who wants it; email me off list and I will send it to you. end In total confusion, Kirk D Bailey +----------------------------------------------------+ | Providing Excellent email service for free!! | | Webmaster, Howlermonkey Email services Co. | | highprimate@howlermonkey.net www.howlermonkey.net/ | +----------------------------------------------------+ ODD#1.8.01/kdb/sigme FreeLotto.com Free catalogs, magazines, and coupons for all types of cars, all types of people. From dsh8290@rit.edu Wed Jan 2 01:09:04 2002 From: dsh8290@rit.edu (dman) Date: Tue, 1 Jan 2002 20:09:04 -0500 Subject: [Tutor] what small microcontroller chips can I controll with small basic python codes. In-Reply-To: <000801c192c6$4ff7bbe0$030ad2d2@koni> References: <000801c192c6$4ff7bbe0$030ad2d2@koni> Message-ID: <20020102010904.GD12886@localhost> On Tue, Jan 01, 2002 at 05:14:50AM -0800, info007 wrote: | what small microcontroller chips can I controll with small basic | python codes. None. Typically working with hardware requires writing certain values at certain memory locations, but python is too high-level to let you do that. C is much better suited for device driving. | Example--- Atmel........ etc.......... | | And where can I find the work sheet and schematics to do this... Presumably your microcontroller supplier will have them, or they might be on the manufacturer's website. HTH, -D -- Stay away from a foolish man, for you will not find knowledge on his lips. Proverbs 14:7 From highprimate@howlermonkey.net Wed Jan 2 06:07:50 2002 From: highprimate@howlermonkey.net (Kirk D Bailey) Date: Wed, 2 Jan 01:07:50 2002 -0500 Subject: [Tutor] stringing me along Message-ID: <200201020607.g0267oM20096@ns.howlermonkey.net> ok, I want to turn a number into a string. I would have thought it would be in the STRING module, but shows what I know. Pickle sounded like it might work, but seems all wrong. I just want to take a nice fairly long number and turn it into a string, This seems so simply, maybe that's my problem. HHHHHHEEEEEEELLLLLLLLLLPPPPPP!!!!! Thankyou. end In total confusion, Kirk D Bailey +----------------------------------------------------+ | Providing Excellent email service for free!! | | Webmaster, Howlermonkey Email services Co. | | highprimate@howlermonkey.net www.howlermonkey.net/ | +----------------------------------------------------+ ODD#1.8.01/kdb/sigme It's a downpour of 100% free catalogs! Visit FreeShop for more free catalogs than ever before. From shalehperry@attbi.com Wed Jan 2 06:13:02 2002 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Tue, 01 Jan 2002 22:13:02 -0800 (PST) Subject: [Tutor] stringing me along In-Reply-To: <200201020607.g0267oM20096@ns.howlermonkey.net> Message-ID: On 02-Jan-2002 Kirk D Bailey wrote: > ok, I want to turn a number into a string. > > I would have thought it would be in the STRING module, but shows what > I know. > > Pickle sounded like it might work, but seems all wrong. I just want > to take a nice fairly long number and turn it into a string, This > seems so simply, maybe that's my problem. > what you want is not clear. Do you want: >>> cool_thing(100) >>> print cool_thing One Hundred or do you want >>> cool_thing(100) >>> print cool_thing '100' ?? From wheelege@hotmail.com Wed Jan 2 06:24:04 2002 From: wheelege@hotmail.com (Glen Wheeler) Date: Wed, 2 Jan 2002 17:24:04 +1100 Subject: [Tutor] stringing me along References: Message-ID: > > or do you want > > >>> cool_thing(100) > >>> print cool_thing > '100' > > ?? > Which is just str(x)... From highprimate@howlermonkey.net Wed Jan 2 07:41:52 2002 From: highprimate@howlermonkey.net (Kirk D Bailey) Date: Wed, 2 Jan 02:41:52 2002 -0500 Subject: [Tutor] file overwrite Message-ID: <200201020741.g027fqM20642@ns.howlermonkey.net> OK, I found 2 ways of turning a big number into a string, and It is a working program- except: It stores the entire subject line in the pending file. OK, but it OVERWRITES previous entries, so there is always only one, the lastone! Everything else works fine. Here is the program listing: ns# list TLcommander.py Listing of file TLcommander.py in directory:/www/www.howlermonkey.net/cgi-bin #!/usr/local/bin/python # import os, sys, string, cgi, random, time, smtplib # We will use some functions from these msg="" #initiate msg as a null string. domainname='howlermonkey.net' # this is our domain name, edit to suit pathtostuff='/www/www.howlermonkey.net/' # this is the web dir path2bin=pathtostuff+'cgi-bin/' # this is the web cgi-bin path2lists=path2bin+'lists/' # this is where the lists live CRLF="\r\n" # this is used a lot in the forming of headers later. #10 form = cgi.FieldStorage() nowNUMBER = time.time() # thie returns a 9 tuple numberic expression timestamp=hex(int(nowNUMBER)) # turn that time number into a string! command = form["command"].value # of the time this script runs. to_addr = form["email"].value listname = form["listname"].value print 'Content-Type: text/html'+CRLF # HTML is following print 'TLwebmanager form input results' print '

' #20 print if not (form.has_key("email") and form.has_key("listname") and form.has_key("command")): print "

Error

" print 'Something is wrong with how you filled out your form data; I am confused.' print 'POSSIBLY there was a transmission error, or a typo?' print "Please ensure that you fill in all 3 data fields.(one is a radio button)." print "Nonsense or fraudulent information will result in" print "your request being discarded by a robot, unread." print "click [BACK] and try again. Thank you." print '-Tiny.


' #30 sys.exit() else: print '


Submitted request information

' print '



' print "Declared EMail:", to_addr,'
' print "Requested LIST:", listname,'
' print "Issued Command:", command,'

' print '



' print "A email is being sent to you with these pieces of information in the Subject." #40 print "For most clients, simply replying to it is sufficent. The body is ignored," print "only the headers and subject line matter. The Letter itself explains what" print "is happening, and what to do. IN breif, reply to the message; just click" print "[REPLY] and then [SEND] (however your email client names them)." print "

" print "If you change your mind before doing so, simply delete the letter." print "


" print "Respectfully," print "-Tiny the list robot.


" #50 # keep that above line blank! subject = command + " " + listname + " " + timestamp f1=open('./lists/pending','w') # open the pending file f1.write(subject+"\n") # write the entire stubject string into it f1.close() # and close the file. TinyList will read and compare it. to_addr=form["email"].value from_addr='nobody@'+domainname # if the letter bounces, it returns to this address; msg=msg+"To: "+to_addr+CRLF # make sure it is not oing to waste your time with childish # # which will EAT bounces. OR, route to the postmaster. Your call. #60 Now build that outbound message. msg=msg + "Subject: " + subject + CRLF msg=msg + "X-Loop: postmaster@"+ domainname + CRLF msg=msg + "From: "+ from_addr + CRLF msg=msg + "Reply-To: TinyList@"+ domainname + CRLF+CRLF msg=msg + """ To whom it may concern; Someone (could be you) recently tried to """ + command + """ this email address to the email list:""" + listname + """. If you want this to happen, simply reply to this letter; do not alter the subject line. Don't worry about your EMail program sticking a "Re:" in front of the subject material, I know how to handle that. My training is FAIL-SAFE; if a message is invalid or makes no sense, I simply throw it away and do nothing. If you do NOT want this to happen, just delete this letter and it's over. I clean up dead pendings once a day when they are more than 7 days old, so a week from now all record of this will vanish. IF there is any problem, please feel free to contact the postmaster: mailto:postmaster@"""+domainname+"""?Subject=List%20Service%20Inquiry should work nicely. Respectfully, -Tiny the list robot. This is a service hosted at http://www."""+domainname+"""/ and we welcome your next visit. """ #83 # # and do smtp work in this block. # # # # server = smtplib.SMTP('localhost') # you MIGHT want to comment this out; Your Milage May Vary. server.sendmail(from_addr, to_addr, msg) # 400 send envlope and msg! server.quit() # then close the connection. #93 end In total confusion, Kirk D Bailey +----------------------------------------------------+ | Providing Excellent email service for free!! | | Webmaster, Howlermonkey Email services Co. | | highprimate@howlermonkey.net www.howlermonkey.net/ | +----------------------------------------------------+ ODD#1.8.01/kdb/sigme VOTE! VOTE EARLY, VOTE OFTEN! PUNCH THE CARD ALL THE WAY THROUGH! LEAN ON IT! HAMMER THE THING HOME! (A PUBLIC SERVICE ANNOUNCEMENT BROUGHT TO YOU IN SYMPATHY OF THE FLORIDA SUPERVISOR OF ELECTIONS OFFICE.) From glingl@aon.at Wed Jan 2 09:28:24 2002 From: glingl@aon.at (Gregor Lingl) Date: Wed, 2 Jan 2002 10:28:24 +0100 Subject: [Tutor] file overwrite References: <200201020741.g027fqM20642@ns.howlermonkey.net> Message-ID: <002d01c1936f$d409ceb0$1664a8c0@mega> In the Python-Tutorial we find at http://www.python.org/doc/current/tut/node9.html#SECTION00920000000000000000 0 7.2 Reading and Writing Files open() returns a file object , and is most commonly used with two arguments: "open(filename, mode)". >>> f=open('/tmp/workfile', 'w') >>> print f The first argument is a string containing the filename. The second argument is another string containing a few characters describing the way in which the file will be used. mode can be 'r' when the file will only be read, 'w' for only writing (an existing file with the same name will be erased), and 'a' opens the file for appending; any data written to the file is automatically added to the end. ... ------ So use: f1=open('./lists/pending','a') instead of f1=open('./lists/pending','w') if this was the line that bothered you. Gregor ... > # keep that above line blank! > subject = command + " " + listname + " " + timestamp > f1=open('./lists/pending','w') # open the pending file > f1.write(subject+"\n") # write the entire stubject string into it > f1.close() # and close the file. From dyoo@hkn.eecs.berkeley.edu Wed Jan 2 10:09:34 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 2 Jan 2002 02:09:34 -0800 (PST) Subject: [Tutor] usenet In-Reply-To: <200201020100.g0210RM18868@ns.howlermonkey.net> Message-ID: On Tue, 1 Jan 2002, Kirk D Bailey wrote: > gang, is there any python software to receive usenet and port it to > email messages? That's "NNTP" stuff --- I've never handled newsgroups in Python myself, so I'd have to look at the documentation at: http://www.python.org/doc/lib/module-nntplib.html a bit before feeling very comfortable about it. There are some examples in the documentation, so take a look at that first. If you have questions on it, please feel free to ask here. But it's great to hear that your project's beginning to mature! Congrats! From grimmtoothtoo@yahoo.com Wed Jan 2 13:45:47 2002 From: grimmtoothtoo@yahoo.com (Grimmtooth) Date: Wed, 2 Jan 2002 08:45:47 -0500 Subject: [Tutor] stringing me along In-Reply-To: <200201020607.g0267oM20096@ns.howlermonkey.net> Message-ID: > ok, I want to turn a number into a string. a = some_number str = "%d" % a :-) _________________________________________________________ Do You Yahoo!? Get your free @yahoo.com address at http://mail.yahoo.com From mgoodfellow@usa.net Wed Jan 2 17:11:39 2002 From: mgoodfellow@usa.net (Michael Goodfellow) Date: 2 Jan 2002 12:11:39 EST Subject: [Tutor] is this a bug? Message-ID: <20020102171139.26360.qmail@cpdvg100.netaddress.usa.net> While just working through some list syntax eaxamples, I typed this: >>> a =3D [66.6, 333, 333, 1, 1234.5] >>> a # then hit enter key # It returned this: [66.599999999999994, 333, 333, 1, 1234.5] Any comments? Thanks, Michael ____________________________________________________________________ Get free e-mail and a permanent address at http://www.amexmail.com/?A=3D1= From shalehperry@attbi.com Wed Jan 2 17:17:19 2002 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Wed, 02 Jan 2002 09:17:19 -0800 (PST) Subject: [Tutor] is this a bug? In-Reply-To: <20020102171139.26360.qmail@cpdvg100.netaddress.usa.net> Message-ID: On 02-Jan-2002 Michael Goodfellow wrote: > While just working through some list syntax eaxamples, I typed this: > >>>> a = [66.6, 333, 333, 1, 1234.5] >>>> a # then hit enter key > ># It returned this: > > [66.599999999999994, 333, 333, 1, 1234.5] > > Any comments? > .6 is not a perfect decimal. Which is why you get the number above. Think about it -- 2/3 is a repeating decimal. From scarblac@pino.selwerd.nl Wed Jan 2 17:25:07 2002 From: scarblac@pino.selwerd.nl (Remco Gerlich) Date: Wed, 2 Jan 2002 18:25:07 +0100 Subject: [Tutor] is this a bug? In-Reply-To: <20020102171139.26360.qmail@cpdvg100.netaddress.usa.net>; from mgoodfellow@usa.net on Wed, Jan 02, 2002 at 12:11:39PM -0500 References: <20020102171139.26360.qmail@cpdvg100.netaddress.usa.net> Message-ID: <20020102182507.A15282@pino.selwerd.nl> On 0, Michael Goodfellow wrote: > While just working through some list syntax eaxamples, I typed this: > > >>> a = [66.6, 333, 333, 1, 1234.5] > >>> a # then hit enter key > > # It returned this: > > [66.599999999999994, 333, 333, 1, 1234.5] > > Any comments? The problem is that, when converted to binary, 66.6 is repeating. There is no way to represent it exactly in a finite amount of binary digits. This is not a Python problem but a symptom of the way computers do floating point math (some other languages may not *show* this, but they have it too). The str() of a number has an abbreviated form, the repr() shows the Truth. Compare >>> str(66.6) 66.6 >>> repr(66.6) 66.599999999999994 -- Remco Gerlich From glingl@aon.at Wed Jan 2 17:41:33 2002 From: glingl@aon.at (Gregor Lingl) Date: Wed, 2 Jan 2002 18:41:33 +0100 Subject: [Tutor] is this a bug? References: Message-ID: <004b01c193b4$b8371ae0$1664a8c0@mega> > >>>> a = [66.6, 333, 333, 1, 1234.5] > >>>> a # then hit enter key > > > ># It returned this: > > > > [66.599999999999994, 333, 333, 1, 1234.5] > > > > Any comments? > > > > .6 is not a perfect decimal. Which is why you get the number above. Think > about it -- 2/3 is a repeating decimal. > Perfect in the sense you *need* are only (negative) powers of 2 (and integer multiples of them): >>> 0.5 0.5 >>> 0.25 0.25 >>> 0.125 0.125 >>> 0.0625 0.0625 >>> 0.0625 / 2 0.03125 >>> 0.03125 / 2 0.015625 >>> _ / 2 0.0078125 >>> _ / 2 0.00390625 >>> 0.03125 * 7 0.21875 but: >>> 0.0624 0.062399999999999997 >>> 0.0624 * 7 0.43679999999999997 >>> ond so on ... I think this depends not on the decimal beeing repeating like 2/3 or not (like 0.6 = 3/5). Gregor Gregor From glingl@aon.at Wed Jan 2 17:49:54 2002 From: glingl@aon.at (Gregor Lingl) Date: Wed, 2 Jan 2002 18:49:54 +0100 Subject: [Tutor] is this a bug? References: <20020102171139.26360.qmail@cpdvg100.netaddress.usa.net> <20020102182507.A15282@pino.selwerd.nl> Message-ID: <006c01c193b5$e34e55d0$1664a8c0@mega> I understand; Remco braught it to the point: > The problem is that, when converted to binary, 66.6 is repeating. There is > no way to represent it exactly in a finite amount of binary digits. > It depends on the number beeing a repeating binary, not a repeating decimal Gregor From dyoo@hkn.eecs.berkeley.edu Wed Jan 2 20:17:04 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 2 Jan 2002 12:17:04 -0800 (PST) Subject: [Tutor] is this a bug? [Research papers on floating point] In-Reply-To: <006c01c193b5$e34e55d0$1664a8c0@mega> Message-ID: On Wed, 2 Jan 2002, Gregor Lingl wrote: > > I understand; Remco braught it to the point: > > > The problem is that, when converted to binary, 66.6 is repeating. There is > > no way to represent it exactly in a finite amount of binary digits. > > > > It depends on the number beeing a repeating binary, not a repeating decimal Hmmmm! I did a quick search on Google, and found an interesting paper on this topic: How to Read Floating Point Numbers Accurately: http://citeseer.nj.nec.com/william90how.html The math does seem a bit intimidating at first; I'd have to really study it to understand it. Still, perhaps it might interest someone on Tutor who's interested in floating-point representation issues. The rest of the web site: http://citeseer.nj.nec.com/directory.html looks incredibly cool for anyone with a appetite for CS research papers; this site appear to archive lots of good papers on computer science! From vip333d@yahoo.com Wed Jan 2 20:29:50 2002 From: vip333d@yahoo.com (vip333d@yahoo.com) Date: Wed, 2 Jan 2002 12:29:50 -0800 (PST) Subject: [Tutor] 2 quick questions... Message-ID: <20020102202950.25792.qmail@web12305.mail.yahoo.com> Dear Tutor, I want to make a somewhat simple program, that finds for me complex numbers, and does it by some algorithm that says: if N==2**(k-1)*(2**k-1) [NOT: N==2**(k-1)*(2**(k-1))] while 2**k-1 is a Number wich divides only with 1 and itself. I have got over the problem of finding numbers that divide only by themself and 1, but I have 2 problems: 1) to say that k can be any number, I tried saying k = range(x,y), but it didn't work. How can I? 2) I have all the numbers wich devide by 1 and themselves on a list. How can I see if the phrase: 2**k-1 is in the list? please don't do all the work for me, I just wanna practice. complete newbie __________________________________________________ Do You Yahoo!? Send your FREE holiday greetings online! http://greetings.yahoo.com From shalehperry@attbi.com Wed Jan 2 20:47:18 2002 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Wed, 02 Jan 2002 12:47:18 -0800 (PST) Subject: [Tutor] 2 quick questions... In-Reply-To: <20020102202950.25792.qmail@web12305.mail.yahoo.com> Message-ID: On 02-Jan-2002 vip333d@yahoo.com wrote: > Dear Tutor, > I want to make a somewhat simple program, that finds > for me complex numbers, and does it by some algorithm > that says: > if N==2**(k-1)*(2**k-1) > [NOT: N==2**(k-1)*(2**(k-1))] > while 2**k-1 is a Number wich divides only with 1 and > itself. > I have got over the problem of finding numbers that > divide only by themself and 1, but I have 2 problems: > 1) to say that k can be any number, I tried saying k = > range(x,y), but it didn't work. How can I? > 2) I have all the numbers wich devide by 1 and > themselves on a list. How can I see if the phrase: > 2**k-1 is in the list? > > please don't do all the work for me, I just wanna > practice. > Use parens to be more clear in your math. (2**k)-1 or 2**(k-1) for instance. l = [1,2,3,4] 3 in l 1 the 'in' operator tells you if an item is in a sequence. 'a' in 'Sean' 1 From dyoo@hkn.eecs.berkeley.edu Wed Jan 2 23:34:50 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 2 Jan 2002 15:34:50 -0800 (PST) Subject: [Tutor] 2 quick questions... [declarative/imperative programming] In-Reply-To: <20020102202950.25792.qmail@web12305.mail.yahoo.com> Message-ID: On Wed, 2 Jan 2002 vip333d@yahoo.com wrote: > I want to make a somewhat simple program, that finds for me complex > numbers, and does it by some algorithm that says: > > if N==2**(k-1)*(2**k-1) > [NOT: N==2**(k-1)*(2**(k-1))] > while 2**k-1 is a Number wich divides only with 1 and > itself. Python is an "imperative" language, which means that programming it in involves telling Python _how_ to do something, step by step. This may different from the math definitions that you may be familiar with. In math, one can declare that "k can be any number in the range(x, y)". This is "declarative" because the statement doesn't say exactly how to go about finding k. In contrast, imperative programming tells Python exactly how to find things. Here's an example of an declarative statement that might clarify this distinction between "declarative" versus "imperative" programming: "A prime number 'n' has no factors except for 1 and itself." How do we find out if a number 'n' is prime? In imperative form, we need to tell Python to actually search through the possibilities: ### def isPrime(n): """Returns 1 if n is prime, and 0 otherwise.""" for i in range(2, n): if n % i == 0: return 0 return 1 ### which translates to the following idea: "Let's go through all the numbers from 0 to n. If any one of these numbers evenly divides n, then n must not be prime! Otherwise, if we exhaust the possibilities, n must be prime." The idea is the same, but expressed in such a way that we can trace the calculation. This is not to say that it's impossible to translate: "A prime number 'n' has no factors except for 1 and itself." in Python: it just takes more work and a willingness to explain how to get the factors of a number: ### def getFactors(n): """Returns the factors of n, in ascending order.""" factors = [1] for i in range(2, n): if n % i == 0: factors.append(i) factors.append(n) return factors def isPrime(n): """Returns 1 if the only factors of n are 1 and n, 0 otherwise.""" return getFactors(n) == [1, n] ### And this definition of isPrime() works too. Note that getFactors() itself needs to explain, step by step, how to get the factors of a number. Imperative programming can be a little weird at first, so please feel free to ask questions. From dsh8290@rit.edu Thu Jan 3 00:28:15 2002 From: dsh8290@rit.edu (dman) Date: Wed, 2 Jan 2002 19:28:15 -0500 Subject: [Tutor] 2 quick questions... [declarative/imperative programming] In-Reply-To: References: <20020102202950.25792.qmail@web12305.mail.yahoo.com> Message-ID: <20020103002815.GA22659@localhost> On Wed, Jan 02, 2002 at 03:34:50PM -0800, Danny Yoo wrote: ... | How do we find out if a number 'n' is prime? In imperative form, we need | to tell Python to actually search through the possibilities: | | ### | def isPrime(n): | """Returns 1 if n is prime, and 0 otherwise.""" | for i in range(2, n): ^ If the number is prime, this loop runs twice as long as it needs to. for i in range(2, int((n/2)+1) ): | if n % i == 0: | return 0 | return 1 | ### | ### | def getFactors(n): | """Returns the factors of n, in ascending order.""" | factors = [1] | for i in range(2, n): | if n % i == 0: | factors.append(i) | factors.append(n) | return factors You can get fancier with this and add a cache if you want. The advantage of this extra complexity comes if you use the function frequently for the same numbers. In that case it reduces the number of computations that need to be performed. The other tradeoff is increased memory usage. primes = {} def isPrime( n ) : # we already did the calculation once, don't do it again if n in primes : # if using python < 2.2, then use has_key() instead return 1 elif getFactors(n) == [1, n] : primes[ n ] = None # store it in the cache return 1 else : return 0 -D -- Thy Word is a lamp unto my feet and a light unto my path. Psalms 119:105 From highprimate@howlermonkey.net Thu Jan 3 04:39:19 2002 From: highprimate@howlermonkey.net (Kirk D Bailey) Date: Wed, 2 Jan 23:39:19 2002 -0500 Subject: [Tutor] TL Message-ID: <200201030439.g034dJM25997@ns.howlermonkey.net> ok, TinyList is almost done. I got the module done that handles accepting the command and sending out the confo letter, and placing the 'magic cookie' in the pending file. ALl I have to do now is reinvent the wheel and raise the dead and it will be finished. Aclually, all that is left is to build the script that receives replys, rips out the from and suject fields, compares the subject to the entire pending file, and if a match is made, delete that one from the pending file and add them to the list's membvership- and let them know we did just that. This also will handle deleting users. Anyone who wants to look at the pages that are already done, just click this for the first link: http://www.howlermonkey.net/cgi-bin/TLwebmgr.py All python, all the time. I *LOVE* this language! end In total confusion, Kirk D Bailey +----------------------------------------------------+ | Providing Excellent email service for free!! | | Webmaster, Howlermonkey Email services Co. | | highprimate@howlermonkey.net www.howlermonkey.net/ | +----------------------------------------------------+ ODD#1.8.01/kdb/sigme Winfire (FreeDSL)
Banner 10000066banner From virketis@fas.harvard.edu Thu Jan 3 12:39:02 2002 From: virketis@fas.harvard.edu (Pijus Virketis) Date: Thu, 3 Jan 2002 14:39:02 +0200 Subject: [Tutor] fish or fowl? Message-ID: <023e01c19453$d98fc940$090e3bd4@virketis2> This is a multi-part message in MIME format. ------=_NextPart_000_023B_01C19464.6364DEC0 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Dear all,=20 here is a little thing I have been wondering for a while. In Python, I = can say something like this: >>> if raw_input() =3D=3D "f": print "foo" I get a prompt, and upon entering "f", foo is printed. Very nice, very = convenient. Now, here's the question: how does the raw_input() call = actually get evaluated? Is there a variable assignment going on in the = background? As if I had typed: >>> input_string =3D raw_input() >>> if input_string =3D=3D "f": print "foo" Or is there some other behaviour? Can I retrieve the value afterwards? I = guess I am just curious what happens under the hood here.=20 Cheers,=20 Pijus ------=_NextPart_000_023B_01C19464.6364DEC0 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable

Dear all,
 
here is a little thing I have been = wondering for a=20 while. In Python, I can say something like this:
 
>>> if raw_input() =3D=3D "f": = print=20 "foo"
 
I get a prompt, and upon entering "f", = foo is=20 printed. Very nice, very convenient. Now, here's the question: how does = the=20 raw_input() call actually get evaluated? Is there a variable assignment = going on=20 in the background? As if I had typed:
 
>>> input_string =3D=20 raw_input()
>>> if input_string = =3D=3D "f": print=20 "foo"
 
Or is there some other behaviour? Can I = retrieve=20 the value afterwards? I guess I am just curious what happens under = the hood=20 here.
 
Cheers,
 
Pijus
------=_NextPart_000_023B_01C19464.6364DEC0-- From scarblac@pino.selwerd.nl Thu Jan 3 12:57:56 2002 From: scarblac@pino.selwerd.nl (Remco Gerlich) Date: Thu, 3 Jan 2002 13:57:56 +0100 Subject: [Tutor] fish or fowl? In-Reply-To: <023e01c19453$d98fc940$090e3bd4@virketis2>; from virketis@fas.harvard.edu on Thu, Jan 03, 2002 at 02:39:02PM +0200 References: <023e01c19453$d98fc940$090e3bd4@virketis2> Message-ID: <20020103135756.A16902@pino.selwerd.nl> On 0, Pijus Virketis wrote: > Dear all, > > here is a little thing I have been wondering for a while. In Python, I can say something like this: > > >>> if raw_input() == "f": print "foo" > > I get a prompt, and upon entering "f", foo is printed. Very nice, very > convenient. Now, here's the question: how does the raw_input() call actually > get evaluated? Is there a variable assignment going on in the background? As > if I had typed: > > > >>> input_string = raw_input() > >>> if input_string == "f": print "foo" > > Or is there some other behaviour? Can I retrieve the value afterwards? I > guess I am just curious what happens under the hood here. If you want to know, you can disassemble code objects. Put it in a function: def f(): if raw_input() == "f": print "foo" And then: >>> import dis >>> dis.disassemble(f.func_code) 0 SET_LINENO 1 3 SET_LINENO 2 6 LOAD_GLOBAL 0 (raw_input) 9 CALL_FUNCTION 0 12 LOAD_CONST 1 ('f') 15 COMPARE_OP 2 (==) 18 JUMP_IF_FALSE 12 (to 33) 21 POP_TOP 22 SET_LINENO 2 25 LOAD_CONST 2 ('foo') 28 PRINT_ITEM 29 PRINT_NEWLINE 30 JUMP_FORWARD 1 (to 34) >> 33 POP_TOP >> 34 LOAD_CONST 0 (None) 37 RETURN_VALUE I don't know much about this either, but it's something like this: - Set some line number info at the start of a function, for debugging - Load a global 'raw_input' into the interpreter's memory spot 0 - Call the function in memory spot 0 - Load the constant 'f' into memory spot 1 - Compare the two - If false, then goto the end of the block - Else, load the constant 'foo' into memory spot 2 - Print it - Print a newline - Jump to the end - Load None into memory spot 0 - Return that (all functions return 0 if there was no explicit return statement) I don't know what the 'pop top' lines are for, probably restore some memory state to the way it was before. No, you can't get to those memory spots from inside Python, afaik, although you could construct a block of marshalled function code, de-marshall it, transplant it into a function. Let the code put one of those values in a variable. This is wizardry that is above my level though :-). In Python, all you need to know is that 'raw_input() == "f"' is an expression that is evaluated, first the left half ('raw_input()') is evaluated by running the function, then the right half is evaluated ('"f"', happens to be a constant so no further evaluation needed). Then they're compared and an action is taken based on the whole result. Or, in short, it just does what it seems to do, and you don't have to care about the rest :) -- Remco Gerlich From James.Alexander.McCarney@M3iSystems.com Thu Jan 3 15:47:19 2002 From: James.Alexander.McCarney@M3iSystems.com (McCarney, James Alexander) Date: Thu, 3 Jan 2002 10:47:19 -0500 Subject: [Tutor] practical python sites/scripts Message-ID: <23FD7B1A77E8D211BCB900001D108C02018B28D8@camelot> This message is in MIME format. Since your mail reader does not understand this format, some or all of this message may not be legible. ------_=_NextPart_001_01C1946D.ED8B8758 Content-Type: text/plain; charset="iso-8859-1" I am quite interested in knowing of any practical Python sites you like. Sure I could 'google' it, but I would probably get lots of hits. The obvious one of course is www.python.org , but I am more interested in learning what people such as yourselves actually use Python for and the sites you like to browse. I would appreciate any constructive feedback you could provide. Thank you. James Alexander McCarney, Technical Writer M3i Systems Inc., 1111 Saint-Charles Avenue West 11th Floor, East Tower, Longueuil, Quebec, J4K 5G4 Canada Telephone: (450) 928-3386 x2262 Fax: (450) 442-5076 http://www.m3isystems.com ------_=_NextPart_001_01C1946D.ED8B8758 Content-Type: text/html; charset="iso-8859-1"
I am quite interested in knowing of any practical Python sites you like. Sure I could 'google' it,
but I would probably get lots of hits. The obvious one of course is www.python.org, but I am more interested in learning what people such as yourselves actually use Python for and the sites you like to browse.
 
I would appreciate any constructive feedback you could provide. Thank you.

 

James Alexander McCarney, Technical Writer
M3i Systems Inc., 1111 Saint-Charles Avenue West
11th Floor, East Tower, Longueuil, Quebec, J4K 5G4
Canada

Telephone: (450) 928-3386 x2262
Fax: (450) 442-5076

http://www.m3isystems.com

 
------_=_NextPart_001_01C1946D.ED8B8758-- From shalehperry@attbi.com Thu Jan 3 16:19:21 2002 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Thu, 03 Jan 2002 08:19:21 -0800 (PST) Subject: [Tutor] fish or fowl? In-Reply-To: <023e01c19453$d98fc940$090e3bd4@virketis2> Message-ID: > > I get a prompt, and upon entering "f", foo is printed. Very nice, very > convenient. Now, here's the question: how does the raw_input() call actually > get evaluated? Is there a variable assignment going on in the background? As > if I had typed: > >>>> input_string = raw_input() >>>> if input_string == "f": print "foo" > > Or is there some other behaviour? Can I retrieve the value afterwards? I > guess I am just curious what happens under the hood here. > python separate expressions from statements. In some other languages (C, perl) you can do: if (input = raw_input()) == "f": print "foo" handle_input(input) in python assignment is not valid in a test condition. So, another way to approach this (and you see it in other places in python): input = raw_input() if input == "f": print "foo" handle_input(input) Which you may recognize as being similar to the read a line from a file idiom that was common before the 2.x series: line = f.readline() if line: parse_line(line) and also: while 1: line = f.readline() if not line: break parse_line(line) which confused some new coders who were expecting: while (line = f.readline()): parse_line(line) Hope this helps. From toodles@yifan.net Thu Jan 3 16:24:22 2002 From: toodles@yifan.net (Andy W) Date: Fri, 4 Jan 2002 00:24:22 +0800 Subject: [Tutor] practical python sites/scripts References: <23FD7B1A77E8D211BCB900001D108C02018B28D8@camelot> Message-ID: <000901c19473$1b8f4a90$0300a8c0@sun> This is a multi-part message in MIME format. ------=_NextPart_000_0006_01C194B6.28286820 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Hiya, Useless Python is a rather good site, it holds programs written mainly = by us on the tutor list. It also has links to other Python pages, = tutorials and such things. http://www.lowerstandard.com/python/ The Vaults of Parnassus is also good. It has a large amount of programs. http://www.vex.net/parnassus/ Other than that... there's always http://www.pygame.org/ *grin* Andrew ----- Original Message -----=20 From: McCarney, James Alexander=20 To: 'tutor@python.org'=20 Sent: Thursday, January 03, 2002 11:47 PM Subject: [Tutor] practical python sites/scripts I am quite interested in knowing of any practical Python sites you = like. Sure I could 'google' it, but I would probably get lots of hits. The obvious one of course is = www.python.org, but I am more interested in learning what people such as = yourselves actually use Python for and the sites you like to browse. I would appreciate any constructive feedback you could provide. Thank = you. James Alexander McCarney, Technical Writer M3i Systems Inc., 1111 Saint-Charles Avenue West=20 11th Floor, East Tower, Longueuil, Quebec, J4K 5G4=20 Canada=20 Telephone: (450) 928-3386 x2262 Fax: (450) 442-5076 http://www.m3isystems.com ------=_NextPart_000_0006_01C194B6.28286820 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
Hiya,
 
Useless Python is a rather good site, = it holds=20 programs written mainly by us on the tutor list. It also has links to = other=20 Python pages, tutorials and such things.
http://www.lowerstandard.co= m/python/
 
The Vaults of Parnassus is also good. = It has a=20 large amount of programs.
http://www.vex.net/parnassus/<= /FONT>
 
Other than that... there's always http://www.pygame.org/
*grin*
 
Andrew
----- Original Message -----
From:=20 McCarney, = James=20 Alexander
Sent: Thursday, January 03, = 2002 11:47=20 PM
Subject: [Tutor] practical = python=20 sites/scripts

I am = quite=20 interested in knowing of any practical Python sites you like. Sure I = could=20 'google' it,
but = I would=20 probably get lots of hits. The obvious one of course is www.python.org, but I am more = interested in=20 learning what people such as yourselves actually use Python for and = the sites=20 you like to browse.
 
I = would appreciate=20 any constructive feedback you could provide. Thank = you.

 

James = Alexander=20 McCarney, Technical Writer
M3i Systems = Inc., 1111=20 Saint-Charles Avenue West
11th Floor, East = Tower,=20 Longueuil, Quebec, J4K 5G4
Canada =

Telephone: (450) 928-3386 = x2262
Fax:=20 (450) 442-5076

http://www.m3isystems.com

 
------=_NextPart_000_0006_01C194B6.28286820-- From toodles@yifan.net Thu Jan 3 17:04:19 2002 From: toodles@yifan.net (Andy W) Date: Fri, 4 Jan 2002 01:04:19 +0800 Subject: [Tutor] practical python sites/scripts References: <23FD7B1A77E8D211BCB900001D108C02018B28D9@camelot> Message-ID: <001c01c19478$b07134c0$0300a8c0@sun> > Thanx Andy! What do u use Py for? Hmm... well I'm only a recreational programmer at the moment, so whatever takes my fancy. Sometimes I want to do a task like manage my files on my computer, so I'll make a program in Python to do it. The last program I made was to create an HTML list using a template and a text file. Before that I made a program to walk a directory and find the MP3 files within, and extract the ID3 tags from them. I've made a couple really bad games *grin*, one which is a MUD base, which is on Useless Python. I also find Python useful for doing mathematical tasks, partially due to the interactive interpreter. Andy From DavidCraig@pia.ca.gov Thu Jan 3 18:22:17 2002 From: DavidCraig@pia.ca.gov (DavidCraig@pia.ca.gov) Date: Thu, 03 Jan 2002 10:22:17 -0800 Subject: [Tutor] Trying to set-up Idle IDE Development Studio 1.0 Message-ID: I downloaded IDE Development Studio 1.0 from the Vaults of Parnassus and installed it. When I opened it to the modified Idle development environment all appeared to be well. I was able type into the interpreter but anytime that I tried to open or save a file or open any pull down menu I get the following error message: Idledev Failure Error finding editor command C:/'Program' PATH:C:\PYTHON21 I am using Win 98, 2nd Edition, and have attempted to adjust the path in autoexec.bat but to no avail. Does anyone know where I can look for more information to resolve this and try to use the IDE. TIA Dave D. H. Craig, CSM From dsh8290@rit.edu Thu Jan 3 20:00:39 2002 From: dsh8290@rit.edu (dman) Date: Thu, 3 Jan 2002 15:00:39 -0500 Subject: [Tutor] Trying to set-up Idle IDE Development Studio 1.0 In-Reply-To: References: Message-ID: <20020103200039.GA1881@localhost> On Thu, Jan 03, 2002 at 10:22:17AM -0800, DavidCraig@pia.ca.gov wrote: | I downloaded IDE Development Studio 1.0 from the Vaults of Parnassus and | installed it. When I opened it to the modified Idle development | environment all appeared to be well. I was able type into the interpreter | but anytime that I tried to open or save a file or open any pull down menu | I get the following error message: | | Idledev Failure | Error finding editor command C:/'Program' PATH:C:\PYTHON21 ^^^ | I am using Win 98, 2nd Edition, Yep, classic problem for windows. The problem is that space bewteen "Program" and "Files" in the path. The space character is often a delimiter in strings; it is likely that something here is using it as a delimiter when you want it embedded. The easiest solution is to put everything you need in directories with no spaces in the names. HTH, -D -- Only two things are infinite, the universe and human stupidity, and I'm not sure about the former. Albert Einstein From bwinton@tor.dhs.org Thu Jan 3 20:32:39 2002 From: bwinton@tor.dhs.org (Blake Winton) Date: Thu, 03 Jan 2002 15:32:39 -0500 Subject: [Tutor] Trying to set-up Idle IDE Development Studio 1.0 In-Reply-To: <20020103200039.GA1881@localhost> Message-ID: > On Thu, Jan 03, 2002 at 10:22:17AM -0800, DavidCraig@pia.ca.gov wrote: > | Idledev Failure > | Error finding editor command C:/'Program' PATH:C:\PYTHON21 > ^^^ > | I am using Win 98, 2nd Edition, > > Yep, classic problem for windows. The problem is that space bewteen > "Program" and "Files" in the path. The space character is often a > delimiter in strings; it is likely that something here is using it as > a delimiter when you want it embedded. The easiest solution is to put > everything you need in directories with no spaces in the names. Or just change the link to "Progra~1"... Later, Blake. From alan.gauld@bt.com Thu Jan 3 22:21:29 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Thu, 3 Jan 2002 22:21:29 -0000 Subject: [Tutor] practical python sites/scripts Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C226@mbtlipnt02.btlabs.bt.co.uk> ------_=_NextPart_001_01C194A4.FDDB7550 Content-type: text/plain; charset="iso-8859-1" > Useless Python is a rather good site, Seconded, especially for beginners but also for little sample program snippets for modules you haven't used before. > The Vaults of Parnassus is also good. It has a large amount of programs. http://www.vex.net/parnassus/ Essential when looking for code, not much use for info. The other biggies that I use are: ActiveState - they have mail list archives(searchable) lots of white papers etc and of course the windows collection of downloads The O'Reilly Python site has some good articles and sample book chapters Dr Dobbs Journal python site is good too Dive into Python has some nice stuff in the form of an online book. And never forget Google's newsgroup archives which turn up all sorts of things from comp.lang.python. Finally for all things OO cetus-links.org have a wealth of Python links too. Thats my list :-) Alan G. ------_=_NextPart_001_01C194A4.FDDB7550 Content-type: text/html; charset="iso-8859-1"
 >  Useless Python is a rather good site,  
 
Seconded, especially for beginners but also for little sample program snippets
for modules you haven't used before.
 
 >  The Vaults of Parnassus is also good. It has a large amount of programs.
 
Essential when looking for code, not much use for info.
 
The other biggies that I use are:
 
ActiveState - they have mail list archives(searchable)
lots of white papers etc and of course the windows
collection of downloads 
 
The O'Reilly Python site has some good articles and sample book chapters
 
Dr Dobbs Journal python site is good too
 
Dive into Python has some nice stuff in the form of an online book.
 
And never forget Google's newsgroup archives which turn up all sorts
of things from comp.lang.python.
 
Finally for all things OO cetus-links.org have a wealth of Python links too.
 
Thats my list :-)
 
Alan G.
------_=_NextPart_001_01C194A4.FDDB7550-- From scarblac@pino.selwerd.nl Fri Jan 4 00:09:41 2002 From: scarblac@pino.selwerd.nl (Remco Gerlich) Date: Fri, 4 Jan 2002 01:09:41 +0100 Subject: [Tutor] practical python sites/scripts In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66C226@mbtlipnt02.btlabs.bt.co.uk>; from alan.gauld@bt.com on Thu, Jan 03, 2002 at 10:21:29PM -0000 References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C226@mbtlipnt02.btlabs.bt.co.uk> Message-ID: <20020104010941.A17777@pino.selwerd.nl> On 0, alan.gauld@bt.com wrote: (snip: Python www tips) The Python page I check most often: The Daily Python-URL, at http://www.secretlabs.com/daily/ -- Remco Gerlich From urnerk@qwest.net Fri Jan 4 04:09:04 2002 From: urnerk@qwest.net (Kirby Urner) Date: Thu, 03 Jan 2002 20:09:04 -0800 Subject: [Tutor] practical python sites/scripts In-Reply-To: <23FD7B1A77E8D211BCB900001D108C02018B28D8@camelot> Message-ID: <4.2.0.58.20020103200802.01b3bd60@pop3.norton.antivirus> At 10:47 AM 1/3/2002 -0500, you wrote: >I am quite interested in knowing of any practical Python sites you like. >Sure I could 'google' it, >but I would probably get lots of hits. The obvious one of course is >www.python.org, but I am more interested in >learning what people such as yourselves actually use Python for and the >sites you like to browse. > >I would appreciate any constructive feedback you could provide. Thank you. I use Python to learn/teach math (and programming): http://www.inetarena.com/~pdx4d/ocn/cp4e.html Kirby From e.kotyk@shaw.ca Fri Jan 4 16:30:17 2002 From: e.kotyk@shaw.ca (Eve Kotyk) Date: Fri, 04 Jan 2002 16:30:17 +0000 Subject: [Tutor] Learning Programming Message-ID: <3C35D899.8ECB0E03@shaw.ca> Some one wrote yesterday that they were to planning to learn to program in Python within a year. I have wanted to learn programming for sometime. I began with C (on Linux) and though I have read a book on C programming (I also did the exercises) I am anything but proficient in C. Subsequently Python was recommended at a good language for a novice. I have completed the tutorial by Josh Cogliati and have written a few small modules on my own. I have two questions: 1) What is a reasonable length of time in which to learn a programming language ?(I'm a little disheartened at my prgress). 2) I think I would learn more quickly if I had a project to work on...how do you choose a project? -- ekotyk http://members.shaw.ca/e.kotyk/virtualstudio.htm From jrm@videotron.ca Thu Jan 3 22:09:33 2002 From: jrm@videotron.ca (Jean Montambeault) Date: Fri, 4 Jan 2002 00:09:33 +0200 Subject: [Tutor] Learning Programming References: <3C35D899.8ECB0E03@shaw.ca> Message-ID: <000501c194a3$535f0200$0100c0a8@videotron.ca> ----- Original Message ----- From: "Eve Kotyk" To: "Tutor" > I have two questions: > > 1) What is a reasonable length of time in which to learn a programming > language ?(I'm a little disheartened at my prgress). What about a lifetime ? I don't think that anybody can truly say that they ever know everything there is about the job. This said I don't know if you intend to become a pro (then go to school and you'll easily see if you compare to your peers) or an amateur (looks that way) like me. In the second case : just enjoy yourself, don't stress and if one day, one month or one year you don't feel like programming do whatever else pleases you. > > > 2) I think I would learn more quickly if I had a project to work > on...how do you choose a project? I think that it is important that you do things that you like, don't you ? I like computer graphics and computer animation. Since I use Blender and that it has Python as a scripting language I mostly write small plug-ins to do special things. I might try to do the same for The Gimp one day. I don't know you but here are some examples : - it's fairly easy to write a surprisingly sophisticated text editor using the power of the text widget in Tkinter. There's tons of them and good ones at that but there's always room for something specialized. - you could elaborate some personnal database scheme for receipes, CDs or whatever. - if you like web programming Python can help you greatly. - use Python instead of bash programming. - whatever you feel like pretty much. Have a look at the Useless Python or the Vaults of Parnassus to see what other people like to program. This helps ? Jean M. > > > -- > > ekotyk > > http://members.shaw.ca/e.kotyk/virtualstudio.htm > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From paulsid@shaw.ca Fri Jan 4 06:54:22 2002 From: paulsid@shaw.ca (Paul Sidorsky) Date: Thu, 03 Jan 2002 23:54:22 -0700 Subject: [Tutor] Learning Programming References: <3C35D899.8ECB0E03@shaw.ca> Message-ID: <3C35519E.6A841232@shaw.ca> Eve Kotyk wrote: > in Python within a year. I have wanted to learn programming for > sometime. I began with C (on Linux) and though I have read a book on C > programming (I also did the exercises) I am anything but proficient in > C. Subsequently Python was recommended at a good language for a > novice. I have completed the tutorial by Josh Cogliati and have written > a few small modules on my own. Well, that's a good first step! Although I disagree with the large body of people who say you can't or shouldn't teach C as a first language, when you're learning on your own it's certainly easier to learn a language like Python. > 1) What is a reasonable length of time in which to learn a programming > language ? Of course, it depends. Keep in mind that I'm by no means an expert on the subject... For the average person to learn a language like Python from scratch (i.e. little to no programming experience) enough to write some small programs, I would say probably 2-3 months is about right. Learning Python enough to make large applications might take 6 months to a year. To learn a language enough to literally "think in it" takes a few years. Guruhood can take decades if it ever comes at all. > (I'm a little disheartened at my prgress). Don't be. The fact you are progressing (at least your post made it seem that way) even a little is always a good sign. Many people either don't even try or give up really quickly if they do. (I've heard "I could never do that" too many times, unfortunately.) The best sign is that you're doing this largely on your own. Taking months or years to learn a language is not something to be ashamed of. While it's true that CS and IT students will eventually be expected to learn languages within days and "sight read" (to borrow a musical term) languages, this is because to make a living at programming it's necessary to be able to learn and adapt quickly. But for a hobby or job-enhancing skill, take your time if you need to. > 2) I think I would learn more quickly if I had a project to work > on...how do you choose a project? This is always tough. Well, it's not as tough as thinking of /names/ for projects, but it's pretty close. :-) Things I do are: - Write a game. Games are generally fun to write and can be made as shallow or as deep as you want. Pick your favourite board or card game and try to program it. Text mode is fine. When you get more advanced try to come up with a graphical game, then try real-time, etc. - Programs that are useful are always a good idea. Maybe there's something you'd like to have at work or for a common household task or for a club you belong to. Even if you aren't actually able to use the program in practice it still makes for a good project. - Watch the big newsgroup/mailing list. You might get ideas there. Or, when somebody else asks a question try to figure out the answer on your own, even if it takes you a while. - Look for University/College CS course pages and try some of the assignments you find. I'd suggest sticking to first year courses because after that the problem descriptions (and the projects themselves) get a lot more technical and/or vague. I had a blast in my first year of University because the assignments were generally a whole lot of fun, even though I already knew most of the course material. Good luck! -- ====================================================================== Paul Sidorsky Calgary, Canada paulsid@shaw.ca http://members.shaw.ca/paulsid/ From rbl@hal.epbi.cwru.edu Fri Jan 4 04:48:14 2002 From: rbl@hal.epbi.cwru.edu (Robin B. Lake) Date: Thu, 3 Jan 2002 23:48:14 -0500 (EST) Subject: [Tutor] Learning Programming Message-ID: <200201040448.g044mE9B006175@hal.epbi.cwru.edu> > Some one wrote yesterday that they were to planning to learn to program > in Python within a year. I have wanted to learn programming for > sometime. I began with C (on Linux) and though I have read a book on C > programming (I also did the exercises) I am anything but proficient in > C. Subsequently Python was recommended at a good language for a > novice. I have completed the tutorial by Josh Cogliati and have written > a few small modules on my own. > > I have two questions: > > 1) What is a reasonable length of time in which to learn a programming > language ?(I'm a little disheartened at my prgress). > I've been teaching programming for 25+ years. It took a while to learn that you DON'T want to "learn a programming language", but rather should "learn how to program". The difference is that in learning how to program, you should FIRST learn how to read and understand a program before you try to write one. Just like we, as children, learn to read before we learn to write. Learning to understand what you read involves knowing something about what programs DO, how information is stored (Data Structures), and a bit about logic (loops and logical operations). Learning to WRITE a program should, in my experience, be done with "pseudocode" --- that expresses the structures and the logic of the problem, without worrying about the details of any programming language rules. THEN you can decide which language will best fit your problem. With pseudocode in hand it becomes pretty straightforward to translate that pseudocode into C, Python, Basic or anything short of APL. > > 2) I think I would learn more quickly if I had a project to work > on...how do you choose a project? Most textbooks have projects and problems. Breaking a project into simple modules and functions is the subject of another course/lecture. Cheers, Robin Lake lake@cwru.edu > > > -- > > ekotyk > > http://members.shaw.ca/e.kotyk/virtualstudio.htm > > From alan.gauld@bt.com Fri Jan 4 17:39:58 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Fri, 4 Jan 2002 17:39:58 -0000 Subject: [Tutor] Learning Programming Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C22F@mbtlipnt02.btlabs.bt.co.uk> > Subsequently Python was recommended at a good language for a > novice. I have completed the tutorial by Josh Cogliati and > have written a few small modules on my own. Congratulations, that's the hardest bit over :-) > 1) What is a reasonable length of time in which to learn a > programming language ? It depends on the language. Something enormous like C++ can take many months or years. In fact I've been learning C++ for over 15 years and still only know the basics! I've been learning Python for about 4 years and know about the same amount... > I'm a little disheartened at my prgress. Don't be, the more you use a language the more you learn. You only need the bare minimum to start using a language and that can literally be learnt in a couple of days - in the case of Python a couple of hours is enough for an experienced programmer to start using Python. It's the layers of detail that take a long time - like all of the modules in Python for example. > 2) I think I would learn more quickly if I had a > project to work on...how do you choose a project? Something you need doing but put off coz it'll take too long? Or something you already do manually but could automate? Or just pick one of the challenges on the Useless Python site. Alan G. From alan.gauld@bt.com Fri Jan 4 17:47:18 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Fri, 4 Jan 2002 17:47:18 -0000 Subject: [Tutor] Learning Programming Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C230@mbtlipnt02.btlabs.bt.co.uk> > From: Robin B. Lake [mailto:rbl@hal.epbi.cwru.edu] > learn that you DON'T want to "learn a programming language", but > rather should "learn how to program". This is excellent advice. Its the reason I used 3 languages on my web tutor rather than just python: to try to illustrate that the same principles apply in all languages. > children, learn to read before we learn to write. Thats also good advice, I can read many programming languages (around 30 maybe?) but I can only write in about 12... > Learning to WRITE a program should, in my experience, be done with > "pseudocode" --- that expresses the structures and the logic of > the problem,... > THEN you can decide which language will best fit your problem. Also very good advice. Alan g. Author of the 'Learning to Program' web site http://www.freenetpages.co.uk/hp/alan.gauld From James.Alexander.McCarney@M3iSystems.com Fri Jan 4 19:40:02 2002 From: James.Alexander.McCarney@M3iSystems.com (McCarney, James Alexander) Date: Fri, 4 Jan 2002 14:40:02 -0500 Subject: [Tutor] CGI and ODBC questions Message-ID: <23FD7B1A77E8D211BCB900001D108C02018B28E1@camelot> Hail noble Python gurus! Well Py is way cool, but I am sure you all knew that long before I ever found out. ;-) I am turning my attention to server-side cgi-bin processing. What I have is this: -platform: W 2000 -web server: (either Apache or IIS[gag]): would like to go w Apache, but may have to port to IIS - Python (yay!) v 2.1.1 - Access Database (ODBC driver) (Could go with mySQL, but Access is what I have right now.) What I want is this: Reader/reviewer has some comments about nifty documents I may have penned. Script serves a form he can fill in and commit to the dB. Script also e-mails me and tells me that this event has occurred. There is ample documentation on the cgi module, so I will do my homework there. But where is it written in Python/server cyberland about setting up Python with the server on NT? Likely with the http server docs you may claim. So has anyone gone down this road before? Does anyone have knowledge on setting up Python with one or other of these servers? And can anyone tell me how to get there from here? Best regards to all of you and thanks for any constructive help you may provide. James Alexander McCarney, Technical Writer M3i Systems Inc., 1111 Saint-Charles Avenue West 11th Floor, East Tower, Longueuil, Quebec, J4K 5G4 Canada Telephone: (450) 928-3386 x2262 Fax: (450) 442-5076 http://www.m3isystems.com From ylee12@uiuc.edu Fri Jan 4 21:24:59 2002 From: ylee12@uiuc.edu (Young-Jin Lee) Date: Fri, 4 Jan 2002 15:24:59 -0600 Subject: [Tutor] [Q] using IDLE in redhat Message-ID: <017601c19566$43c632f0$95757e82@visit2> Hi, I'm new to redhat and I'm looking for a help on how to use IDLE in redhat. I installed Python 2.2 the other day and tried to learn IDLE by typing it "idle", but it didn't work at all. I thought I should add a path to the idle so I added "PATH=$PATH:/usr/lib/python2.2/Tools; export PATH". But when I typed "idle" at my home directory, I got "bash:idle: command not found". I have never used bash shell. (I have used csh in IRIX, but I decided to use bash because bash seems to be a standard in Linux). When I tried it with a full path, "/usr/lib/python2.2/Tools/idle/idle", I got the following python exception. Traceback (innermost last): File "/usr/lib/python2.2/Tools/idle/idle", line 5, in ? from idlelib import IdleConf ImportError: No module named idlelib The configuration seems to be not correct, but I have no idea. Is there a good tutorial or guide on how to use IDLE in redhat (or Linux)? Thanks in advance. YJ From dsh8290@rit.edu Fri Jan 4 21:44:20 2002 From: dsh8290@rit.edu (dman) Date: Fri, 4 Jan 2002 16:44:20 -0500 Subject: [Tutor] [Q] using IDLE in redhat In-Reply-To: <017601c19566$43c632f0$95757e82@visit2> References: <017601c19566$43c632f0$95757e82@visit2> Message-ID: <20020104214420.GA9130@localhost> On Fri, Jan 04, 2002 at 03:24:59PM -0600, Young-Jin Lee wrote: | Hi, I'm new to redhat and I'm looking for a help on how to use IDLE in | redhat. | I installed Python 2.2 the other day and tried to learn IDLE by typing it | "idle", but it didn't work at all. | I thought I should add a path to the idle so I added | "PATH=$PATH:/usr/lib/python2.2/Tools; export PATH". $PATH is what the shell uses to find commands. $PYTHONPATH is what python uses to find modules. | But when I typed "idle" at my home directory, I got "bash:idle: command not | found". I have never used bash shell. (I have used csh in IRIX, but I | decided to use bash because bash seems to be a standard in Linux). | When I tried it with a full path, "/usr/lib/python2.2/Tools/idle/idle", I | got the following python exception. | Traceback (innermost last): | File "/usr/lib/python2.2/Tools/idle/idle", line 5, in ? | from idlelib import IdleConf | ImportError: No module named idlelib This means you need to set $PYTHONPATH correctly. I don't know what is correct for a redhat system, but the debian packages work out-of-the-box. -D -- If you hold to [Jesus'] teaching, you are really [Jesus'] disciples. Then you will know the truth, and the truth will set you free. John 8:31-32 From arcege@speakeasy.net Fri Jan 4 23:52:27 2002 From: arcege@speakeasy.net (Michael P. Reilly) Date: Fri, 4 Jan 2002 18:52:27 -0500 Subject: [Tutor] [Q] using IDLE in redhat In-Reply-To: <017601c19566$43c632f0$95757e82@visit2>; from ylee12@uiuc.edu on Fri, Jan 04, 2002 at 03:24:59PM -0600 References: <017601c19566$43c632f0$95757e82@visit2> Message-ID: <20020104185227.B901@speakeasy.net> On Fri, Jan 04, 2002 at 03:24:59PM -0600, Young-Jin Lee wrote: > Hi, I'm new to redhat and I'm looking for a help on how to use IDLE in > redhat. > I installed Python 2.2 the other day and tried to learn IDLE by typing it > "idle", but it didn't work at all. > I thought I should add a path to the idle so I added > "PATH=$PATH:/usr/lib/python2.2/Tools; export PATH". > But when I typed "idle" at my home directory, I got "bash:idle: command not > found". I have never used bash shell. (I have used csh in IRIX, but I > decided to use bash because bash seems to be a standard in Linux). > When I tried it with a full path, "/usr/lib/python2.2/Tools/idle/idle", I > got the following python exception. > Traceback (innermost last): > File "/usr/lib/python2.2/Tools/idle/idle", line 5, in ? > from idlelib import IdleConf > ImportError: No module named idlelib > > The configuration seems to be not correct, but I have no idea. Is there a > good tutorial or guide on how to use IDLE in redhat (or Linux)? > > Thanks in advance. Unfortunately, Idle got screwed when they tried to get it into Python 2.1 with the new distutils. You must now install IDLE before you can use it; you cannot use it in its place like you could with earlier releases. You need to install it by running the setup.py file in the Tools/idle directory. $ cd .../Tools/idle $ python2.2 ./setup.py -Arcege From highprimate@howlermonkey.net Sat Jan 5 05:39:28 2002 From: highprimate@howlermonkey.net (Kirk D Bailey) Date: Sat, 5 Jan 00:39:28 2002 -0500 Subject: [Tutor] it slices, it dices, it makes BILLIONS and BILLIONS of juliene fries... Message-ID: <200201050539.g055dSo10648@ns.howlermonkey.net> But more importantly, I want to take a string of seceral words and chop it into a list with each word an item in the list. Among other things. But let's talk about the other things later. end In total confusion, Kirk D Bailey +----------------------------------------------------+ | Providing Excellent email service for free!! | | Webmaster, Howlermonkey Email services Co. | | highprimate@howlermonkey.net www.howlermonkey.net/ | +----------------------------------------------------+ ODD#1.8.01/kdb/sigme Totally Free Paging! From toodles@yifan.net Sat Jan 5 06:09:34 2002 From: toodles@yifan.net (Andy W) Date: Sat, 5 Jan 2002 14:09:34 +0800 Subject: [Tutor] it slices, it dices, it makes BILLIONS and BILLIONS of juliene fries... References: <200201050539.g055dSo10648@ns.howlermonkey.net> Message-ID: <001701c195af$8da39d10$0300a8c0@sun> > But more importantly, I want to take a string of seceral words and > chop it into a list with each word an item in the list. > > Among other things. But let's talk about the other things later. several_words_string="Scooby Dooby Doo" several_words_list=several_words.split() That is, as long as the words are separated by spaces. Otherwise several_words.split(separator) > > > end > > In total confusion, > Kirk D Bailey > > +----------------------------------------------------+ > | Providing Excellent email service for free!! | > | Webmaster, Howlermonkey Email services Co. | > | highprimate@howlermonkey.net www.howlermonkey.net/ | > +----------------------------------------------------+ > > ODD#1.8.01/kdb/sigme > > SRC="amtfp2.gif" WIDTH=468 HEIGHT=60 alt="Totally Free Paging!"> > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From highprimate@howlermonkey.net Sat Jan 5 06:17:03 2002 From: highprimate@howlermonkey.net (Kirk D Bailey) Date: Sat, 5 Jan 01:17:03 2002 -0500 Subject: [Tutor] sliced! Message-ID: <200201050617.g056H3o10852@ns.howlermonkey.net> OK, I tripped over string.replace(subject, search, replacement) in string module, and also string.split, so that part is finished, it now digests the subject line nicely. Got another question. --------------------------------------------------------- Def writependings(omitme, list): # write back the pendings, f6.open('./lists/pending','w') # OMITTING one item. for item in list: if item != omitme: f6.write(item)+CRLF f6.close() ---------------------------------------------------------- This code creates a error message; ------------------------------------------------------------ ns# ./TLlistmaster.py < testfile File "./TLlistmaster.py", line 201 Def writependings(omitme, list): # write back the pendings, ^ SyntaxError: invalid syntax ns#_ -------------------------------------------------------------- Now, whofore would it do an evil thing like that? end In total confusion, Kirk D Bailey +----------------------------------------------------+ | Providing Excellent email service for free!! | | Webmaster, Howlermonkey Email services Co. | | highprimate@howlermonkey.net www.howlermonkey.net/ | +----------------------------------------------------+ ODD#1.8.01/kdb/sigme Return to the Forgotten Realms on a visually dazzling role-playing adventure that brings to life the grand tradition of Advanced Dungeons & Dragons through cutting edge art and technology. Now available for pre-order. Only $39.95 from Outpost.com. FREE SHIPPING. OVERNIGHT. From highprimate@howlermonkey.net Sat Jan 5 06:25:34 2002 From: highprimate@howlermonkey.net (Kirk D Bailey) Date: Sat, 5 Jan 01:25:34 2002 -0500 Subject: [Tutor] oops! Message-ID: <200201050625.g056PYo10915@ns.howlermonkey.net> OK, noticed an oops. incorrect open statement, was f6.open(foo), not f6=open(foo). open statement is fixed, but it still barks like a dog. Here's the New and improved code: # Def writependings(omitme, list): # write back the pendings, f6=open('./lists/pending','w') # OMITTING one item. for item in list: if item != omitme: f6.write(item)+CRLF f6.close() # Gives this result: [ Wrote 266 lines ] ns# ./TLlistmaster.py < testfile File "./TLlistmaster.py", line 201 Def writependings(omitme, list): # write back the pendings, ^ SyntaxError: invalid syntax ns#_ COULD IT BE this function name is simply too long? end In total confusion, Kirk D Bailey +----------------------------------------------------+ | Providing Excellent email service for free!! | | Webmaster, Howlermonkey Email services Co. | | highprimate@howlermonkey.net www.howlermonkey.net/ | +----------------------------------------------------+ ODD#1.8.01/kdb/sigme http://www.winfreestuff.com From dyoo@hkn.eecs.berkeley.edu Sat Jan 5 06:40:05 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 4 Jan 2002 22:40:05 -0800 (PST) Subject: [Tutor] oops! In-Reply-To: <200201050625.g056PYo10915@ns.howlermonkey.net> Message-ID: On Sat, 5 Jan 2002, Kirk D Bailey wrote: > Def writependings(omitme, list): # write back the pendings, > f6=open('./lists/pending','w') # OMITTING one item. > for item in list: > if item != omitme: > f6.write(item)+CRLF > f6.close() > > ns# ./TLlistmaster.py < testfile > File "./TLlistmaster.py", line 201 > Def writependings(omitme, list): # write back the pendings, > ^ > SyntaxError: invalid syntax > ns#_ > > COULD IT BE this function name is simply too long? Function names can be pretty long: ### >>> def salutatiousGreeting(): print "salutations!" ... >>> salutatiousGreeting() salutations! ### What you're running into is the case sensitivity of Python keywords: ### >>> Def hello(): File "", line 1 Def hello(): ^ SyntaxError: invalid syntax ### The error's pointing at the "hello", but it's really the 'Def' that's confusing Python. Lowercase the 'Def', and you should be ok. From dyoo@hkn.eecs.berkeley.edu Sat Jan 5 09:53:04 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 5 Jan 2002 01:53:04 -0800 (PST) Subject: [Tutor] A small math puzzle [recreational Python] Message-ID: Hi everyone, I ran across this puzzle while browsing the the 'alt.math.undergrad' newsgroup. I thought it might make a fun programming exercise, so here's my paraphrase of the puzzle: A "rearrangement without fixed letters" of a given word is a mixup of the letters so that, if one were to overlap the original with the rearrangement, no letters should match. For example, given the word: 'TERESA' here are a two "rearrangements without fixed letters": ['RTESAE', 'SATREE'] However, here's an example that is a rearrangement but doesn't work because it has a fixed letter: 'TRESAE' ^ In this example, the 'T' makes this rearrangement inacceptable, since 'TERESA' itself begins with a 'T' too. The puzzle is to write a program that counts all the possible rearrangements without fixed letters. Have fun! From lha2@columbia.edu Sat Jan 5 13:32:15 2002 From: lha2@columbia.edu (Lloyd Hugh Allen) Date: Sat, 05 Jan 2002 08:32:15 -0500 Subject: [Tutor] A small math puzzle [recreational Python] References: Message-ID: <3C37005F.9EFCF016@mail.verizon.net> Danny Yoo wrote: > However, here's an example that is a rearrangement but doesn't work > because it has a fixed letter: > > 'TRESAE' > ^ > > In this example, the 'T' makes this rearrangement inacceptable, since > 'TERESA' itself begins with a 'T' too. > > The puzzle is to write a program that counts all the possible > rearrangements without fixed letters. > > Have fun! Is it necessary to actually construct the list of rearrangements, or do you just want a function that will compute how many rearrangements exist? From toodles@yifan.net Sat Jan 5 14:26:20 2002 From: toodles@yifan.net (Andy W) Date: Sat, 5 Jan 2002 22:26:20 +0800 Subject: [Tutor] A small math puzzle [recreational Python] References: Message-ID: <000f01c195f4$f36f48c0$0300a8c0@sun> Here's a solution, albeit a cruddy one :-) It uses permutations, so therefore gets dreadfully slow from about 8 letters onwards. I knew this would happen, I just couldn't get my mind around the mathematical approach... Andy W. PS. The function actually returns all the rearrangements, not the number of them. Of course that can easily be changed... #Code def perm(set,n): """ By Kirby Urner. Return all permutations of a set. Thanks to Daniel Ajoy for sharing his Logo version with me. """ set=listify(set) if len(set)==0: return [] elif len(set)==1: return set answ = [] for i in range(len(set)): base = [set[0]] rest = set[1:] answ = answ + [base + listify(i) for i in perm(rest,n-1)] set = [set[-1]]+set[:-1] return answ def listify(obj): "Used in conjunction with perm()" if type(obj) is not type([]): try: l=list(obj) except: l=[obj] return l else: return obj def get_rearrangements(word): word=word.upper() perms=perm([char for char in word],len(word)) #Get the permutations of the letters rearrangements=perms[:] #Copy for keeping the good ones in for p in perms: ok=1 for n in range(len(p)): if p[n]==word[n]: #Check whether the character is the same... ok=0 if not ok: rearrangements.remove(p) #If it is, remove it! return [''.join(r) for r in rearrangements] ----- Original Message ----- From: "Danny Yoo" To: Sent: Saturday, January 05, 2002 5:53 PM Subject: [Tutor] A small math puzzle [recreational Python] > Hi everyone, > > I ran across this puzzle while browsing the the 'alt.math.undergrad' > newsgroup. I thought it might make a fun programming exercise, so here's > my paraphrase of the puzzle: > > > A "rearrangement without fixed letters" of a given word is a mixup of the > letters so that, if one were to overlap the original with the > rearrangement, no letters should match. For example, given the word: > > 'TERESA' > > here are a two "rearrangements without fixed letters": > > ['RTESAE', 'SATREE'] > > However, here's an example that is a rearrangement but doesn't work > because it has a fixed letter: > > 'TRESAE' > ^ > > In this example, the 'T' makes this rearrangement inacceptable, since > 'TERESA' itself begins with a 'T' too. > > > The puzzle is to write a program that counts all the possible > rearrangements without fixed letters. > > > Have fun! > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From printers@sendme.cz Sat Jan 5 15:21:59 2002 From: printers@sendme.cz (A) Date: Sat, 5 Jan 2002 16:21:59 +0100 Subject: [Tutor] How can handle exception? Message-ID: <3C372827.12259.7C1054@localhost> Hello, My program sometimes raise the exception socket.error: (10061, 'Connection refused') How can I handle this kind of exception? Thank you for help. Ladislav From toodles@yifan.net Sat Jan 5 15:57:53 2002 From: toodles@yifan.net (Andy W) Date: Sat, 5 Jan 2002 23:57:53 +0800 Subject: [Tutor] How can handle exception? References: <3C372827.12259.7C1054@localhost> Message-ID: <000501c19601$bd9fe170$0300a8c0@sun> Hi Ladislav > Hello, > My program sometimes raise the exception > > socket.error: (10061, 'Connection refused') > > How can I handle this kind of exception? Enclose it in try, except socket.error. ie.:- try: #do stuff here except socket.error: #handle exception here Andy > Thank you for help. > Ladislav > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From urnerk@qwest.net Sat Jan 5 16:25:10 2002 From: urnerk@qwest.net (Kirby Urner) Date: Sat, 05 Jan 2002 08:25:10 -0800 Subject: [Tutor] A small math puzzle [recreational Python] In-Reply-To: <000f01c195f4$f36f48c0$0300a8c0@sun> References: Message-ID: <4.2.0.58.20020105071200.019b5da0@pop3.norton.antivirus> A permutations with no element in its original position is called a derangement. Leonhard Euler came up with a formula for computing the number of derangements, based on N elements, as a function of N: drs(n) = n! * [1/0! - 1/1! + 1/2! - 1/3! + ... + ((-1)^n)/n!] (drs stands for derangements). However, as Tim Peters pointed out on edu-sig awhile back, the series in brackets is approaching 1/e (e = math.e) so for larger values of n, you can just go drs(n) = round(n!/e) to get a fairly good approximation. My approach to the above function was to use long integers for their precision, i.e. to not let floating point numbers enter into it. The code is simplified thanks to a fraction object, which internally keeps numerator and denominator separate, and which adds fractions by finding a common denominator. Many people have written such objects in Python. Some languages, like Scheme, have this rational number type built in, and Python might too, one day -- the type system is extensible after all. Let's look at the guts of a simple Fraction object (good enough to get the job done for this application -- even a little bit fancier than we need): class F: def __init__(self,numer,denom): # reduce inputs to lowest terms gcd = self.gcd(numer,denom) self.num = numer//gcd self.den = denom//gcd def __add__(self,other): # find lowest common multiple a,b = self.num, other.num comden = self.lcm(self.den, other.den) if comden != self.den: a *= comden//self.den if comden != other.den: b *= comden//other.den return F(a+b,comden) def __sub__(self,other): return self + (-other) def __neg__(self): return F(-self.num,self.den) def gcd(self,a,b): # find greatest common divisor of a,b if b==0: return a else: return self.gcd(b,a%b) def lcm(self,a,b): # find lowest common multiple of a,b return a*b//self.gcd(a,b) def __repr__(self): # represent as (a/b) return "(%s/%s)" % (self.num, self.den) >>> m = F(1,2) >>> n = F(2,3) >>> n+m (7/6) >>> n-m (1/6) This isn't a complete Fraction definition, as we don't have the ability to multiply fraction objects (easier than __add__), or do some other things we'd like. But we can add and subtract, which is enough for computing: [F(1,0!) - F(1,1!) + F(1,2!) - F(1,3!) + ... + F((-1)^n),n!)] in the above example. Except factorial notation isn't legal Python. We need a simple factorial function: >>> from operator import mul >>> def fact(n): if n<=1: return 1 else: return reduce(mul,range(2,n+1)) So now we're ready to implement the above expression in brackets: >>> def brackets(n): sign = -1 sum = F(1,1) for i in range(1,n+1): if sign == 1: sum = sum + F(1,fact(i)) if sign == -1: sum = sum - F(1,fact(i)) sign *= -1 return sum >>> brackets(10) (16481/44800) >>> brackets(30) (3364864615063302680426807870189/9146650338351415815045120000000) >>> from __future__ import division >>> (3364864615063302680426807870189/9146650338351415815045120000000) 0.36787944117144233 >>> from math import e # e used below as well >>> 1/e 0.36787944117144233 So the brackets expression is indeed approaching 1/e, which is a check on our algorithm. The final step is to return the number of derangements: >>> def drs(n): b = brackets(n) num = b.num den = b.den return fact(n)* num // den >>> drs(1) 0 >>> drs(2) 1 >>> drs(3) 2 >>> drs(4) 9 >>> drs(9) 133496L >>> drs(30) 97581073836835777732377428235481L # too many to list out! That's lots of derangements for 30 distinct element sets, but is still less than the number of permutations, which is 30!: >>> fact(30) 265252859812191058636308480000000L Indeed, drs(30) is less than fact(30) by a factor of 1/e. The rounding approach gives drs(30) to a lesser degree of precision, owing to floating point's limitations: >>> round(fact(30)*1/e) 9.758107383683579e+031 -- which is why I prefer the long integer approach, from a number theoretic point of view, even though it's slower. In a math-through-programming curriculum, I'd favor having students evolve fraction objects, as per above, adding to their capabilities over time, and then tossing out little puzzles like this which make use of fraction object capabilities. Of course the drs(n) function could have be written without any reference to fraction objects per se, but having fraction objects available, like matrix objects, or polynomial objects, helps keep the code clean. Kirby From karthikg@aztec.soft.net Sat Jan 5 16:44:03 2002 From: karthikg@aztec.soft.net (Karthik Gurumurthy) Date: Sat, 5 Jan 2002 22:14:03 +0530 Subject: [Tutor] CGI and ODBC questions In-Reply-To: <23FD7B1A77E8D211BCB900001D108C02018B28E1@camelot> Message-ID: for apache server, Look for the file httpd.conf under the directory where you installed apache in my case..this is the path. D:\Program Files\Apache Group\Apache\conf say Create a folder PythonScripts under \Apache look for an already exiting entry for ScriptAlias in httpd.conf file. You can copy the same and create a new one like this where you can put your python files .... ScriptAlias /python/ "d:/Program Files/Apache Group/Apache/PythonScripts/" .... Look for a AllowOverride None Options None Copy the same thing and change the folder name. So you will have another entry like this. AllowOverride None Options None Then add the following entry to the httpd.conf file: ScriptInterpreterSource Registry Now you can place all your python cgi files in the PythonScripts folder and acess it like this: http://localhost/python/test.py hope it works for you! karthik. -----Original Message----- From: tutor-admin@python.org [mailto:tutor-admin@python.org]On Behalf Of McCarney, James Alexander Sent: Saturday, January 05, 2002 1:10 AM To: 'tutor@python.org' Subject: [Tutor] CGI and ODBC questions Hail noble Python gurus! Well Py is way cool, but I am sure you all knew that long before I ever found out. ;-) I am turning my attention to server-side cgi-bin processing. What I have is this: -platform: W 2000 -web server: (either Apache or IIS[gag]): would like to go w Apache, but may have to port to IIS - Python (yay!) v 2.1.1 - Access Database (ODBC driver) (Could go with mySQL, but Access is what I have right now.) What I want is this: Reader/reviewer has some comments about nifty documents I may have penned. Script serves a form he can fill in and commit to the dB. Script also e-mails me and tells me that this event has occurred. There is ample documentation on the cgi module, so I will do my homework there. But where is it written in Python/server cyberland about setting up Python with the server on NT? Likely with the http server docs you may claim. So has anyone gone down this road before? Does anyone have knowledge on setting up Python with one or other of these servers? And can anyone tell me how to get there from here? Best regards to all of you and thanks for any constructive help you may provide. James Alexander McCarney, Technical Writer M3i Systems Inc., 1111 Saint-Charles Avenue West 11th Floor, East Tower, Longueuil, Quebec, J4K 5G4 Canada Telephone: (450) 928-3386 x2262 Fax: (450) 442-5076 http://www.m3isystems.com _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From urnerk@qwest.net Sat Jan 5 19:04:40 2002 From: urnerk@qwest.net (Kirby Urner) Date: Sat, 05 Jan 2002 11:04:40 -0800 Subject: [Tutor] A small math puzzle [recreational Python] In-Reply-To: <20020105125110.A9441@tor.dhs.org> References: <4.2.0.58.20020105071200.019b5da0@pop3.norton.antivirus> <000f01c195f4$f36f48c0$0300a8c0@sun> <4.2.0.58.20020105071200.019b5da0@pop3.norton.antivirus> Message-ID: <4.2.0.58.20020105110025.019ba670@pop3.norton.antivirus> At 12:51 PM 1/5/2002 -0500, Blake Winton wrote: >* Kirby Urner [020105 11:23]: > > A permutations with no element in its original position is > > called a derangement. Leonhard Euler came up with a formula > > for computing the number of derangements, based on N elements, > > as a function of N: > > > > drs(n) = n! * [1/0! - 1/1! + 1/2! - 1/3! + ... + ((-1)^n)/n!] > >But does this take into account the fact that two letters might >be the same? I believe the puzzle, as stated, is a little >trickier than this formula would account for. > >Later, >Blake. I hope you don't mind my posting this CC to the list, but yes, I think you have a very good point. I should think about it some more. I was too quick to pop in with a solution I'd already done some thinking about (in which all the elements of the permuted set were distinct) -- and of course I was piggy-backing on Euler for the key result. I expect there's a modification of the above formula that would accommodate repetitions of elements. I'd like to find out what it is. Kirby From arcege@speakeasy.net Sat Jan 5 20:04:47 2002 From: arcege@speakeasy.net (Michael P. Reilly) Date: Sat, 5 Jan 2002 15:04:47 -0500 Subject: [Tutor] A small math puzzle [recreational Python] In-Reply-To: <4.2.0.58.20020105071200.019b5da0@pop3.norton.antivirus>; from urnerk@qwest.net on Sat, Jan 05, 2002 at 08:25:10AM -0800 References: <000f01c195f4$f36f48c0$0300a8c0@sun> <4.2.0.58.20020105071200.019b5da0@pop3.norton.antivirus> Message-ID: <20020105150447.E901@speakeasy.net> On Sat, Jan 05, 2002 at 08:25:10AM -0800, Kirby Urner wrote: And for people using versions of Python out there in the real world... > class F: > > def __init__(self,numer,denom): > # reduce inputs to lowest terms > gcd = self.gcd(numer,denom) > self.num = numer//gcd > self.den = denom//gcd self.num = int(numer / gcd) self.den = int(denom / gcd) > def __add__(self,other): > # find lowest common multiple > a,b = self.num, other.num > comden = self.lcm(self.den, other.den) > if comden != self.den: > a *= comden//self.den a = a * int(comdem / self.den) > if comden != other.den: > b *= comden//other.den b = b * int(comdem / other.den) > return F(a+b,comden) > > def __sub__(self,other): > return self + (-other) > > def __neg__(self): > return F(-self.num,self.den) > > def gcd(self,a,b): > # find greatest common divisor of a,b > if b==0: return a > else: return self.gcd(b,a%b) > > def lcm(self,a,b): > # find lowest common multiple of a,b > return a*b//self.gcd(a,b) return int(a * b / self.gcd(a,b)) > def __repr__(self): > # represent as (a/b) > return "(%s/%s)" % (self.num, self.den) > > >>> m = F(1,2) > >>> n = F(2,3) > >>> n+m > (7/6) > >>> n-m > (1/6) Make sure that you have the proper use of operators - this is a list for people learning Python, and not all people can use Python 2.2 (which adds the '//' operator and Python 2.0 which adds the '*=' operator). If you are going to add code that will break when a newbie tries to put it into a file and run it, make sure that you say which version you are using. -Arcege From urnerk@qwest.net Sat Jan 5 20:18:13 2002 From: urnerk@qwest.net (Kirby Urner) Date: Sat, 05 Jan 2002 12:18:13 -0800 Subject: [Tutor] A small math puzzle [recreational Python] In-Reply-To: <20020105150447.E901@speakeasy.net> References: <4.2.0.58.20020105071200.019b5da0@pop3.norton.antivirus> <000f01c195f4$f36f48c0$0300a8c0@sun> <4.2.0.58.20020105071200.019b5da0@pop3.norton.antivirus> Message-ID: <4.2.0.58.20020105121513.019ced80@pop3.norton.antivirus> > >If you are going to add code that will break when a newbie tries to >put it into a file and run it, make sure that you say which version you >are using. > > -Arcege OK. I generally assume that a newbie has no ties to the past and will naturally want to use the latest and greatest Python. But I should be explicit about this assumption: i.e. advice to all newcomers: don't waste your time with anything less than Python 2.1, if you're not locked into such a restriction by your paying job. In particular, my Fraction object was written using the 2.2 release (no longer in beta). Kirby From dyoo@hkn.eecs.berkeley.edu Sat Jan 5 20:22:28 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 5 Jan 2002 12:22:28 -0800 (PST) Subject: [Tutor] A small math puzzle [recreational Python] In-Reply-To: <3C37005F.9EFCF016@mail.verizon.net> Message-ID: On Sat, 5 Jan 2002, Lloyd Hugh Allen wrote: > Danny Yoo wrote: > > However, here's an example that is a rearrangement but doesn't work > > because it has a fixed letter: > > > > 'TRESAE' > > ^ > > > > In this example, the 'T' makes this rearrangement inacceptable, since > > 'TERESA' itself begins with a 'T' too. > > > > The puzzle is to write a program that counts all the possible > > rearrangements without fixed letters. > > > > Have fun! > > Is it necessary to actually construct the list of rearrangements, or > do you just want a function that will compute how many rearrangements > exist? If you can think of a way to do it without actually generating the rearrangements, that would be great! From discuss@sendme.cz Sat Jan 5 09:21:42 2002 From: discuss@sendme.cz (A) Date: Sat, 5 Jan 2002 10:21:42 +0100 Subject: [Tutor] How can handle exception? Message-ID: <3C36D3B6.20197.82DFF6@localhost> Hello, My program sometimes raise the exception socket.error: (10061, 'Connection refused') How can I handle this kind of exception? Thank you for help. Ladislav From Mazni Zambri" <@skali.com Sat Jan 5 15:16:23 2002 From: Mazni Zambri" <@skali.com (Mazni Zambri) Date: Sat, 05 Jan 2002 10:16:23 -0500 Subject: [Tutor] looking for some sample codes Message-ID: <101024377401@skali.com> Can you tell me where I can get good sample Python codes? Thanks From marklists@mceahern.com Sat Jan 5 15:34:52 2002 From: marklists@mceahern.com (Mark McEahern) Date: Sat, 5 Jan 2002 07:34:52 -0800 Subject: [Tutor] RE: How can handle exception? In-Reply-To: <3C372827.12259.7C1054@localhost> Message-ID: Ladislav: > Hello, > My program sometimes raise the exception > > socket.error: (10061, 'Connection refused') > > How can I handle this kind of exception? try: # your code that's failing except: # what you want to do when it fails // mark From dyoo@hkn.eecs.berkeley.edu Sat Jan 5 20:41:22 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 5 Jan 2002 12:41:22 -0800 (PST) Subject: [Tutor] A small math puzzle [recreational Python] In-Reply-To: <000f01c195f4$f36f48c0$0300a8c0@sun> Message-ID: On Sat, 5 Jan 2002, Andy W wrote: > Here's a solution, albeit a cruddy one :-) It uses permutations, so > therefore gets dreadfully slow from about 8 letters onwards. I knew > this would happen, I just couldn't get my mind around the mathematical > approach... I took a similar approach on this on as well; I'm still trying to wrap my head around doing it mathematically, without actually constructing them... I'm slow at this sort of stuff. *grin* I wanted to play around with some features in Python 2.2, so my solution uses generators: ### from __future__ import generators import string def permIter(seq): """Given some sequence 'seq', returns an iterator that gives all permutations of that sequence.""" ## Base case if len(seq) == 1: yield(seq[0]) raise StopIteration ## Inductive case for i in range(len(seq)): element_slice = seq[i:i+1] rest_iter = permIter(seq[:i] + seq[i+1:]) for rest in rest_iter: yield(element_slice + rest) raise StopIteration def isFixedLetterRearrangement(word1, word2): """Returns true if word1 and word2 contain the same letters, but mismatches at every single position.""" return (hasSameElements(word1, word2) and mismatchesEverywhere(word1, word2)) def hasSameElements(seq1, seq2): l1, l2 = list(seq1), list(seq2) l1.sort() l2.sort() return l1 == l2 def mismatchesEverywhere(seq1, seq2): for i in range(len(seq1)): if seq1[i] == seq2[i]: return 0 return 1 if __name__ == "__main__": teresa_rearrangements = [x for x in permIter("teresa") if isFixedLetterRearrangement(x, "teresa")] print "There are", len(teresa_rearrangements), print "distinct rearrangements." print "Here they are:" print string.join(teresa_rearrangements, "\n") ### From dyoo@hkn.eecs.berkeley.edu Sat Jan 5 20:49:34 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 5 Jan 2002 12:49:34 -0800 (PST) Subject: [Tutor] looking for some sample codes In-Reply-To: <101024377401@skali.com> Message-ID: On Sat, 5 Jan 2002, Mazni Zambri wrote: > Can you tell me where I can get good sample Python codes? Hi Mazni, Yes, you can find a lot of good samples at Useless Python: http://www.lowerstandard.com/python/ The programs there have been written by people here on the Tutor mailing list, so if you want to talk about any programs, please feel free to ask about them. Another good place to look for samples of Python code is at the Vaults of Parnassus: http://www.vex.net/parnassus/ which is a central repository for Python. It's great if you're looking for extra library modules. There's one more place I can think of at the moment: ActiveState's "Python Cookbook": http://aspn.activestate.com/ASPN/Cookbook/Python The Cookbook collects a lot of useful snippets of Python code, and is altogether very nice. Hope this helps! From urnerk@qwest.net Sat Jan 5 20:55:56 2002 From: urnerk@qwest.net (Kirby Urner) Date: Sat, 05 Jan 2002 12:55:56 -0800 Subject: [Tutor] A small math puzzle [recreational Python] In-Reply-To: References: <000f01c195f4$f36f48c0$0300a8c0@sun> Message-ID: <4.2.0.58.20020105125327.00b73f00@pop3.norton.antivirus> Re pure derangements with all elements distinct, a simpler algorithm, which ignores the whole "fraction object" thread, is just: >>> def drs(n): if n==1: return 0 return n * drs(n-1) + (-1)**n >>> drs(1) 0 >>> drs(2) 1 >>> drs(3) 2 >>> drs(4) 9 >>> drs(5) 44 >>> drs(6) 265 >>> drs(7) 1854 But that's not the answer to the puzzle, as it doesn't allow repeats of the same letters. Kirby Reference: http://www.theory.csc.uvic.ca/~cos/inf/perm/Derangements.html From dyoo@hkn.eecs.berkeley.edu Sat Jan 5 21:26:48 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 5 Jan 2002 13:26:48 -0800 (PST) Subject: [Tutor] A small math puzzle [deranged recreational Python] In-Reply-To: <4.2.0.58.20020105125327.00b73f00@pop3.norton.antivirus> Message-ID: On Sat, 5 Jan 2002, Kirby Urner wrote: > Re pure derangements with all elements distinct, a simpler > algorithm, which ignores the whole "fraction object" thread, > is just: > > >>> def drs(n): > if n==1: return 0 > return n * drs(n-1) + (-1)**n > > >>> drs(1) > 0 > >>> drs(2) > 1 > >>> drs(3) > 2 > >>> drs(4) > 9 > >>> drs(5) > 44 > >>> drs(6) > 265 > >>> drs(7) > 1854 > > But that's not the answer to the puzzle, as it doesn't > allow repeats of the same letters. I knew that I heard the word "derangements" before! In the book "Concrete Mathematics", there's another derivation for derangements. Here's another implementation of drs: ### from math import floor, e def drs2(n): return int(floor(factorial(n)/e + 0.5) + (n==0)) def factorial(n): if n == 0: return 1 return factorial(n-1) * n ### And to test it out: ### >>> [drs2(n) for n in range(8)] [1, 0, 1, 2, 9, 44, 265, 1854] ### From bwinton@tor.dhs.org Sat Jan 5 22:49:49 2002 From: bwinton@tor.dhs.org (Blake Winton) Date: Sat, 5 Jan 2002 17:49:49 -0500 Subject: [Tutor] A small math puzzle [recreational Python] In-Reply-To: <4.2.0.58.20020105110025.019ba670@pop3.norton.antivirus> References: <4.2.0.58.20020105071200.019b5da0@pop3.norton.antivirus> <000f01c195f4$f36f48c0$0300a8c0@sun> <4.2.0.58.20020105071200.019b5da0@pop3.norton.antivirus> <20020105125110.A9441@tor.dhs.org> <4.2.0.58.20020105110025.019ba670@pop3.norton.antivirus> Message-ID: <20020105174949.A9743@tor.dhs.org> * Kirby Urner [020105 14:01]: > At 12:51 PM 1/5/2002 -0500, Blake Winton wrote: > >* Kirby Urner [020105 11:23]: > > > A permutations with no element in its original position is > > > called a derangement. > >But does this take into account the fact that two letters might > >be the same? I believe the puzzle, as stated, is a little > >trickier than this formula would account for. > I hope you don't mind my posting this CC to the list, I didn't think it was worthy of a post, but now that I think about it a little more, it's a devilish twist... > I expect there's a modification of the above formula that > would accommodate repetitions of elements. I'd like to > find out what it is. I thought so at first, but then I started thinking about it a little more... For instance, the string "DDT" has no derangement, and I'm not sure how we'ld take that into account. Later, Blake. -- 9:40pm up 52 days, 21:07, 2 users, load average: 0.02, 0.09, 0.07 From grimmtoothtoo@yahoo.com Sat Jan 5 23:28:49 2002 From: grimmtoothtoo@yahoo.com (Grimmtooth) Date: Sat, 5 Jan 2002 18:28:49 -0500 Subject: [Tutor] Escape characters in strings In-Reply-To: <20020105174949.A9743@tor.dhs.org> Message-ID: Is there a reliable way to catch backslashes in strings so that they don't get converted to escaped characters under some circumstances? Example: 12/13 14:04:53 2> S:L.TG23 Y1 12007030050020C100021340 12/13 14:04:53 2> S:12888888881003030000000001249000212011213140434210 12/13 14:04:53 2> S:10125414C200344012888888881=0512101543211234567800 12/13 14:04:53 2> S:1 700000000740 0242C00000000000000EN00420107 12/13 14:04:53 2> S:6O02450U300001000\300009990\000000000999\950U30000 12/13 14:04:53 2> S:1000\300002500\000000000250. In the example, each case where '\300' occurs gets converted to an escaped character ('A' with a dot over it). I've worked around this by pre-processing the raw string ( s = string.replace(s, '\300', '!300')) but it's a royal pain in the backside and could have ramifications I haven't forseen. This is one aspect of Python that bugs me, that I haven't come to terms with so far ... _________________________________________________________ Do You Yahoo!? Get your free @yahoo.com address at http://mail.yahoo.com From urnerk@qwest.net Sun Jan 6 00:05:38 2002 From: urnerk@qwest.net (Kirby Urner) Date: Sat, 05 Jan 2002 16:05:38 -0800 Subject: [Tutor] A small math puzzle [recreational Python] In-Reply-To: <20020105174949.A9743@tor.dhs.org> References: <4.2.0.58.20020105110025.019ba670@pop3.norton.antivirus> <4.2.0.58.20020105071200.019b5da0@pop3.norton.antivirus> <000f01c195f4$f36f48c0$0300a8c0@sun> <4.2.0.58.20020105071200.019b5da0@pop3.norton.antivirus> <20020105125110.A9441@tor.dhs.org> <4.2.0.58.20020105110025.019ba670@pop3.norton.antivirus> Message-ID: <4.2.0.58.20020105160302.00ad9980@pop3.norton.antivirus> I sent the following post to sci.math, in case a guru over there has an answer (googling didn't turn up anything -- lots of postscript files with buried treasure). =============== I am aware of the expression for the number of derangements of n distinct elements: d(n) = !n = n![1/0! - 1/1! + 1/2! ... (-1)^n/n!] where the bracketed expression approaches 1/e as n->infinity. What I haven't been able to find, let alone derive, is an expression that works for multisets, e.g. all the permutations d(n) of DEADBEEF where no letter is where it was (EAFEDDBE would be one of them but EAEEDDBF wouldn't be). By rearrangement (A B F D D E E E) would give me coefficients C = [1,1,1,2,3]. len(C) would be the number of distinct characters while \sigma C[i] i = 1...len(C) would be the number of elements in the bag. So I guess what I'm looking for is some expression or algorithm that accepts arguments C and returns the number of derangements. I find that GAP (Groups, Algorithms and Programming) will enumerate derangements of bags, as per the examples below: gap> Derangements( [1,1,2,2,3,3] ); [ [ 2, 2, 3, 3, 1, 1 ], [ 2, 3, 1, 3, 1, 2 ], [ 2, 3, 1, 3, 2, 1 ], [ 2, 3, 3, 1, 1, 2 ], [ 2, 3, 3, 1, 2, 1 ], [ 3, 2, 1, 3, 1, 2 ], [ 3, 2, 1, 3, 2, 1 ], [ 3, 2, 3, 1, 1, 2 ], [ 3, 2, 3, 1, 2, 1 ], [ 3, 3, 1, 1, 2, 2 ] ] gap> NrDerangements( [1,2,2,3,3,3,4,4,4,4] ); 338 I'm wondering if NrDerangements is doing something more than a brute force count of derangements it generates. Kirby From dsh8290@rit.edu Sun Jan 6 00:23:54 2002 From: dsh8290@rit.edu (dman) Date: Sat, 5 Jan 2002 19:23:54 -0500 Subject: [Tutor] Escape characters in strings In-Reply-To: References: <20020105174949.A9743@tor.dhs.org> Message-ID: <20020106002354.GA15140@localhost> On Sat, Jan 05, 2002 at 06:28:49PM -0500, Grimmtooth wrote: | | Is there a reliable way to catch backslashes in strings so that they don't | get converted to escaped characters under some circumstances? Are you eval()ing the strings? If not then the interpreter doesn't do any funny stuff with it. | Example: | | 12/13 14:04:53 2> S:L.TG23 Y1 12007030050020C100021340 | 12/13 14:04:53 2> S:12888888881003030000000001249000212011213140434210 | 12/13 14:04:53 2> S:10125414C200344012888888881=0512101543211234567800 | 12/13 14:04:53 2> S:1 700000000740 0242C00000000000000EN00420107 | 12/13 14:04:53 2> S:6O02450U300001000\300009990\000000000999\950U30000 | 12/13 14:04:53 2> S:1000\300002500\000000000250. Is this from a log file? How are you reading the data? Can you show us the code? | In the example, each case where '\300' occurs gets converted to an escaped | character ('A' with a dot over it). I've worked around this by | pre-processing the raw string ( s = string.replace(s, '\300', '!300')) but | it's a royal pain in the backside and could have ramifications I haven't | forseen. If you do want to eval() the string you can replace( "\\" , "\\\\" ) to escape all backslashes first. HTH, -D -- How great is the love the Father has lavished on us, that we should be called children of God! 1 John 3:1 From grimmtoothtoo@yahoo.com Sun Jan 6 02:22:12 2002 From: grimmtoothtoo@yahoo.com (Grimmtooth) Date: Sat, 5 Jan 2002 21:22:12 -0500 Subject: [Tutor] Escape characters in strings In-Reply-To: <20020106002354.GA15140@localhost> Message-ID: > | Example: > | > | 12/13 14:04:53 2> S:L.TG23 Y1 12007030050020C100021340 > | 12/13 14:04:53 2> S:12888888881003030000000001249000212011213140434210 > | 12/13 14:04:53 2> S:10125414C200344012888888881=0512101543211234567800 > | 12/13 14:04:53 2> S:1 700000000740 0242C00000000000000EN00420107 > | 12/13 14:04:53 2> S:6O02450U300001000\300009990\000000000999\950U30000 > | 12/13 14:04:53 2> S:1000\300002500\000000000250. > > Is this from a log file? How are you reading the data? Can you show > us the code? 1) Yes and no. 2) (a) either the user pastes this data into a wxWindows Text Control then I GetValue() it or else it is read from a logfile directly using readlines() into an array. In the current case, I've hardcoded the text in using a """ triple-quoted string. The problem occurs no matter which way it goes. 3) I could, but it would be a lot of code. Let me paraphrase it: first, get code from text control or log file. then, using a function Stitch(), I locate all lines beginning with S: after the 2> by first slicing [] them out then concatenating them together with '+'. This returns one continuous string. for i in s: x = i[18:-1] # first 18 are time stamp, last is CR. Trim both. if len(x) > 0: if x[0] == 'S': snd.append(x) then, I pass the string to a Parser class. This in turn slices out particular parts of the long string and assigns them to additional classes, each designed to parse the particular data it is passed. class BaseElement: def __init__(self, parent): pass def Show(self): pass class AdditionalAmounts(BaseElement): data = None def __init__(self, parent, txt): self.data, parent.remainder = lllvar(txt) def llvar(data): len = int(data[:2]) return(data[2:len+2], data[len+2:]) the BaseElement class is an empty, defined to give me a None if I don't override the __init__ and Show methods. Assuming that I've sliced off everything prior to the part of interest already (which I have), the above code fragments are the ones that get processed. First, the string is passed to AdditionalAmounts.__init__(). __init__() calls llvar() to seperate the data and from the remainder of the log entry (an llvar is a data field that is preceded by two digits indicating how many bytes the data contains). The process of actually processing the data is where I end up tripping over the escaped \ characters. > If you do want to eval() the string you can replace( "\\" , "\\\\" ) > to escape all backslashes first. Doesn't work, that was the first thing I tried. For some reason Python's not finding the '\' because it thinks '\300' is a single character rather than four. Even 'print x' will hide the \ in this case. _________________________________________________________ Do You Yahoo!? Get your free @yahoo.com address at http://mail.yahoo.com From tim.one@home.com Sun Jan 6 03:18:04 2002 From: tim.one@home.com (Tim Peters) Date: Sat, 5 Jan 2002 22:18:04 -0500 Subject: [Tutor] A small math puzzle [recreational Python] In-Reply-To: Message-ID: [talking about derangements of words with duplicate letters] FYI, you can compute this without exhaustive generation, but it's not simple. See, e.g., section 4-7 (Permutations with Forbidden Positions) in Liu's "Introduction to Combinatorial Mathematics". That section is at the end of the chapter on the principle of inclusion and exclusion, and builds on everything before it, so it's not easy to summarize. I expect it's substantially easier to write a program to generate all possibilities! From wheelege@hotmail.com Sun Jan 6 04:56:58 2002 From: wheelege@hotmail.com (Glen Wheeler) Date: Sun, 6 Jan 2002 15:56:58 +1100 Subject: [Tutor] Escape characters in strings References: Message-ID: Hi, I was writing an internet script and when parsing text I came upon this very problem. Nothing I tried would stop python from considering \xxx to be anything other than one character...the way I did it in the end was to redesign the way I parsed the strings and 'ignore' the \xxx parts. This isn't helpful for you, since you obviously can't ignore them. I am just posting here to show that your not the only one who has encountered this problem before... Hmmm, upon a bit of fiddling.... for i in s: if '\\' in repr(i): j = '' j = repr(i)[1:-1] n.append(j) else: n.append(i) Sorta works :) Glen > [...] > > Doesn't work, that was the first thing I tried. For some reason Python's not > finding the '\' because it thinks '\300' is a single character rather than > four. > > Even 'print x' will hide the \ in this case. > From highprimate@howlermonkey.net Sun Jan 6 05:11:49 2002 From: highprimate@howlermonkey.net (Kirk D Bailey) Date: Sun, 6 Jan 00:11:49 2002 -0500 Subject: [Tutor] TLlistmaster.py Message-ID: <200201060511.g065Bn502165@ns.howlermonkey.net> To whoever feels like it; I have got TLlistmaster.py almost complete. There is one minor bug in there. Regretfully, it's a tiny little stinkbug and it is driving me crazy(ier). First, take a look at the script as it stands this very instant- page inherently self updates. http://www.howlermonkey.net/TLlistmaster.shtml Second, there is no error code, but it fails to see the presence of the subject line in the pending file. Here is the screen capture from a sample run: (beware wordwrap) ns# ./TLlistmaster.py < testfile From:= highprimate@howlermonkey.net Subject field as extracted:='Re: join highprimate@howlermonkey.net evil-humor 1010287984' CLEANED UP subject line='join highprimate@howlermonkey.net evil-humor 1010287984' command='join' oldfrom='highprimate@howlermonkey.net' listname='evil-humor' Pending action='join testcode@howlermonkey.net testlist3 1010173860' This person wants to join'evil-humor' list! cannot find subject in pending file! ns# I included a LOT of print statements in the program to generate all these status reports. The language's interpeter is not creating ANY errors. I am stumped for the moment, and tired, and battling with a cranky isp, so I think I will smoke a house pipe and drink some fine coniac and go night night, but feel free to look at this, and write me some questions, answers, suggestions, pithy things to double check, evil jokes, etc... So close... SO close... end In total confusion, Kirk D Bailey +----------------------------------------------------+ | Providing Excellent email service for free!! | | Webmaster, Howlermonkey Email services Co. | | highprimate@howlermonkey.net www.howlermonkey.net/ | +----------------------------------------------------+ ODD#1.8.01/kdb/sigme Refill your inkjet cartridges. Same top quality print. Low Low price. Click Here. (They have a nice affiliate program too!) From karthikg@aztec.soft.net Sun Jan 6 07:24:38 2002 From: karthikg@aztec.soft.net (Karthik Gurumurthy) Date: Sun, 6 Jan 2002 12:54:38 +0530 Subject: [Tutor] confused if i should be doing type checking in the code ( a confused java programmer) In-Reply-To: <200201060511.g065Bn502165@ns.howlermonkey.net> Message-ID: hi all, have been doing python for a couple of months now and have been doing java for more than a year now. had trouble implementing immutable constants in python i wanted a public static "final" equivalent in python. class MovieRating: REGULAR = 1 NEW = 2 CHILDREN = 3 Now even though i can access it like MovieRating.REGULAR But someone can modify the value MovieRating.REGULAR = 100 # UnAcceptable I was trying to emulate the java enum equivalent but was not able implement it successfully. class MovieRating{ public static final MovieRating REGULAR = new MovieRating(1) public static final MovieRating NEW = new MovieRating(2) public static final MovieRating CHILDREN = new MovieRating(3) private int value; private MovieRating(int i){ value = i; } } Now the client cannot instantiate MovieRating but can get all the constant instances. so there's a proper type checking in another code which accepts only MovieRating instances instead of just integers. So in python code i needed a singleton and then the immutable constants. Then came across this recipie in Cookbook and Well it's brillaint! i had'nt even imagined such things could be done. http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65207 I used that code and wrote this: class _MovieRating: def __init__(self): self.__dict__['REGULAR'] = 1 self.__dict__['NEW'] = 2 self.__dict__['CHILDREN'] = 3 def __setattr__(self,name,value): if self.__dict__.has_key(name): raise "Cannot assign to a readonly movie rating %s" % (name,) else: raise "Cannot add new constants" import sys sys.modules[__name__] = _Movie() So in java if there's a functon which accepts the movie ratings, void func(MovieRating rating,Click Here. (They have a nice affiliate program too!) _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From karthikg@aztec.soft.net Sun Jan 6 09:00:09 2002 From: karthikg@aztec.soft.net (Karthik Gurumurthy) Date: Sun, 6 Jan 2002 14:30:09 +0530 Subject: [Tutor] scoping rules In-Reply-To: Message-ID: Just wanted to confirm the scoping rules. >>> a = 1298 >>> def func(x): a = 908 def func(x): print "isnide func" print "\tlocals",locals() print "\tglobals",globals() i =123 print "\tlocals again",locals() a+=1 ###statement print a print "ok",locals() func(87) print a i observed the following. When i commented the marked statement inside the inner func, a (908 from the enclosing function's local namespace) was present in the inner function's local namespace. the global a was present in the global namespace.fine. The moment i uncomment it (ie a = a + 1), the reference to "enclosing function's a" from locals() of inner func was removed. BUT, reference to a in the global namespace remained. Then why did'nt it increment the global a? since it is supposed to look up the locals() first and when not found search globals()? instead i got an unbound error. Does it mean that moment we try to add to / manipulate a variable, python expects the variable to be initialized in the function's own local namespace? I mean as long as we are "reading", it is all fine. it worked when i put the flag global a right in the begining of the function. Does this mean that i will not be able to increment a (908) (defined in the enclosing function) inside the inner function? hope i have framed my question properly. thanks karthik. From karthikg@aztec.soft.net Sun Jan 6 13:48:08 2002 From: karthikg@aztec.soft.net (Karthik Gurumurthy) Date: Sun, 6 Jan 2002 19:18:08 +0530 Subject: [Tutor] Am stuck help please In-Reply-To: <200201060511.g065Bn502165@ns.howlermonkey.net> Message-ID: consider a class Movie with static fields. class Movie: REGULAR = 1 CHILDREN = 0 NEW_RELEASE = 2 def __init__(title = 'Gladiator',rating = REGULAR): print rating Now the data for constructing Movie objects come from a text file who contents will be like this: Gladiator:Movie.REGULAR Rain Man:Movie.REGULAR Shrek:Movie.CHILDREN after getting these things out, i construct the movie objects, I store the read data in a dict say titles then i do movies = [apply(Movie,(title,rate)) for title,rate in titles.items()] The PROBLEM! : the value Movie.REGULAR etc are being treated as strings and not int. How do i make the interpreter treat them as ints (rather as static fields of Movie) and send to the constructor?..i mean a neat pythonic way using if-elif and re-assigning the values is fine. am looking for a better way. thanks, karthik. -----Original Message----- From: tutor-admin@python.org [mailto:tutor-admin@python.org]On Behalf Of Kirk D Bailey Sent: Sunday, January 06, 2002 10:42 AM To: tutor@python.org Subject: [Tutor] TLlistmaster.py To whoever feels like it; I have got TLlistmaster.py almost complete. There is one minor bug in there. Regretfully, it's a tiny little stinkbug and it is driving me crazy(ier). First, take a look at the script as it stands this very instant- page inherently self updates. http://www.howlermonkey.net/TLlistmaster.shtml Second, there is no error code, but it fails to see the presence of the subject line in the pending file. Here is the screen capture from a sample run: (beware wordwrap) ns# ./TLlistmaster.py < testfile From:= highprimate@howlermonkey.net Subject field as extracted:='Re: join highprimate@howlermonkey.net evil-humor 1010287984' CLEANED UP subject line='join highprimate@howlermonkey.net evil-humor 1010287984' command='join' oldfrom='highprimate@howlermonkey.net' listname='evil-humor' Pending action='join testcode@howlermonkey.net testlist3 1010173860' This person wants to join'evil-humor' list! cannot find subject in pending file! ns# I included a LOT of print statements in the program to generate all these status reports. The language's interpeter is not creating ANY errors. I am stumped for the moment, and tired, and battling with a cranky isp, so I think I will smoke a house pipe and drink some fine coniac and go night night, but feel free to look at this, and write me some questions, answers, suggestions, pithy things to double check, evil jokes, etc... So close... SO close... end In total confusion, Kirk D Bailey +----------------------------------------------------+ | Providing Excellent email service for free!! | | Webmaster, Howlermonkey Email services Co. | | highprimate@howlermonkey.net www.howlermonkey.net/ | +----------------------------------------------------+ ODD#1.8.01/kdb/sigme Refill your inkjet cartridges. Same top quality print. Low Low price. Click Here. (They have a nice affiliate program too!) _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From karthikg@aztec.soft.net Sun Jan 6 13:50:27 2002 From: karthikg@aztec.soft.net (Karthik Gurumurthy) Date: Sun, 6 Jan 2002 19:20:27 +0530 Subject: [Tutor] RE: Am stuck help please In-Reply-To: Message-ID: sorry! within seconds of sending the mail i got the answer using eval() helped me here. movies = [apply(Movie,(title,eval(rate))) for title,rate in titles.items()] karthik. -----Original Message----- From: karthik Guru [mailto:karthikg@aztec.soft.net] Sent: Sunday, January 06, 2002 7:18 PM To: tutor@python.org Subject: Am stuck help please Importance: High consider a class Movie with static fields. class Movie: REGULAR = 1 CHILDREN = 0 NEW_RELEASE = 2 def __init__(title = 'Gladiator',rating = REGULAR): print rating Now the data for constructing Movie objects come from a text file who contents will be like this: Gladiator:Movie.REGULAR Rain Man:Movie.REGULAR Shrek:Movie.CHILDREN after getting these things out, i construct the movie objects, I store the read data in a dict say titles then i do movies = [apply(Movie,(title,rate)) for title,rate in titles.items()] The PROBLEM! : the value Movie.REGULAR etc are being treated as strings and not int. How do i make the interpreter treat them as ints (rather as static fields of Movie) and send to the constructor?..i mean a neat pythonic way using if-elif and re-assigning the values is fine. am looking for a better way. thanks, karthik. -----Original Message----- From: tutor-admin@python.org [mailto:tutor-admin@python.org]On Behalf Of Kirk D Bailey Sent: Sunday, January 06, 2002 10:42 AM To: tutor@python.org Subject: [Tutor] TLlistmaster.py To whoever feels like it; I have got TLlistmaster.py almost complete. There is one minor bug in there. Regretfully, it's a tiny little stinkbug and it is driving me crazy(ier). First, take a look at the script as it stands this very instant- page inherently self updates. http://www.howlermonkey.net/TLlistmaster.shtml Second, there is no error code, but it fails to see the presence of the subject line in the pending file. Here is the screen capture from a sample run: (beware wordwrap) ns# ./TLlistmaster.py < testfile From:= highprimate@howlermonkey.net Subject field as extracted:='Re: join highprimate@howlermonkey.net evil-humor 1010287984' CLEANED UP subject line='join highprimate@howlermonkey.net evil-humor 1010287984' command='join' oldfrom='highprimate@howlermonkey.net' listname='evil-humor' Pending action='join testcode@howlermonkey.net testlist3 1010173860' This person wants to join'evil-humor' list! cannot find subject in pending file! ns# I included a LOT of print statements in the program to generate all these status reports. The language's interpeter is not creating ANY errors. I am stumped for the moment, and tired, and battling with a cranky isp, so I think I will smoke a house pipe and drink some fine coniac and go night night, but feel free to look at this, and write me some questions, answers, suggestions, pithy things to double check, evil jokes, etc... So close... SO close... end In total confusion, Kirk D Bailey +----------------------------------------------------+ | Providing Excellent email service for free!! | | Webmaster, Howlermonkey Email services Co. | | highprimate@howlermonkey.net www.howlermonkey.net/ | +----------------------------------------------------+ ODD#1.8.01/kdb/sigme Refill your inkjet cartridges. Same top quality print. Low Low price. Click Here. (They have a nice affiliate program too!) _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From urnerk@qwest.net Sun Jan 6 14:45:41 2002 From: urnerk@qwest.net (Kirby Urner) Date: Sun, 06 Jan 2002 06:45:41 -0800 Subject: [Tutor] scoping rules In-Reply-To: References: Message-ID: <4.2.0.58.20020106062225.00ca9860@pop3.norton.antivirus> > >Does this mean that i will not be able to increment a (908) >(defined in the enclosing function) inside the inner function? > >hope i have framed my question properly. > >thanks >karthik. Local variables within a function override any variables of the same name outside the function, unless you use global. Example: >>> def inc(n): n = n + 1 print n >>> n = 10 >>> inc(n) 11 >>> n # n was unchanged 10 But: >>> def inc(): global n n = n + 1 print n >>> n = 10 >>> inc() 11 >>> n # n was changed 11 In general, it's not a great idea to have functions modify global variables as a side effect. A better approach is have all necessary inputs passed as arguments and all outputs returned via the return statement. For example: >>> def func(x): a = 908 def inc(x): print "isnide func" print "\tlocals",locals() print "\tglobals",globals() i =123 print "\tlocals again",locals() x+=1 ###statement return x print "ok",locals() a = inc(a) print a Here the value to be modified comes through the "front door" as an argument, and is returned through the "back door" as a returned value, which is rebound to variable 'a', duly incremented. The inc() function produces no side effects (i is thrown away), unless we count the prints to stdout. But of course part of the reason for including a function inside another function is you might want to take advantage of one or more constants in the enclosing scope. This you can do: >>> def func(): constant = 908 def inc(x): x+= constant return x print "ok",locals() a = 87 a = inc(a) return a >>> func() ok {'constant': 908, 'inc': } 995 Here you are not rebinding constant by assignment, merely making use of it as a part of the enclosing scope. The inner function has no problem with this, and this is part of the incentive for enclosing functions inside of functions: you get to treat the local scope of the outer function as part of the global scope (but in this example, in a way which doesn't try to modify global variables through side effects). Kirby From urnerk@qwest.net Sun Jan 6 14:54:22 2002 From: urnerk@qwest.net (Kirby Urner) Date: Sun, 06 Jan 2002 06:54:22 -0800 Subject: [Tutor] Am stuck help please In-Reply-To: References: <200201060511.g065Bn502165@ns.howlermonkey.net> Message-ID: <4.2.0.58.20020106065249.00c402c0@pop3.norton.antivirus> > >The PROBLEM! : the value Movie.REGULAR etc are being treated as strings and >not int. >>> class Movie: REGULAR = 1 CHILDREN = 0 NEW_RELEASE = 2 def __init__(self,title,rating=REGULAR): self.title = title self.rating = eval(rating) >>> o = apply(Movie,("Shrek","Movie.CHILDREN")) >>> o.title 'Shrek' >>> o.rating 0 Kirby From arcege@speakeasy.net Sun Jan 6 15:04:43 2002 From: arcege@speakeasy.net (Michael P. Reilly) Date: Sun, 6 Jan 2002 10:04:43 -0500 Subject: [Tutor] confused if i should be doing type checking in the code ( a confused java programmer) In-Reply-To: ; from karthikg@aztec.soft.net on Sun, Jan 06, 2002 at 12:54:38PM +0530 References: <200201060511.g065Bn502165@ns.howlermonkey.net> Message-ID: <20020106100443.J901@speakeasy.net> On Sun, Jan 06, 2002 at 12:54:38PM +0530, Karthik Gurumurthy wrote: > hi all, > > have been doing python for a couple of months now and have been doing java > for more than a year now. > > had trouble implementing immutable constants in python There are no 'immutable constants' (a bit redundant? *chuckle*) in Python. Like in most languages, Python will let you do what you want. There is a lot of extra processing that must occur to get security (cf. Ada). Python decided to take a more co-operative approach to programming - it is the developers responsibility not to break the code. Most people figure out pretty quickly that you do go attempting to change things that a) you don't know what it does, and b) when you do know, that will break it. The idea here with Python was "we won't stop you changing it, because if you are, then you probably want to handling what happens when it breaks yourself." > i wanted a public static "final" equivalent in python. > > class MovieRating: > REGULAR = 1 > NEW = 2 > CHILDREN = 3 > > Now even though i can access it like > > MovieRating.REGULAR > But someone can modify the value > > MovieRating.REGULAR = 100 # UnAcceptable You might think about class MovieRating: (REGULAR, NEW, CHILDREN) = range(1, 4) > I was trying to emulate the java enum equivalent but was not able > implement it successfully. > > class MovieRating{ > > public static final MovieRating REGULAR = new MovieRating(1) > public static final MovieRating NEW = new MovieRating(2) > public static final MovieRating CHILDREN = new MovieRating(3) > > private int value; > > private MovieRating(int i){ > value = i; > } > } > > Now the client cannot instantiate MovieRating but can get all the constant > instances. > so there's a proper type checking in another code which accepts only > MovieRating instances > instead of just integers. > > So in python code i needed a singleton and then the immutable constants. > Then came across this recipie in Cookbook and Well it's brillaint! > i had'nt even imagined such things could be done. > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65207 > > I used that code and wrote this: > > class _MovieRating: > def __init__(self): > self.__dict__['REGULAR'] = 1 > self.__dict__['NEW'] = 2 > self.__dict__['CHILDREN'] = 3 > def __setattr__(self,name,value): > if self.__dict__.has_key(name): > raise "Cannot assign to a readonly movie rating %s" % (name,) > else: > raise "Cannot add new constants" You might also want to add a __delattr__ method. Since I could go with "del _MovieRating.NEW" and get no exception. > import sys > sys.modules[__name__] = _Movie() I was talking about 'Python letting you change what you like' above. This is a perfect example of this. You are changing an internal structure that in a 'security conscious' language like Java, would not be permitted. But because Python lets you, you can make your program import a class instead of a module. (Incidently, for consistancy, you might want to add '_MovieRating.__name__ = __name__' to make sure that the module name is the same as the class name when you go to check things. But you doing this will also have to risk breaking reload() code. If that is an acceptable risk, then there's nothing wrong. Otherwise, you might have to handle that (reload will only work with a module object). > So in java if there's a functon which accepts the movie ratings, > > void func(MovieRating rating, > } > > We have been taught to use enum pattern in java to store constants instead > of primtives like > ints or strings because we get the benefit of type checking in the compile > stage itself and no one > can send in a wrong rating value. They added enums to C thirty years ago. They were rarely ever used. Programmers decided to use CPP #define's instead. There were a number of reasons why. My point is: just because one language uses a construct, it does not mean it is necessary the way you should do it in another language. Feel free to use Python's features, and not be constrainted by how you have used other languages. :) > Since this kind of a things cannot be done in python ,should i be writing > this kind of code in python as well?? > > def func(rating,x) > if type(rating) != MovieRating: > raise 'You have passed an Incorrect type' > > if i do that then all my python functions and methods will be littered with > such type checking code! There is nothing stopping you from doing this, but you should use isinstance instead. It will handle instances from subclasses better. But also, let's say that you have something you want to add later, how about a HotelRating. Then you'll have to change all your code to make sure that you handle the types properly. What you might want to think about is to have a general 'Rating' - what ideas are important to capture about a rating. Then make sure you use the objects based on those ideas. Trust your program and the developer to co-operate with each other. > even after a couple of months of python..i think i have not been able to > understand the differences in the way > you code in java and python! :-( > probably am missing something here..the purpose of the 2 languages appear to > be very different to me now. I'd say that you are correct, the purposes of the languages are different. Java was designed as a strongly typed, platform-independent language that was similar, but 'better' than C++. Python was designed with a very different idea - a language with a simple, concise syntax that is powerful enough to do what you would like from a high-level language. > anyways, > i took a look at the __slots__ concept as well which i guess does not allow > us to add attributes to an instance. > I saw a recipe for writing properties. That was smart! > But now python supports properties at syntax level. I tried that out with > py2.2 > > Then what prevents python from having a final equivalent when we could have > such nice things like properties? Yes, 'properties', as a construct, were added in Python 2.2. But they were there before. Just that the coding of them was a little less clear before (this is debatable, I found that the added properties just made things more confusing for people), or more explicit depending on how you thought of the idea of 'properties'. Before Python 2.2, one way you could have __slot__ properties is with: class Slot-Mixin: def slotinit(self): # called by __init__() self.__dict__['slots'] = {} for slotname in self.__class__.__slots__: self.slots[slotname] = None def __getattr__(self, attr): if attr in self.__slots__: return self.slots[attr] else: raise AttributeError(attr) def __setattr__(self, attr, value): if attr in self.__slots__: self.slots[attr] = value else: self.__dict__[attr] = value def __delattr__(self, attr): if attr in self.__slots__: raise AttributeError("cannot delete slot property") else: del self.__dict__[attr] And for the 'get_' and 'set_' methods, you could do this by adding another test to each of the methods. It gets complicated when you have subclasses, but then, that is why we wanted the new attribute methods. :) The point here is that these mechanisms are used in other languages, and they are not always needed in Python. Sometimes there are ways that just takes some exposure and alternate programming to figure out. -Arcege From Charlie@begeistert.org Sun Jan 6 16:25:53 2002 From: Charlie@begeistert.org (Charlie Clark) Date: Sun, 06 Jan 2002 17:25:53 +0100 Subject: [Tutor] Trapping exceptions in batch scripts Message-ID: <1010334353_PM_BeOS.Charlie@begeistert.org> Dear all, I have a collection of scripts (about) which are scheduled to run repeatedly. As there are occasionally errors I need to catch the exceptions and have decided to write an external script which simply runs other scripts and logs any errors. I thought this would be better than trying to implement error handling in each script but would appreciate comments on this. script_runner.py takes the last command line argument as the name of the script to be run. There seems to be two ways of actually running a script either by importing it or by using execfile Import has to be called via __import__ as it is not possible to pass a variable to import. This seems somewhat clumsy but when I tried execfile I got some confusing error messages claiming that names weren't properly defined. The scripts themselves ran fine but occasionally produced name errors when run using execfile. I've read that execfile is very similar to __import__ except that is doesn't create any modules. I'm not sure what this means but I can imagine it has something to do with namespaces. Would be grateful for an explanation. Charlie From dajoy@operamail.com Sun Jan 6 17:10:52 2002 From: dajoy@operamail.com (Daniel Ajoy) Date: Sun, 6 Jan 2002 12:10:52 -0500 Subject: [Tutor] Re: A small math puzzle [recreational Python] Message-ID: <3C39041C@operamail.com> I believe these are the values (84): ETERAS ETESAR ETEARS ETSRAE ETSARE ETSAER ETARES ETASRE ETASER ERTSAE ERTAES ERETAS ERESAT EREATS ERSTAE ERSATE ERSAET ERATES ERASTE ERASET ESTRAE ESTARE ESTAER ESETAR ESERAT ESEATR ESEART ESATRE ESATER ESARTE ESARET EATRES EATSRE EATSER EAETRS EAERTS EAESTR EAESRT EASTRE EASTER EASRTE EASRET RTESAE RTEAES RTSAEE RTASEE RSTAEE RSETAE RSEATE RSEAET RSATEE RATSEE RAETES RAESTE RAESET RASTEE STERAE STEARE STEAER STAREE SRTAEE SRETAE SREATE SREAET SRATEE SATREE SAETRE SAETER SAERTE SAERET ATERES ATESRE ATESER ATSREE ARTSEE ARETES ARESTE ARESET ARSTEE ASTREE ASETRE ASETER ASERTE ASERET Sorry I used something else to solve the problem, but you might check your Python solution against mine. Daniel From karthikg@aztec.soft.net Sun Jan 6 18:42:39 2002 From: karthikg@aztec.soft.net (Karthik Gurumurthy) Date: Mon, 7 Jan 2002 00:12:39 +0530 Subject: [Tutor] module Cyclic references In-Reply-To: Message-ID: hi all, my code is behaving in a strange way. I have 4 modules test.py -- > from movie import Movie, Rental movie.py --> has 2 classes Movie , Rental #needs price and hence does import price price.py --> needs Movie #does from movie import Movie, Rental cust.py --> has one class Customer so this is the sequence. test-->loads movie --> load price which in turn needs movie. Can someone tell me what's wrong here?? >>> import test Traceback (most recent call last): File "", line 1, in ? File "test.py", line 1, in ? from movie import Movie, Rental File "movie.py", line 1, in ? import price File "price.py", line 1, in ? from movie import Movie, Rental ImportError: cannot import name Movie >>> This sequence works just fine! >>> import price >>> import movie >>> import cust >>> import test thanks karthik. -----Original Message----- From: python-list-admin@python.org [mailto:python-list-admin@python.org]On Behalf Of marco Sent: Saturday, December 22, 2001 5:48 AM To: python-list@python.org Subject: Re: vi or emacs for editing Python on Linux? "maxm" writes: > One of my biggest problems in switching is my editor. On windows I use > Ultraedit as a general editor, and i type really fast in it. Knowing the > shortcuts and all. Every time I boot up one of my Linux machines I have a > hard time editing files under the arcane unix editors. I have tried both > emacs and vim and I disklike both! Maybe Nedit is good for Windows people: www.nedit.org (but I use emacs myself -- those "arcane" editors are tried and true). -- mdlch@altavista.net Gunnm: Broken Angel http://reimeika.ca/ -- http://mail.python.org/mailman/listinfo/python-list From toodles@yifan.net Sun Jan 6 18:29:12 2002 From: toodles@yifan.net (Andy W) Date: Mon, 7 Jan 2002 02:29:12 +0800 Subject: [Tutor] Re: A small math puzzle [recreational Python] References: <3C39041C@operamail.com> Message-ID: <001701c196e0$0b7c22d0$0300a8c0@sun> > I believe these are the values (84): Hmm, both my and Danny Yoo's solutions gave 168 distinct rearrangements (or derangements, or whatever!). I'll do a quick check, by removing all the words you have supplied from the derangements my function provides, and see if the remaining words are in fact derangements. ...a couple of minutes later... This is what I got back after removing the words:- ['ATSREE', 'ATESER', 'ATESRE', 'ATERES', 'ASTREE', 'ASERET', 'ASERTE', 'ASETRE', 'ASETER', 'ARETES', 'ARESTE', 'ARESET', 'ARTSEE', 'ARSTEE', 'SATREE', 'SAERET', 'SAERTE', 'SAETRE', 'SAETER', 'SRETAE', 'SREATE', 'SREAET', 'SRTAEE', 'SRATEE', 'STAREE', 'STEAER', 'STEARE', 'STERAE', 'RTASEE', 'RTSAEE', 'RTESAE', 'RTEAES', 'RATSEE', 'RASTEE', 'RAETES', 'RAESTE', 'RAESET', 'RSATEE', 'RSETAE', 'RSEATE', 'RSEAET', 'RSTAEE', 'ERESAT', 'ERETAS', 'EREATS', 'ERTAES', 'ERTSAE', 'ERATES', 'ERASTE', 'ERASET', 'ERSATE', 'ERSAET', 'ERSTAE', 'ETARES', 'ETASRE', 'ETASER', 'ETSARE', 'ETSAER', 'ETSRAE', 'ETESAR', 'ETERAS', 'ETEARS', 'EATRES', 'EATSRE', 'EATSER', 'EASTRE', 'EASTER', 'EASRET', 'EASRTE', 'EAESTR', 'EAESRT', 'EAERTS', 'EAETRS', 'ESATRE', 'ESATER', 'ESARET', 'ESARTE', 'ESEATR', 'ESEART', 'ESERAT', 'ESETAR', 'ESTRAE', 'ESTARE', 'ESTAER'] Must be something wrong, as these are derangements. HTH Andy W > > ETERAS ETESAR ETEARS ETSRAE ETSARE ETSAER ETARES > ETASRE ETASER ERTSAE ERTAES ERETAS ERESAT EREATS > ERSTAE ERSATE ERSAET ERATES ERASTE ERASET ESTRAE > ESTARE ESTAER ESETAR ESERAT ESEATR ESEART ESATRE > ESATER ESARTE ESARET EATRES EATSRE EATSER EAETRS > EAERTS EAESTR EAESRT EASTRE EASTER EASRTE EASRET > RTESAE RTEAES RTSAEE RTASEE RSTAEE RSETAE RSEATE > RSEAET RSATEE RATSEE RAETES RAESTE RAESET RASTEE > STERAE STEARE STEAER STAREE SRTAEE SRETAE SREATE > SREAET SRATEE SATREE SAETRE SAETER SAERTE SAERET > ATERES ATESRE ATESER ATSREE ARTSEE ARETES ARESTE > ARESET ARSTEE ASTREE ASETRE ASETER ASERTE ASERET > > > Sorry I used something else to solve the problem, but > you might check your Python solution against mine. > > Daniel > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From toodles@yifan.net Sun Jan 6 18:37:42 2002 From: toodles@yifan.net (Andy W) Date: Mon, 7 Jan 2002 02:37:42 +0800 Subject: [Tutor] module Cyclic references References: Message-ID: <002101c196e1$3b56d940$0300a8c0@sun> > hi all, Hi > my code is behaving in a strange way. Goody, I like strange things. *gets to the task at hand* > >>> import test > Traceback (most recent call last): > File "", line 1, in ? > File "test.py", line 1, in ? > from movie import Movie, Rental > File "movie.py", line 1, in ? > import price > File "price.py", line 1, in ? > from movie import Movie, Rental > ImportError: cannot import name Movie > >>> > > This sequence works just fine! > >>> import price > >>> import movie > >>> import cust > >>> import test Umm this sounds too simple to be true, but is there a typo or something? Unless I'm totally wrong, and someone smarter and more brilliant comes up with a different answer, can you please do the following: ### import movie print dir(movie) ### and then email again what it comes up with. Andy W > > thanks > karthik. > > -----Original Message----- > From: python-list-admin@python.org > [mailto:python-list-admin@python.org]On Behalf Of marco > Sent: Saturday, December 22, 2001 5:48 AM > To: python-list@python.org > Subject: Re: vi or emacs for editing Python on Linux? > > > "maxm" writes: > > > One of my biggest problems in switching is my editor. On windows I use > > Ultraedit as a general editor, and i type really fast in it. Knowing the > > shortcuts and all. Every time I boot up one of my Linux machines I have a > > hard time editing files under the arcane unix editors. I have tried both > > emacs and vim and I disklike both! > > Maybe Nedit is good for Windows people: www.nedit.org > (but I use emacs myself -- those "arcane" editors are > tried and true). > > -- > mdlch@altavista.net > Gunnm: Broken Angel > http://reimeika.ca/ > -- > http://mail.python.org/mailman/listinfo/python-list > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From karthikg@aztec.soft.net Sun Jan 6 19:00:49 2002 From: karthikg@aztec.soft.net (Karthik Gurumurthy) Date: Mon, 7 Jan 2002 00:30:49 +0530 Subject: [Tutor] module Cyclic references In-Reply-To: <002101c196e1$3b56d940$0300a8c0@sun> Message-ID: thanks Andy this is what am getting the error is being signalled by price.py which has from movie import Movie, Rental as the first line >>> import movie Traceback (most recent call last): File "", line 1, in ? File "movie.py", line 1, in ? import price File "price.py", line 1, in ? from movie import Movie, Rental ImportError: cannot import name Movie >>> -----Original Message----- From: tutor-admin@python.org [mailto:tutor-admin@python.org]On Behalf Of Andy W Sent: Monday, January 07, 2002 12:08 AM To: python-list@python.org Cc: tutor@python.org Subject: Re: [Tutor] module Cyclic references > hi all, Hi > my code is behaving in a strange way. Goody, I like strange things. *gets to the task at hand* > >>> import test > Traceback (most recent call last): > File "", line 1, in ? > File "test.py", line 1, in ? > from movie import Movie, Rental > File "movie.py", line 1, in ? > import price > File "price.py", line 1, in ? > from movie import Movie, Rental > ImportError: cannot import name Movie > >>> > > This sequence works just fine! > >>> import price > >>> import movie > >>> import cust > >>> import test Umm this sounds too simple to be true, but is there a typo or something? Unless I'm totally wrong, and someone smarter and more brilliant comes up with a different answer, can you please do the following: ### import movie print dir(movie) ### and then email again what it comes up with. Andy W > > thanks > karthik. > > -----Original Message----- > From: python-list-admin@python.org > [mailto:python-list-admin@python.org]On Behalf Of marco > Sent: Saturday, December 22, 2001 5:48 AM > To: python-list@python.org > Subject: Re: vi or emacs for editing Python on Linux? > > > "maxm" writes: > > > One of my biggest problems in switching is my editor. On windows I use > > Ultraedit as a general editor, and i type really fast in it. Knowing the > > shortcuts and all. Every time I boot up one of my Linux machines I have a > > hard time editing files under the arcane unix editors. I have tried both > > emacs and vim and I disklike both! > > Maybe Nedit is good for Windows people: www.nedit.org > (but I use emacs myself -- those "arcane" editors are > tried and true). > > -- > mdlch@altavista.net > Gunnm: Broken Angel > http://reimeika.ca/ > -- > http://mail.python.org/mailman/listinfo/python-list > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From deliberatus@my995internet.com Sun Jan 6 18:49:22 2002 From: deliberatus@my995internet.com (kirk Bailey) Date: Sun, 06 Jan 2002 13:49:22 -0500 Subject: [Tutor] Last module hangup References: Message-ID: <3C389C32.C06B3CFD@netzero.net> Gang, still seeking a clue about this last module's error message. Note I have a new email address on this list- old one, just using it again now that my current isp decided to FUCK UP ROYALLY, pardon the French please. TLlistmaster.py still throws an error, and it befuddles me. http://www.howlermonkey.net/TLlistmaster.shtml will list the current script. -- -Respectfully, -Kirk D Bailey end ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ |___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___| | _ \___ __ _ __| |_(_)_ _ __ _| |_| |_ ___ / __/ _ \| \| | | / _ Y _` (_-< _| | ' \/ _` | _| ' \/ -_) (_| (_) | .` |_ |_|_\___|__,_/__/\__|_|_||_\__, |\__|_||_\___|\___\___/|_|\_( ) |___/ |/ Kirk Bailey, consulting loose cannon www.howlermonkey.net highprimate@howlermonkey.net http://gipco.webjump.com idiot1@netzero.net _ _ _ _ ___ _ _ ___ _ _ _ _| |_ __ _| |_ __ _| |_(_)_ __ ___ / _ \ ' \/ -_) ' \ || | _/ _` | _/ _` | _| | ' \/ -_)_ \___/_||_\___|_||_\_,_|\__\__,_|\__\__,_|\__|_|_|_|_\___(_)_ ___ |___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___| ---------------------------------------------------- Sign Up for NetZero Platinum Today Only $9.95 per month! http://my.netzero.net/s/signup?r=platinum&refcd=PT97 From Bob@talktext.com Sun Jan 6 18:58:08 2002 From: Bob@talktext.com (Bob Dempsey) Date: Sun, 6 Jan 2002 13:58:08 -0500 Subject: [Tutor] DNS 6.0 Message-ID: <000001c196e4$151bd520$754c9e18@veronica> This is a multi-part message in MIME format. ------=_NextPart_000_0001_01C196BA.2C45CD20 Content-Type: text/plain; charset="us-ascii" Content-Transfer-Encoding: 7bit And does anyone know it python will work with NaturallySpeaking 6.0 professional yet? I sure hope and does for or it will one day soon! Regards, Bob ------=_NextPart_000_0001_01C196BA.2C45CD20 Content-Type: text/html; charset="us-ascii" Content-Transfer-Encoding: quoted-printable DNS 6.0

And does = anyone know it python will work = with NaturallySpeaking 6.0 professional = yet?

I sure = hope and does = for = or it = will one day = soon!

Regards, = Bob

------=_NextPart_000_0001_01C196BA.2C45CD20-- From alan.gauld@bt.com Sun Jan 6 19:53:32 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Sun, 6 Jan 2002 19:53:32 -0000 Subject: [Tutor] A small math puzzle [recreational Python] Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C231@mbtlipnt02.btlabs.bt.co.uk> > OK. I generally assume that a newbie has no ties to the > past and will naturally want to use the latest and > greatest Python. Yeah, but they won't stay that way for long... Pretty soon they'll regress to the last version not the current! ;-) Seriously, many of the newbie books on the market (including mine) are based around 1.5.2 or maybe v2.0. So beginners are quite likely to be using older versions. And as you say professionals will most likely be on older versions for all sorts of reasons, not least the desire not to be on the bleeding edge. > advice to all newcomers: don't waste your time with anything > less than Python 2.1, if you're not locked into such a > restriction by your paying job. It could be a CGI web server restriction too. Personally I'm reading about 2.2 but still using 2.1 (and I'm now onto v2.0 at work). Alan g From alan.gauld@bt.com Sun Jan 6 20:28:46 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Sun, 6 Jan 2002 20:28:46 -0000 Subject: [Tutor] confused if i should be doing type checking in the co de ( a confused java programmer) Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C233@mbtlipnt02.btlabs.bt.co.uk> Hi Karthik, > have been doing python for a couple of months now and have > been doing java for more than a year now. You have my sympathy, Java is a truly dreadful language. > had trouble implementing immutable constants in python Yep, you can do it by playing tricks with classes to implement singletons etc but its not really necessary. Bjarne Strtoustrup used to say when Smalltalkers criticised C++ : "If you want to program in Smalltalk then use Smalltalk not C++" Every language has its own idioms and Python is a dynamic language wheras Java is a static, strictly types language. There are lots of things you can do in Python that you can't do in Java and vice versa, thats always the way with programming languages. Don't get hung up on translating every single feature, learn the strong points of each language and use them to best effect. Accept the weaknesses, you'll get less grey hair that way. > i wanted a public static "final" equivalent in python. Why exactly? Are you so lacking in discipline that you won't observe a naming convention say? If so adopt a functional style of programming, that will save you from making any such mistakes... Or is it maybe just that you are used to that level of hand holding from Java? > class MovieRating: > REGULAR = 1 > NEW = 2 > CHILDREN = 3 Why not use a dictionary? Unless you are also writing methods to manipulate movie ratings a dictionary would be a more natural way to express this: MovieRating = {'REGULAR':1, 'NEW':2,'CHILDREN':3) Now access via: MovieRating['Regular'] You can still change it but its a more Pythonic approach IMHO. > MovieRating.REGULAR = 100 # UnAcceptable Yes, but if you comment (or better document) the fact that you shouldn't change uppercased values(a fairly common convention) then why would anyone sanely ever do so? (OK I know they might not read the docs! But programming by "contract" or convention is not that unusual) > Now the client cannot instantiate MovieRating but can get all > the constant instances. Which aren't really instances at all nor is the MovieRating really a class in the OO sense, thats what I meant earlier about Java being a bad language. It encourages programmers to use classes to do all sorts of really BAD things to the Object Model. > Then came across this recipie in Cookbook and Well it's brillaint! > i had'nt even imagined such things could be done. Yes thats the clever stuff with classes. Its open and extensible, its Python(and Lisp and Smalltalk and Perl and...) It also opens the way to lots of things that are really difficult in Java or C++. And with the new support for metaclasses and classmethods in PythonV2.2 things get even more interesting. > We have been taught to use enum pattern in java to store > constants instead of primtives like ints or strings because > we get the benefit of type checking in the compile > stage itself and no one can send in a wrong rating value. Says more about Javas compiler (and the stupid distinction between primitives and classes) than anything else! > Since this kind of a things cannot be done in python ,should > i be writing this kind of code in python as well?? > > def func(rating,x) > if type(rating) != MovieRating: > raise 'You have passed an Incorrect type' In the few cases when you do need to check types yes, but usually its better to write generic functions that can accept almost any type then catch the exceptions with: try: #doit here except TypeError: # oops! that wont work > understand the differences in the way > you code in java and python! :-( Don't worry about it, it always takes a wee while. But also don't try to do too literal a translation, understand that each will have its own stengths and weaknesses. Alan g. (Who writes in Python for fun and profit and in Java only when my customer insists!) From dsh8290@rit.edu Sun Jan 6 21:06:00 2002 From: dsh8290@rit.edu (dman) Date: Sun, 6 Jan 2002 16:06:00 -0500 Subject: [Tutor] Escape characters in strings In-Reply-To: References: <20020106002354.GA15140@localhost> Message-ID: <20020106210600.GC22531@localhost> On Sat, Jan 05, 2002 at 09:22:12PM -0500, Grimmtooth wrote: | | > | Example: | > | | > | 12/13 14:04:53 2> S:L.TG23 Y1 12007030050020C100021340 | > | 12/13 14:04:53 2> S:12888888881003030000000001249000212011213140434210 | > | 12/13 14:04:53 2> S:10125414C200344012888888881=0512101543211234567800 | > | 12/13 14:04:53 2> S:1 700000000740 0242C00000000000000EN00420107 | > | 12/13 14:04:53 2> S:6O02450U300001000\300009990\000000000999\950U30000 | > | 12/13 14:04:53 2> S:1000\300002500\000000000250. | > | > Is this from a log file? How are you reading the data? Can you show | > us the code? | | 1) Yes and no. | | 2) (a) either the user pastes this data into a wxWindows Text Control then I | GetValue() it I can't test this out since I don't know enough of wx to whip up a window with a text control. I expect that the text control would give you back each character unscathed. | or else it is read from a logfile directly using readlines() | into an array. Technically it is a 'list', but anyways, it works for me. I created a file containing ----- foo\300bar ---- $ python2.1 Python 2.1.1+ (#1, Dec 30 2001, 17:17:30) [GCC 2.95.4 20011223 (Debian prerelease)] on linux2 Type "copyright", "credits" or "license" for more information. >>> f = open( "data" , "r" ) >>> print f.readlines() ['foo\\300bar\n'] >>> The "extra" backslash in the output is to indicate that a real backslash is in the string. | In the current case, I've hardcoded the text in using a """ | triple-quoted string. This is going to be problematic -- any string literal in python source is eval()ed. You want to be sure and use a 'raw' string in your python source, or put the test data into a file. | The problem occurs no matter which way it goes. You've tested all three data input methods? Can you make my code above fail? | 3) I could, but it would be a lot of code. Let me paraphrase it: | | first, get code from text control or log file. | | then, using a function Stitch(), I locate all lines beginning with S: | after the 2> by first slicing [] them out then concatenating them together | with '+'. This returns one continuous string. | | for i in s: | x = i[18:-1] # first 18 are time stamp, last is CR. Trim both. | | if len(x) > 0: | if x[0] == 'S': | snd.append(x) | | then, I pass the string to a Parser class. This in turn slices out | particular parts of the long string and assigns them to additional classes, | each designed to parse the particular data it is passed. | | class BaseElement: | def __init__(self, parent): | pass | | def Show(self): | pass | | class AdditionalAmounts(BaseElement): | | data = None | | def __init__(self, parent, txt): | self.data, parent.remainder = lllvar(txt) | | | def llvar(data): | len = int(data[:2]) | return(data[2:len+2], data[len+2:]) | | | the BaseElement class is an empty, defined to give me a None if I don't | override the __init__ and Show methods. Assuming that I've sliced off | everything prior to the part of interest already (which I have), the above | code fragments are the ones that get processed. First, the string is passed | to AdditionalAmounts.__init__(). __init__() calls llvar() to seperate the | data and from the remainder of the log entry (an llvar is a data field that | is preceded by two digits indicating how many bytes the data contains). The | process of actually processing the data is where I end up tripping over the | escaped \ characters. I don't see anything in the code above that would cause python to evaluate the string you have. | > If you do want to eval() the string you can replace( "\\" , "\\\\" ) | > to escape all backslashes first. | | Doesn't work, that was the first thing I tried. For some reason | Python's not finding the '\' because it thinks '\300' is a single | character rather than four. | | Even 'print x' will hide the \ in this case. I can achieve this with >>> print '\300' À >>> because that string is part of the code. However if I change the code to >>> print '\\300' \300 >>> print r'\300' \300 >>> I get the desired result. HTH, -D PS. It would be quite useless if the interpreter was constantly evaluating string data you are working with according to it's source code rules. -- If any of you lacks wisdom, he should ask God, who gives generously to all without finding fault, and it will be given to him. But when he asks he must believe and not doubt, because he who doubts is like a wave of the sea, blown and tossed by the wind. James 1:5-6 From dsh8290@rit.edu Sun Jan 6 21:09:54 2002 From: dsh8290@rit.edu (dman) Date: Sun, 6 Jan 2002 16:09:54 -0500 Subject: [Tutor] DNS 6.0 In-Reply-To: <000001c196e4$151bd520$754c9e18@veronica> References: <000001c196e4$151bd520$754c9e18@veronica> Message-ID: <20020106210954.GD22531@localhost> On Sun, Jan 06, 2002 at 01:58:08PM -0500, Bob Dempsey wrote: | And does anyone know it python will work with NaturallySpeaking 6.0 | professional yet? Oh, I was wondering what Domain Name Service 6.0 was :-). | I sure hope and does for or it will one day soon! In what way do you want it to work? Do you want to be able to dictate the code? I hope you can dictate text to put in a file, and python doesn't care where files the files come from. I don't know what would be needed to hook NaturallySpeaking's output to python's stdin (as in standard unix technique of piping). I can't imagine that coding (all that punctuation and stuff) could be easier by voice than by keyboard. -D -- Thy Word is a lamp unto my feet and a light unto my path. Psalms 119:105 From dsh8290@rit.edu Sun Jan 6 21:14:51 2002 From: dsh8290@rit.edu (dman) Date: Sun, 6 Jan 2002 16:14:51 -0500 Subject: [Tutor] scoping rules In-Reply-To: References: Message-ID: <20020106211451.GE22531@localhost> First: Karthik, can you please ask new questions by creating a new mail message instead of replying to an existing one? I tend to lose your questions in the middle of other threads. On Sun, Jan 06, 2002 at 02:30:09PM +0530, Karthik Gurumurthy wrote: | | Just wanted to confirm the scoping rules. | | >>> a = 1298 | >>> def func(x): | a = 908 | def func(x): | print "isnide func" | print "\tlocals",locals() | print "\tglobals",globals() | i =123 | print "\tlocals again",locals() | a+=1 ###statement | print a | print "ok",locals() | func(87) | print a | | i observed the following. | | When i commented the marked statement inside the inner func, | a (908 from the enclosing function's local namespace) was present in the | inner function's local namespace. | the global a was present in the global namespace.fine. | | The moment i uncomment it (ie a = a + 1), the reference to "enclosing | function's a" from locals() of | inner func was removed. | | BUT, reference to a in the global namespace remained. Then why did'nt it | increment the global a? | since it is supposed to look up the locals() first and when not found search | globals()? | instead i got an unbound error. | | Does it mean that moment we try to add to / manipulate a variable, python | expects the variable to | be initialized in the function's own local namespace? I mean as long as we | are "reading", it is all fine. | | it worked when i put the flag global a right in the begining of the | function. | | Does this mean that i will not be able to increment a (908) (defined in the | enclosing function) | inside the inner function? You are right. Here's what's going on : When you have an assignment statement, a new local variable is created. The compiler (with the nested scopes modifications) will flag those names as being local. When you have the "a+=1" line the compiler sees that 'a' is a local variable. Thus you get the "UnboundLocal" error when you try and reference 'a' (to get it's original value). If you say 'global' it works only because 'a' is at the module level. If you say 'global a' and then assign to 'a', 'a' is going to be at the module level. For example this won't work : def f() : a = 908 def g() : global a a+=1 g() f() The limitation with nested scopes is that you can't assign to any variable that is not local or global (module-level). The problem is: how will the compiler know which scope you want to assign in? In C/C++/Java it is known based on variable declarations, but python doesn't have that. HTH, -D -- "GUIs normally make it simple to accomplish simple actions and impossible to accomplish complex actions." --Doug Gwyn (22/Jun/91 in comp.unix.wizards) From dyoo@hkn.eecs.berkeley.edu Sun Jan 6 22:10:47 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 6 Jan 2002 14:10:47 -0800 (PST) Subject: [Tutor] Re: A small math puzzle [recreational Python] In-Reply-To: <001701c196e0$0b7c22d0$0300a8c0@sun> Message-ID: On Mon, 7 Jan 2002, Andy W wrote: > > I believe these are the values (84): > > Hmm, both my and Danny Yoo's solutions gave 168 distinct > rearrangements (or derangements, or whatever!). I'll do a quick check, > by removing all the words you have supplied from the derangements my > function provides, and see if the remaining words are in fact > derangements. > > ...a couple of minutes later... > > This is what I got back after removing the words:- > > ['ATSREE', 'ATESER', 'ATESRE', 'ATERES', 'ASTREE', 'ASERET', 'ASERTE', > 'ASETRE', 'ASETER', 'ARETES', 'ARESTE', 'ARESET', 'ARTSEE', 'ARSTEE', > 'SATREE', 'SAERET', 'SAERTE', 'SAETRE', 'SAETER', 'SRETAE', 'SREATE', > 'SREAET', 'SRTAEE', 'SRATEE', 'STAREE', 'STEAER', 'STEARE', 'STERAE', > 'RTASEE', 'RTSAEE', 'RTESAE', 'RTEAES', 'RATSEE', 'RASTEE', 'RAETES', > 'RAESTE', 'RAESET', 'RSATEE', 'RSETAE', 'RSEATE', 'RSEAET', 'RSTAEE', > 'ERESAT', 'ERETAS', 'EREATS', 'ERTAES', 'ERTSAE', 'ERATES', 'ERASTE', > 'ERASET', 'ERSATE', 'ERSAET', 'ERSTAE', 'ETARES', 'ETASRE', 'ETASER', > 'ETSARE', 'ETSAER', 'ETSRAE', 'ETESAR', 'ETERAS', 'ETEARS', 'EATRES', > 'EATSRE', 'EATSER', 'EASTRE', 'EASTER', 'EASRET', 'EASRTE', 'EAESTR', > 'EAESRT', 'EAERTS', 'EAETRS', 'ESATRE', 'ESATER', 'ESARET', 'ESARTE', > 'ESEATR', 'ESEART', 'ESERAT', 'ESETAR', 'ESTRAE', 'ESTARE', 'ESTAER'] > > Must be something wrong, as these are derangements. No, no, he's right! We're double counting! We got caught by the two E letters, so that every unique permutation gets generated twice. To fix the problem, we need to make sure to take our list of rearrangements and filter out the unique elements. Here's my corrected code: ### from __future__ import generators import string def permIter(seq): """Given some sequence 'seq', returns an iterator that gives all permutations of that sequence.""" ## Base case if len(seq) == 1: yield(seq[0]) raise StopIteration ## Inductive case for i in range(len(seq)): element_slice = seq[i:i+1] rest_iter = permIter(seq[:i] + seq[i+1:]) for rest in rest_iter: yield(element_slice + rest) raise StopIteration def isFixedLetterRearrangement(word1, word2): """Returns true if word1 and word2 contain the same letters, but mismatch at every single position.""" return (hasSameElements(word1, word2) and mismatchesEverywhere(word1, word2)) def hasSameElements(seq1, seq2): l1, l2 = list(seq1), list(seq2) l1.sort() l2.sort() return l1 == l2 def mismatchesEverywhere(seq1, seq2): for i in range(len(seq1)): if seq1[i] == seq2[i]: return 0 return 1 def uniq(seq): """Given a sequence of hashable elements, returns a list of all unique elements of the list.""" cache = {} for element in seq: cache[element] = 1 return cache.keys() if __name__ == "__main__": teresa_rearrangements = uniq([x for x in permIter("teresa") if isFixedLetterRearrangement(x, "teresa")]) print "There are", len(teresa_rearrangements), print "distinct rearrangements." print "Here they are:" print string.join(teresa_rearrangements, "\n") ### It's good to know that the majority is not always right. *grin* Thanks for the correction. From dyoo@hkn.eecs.berkeley.edu Sun Jan 6 22:24:43 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 6 Jan 2002 14:24:43 -0800 (PST) Subject: [Tutor] scoping rules In-Reply-To: <20020106211451.GE22531@localhost> Message-ID: On Sun, 6 Jan 2002, dman wrote: > | Does this mean that i will not be able to increment a (908) (defined in the > | enclosing function) > | inside the inner function? > > You are right. Here's what's going on : > > When you have an assignment statement, a new local variable is > created. The compiler (with the nested scopes modifications) will > flag those names as being local. When you have the "a+=1" line the > compiler sees that 'a' is a local variable. Thus you get the > "UnboundLocal" error when you try and reference 'a' (to get it's > original value). If you say 'global' it works only because 'a' is at > the module level. If you say 'global a' and then assign to 'a', 'a' > is going to be at the module level. For example this won't work : > > def f() : > a = 908 > def g() : > global a > a+=1 > g() > f() If we're really trying to make changes to the variable of an enclosing class, there is an idiom we can use: ### def f(): a = [908] def g(): a[0] += 1 g() print a ### And here it is in action: ### >>> f() [909] ### This dodges the issue by assigning to an array element. Since we're not assigning to 'a' itself, Python knows that we're just refering to the 'a' of our enclosing function. From dyoo@hkn.eecs.berkeley.edu Sun Jan 6 22:31:59 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 6 Jan 2002 14:31:59 -0800 (PST) Subject: [Tutor] A small math puzzle [recreational Python] In-Reply-To: Message-ID: On Sat, 5 Jan 2002, Tim Peters wrote: > [talking about derangements of words with duplicate letters] > > FYI, you can compute this without exhaustive generation, but it's not > simple. See, e.g., section 4-7 (Permutations with Forbidden > Positions) in Liu's "Introduction to Combinatorial Mathematics". Thanks for the recommendation! I just ordered it from Amazon. Do you have any other introductory math books you'd recommend for those who are interested in this sort of stuff? From dyoo@hkn.eecs.berkeley.edu Sun Jan 6 22:59:57 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 6 Jan 2002 14:59:57 -0800 (PST) Subject: [Tutor] TLlistmaster.py [bug hunting] In-Reply-To: <200201060511.g065Bn502165@ns.howlermonkey.net> Message-ID: On Sun, 6 Jan 2002, Kirk D Bailey wrote: > I have got TLlistmaster.py almost complete. There is one minor bug in > there. Regretfully, it's a tiny little stinkbug and it is driving me > crazy(ier). What we need to do is isolate the bug. Time to don our hunting caps! *grin* I'll transcribe what I'm looking at while I'm hunting the bug, to show the thought processes I'm going through. > there is no error code, but it fails to see the presence of the > subject line in the pending file. How do we know this? Let's see where it reports that it can't find a subject. I'll quote the part of your code, but strip off the comments for the moment: ### if thecommand == "join": print "This person wants to join'"+listname+"' list!" if subject in pendings: [code cut...] else: print "cannot find subject in pending file!" sys.exit() ### Since the output is printing that "cannot find subject..." stuff, we must be jumping in here, and 'thecommand' must be "join". Also, 'subject' must not be in 'pendings'. What is 'subject', and what is 'pendings'? If we know what the values of these variables are, we might discover why we can't find the subject in the pending file. I'll now search for places where 'subject' is being assigned to... ### subject = string.strip(Message['Subject']) subject = string.replace(subject,"Re:","") subject = string.strip(subject) ### You may want to bundle this processing all together into a "getSubject()" function, because it's very easy to forget to do all this cleanup on the subject string. Also, I think that strip()ping the string twice is superfluous. So 'subject' must be a cleaned up header within the Message. Now let's see what 'pendings' is: ### pendings=readpending() gangstrip(pendings) ### Good! Since there's a function called readpending(), we can focus on that function, without bouncing around in the rest of the code. Let's see what readpending() does. ### def readpending(): f4=open('./lists/pending','r') pending=f4.readlines() f4.close() return pending ### Ok, clear enough. readpending() opens up a file './list/pending' and returns a list of lines. Just as long as the './list/pending' file itself contains that subject, we should be fine. I personally feel that the gangstrip() should be part of readpending(), not parallel to it. So what must be happening is that the subject line isn't in the pendings file. Your debugging output shows: > CLEANED UP subject line='join highprimate@howlermonkey.net evil-humor > 1010287984' which looks ok. What does your pending file contain? Just one line! > Pending action='join testcode@howlermonkey.net testlist3 1010173860' So there's no match! Those two strings are different from each other, and from the debugging output, I'm guessing that there's only one pending action within './list/pending'. Check your pending file, and things that affect your pending file. How does one get added to the pending file? Hope this helps! From dyoo@hkn.eecs.berkeley.edu Sun Jan 6 23:16:51 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 6 Jan 2002 15:16:51 -0800 (PST) Subject: [Tutor] Trapping exceptions in batch scripts In-Reply-To: <1010334353_PM_BeOS.Charlie@begeistert.org> Message-ID: On Sun, 6 Jan 2002, Charlie Clark wrote: > There seems to be two ways of actually running a script either by > importing it or by using execfile Import has to be called via > __import__ as it is not possible to pass a variable to import. I don't think __import__ is a good approach, expecially because if your scripts use the 'if __name__ == "__main__"' idiom, they won't execute during a module import. > This seems somewhat clumsy but when I tried execfile I got some > confusing error messages claiming that names weren't properly defined. > The scripts themselves ran fine but occasionally produced name errors > when run using execfile. The problem is that when we use execfile(), Python doesn't include that file's directory within 'sys.path'. If your script does any 'import'ing, Python won't look at that file's directory when searching for modules. In fact, IDLE's "Run Script" command suffers from the exact same problem; I posted a fix to it: http://mail.python.org/pipermail/tutor/2001-December/010915.html You can use something similar: ### def my_execfile(filename): old_syspath = sys.path[:] sys.path.append(os.path.dirname(os.path.abspath(filename))) execfile(filename) sys.path = old_syspath ### This my_execfile() may behave more nicely because it includes the directory of the script within sys.path, so that if the script uses 'import', it behaves the way you probably want it to. Good luck to you! From dajoy@operamail.com Sun Jan 6 23:55:49 2002 From: dajoy@operamail.com (Daniel Ajoy) Date: Sun, 6 Jan 2002 18:55:49 -0500 Subject: [Tutor] Re: A small math puzzle [recreational Python] Message-ID: <3C390C45@operamail.com> On 6 Jan 2002 at 16:00, tutor-request@python.org wrote: > > I believe these are the values (84): > > Hmm, both my and Danny Yoo's solutions gave 168 distinct rearrangements (or > derangements, or whatever!). > I'll do a quick check, by removing all the words you have supplied from the > derangements my function provides, and see if the remaining words are in > fact derangements. > > ...a couple of minutes later... > > This is what I got back after removing the words:- > > ['ATSREE', 'ATESER', 'ATESRE', 'ATERES', 'ASTREE', 'ASERET', 'ASERTE', > 'ASETRE', 'ASETER', 'ARETES', 'ARESTE', 'ARESET', 'ARTSEE', 'ARSTEE', > 'SATREE', 'SAERET', 'SAERTE', 'SAETRE', 'SAETER', 'SRETAE', 'SREATE', > 'SREAET', 'SRTAEE', 'SRATEE', 'STAREE', 'STEAER', 'STEARE', 'STERAE', > 'RTASEE', 'RTSAEE', 'RTESAE', 'RTEAES', 'RATSEE', 'RASTEE', 'RAETES', > 'RAESTE', 'RAESET', 'RSATEE', 'RSETAE', 'RSEATE', 'RSEAET', 'RSTAEE', > 'ERESAT', 'ERETAS', 'EREATS', 'ERTAES', 'ERTSAE', 'ERATES', 'ERASTE', > 'ERASET', 'ERSATE', 'ERSAET', 'ERSTAE', 'ETARES', 'ETASRE', 'ETASER', > 'ETSARE', 'ETSAER', 'ETSRAE', 'ETESAR', 'ETERAS', 'ETEARS', 'EATRES', > 'EATSRE', 'EATSER', 'EASTRE', 'EASTER', 'EASRET', 'EASRTE', 'EAESTR', > 'EAESRT', 'EAERTS', 'EAETRS', 'ESATRE', 'ESATER', 'ESARET', 'ESARTE', > 'ESEATR', 'ESEART', 'ESERAT', 'ESETAR', 'ESTRAE', 'ESTARE', 'ESTAER'] > > Must be something wrong, as these are derangements. Lets see, "ATSREE" is below, "ATESER" is also below... I think you are counting double. I think its because "TERESA" has 2 E's 168 = 84 * 2 > > ETERAS ETESAR ETEARS ETSRAE ETSARE ETSAER ETARES > > ETASRE ETASER ERTSAE ERTAES ERETAS ERESAT EREATS > > ERSTAE ERSATE ERSAET ERATES ERASTE ERASET ESTRAE > > ESTARE ESTAER ESETAR ESERAT ESEATR ESEART ESATRE > > ESATER ESARTE ESARET EATRES EATSRE EATSER EAETRS > > EAERTS EAESTR EAESRT EASTRE EASTER EASRTE EASRET > > RTESAE RTEAES RTSAEE RTASEE RSTAEE RSETAE RSEATE > > RSEAET RSATEE RATSEE RAETES RAESTE RAESET RASTEE > > STERAE STEARE STEAER STAREE SRTAEE SRETAE SREATE > > SREAET SRATEE SATREE SAETRE SAETER SAERTE SAERET > > ATERES ATESRE ATESER ATSREE ARTSEE ARETES ARESTE > > ARESET ARSTEE ASTREE ASETRE ASETER ASERTE ASERET Daniel From Willem de Beer" This is a multi-part message in MIME format. ------=_NextPart_000_002F_01C19785.D49EB560 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Good day I am using a laptop with Windows 98. I have a script into which I have = imported Numeric.py. If I run it from the MS-DOS prompt, I get the error = message=20 File "C:\PYTHON21\Numeric\Numeric.py", line 80 in ? ImportError: DLL load failed: One of the library files needed to run = this application cannot be found This always happens at line 80 (even if I change line spacings etc. in = Numeric.py), but does not happen when I run the script in the = interactive window. Some advice will be appreciated! Best regards Willem ------=_NextPart_000_002F_01C19785.D49EB560 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
Good day
 
I am using a laptop with Windows = 98. I have=20 a script into which I have imported Numeric.py. If I run it from=20 the MS-DOS prompt, I get the error message
 
File "C:\PYTHON21\Numeric\Numeric.py", = line 80 in=20 ?
ImportError: DLL load failed: One of = the library=20 files needed to run this application cannot be found
 
This always happens at line 80 (even if = I change=20 line spacings etc. in Numeric.py), but does not happen when I run the = script in=20 the interactive window.
 
Some advice will be = appreciated!
 
Best = regards
Willem
 
------=_NextPart_000_002F_01C19785.D49EB560-- From urnerk@qwest.net Mon Jan 7 01:56:20 2002 From: urnerk@qwest.net (Kirby Urner) Date: Sun, 06 Jan 2002 17:56:20 -0800 Subject: [Tutor] A small math puzzle [recreational Python] In-Reply-To: References: Message-ID: <4.2.0.58.20020106175446.00d2d5d0@pop3.norton.antivirus> > >Thanks for the recommendation! I just ordered it from Amazon. Do you >have any other introductory math books you'd recommend for those who are >interested in this sort of stuff? Yikes, out of print and $71 for a used copy. Math books are expensive. Lots over $100. Kirby From toodles@yifan.net Mon Jan 7 02:21:41 2002 From: toodles@yifan.net (Andy W) Date: Mon, 7 Jan 2002 10:21:41 +0800 Subject: [Tutor] Re: A small math puzzle [recreational Python] References: <3C390C45@operamail.com> Message-ID: <003101c19722$0ca7f2a0$0300a8c0@sun> > Lets see, "ATSREE" is below, "ATESER" is also below... I think > you are counting double. I think its because "TERESA" has 2 E's > 168 = 84 * 2 Ahh yes, yes, I'm very sorry about that! That'll learn me for not going through the whole 84 words with a comb ;) Andy From dsh8290@rit.edu Mon Jan 7 02:28:20 2002 From: dsh8290@rit.edu (dman) Date: Sun, 6 Jan 2002 21:28:20 -0500 Subject: [Tutor] Utter newbie question In-Reply-To: <003201c19718$df617540$9d6760cb@renee123> References: <003201c19718$df617540$9d6760cb@renee123> Message-ID: <20020107022820.GA27042@localhost> On Mon, Jan 07, 2002 at 02:15:59PM +1300, Willem de Beer wrote: | Good day | | I am using a laptop with Windows 98. I have a script into which I | have imported Numeric.py. If I run it from the MS-DOS prompt, I get | the error message | | File "C:\PYTHON21\Numeric\Numeric.py", line 80 in ? | ImportError: DLL load failed: One of the library files needed to run this application cannot be found There's more to this error message. What does line 80 look like? I bet it is an import statement that loads the other part of the package. | This always happens at line 80 (even if I change line spacings etc. | in Numeric.py), but does not happen when I run the script in the | interactive window. Numeric is a C (or C++, not sure) extension to python. It has a python wrapper module to provide a nice interface for python programs. You will need both parts for it to function. Where/How did you install Numeric? What is sys.path? Where is the dll it is looking for? On my (debian) system it is one of /usr/lib/python2.1/site-packages/Numeric/_numpy.so /usr/lib/python2.1/site-packages/Numeric/multiarray.so /usr/lib/python2.1/site-packages/Numeric/umath.so /usr/lib/python2.1/site-packages/Numeric/arrayfns.so (.so in unix is similar to .dll in windows) Line 80 in my version of Numeric.py is the end of the module's docstring. Possibly the numeric installer told windows to include it in %PYTHONPATH%, thus when python is run in windows it finds the %libraries, but in DOS it doesn't. -D -- Do not be afraid of those who kill the body but cannot kill the soul. Rather be afraid of the One who can destroy both soul and body in hell. Matthew 10:28 From tim.one@home.com Mon Jan 7 02:43:13 2002 From: tim.one@home.com (Tim Peters) Date: Sun, 6 Jan 2002 21:43:13 -0500 Subject: [Tutor] A small math puzzle [recreational Python] In-Reply-To: <4.2.0.58.20020106175446.00d2d5d0@pop3.norton.antivirus> Message-ID: [Danny Yoo, on Liu's "Introduction to Combinatorial Mathematics"] > Thanks for the recommendation! I just ordered it from Amazon. Do you > have any other introductory math books you'd recommend for those who > are interested in this sort of stuff? "Concrete Mathematics" (Knuth et alia), which I recommend routinely. [Kirby Urner] > Yikes, out of print and $71 for a used copy. > > Math books are expensive. Lots over $100. Here's a free thread then : http://mail.python.org/pipermail/python-list/1999-November/016414.html I mentioned Liu just because that was the textbook I had for my first combinatorics course in college. It's a very good intro, and I'm sorry to hear it's out of print. But the topic here is standard, so should be covered by whatever combinatorics text is in fashion today. Depending on the book, permutations with forbidden positions may be covered in the chapter on inclusion/exclusion (as in Liu), or perhaps a chapter on "rook polynomials" or "sieve formulas". All of that will make more sense if you slog thru the thread above. From karthikg@aztec.soft.net Mon Jan 7 06:25:26 2002 From: karthikg@aztec.soft.net (Karthik Gurumurthy) Date: Mon, 7 Jan 2002 11:55:26 +0530 Subject: [Tutor] would someone help me out with this-->import error? In-Reply-To: <4.2.0.58.20020106065249.00c402c0@pop3.norton.antivirus> Message-ID: This is a multi-part message in MIME format. ------=_NextPart_000_0030_01C19772.31ECE840 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: 7bit hi all, This is as part of my plans to introduce python at our company. I have taken Martin Fowler's refactoring example and am almost done with it when i'm getting a strange import error. I have been working on this since yesterday and have'nt been able to debug it! :-( There is problem somewhere which is causing the cylcic imports to fail. i'm using python2.2. am attaching the a zip file code.zip which has 2 files. 1. movie.py --> refers to price.py 2. price.py --> which in turn tries to import movie.py just try doing >>import movie and you will see the error. I will be doing a GUI demo as well and am planning to use anygui. Since my demo would'nt have many fancy widgets, i guess anygui at it's present state should work for me. The code is'nt complicated. It was working just fine and at the last stage of refactoring it suddenly started raising this error. would be obliged if someone could fix this for me. thanks, karthik ------=_NextPart_000_0030_01C19772.31ECE840 Content-Type: application/x-zip-compressed; name="code.zip" Content-Transfer-Encoding: base64 Content-Disposition: attachment; filename="code.zip" UEsDBBQAAAAIAE5cJyyqIw6YfQEAAGwEAAAIAAAAcHJpY2UucHm1kl9rwjAUxZ8t9Dtc9KU6V5yy l4EDqWUTVEZF9ljS9rbNSBtJ0v359rNNrU6RubG9lCbnJOfcH4kFzyDjrxSBZhsuFCzKRR88zBVh pmEaISNSwpIvUKU8mmUbhlkpKspzy30PcVP+de9MoxVhDL5Pc6p835LI4n4mk/GS51jJrcZtn7i6 pb4LmzGGCWFPgobo8Aibc3+aZxqdSQ4kkEqQUIGO3k9cpVs8eMFQNWkJqqZVdZcOEoRKPMeovd5q qyLQCShB8fIeIHnJ/MDZriHskpyUiETH9MXWNCUf8j/yOjDFmOZ4JEuIuQAkYQo8BpWiRgKyCKqb 96iclLJo21Ajq75lz2+YoSpErt+b7TzO5lPPXV4MAGXBFIzhxr4t1zSGnQHuYVR5alPragxWI17D qAu9+lRdQfu2GwfPHd88ZEgkHs108URL99n33Lk7WbmXDVRXqXv2YGQPWlUn3cjDpGBE/LaO5z6s 5xPvx3yH9uCU7/CQL3zlOzyL9xNQSwMEFAAAAAgAglwnLLogVxcOAgAA5QYAAAgAAABtb3ZpZS5w ec1Uy2rbQBRdK+B/GLySqRF1lwUVgqykBtsINaXLYSpdO1MmkjoapfXf985DL1tuAtkEJMSdc8+5 zxF/qkqpSCV5BrOb2U0mWF2TXfnMwS9//oJMLT7rc28f/6BpvI1vv8UkJCs8ib5utus03qP5Cc00 vv++vU3R+uh5aOOTw4FQyguuKPVrEIel4kpAOL8XLOdMlXK+NJFpVuYQmqiB09FhPU+TAkoNDZXN V5/zA+mJJAzJiGuoLXfoZ0lBCsdGMJlow19oZxBXFNsiX5KMHrnIJRSv0Ry08iXZPfxJQQCrYSRc gyVKxmtwrhsh4MiE8YtQI/6bQaV4WfjzTRGVUuIsiUGJhudGCqmFIupUgZnPYji5I6jokcmjhZZY nFqzU20HI0E1siAXmQc9qyOMJO8k/G4QSfHFbEuMX9sAOfrq0zZA3Qilt0lbrikmXCIzqitwe2Cg yeYSVuSkVSVfyMo1zSh/CFeDOlw0necg1wfblImC20V0vjWoxBbxzEQDloG5GeuN60m6XTpTe+tq nsm9o63E98Hd+EqWFUh18vU4NNhO/wxLlnoG41VLro5vvK9dcn4b3Tz2V2j3dPAvnP6xPekedisM +ej3ZUBM2HwH5707gr0xKmJ3tYhOrXdep87bu3Qf6U/f8csodjXGXoG+1NSVOXvV3f6P8FXORJid 6+Nw8DuNDVzP4HWK+D9QSwECFAAUAAAACABOXCcsqiMOmH0BAABsBAAACAAAAAAAAAABACAAtoEA AAAAcHJpY2UucHlQSwECFAAUAAAACACCXCcsuiBXFw4CAADlBgAACAAAAAAAAAABACAAtoGjAQAA bW92aWUucHlQSwUGAAAAAAIAAgBsAAAA1wMAAAAA ------=_NextPart_000_0030_01C19772.31ECE840-- From karthikg@aztec.soft.net Mon Jan 7 07:18:42 2002 From: karthikg@aztec.soft.net (Karthik Gurumurthy) Date: Mon, 7 Jan 2002 12:48:42 +0530 Subject: [Tutor] RE: would someone help me out with this-->import error? (It's Working now..thanks) In-Reply-To: Message-ID: hi all, a python-list member sent me the solution with a neat explanation. Learnt something here.. it's better to import modules only when you absolutely need it. I could'nt appreciate it earlier when i saw a couple of code snippets doing that. Now i know why? thanks, karthik. -----Original Message----- From: karthik Guru [mailto:karthikg@aztec.soft.net] Sent: Monday, January 07, 2002 11:55 AM To: tutor@python.org Subject: would someone help me out with this-->import error? Importance: High hi all, This is as part of my plans to introduce python at our company. I have taken Martin Fowler's refactoring example and am almost done with it when i'm getting a strange import error. I have been working on this since yesterday and have'nt been able to debug it! :-( There is problem somewhere which is causing the cylcic imports to fail. i'm using python2.2. am attaching the a zip file code.zip which has 2 files. 1. movie.py --> refers to price.py 2. price.py --> which in turn tries to import movie.py just try doing >>import movie and you will see the error. I will be doing a GUI demo as well and am planning to use anygui. Since my demo would'nt have many fancy widgets, i guess anygui at it's present state should work for me. The code is'nt complicated. It was working just fine and at the last stage of refactoring it suddenly started raising this error. would be obliged if someone could fix this for me. thanks, karthik From drogers@vanteon.com Mon Jan 7 19:13:49 2002 From: drogers@vanteon.com (David Rogers) Date: Mon, 7 Jan 2002 11:13:49 -0800 Subject: [Tutor] Py_BuildValue/PyArg_ParseTuple versus "Foo\000OtherFoo\000SpamFoo \000\000" Message-ID: <71CF056160A0D111BCB500A0C99E507402887694@red-exch.vanteon.com> The data structure mentioned in the subject is familiar to at least those who played with environment variables in MSDOS, it's just a sequence of null-terminated strings with an extra null byte indicating the end of the sequence. Has anyone ever considered and/or implemented a format string for this data structure? Thanks,, David David Rogers Senior Software Engineer Redmond Development Center 8700 148th Avenue NE Redmond, WA 98052 Tel: (425) 250-0018 Fax: (425) 250-0100 Email: drogers@vanteon.com Web: www.vanteon.com Boston - Redmond - Rochester - Salt Lake City From glingl@aon.at Mon Jan 7 19:38:59 2002 From: glingl@aon.at (Gregor Lingl) Date: Mon, 7 Jan 2002 20:38:59 +0100 Subject: [Tutor] Re: A small math puzzle [recreational Python] References: Message-ID: <001c01c197b2$f476e510$1664a8c0@mega> Apropos teresa! Ok, I'm late, but when I had a look to Python-Tutor for the first time after a couple of days, i found this RECREATIONAL PYTHON - and I could not resist to recreate (although time was ... forget it) Maybe I could not resist because of teresa beeing a name, which recalls many associations to an Austrian - you know wa had an emperor with this name ("Theresia") more than 200 years ago, the one who heared the six years old Mozart playing his music... And teresa is a popular name here, with many diminutive forms: Resi, Theres, Resl etc... It turned out, that to recreate meant ro recreate this teresa-program. So, if you are already satisfied (or not interested any more) by the rich discussion in this thread, please QUIT HERE! What's new? 1. It's recursive. As far as I observed in this now more than 900 lines - thread, there is no recursive solution so far .. I wonder, why recursion is used so seldom by 'hardcore'- computer-scientists? 2. It's short and rather self-documenting ( if you have any questions - don't hesitate to ask ;-) I tried to follow the rule: "make it as simple as possible, but not simpler..." (can't remember where I read this ... ) 3. As it also essentially constructs all possible cases, it gets slow with growing input, but in contrast to what one would expect from a recursive solution and because of reasons I don't know, it is faster than Danny's solution (approximately by a factor of 10). In all cases I tried, it gave the same results as Danny's, so I expect it to be correct. I'm posting to versions: Version 1: Only counts the rearrangements, as was suggested by Allen ##### def teresa(word): return teres(word, word) def teres(chars, pattern): if not chars: return 1 count = 0 used = [] for char in chars: if char not in used and char != pattern[0]: used.append(char) i = chars.index(char) charsleft = chars[:i] + chars[i+1:] count += teres(charsleft, pattern[1:]) return count ##### >>> teresa('teresa') 84 >>> teresa('theresia') 5430 >>> Version 2: Returns the list of rearrangements. Observe, that this has the same structure as the one above - with only few modifications. def teresl(word): # the l reminding on list return resi(word, word) def resi(chars, pattern, good=''): if not chars: return [good] rearrangements = [] used = [] for char in chars: if char not in used and char != pattern[0]: used.append(char) i = chars.index(char) charsleft = chars[:i] + chars[i+1:] rearrangements += resi(charsleft, pattern[1:], good + char) return rearrangements Just if you are a bit puzzled by this solution: The idea behind it is, to take every possible character for the first position and then to sum up the count (or accumulate the results) of rearrangements of the characters left fitting to the given word without the first character. I did it first by hand for 'teres' and then wrote down, what I did in the form of a Python-Program. Thanks, was really recreational! Best wishes (especially for a fine 2002) Gregor From ylee12@uiuc.edu Mon Jan 7 19:58:08 2002 From: ylee12@uiuc.edu (Young-Jin Lee) Date: Mon, 7 Jan 2002 13:58:08 -0600 Subject: [Tutor] Re: Tutor digest, Vol 1 #1311 - 16 msgs References: Message-ID: <031001c197b5$a0ae0b40$95757e82@visit2> I have touble using IDLE in redhat and I was told I needed to setup the idle before I using it by "$ cd .../Tools/idle $ python2.2 ./setup.py". When I tried the aboves, python asked me to specify the option and command, but I have no idea what to do. Here is the message I got: usage: setup.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...] or: setup.py --help [cmd1 cmd2] or: setup.py --help-commands or: setup.py cmd --help. I also tried "python2 ./setup.py idle", but it didn't work, either. Thanks in advance. YJ ----- Original Message ----- From: To: Sent: Saturday, January 05, 2002 9:59 AM Subject: Tutor digest, Vol 1 #1311 - 16 msgs > Send Tutor mailing list submissions to > tutor@python.org > > To subscribe or unsubscribe via the World Wide Web, visit > http://mail.python.org/mailman/listinfo/tutor > or, via email, send a message with subject or body 'help' to > tutor-request@python.org > > You can reach the person managing the list at > tutor-admin@python.org > > When replying, please edit your Subject line so it is more specific > than "Re: Contents of Tutor digest..." > > > Today's Topics: > > 1. RE: Learning Programming (alan.gauld@bt.com) > 2. RE: Learning Programming (alan.gauld@bt.com) > 3. CGI and ODBC questions (McCarney, James Alexander) > 4. [Q] using IDLE in redhat (Young-Jin Lee) > 5. Re: [Q] using IDLE in redhat (dman) > 6. Re: [Q] using IDLE in redhat (Michael P. Reilly) > 7. it slices, it dices, it makes BILLIONS and BILLIONS of juliene fries... (Kirk D Bailey) > 8. Re: it slices, it dices, it makes BILLIONS and BILLIONS of juliene fries... (Andy W) > 9. sliced! (Kirk D Bailey) > 10. oops! (Kirk D Bailey) > 11. Re: oops! (Danny Yoo) > 12. A small math puzzle [recreational Python] (Danny Yoo) > 13. Re: A small math puzzle [recreational Python] (Lloyd Hugh Allen) > 14. Re: A small math puzzle [recreational Python] (Andy W) > 15. How can handle exception? (A) > 16. Re: How can handle exception? (Andy W) > > --__--__-- > > Message: 1 > From: alan.gauld@bt.com > To: e.kotyk@shaw.ca, tutor@python.org > Subject: RE: [Tutor] Learning Programming > Date: Fri, 4 Jan 2002 17:39:58 -0000 > > > Subsequently Python was recommended at a good language for a > > novice. I have completed the tutorial by Josh Cogliati and > > have written a few small modules on my own. > > Congratulations, that's the hardest bit over :-) > > > 1) What is a reasonable length of time in which to learn a > > programming language ? > > It depends on the language. Something enormous like C++ can > take many months or years. In fact I've been learning C++ for > over 15 years and still only know the basics! > > I've been learning Python for about 4 years and know about > the same amount... > > > I'm a little disheartened at my prgress. > > Don't be, the more you use a language the more you learn. > You only need the bare minimum to start using a language > and that can literally be learnt in a couple of days > - in the case of Python a couple of hours is enough for > an experienced programmer to start using Python. > > It's the layers of detail that take a long time - like > all of the modules in Python for example. > > > 2) I think I would learn more quickly if I had a > > project to work on...how do you choose a project? > > Something you need doing but put off coz it'll take too long? > Or something you already do manually but could automate? > Or just pick one of the challenges on the Useless Python site. > > Alan G. > > > --__--__-- > > Message: 2 > From: alan.gauld@bt.com > To: rbl@hal.epbi.cwru.edu, e.kotyk@shaw.ca > Cc: tutor@python.org > Subject: RE: [Tutor] Learning Programming > Date: Fri, 4 Jan 2002 17:47:18 -0000 > > > From: Robin B. Lake [mailto:rbl@hal.epbi.cwru.edu] > > learn that you DON'T want to "learn a programming language", but > > rather should "learn how to program". > > This is excellent advice. Its the reason I used 3 languages > on my web tutor rather than just python: to try to illustrate > that the same principles apply in all languages. > > > children, learn to read before we learn to write. > > Thats also good advice, I can read many programming languages > (around 30 maybe?) but I can only write in about 12... > > > Learning to WRITE a program should, in my experience, be done with > > "pseudocode" --- that expresses the structures and the logic of > > the problem,... > > THEN you can decide which language will best fit your problem. > > Also very good advice. > > Alan g. > Author of the 'Learning to Program' web site > http://www.freenetpages.co.uk/hp/alan.gauld > > > --__--__-- > > Message: 3 > From: "McCarney, James Alexander" > > To: "'tutor@python.org'" > Date: Fri, 4 Jan 2002 14:40:02 -0500 > Subject: [Tutor] CGI and ODBC questions > > Hail noble Python gurus! > > Well Py is way cool, but I am sure you all knew that long before I ever > found out. ;-) > > I am turning my attention to server-side cgi-bin processing. > > What I have is this: > > -platform: W 2000 > -web server: (either Apache or IIS[gag]): would like to go w Apache, but may > have to port to IIS > - Python (yay!) v 2.1.1 > - Access Database (ODBC driver) (Could go with mySQL, but Access is what I > have right now.) > > What I want is this: > > Reader/reviewer has some comments about nifty documents I may have penned. > > Script serves a form he can fill in and commit to the dB. > > Script also e-mails me and tells me that this event has occurred. > > > There is ample documentation on the cgi module, so I will do my homework > there. > But where is it written in Python/server cyberland about setting up Python > with the server on NT? Likely with the http server docs you may claim. > > So has anyone gone down this road before? Does anyone have knowledge on > setting up Python with one or other of these servers? > > And can anyone tell me how to get there from here? > > Best regards to all of you and thanks for any constructive help you may > provide. > > > James Alexander McCarney, Technical Writer > M3i Systems Inc., 1111 Saint-Charles Avenue West > 11th Floor, East Tower, Longueuil, Quebec, J4K 5G4 > Canada > Telephone: (450) 928-3386 x2262 > Fax: (450) 442-5076 > http://www.m3isystems.com > > > --__--__-- > > Message: 4 > From: "Young-Jin Lee" > To: > Date: Fri, 4 Jan 2002 15:24:59 -0600 > Subject: [Tutor] [Q] using IDLE in redhat > > Hi, I'm new to redhat and I'm looking for a help on how to use IDLE in > redhat. > I installed Python 2.2 the other day and tried to learn IDLE by typing it > "idle", but it didn't work at all. > I thought I should add a path to the idle so I added > "PATH=$PATH:/usr/lib/python2.2/Tools; export PATH". > But when I typed "idle" at my home directory, I got "bash:idle: command not > found". I have never used bash shell. (I have used csh in IRIX, but I > decided to use bash because bash seems to be a standard in Linux). > When I tried it with a full path, "/usr/lib/python2.2/Tools/idle/idle", I > got the following python exception. > Traceback (innermost last): > File "/usr/lib/python2.2/Tools/idle/idle", line 5, in ? > from idlelib import IdleConf > ImportError: No module named idlelib > > The configuration seems to be not correct, but I have no idea. Is there a > good tutorial or guide on how to use IDLE in redhat (or Linux)? > > Thanks in advance. > > YJ > > > > --__--__-- > > Message: 5 > Date: Fri, 4 Jan 2002 16:44:20 -0500 > From: dman > To: tutor@python.org > Subject: Re: [Tutor] [Q] using IDLE in redhat > > On Fri, Jan 04, 2002 at 03:24:59PM -0600, Young-Jin Lee wrote: > | Hi, I'm new to redhat and I'm looking for a help on how to use IDLE in > | redhat. > | I installed Python 2.2 the other day and tried to learn IDLE by typing it > | "idle", but it didn't work at all. > | I thought I should add a path to the idle so I added > | "PATH=$PATH:/usr/lib/python2.2/Tools; export PATH". > > $PATH is what the shell uses to find commands. $PYTHONPATH is what > python uses to find modules. > > | But when I typed "idle" at my home directory, I got "bash:idle: command not > | found". I have never used bash shell. (I have used csh in IRIX, but I > | decided to use bash because bash seems to be a standard in Linux). > | When I tried it with a full path, "/usr/lib/python2.2/Tools/idle/idle", I > | got the following python exception. > | Traceback (innermost last): > | File "/usr/lib/python2.2/Tools/idle/idle", line 5, in ? > | from idlelib import IdleConf > | ImportError: No module named idlelib > > This means you need to set $PYTHONPATH correctly. I don't know what > is correct for a redhat system, but the debian packages work > out-of-the-box. > > -D > > -- > > If you hold to [Jesus'] teaching, you are really [Jesus'] disciples. > Then you will know the truth, and the truth will set you free. > John 8:31-32 > > > > --__--__-- > > Message: 6 > Date: Fri, 4 Jan 2002 18:52:27 -0500 > From: "Michael P. Reilly" > To: tutor@python.org > Subject: Re: [Tutor] [Q] using IDLE in redhat > Reply-To: arcege@speakeasy.net > > On Fri, Jan 04, 2002 at 03:24:59PM -0600, Young-Jin Lee wrote: > > Hi, I'm new to redhat and I'm looking for a help on how to use IDLE in > > redhat. > > I installed Python 2.2 the other day and tried to learn IDLE by typing it > > "idle", but it didn't work at all. > > I thought I should add a path to the idle so I added > > "PATH=$PATH:/usr/lib/python2.2/Tools; export PATH". > > But when I typed "idle" at my home directory, I got "bash:idle: command not > > found". I have never used bash shell. (I have used csh in IRIX, but I > > decided to use bash because bash seems to be a standard in Linux). > > When I tried it with a full path, "/usr/lib/python2.2/Tools/idle/idle", I > > got the following python exception. > > Traceback (innermost last): > > File "/usr/lib/python2.2/Tools/idle/idle", line 5, in ? > > from idlelib import IdleConf > > ImportError: No module named idlelib > > > > The configuration seems to be not correct, but I have no idea. Is there a > > good tutorial or guide on how to use IDLE in redhat (or Linux)? > > > > Thanks in advance. > > Unfortunately, Idle got screwed when they tried to get it into Python 2.1 > with the new distutils. You must now install IDLE before you can use it; > you cannot use it in its place like you could with earlier releases. > > You need to install it by running the setup.py file in the Tools/idle > directory. > $ cd .../Tools/idle > $ python2.2 ./setup.py > > -Arcege > > > > --__--__-- > > Message: 7 > Date: Sat, 5 Jan 00:39:28 2002 -0500 > From: "Kirk D Bailey" > To: tutor@python.org > Subject: [Tutor] it slices, it dices, it makes BILLIONS and BILLIONS of juliene fries... > > But more importantly, I want to take a string of seceral words and > chop it into a list with each word an item in the list. > > Among other things. But let's talk about the other things later. > > > end > > In total confusion, > Kirk D Bailey > > +----------------------------------------------------+ > | Providing Excellent email service for free!! | > | Webmaster, Howlermonkey Email services Co. | > | highprimate@howlermonkey.net www.howlermonkey.net/ | > +----------------------------------------------------+ > > ODD#1.8.01/kdb/sigme > > SRC="amtfp2.gif" WIDTH=468 HEIGHT=60 alt="Totally Free Paging!"> > > > > --__--__-- > > Message: 8 > From: "Andy W" > To: > Subject: Re: [Tutor] it slices, it dices, it makes BILLIONS and BILLIONS of juliene fries... > Date: Sat, 5 Jan 2002 14:09:34 +0800 > > > But more importantly, I want to take a string of seceral words and > > chop it into a list with each word an item in the list. > > > > Among other things. But let's talk about the other things later. > > several_words_string="Scooby Dooby Doo" > several_words_list=several_words.split() > > That is, as long as the words are separated by spaces. Otherwise > several_words.split(separator) > > > > > > > end > > > > In total confusion, > > Kirk D Bailey > > > > +----------------------------------------------------+ > > | Providing Excellent email service for free!! | > > | Webmaster, Howlermonkey Email services Co. | > > | highprimate@howlermonkey.net www.howlermonkey.net/ | > > +----------------------------------------------------+ > > > > ODD#1.8.01/kdb/sigme > > > > href="http://www.totallyfreepaging.com/checksource.asp?ID=89212&PT=AZC1XT" > target="_top"> > SRC="amtfp2.gif" WIDTH=468 HEIGHT=60 alt="Totally Free Paging!"> > > > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > > --__--__-- > > Message: 9 > Date: Sat, 5 Jan 01:17:03 2002 -0500 > From: "Kirk D Bailey" > To: tutor@python.org > Subject: [Tutor] sliced! > > OK, I tripped over string.replace(subject, search, replacement) in > string module, and also string.split, so that part is finished, it > now digests the subject line nicely. > > Got another question. > > --------------------------------------------------------- > Def writependings(omitme, list): # write back the pendings, > f6.open('./lists/pending','w') # OMITTING one item. > for item in list: > if item != omitme: > f6.write(item)+CRLF > f6.close() > ---------------------------------------------------------- > This code creates a error message; > > ------------------------------------------------------------ > ns# ./TLlistmaster.py < testfile > File "./TLlistmaster.py", line 201 > Def writependings(omitme, list): # write back the pendings, > ^ > SyntaxError: invalid syntax > ns#_ > -------------------------------------------------------------- > > Now, whofore would it do an evil thing like that? > > > > > > > end > > In total confusion, > Kirk D Bailey > > +----------------------------------------------------+ > | Providing Excellent email service for free!! | > | Webmaster, Howlermonkey Email services Co. | > | highprimate@howlermonkey.net www.howlermonkey.net/ | > +----------------------------------------------------+ > > ODD#1.8.01/kdb/sigme > > Return to the Forgotten Realms on a visually dazzling role-playing adventure that brings to > life the grand tradition of Advanced > Dungeons & Dragons through cutting edge art and technology. Now available for > pre-order. Only $39.95 from Outpost.com. FREE SHIPPING. OVERNIGHT. > > > > > --__--__-- > > Message: 10 > Date: Sat, 5 Jan 01:25:34 2002 -0500 > From: "Kirk D Bailey" > To: tutor@python.org > Subject: [Tutor] oops! > > OK, noticed an oops. incorrect open statement, was f6.open(foo), > not f6=open(foo). > > open statement is fixed, but it still barks like a dog. > > Here's the New and improved code: > > # > Def writependings(omitme, list): # write back the pendings, > f6=open('./lists/pending','w') # OMITTING one item. > for item in list: > if item != omitme: > f6.write(item)+CRLF > f6.close() > # > Gives this result: > > [ Wrote 266 lines > ] > > ns# ./TLlistmaster.py < testfile > File "./TLlistmaster.py", line 201 > Def writependings(omitme, list): # write back the pendings, > ^ > SyntaxError: invalid syntax > ns#_ > > COULD IT BE this function name is simply too long? > > > > > > > > > end > > In total confusion, > Kirk D Bailey > > +----------------------------------------------------+ > | Providing Excellent email service for free!! | > | Webmaster, Howlermonkey Email services Co. | > | highprimate@howlermonkey.net www.howlermonkey.net/ | > +----------------------------------------------------+ > > ODD#1.8.01/kdb/sigme > > http://www.winfreestuff.com src="http://ad.linksynergy.com/fs-bin/show?id=Jy/DqAOH/SU&bids=18076.1000000 2 > &type=1&subid=0" > > > > > --__--__-- > > Message: 11 > Date: Fri, 4 Jan 2002 22:40:05 -0800 (PST) > From: Danny Yoo > To: Kirk D Bailey > cc: tutor@python.org > Subject: Re: [Tutor] oops! > > On Sat, 5 Jan 2002, Kirk D Bailey wrote: > > > Def writependings(omitme, list): # write back the pendings, > > f6=open('./lists/pending','w') # OMITTING one item. > > for item in list: > > if item != omitme: > > f6.write(item)+CRLF > > f6.close() > > > > ns# ./TLlistmaster.py < testfile > > File "./TLlistmaster.py", line 201 > > Def writependings(omitme, list): # write back the pendings, > > ^ > > SyntaxError: invalid syntax > > ns#_ > > > > COULD IT BE this function name is simply too long? > > > Function names can be pretty long: > > ### > >>> def salutatiousGreeting(): print "salutations!" > ... > >>> salutatiousGreeting() > salutations! > ### > > What you're running into is the case sensitivity of Python keywords: > > ### > >>> Def hello(): > File "", line 1 > Def hello(): > ^ > SyntaxError: invalid syntax > ### > > The error's pointing at the "hello", but it's really the 'Def' that's > confusing Python. Lowercase the 'Def', and you should be ok. > > > > > --__--__-- > > Message: 12 > Date: Sat, 5 Jan 2002 01:53:04 -0800 (PST) > From: Danny Yoo > To: tutor@python.org > Subject: [Tutor] A small math puzzle [recreational Python] > > Hi everyone, > > I ran across this puzzle while browsing the the 'alt.math.undergrad' > newsgroup. I thought it might make a fun programming exercise, so here's > my paraphrase of the puzzle: > > > A "rearrangement without fixed letters" of a given word is a mixup of the > letters so that, if one were to overlap the original with the > rearrangement, no letters should match. For example, given the word: > > 'TERESA' > > here are a two "rearrangements without fixed letters": > > ['RTESAE', 'SATREE'] > > However, here's an example that is a rearrangement but doesn't work > because it has a fixed letter: > > 'TRESAE' > ^ > > In this example, the 'T' makes this rearrangement inacceptable, since > 'TERESA' itself begins with a 'T' too. > > > The puzzle is to write a program that counts all the possible > rearrangements without fixed letters. > > > Have fun! > > > > --__--__-- > > Message: 13 > Date: Sat, 05 Jan 2002 08:32:15 -0500 > From: Lloyd Hugh Allen > Reply-To: lha2@columbia.edu > To: tutor@python.org > Subject: Re: [Tutor] A small math puzzle [recreational Python] > > Danny Yoo wrote: > > However, here's an example that is a rearrangement but doesn't work > > because it has a fixed letter: > > > > 'TRESAE' > > ^ > > > > In this example, the 'T' makes this rearrangement inacceptable, since > > 'TERESA' itself begins with a 'T' too. > > > > The puzzle is to write a program that counts all the possible > > rearrangements without fixed letters. > > > > Have fun! > > Is it necessary to actually construct the list of rearrangements, or do > you just want a function that will compute how many rearrangements > exist? > > > --__--__-- > > Message: 14 > From: "Andy W" > To: "Danny Yoo" , > > Subject: Re: [Tutor] A small math puzzle [recreational Python] > Date: Sat, 5 Jan 2002 22:26:20 +0800 > > Here's a solution, albeit a cruddy one :-) > It uses permutations, so therefore gets dreadfully slow from about 8 letters > onwards. > I knew this would happen, I just couldn't get my mind around the > mathematical approach... > > Andy W. > > PS. The function actually returns all the rearrangements, not the number of > them. Of course that can easily be changed... > > #Code > > def perm(set,n): > """ > By Kirby Urner. > Return all permutations of a set. Thanks to > Daniel Ajoy for sharing his Logo version with me. > """ > > set=listify(set) > > if len(set)==0: return [] > elif len(set)==1: return set > answ = [] > > for i in range(len(set)): > base = [set[0]] > rest = set[1:] > answ = answ + [base + listify(i) for i in perm(rest,n-1)] > set = [set[-1]]+set[:-1] > > return answ > > def listify(obj): > "Used in conjunction with perm()" > if type(obj) is not type([]): > try: > l=list(obj) > except: > l=[obj] > return l > else: return obj > > def get_rearrangements(word): > word=word.upper() > perms=perm([char for char in word],len(word)) #Get the permutations of > the letters > rearrangements=perms[:] #Copy for keeping the good ones in > for p in perms: > ok=1 > for n in range(len(p)): > if p[n]==word[n]: #Check whether the character is the same... > ok=0 > if not ok: > rearrangements.remove(p) #If it is, remove it! > return [''.join(r) for r in rearrangements] > > ----- Original Message ----- > From: "Danny Yoo" > To: > Sent: Saturday, January 05, 2002 5:53 PM > Subject: [Tutor] A small math puzzle [recreational Python] > > > > Hi everyone, > > > > I ran across this puzzle while browsing the the 'alt.math.undergrad' > > newsgroup. I thought it might make a fun programming exercise, so here's > > my paraphrase of the puzzle: > > > > > > A "rearrangement without fixed letters" of a given word is a mixup of the > > letters so that, if one were to overlap the original with the > > rearrangement, no letters should match. For example, given the word: > > > > 'TERESA' > > > > here are a two "rearrangements without fixed letters": > > > > ['RTESAE', 'SATREE'] > > > > However, here's an example that is a rearrangement but doesn't work > > because it has a fixed letter: > > > > 'TRESAE' > > ^ > > > > In this example, the 'T' makes this rearrangement inacceptable, since > > 'TERESA' itself begins with a 'T' too. > > > > > > The puzzle is to write a program that counts all the possible > > rearrangements without fixed letters. > > > > > > Have fun! > > > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > > --__--__-- > > Message: 15 > From: "A" > To: python-list@python.org, tutor@python.org, > activepython@listserv.ActiveState.com > Date: Sat, 5 Jan 2002 16:21:59 +0100 > Reply-to: printers@sendme.cz > Subject: [Tutor] How can handle exception? > > > > Hello, > My program sometimes raise the exception > > socket.error: (10061, 'Connection refused') > > How can I handle this kind of exception? > Thank you for help. > Ladislav > > > > --__--__-- > > Message: 16 > From: "Andy W" > To: , > , > > Subject: Re: [Tutor] How can handle exception? > Date: Sat, 5 Jan 2002 23:57:53 +0800 > > Hi Ladislav > > > Hello, > > My program sometimes raise the exception > > > > socket.error: (10061, 'Connection refused') > > > > How can I handle this kind of exception? > > Enclose it in try, except socket.error. ie.:- > > try: > #do stuff here > except socket.error: > #handle exception here > > Andy > > > Thank you for help. > > Ladislav > > > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > --__--__-- > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > > End of Tutor Digest > From glingl@aon.at Mon Jan 7 20:08:40 2002 From: glingl@aon.at (Gregor Lingl) Date: Mon, 7 Jan 2002 21:08:40 +0100 Subject: [Tutor] Re: A small aftermath [recreational Python] References: <001c01c197b2$f476e510$1664a8c0@mega> Message-ID: <002b01c197b7$198bdb90$1664a8c0@mega> As I now observed, that >>> teresl('mammamia') ['amaimamm', 'amaamimm', 'amiamamm', 'imaamamm'] runs nearly 5000 times(!) as fast as >>> uniq([x for x in permIter("mammamia") if isFixedLetterRearrangement(x, "mammamia")]) ['amaimamm', 'amaamimm', 'imaamamm', 'amiamamm'] I suppose, the reason for this may be, that the teresl-program doesn't need to perform any comparisons of found candidates with the original input-word. Instead in case that there is no more letter found fitting to a given position, the search-space is - sometimes (mammamia!) severely - cut! This conjecture may be supported by the fact that in case of no repetitions >>> len(teresl('abcdefgh')) 14833 runs only less than 5 times as fast as the corresponding uniq - call Gregor From swa@gmx.net Mon Jan 7 21:29:22 2002 From: swa@gmx.net (Sander Wahls) Date: Mon, 7 Jan 2002 22:29:22 +0100 Subject: [Tutor] Closed socket.recv() does not return Message-ID: <02010722265700.02191@starfish> Hi! I've got a strange problem with sockets in python. Normally the recv meth= od=20 of a socket object simply returns '' if the socket has been closed by the= =20 other side, but strangely this doesn't work in every case for me. Is ther= e=20 some way to check if a socket has been closed, something like in Perl if (!defined($socket)) { print "socket has been closed } Thanks in advance! Sander --=20 >>> visit 1024kb.net >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> From swa@gmx.net Mon Jan 7 21:26:57 2002 From: swa@gmx.net (Sander Wahls) Date: Mon, 7 Jan 2002 22:26:57 +0100 Subject: [Tutor] Closed socket.recv() does not return Message-ID: <02010722265700.02191@starfish> Hi! I've got a strange problem with sockets in python. Normally the recv meth= od=20 of a socket object simply returns '' if the socket has been closed by the= =20 other side, but strangely this doesn't work in every case for me. Is ther= e=20 some way to check if a socket has been closed, something like in Perl if (!defined($socket)) { print "socket has been closed } Thanks in advance! Sander --=20 >>> visit 1024kb.net >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> From swa@gmx.net Mon Jan 7 21:30:40 2002 From: swa@gmx.net (Sander Wahls) Date: Mon, 7 Jan 2002 22:30:40 +0100 Subject: [Tutor] Closed socket.recv() does not return Message-ID: <02010722265700.02191@starfish> Hi! I've got a strange problem with sockets in python. Normally the recv meth= od=20 of a socket object simply returns '' if the socket has been closed by the= =20 other side, but strangely this doesn't work in every case for me. Is ther= e=20 some way to check if a socket has been closed, something like in Perl if (!defined($socket)) { print "socket has been closed } Thanks in advance! Sander --=20 >>> visit 1024kb.net >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> From mennosimons@gmx.net Mon Jan 7 23:21:30 2002 From: mennosimons@gmx.net (Huuuuuu) Date: Tue, 8 Jan 2002 00:21:30 +0100 Subject: [Tutor] built-in hex->int question Message-ID: <20020107232144Z43234-28926+7@mail.uni-paderborn.de> Hi Tutor, Why understands the float() function a string argument but not integer-cast-functions? >>> int('0xaf') Traceback (most recent call last): File "", line 1, in ? ValueError: invalid literal for int(): 0xaf >>> long('0xaf') Traceback (most recent call last): File "", line 1, in ? ValueError: invalid literal for long(): 0xaf >>> float('0xaf') 175.0 Thanks, willi From lha2@columbia.edu Mon Jan 7 23:29:32 2002 From: lha2@columbia.edu (Lloyd Hugh Allen) Date: Mon, 07 Jan 2002 18:29:32 -0500 Subject: [Tutor] built-in hex->int question References: <20020107232144Z43234-28926+7@mail.uni-paderborn.de> Message-ID: <3C3A2F5C.A26EE9BE@mail.verizon.net> You can do long(float('0xaf')), if you want to...don't know if that helps. Huuuuuu wrote: > > Hi Tutor, > > Why understands the float() function a string argument but not > integer-cast-functions? > > >>> int('0xaf') > Traceback (most recent call last): > File "", line 1, in ? > ValueError: invalid literal for int(): 0xaf > >>> long('0xaf') > Traceback (most recent call last): > File "", line 1, in ? > ValueError: invalid literal for long(): 0xaf > >>> float('0xaf') > 175.0 > > Thanks, > willi > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From glingl@aon.at Mon Jan 7 23:46:17 2002 From: glingl@aon.at (Gregor Lingl) Date: Tue, 8 Jan 2002 00:46:17 +0100 Subject: [Tutor] built-in hex->int question References: <20020107232144Z43234-28926+7@mail.uni-paderborn.de> <3C3A2F5C.A26EE9BE@mail.verizon.net> Message-ID: <001001c197d5$806eae50$1664a8c0@mega> My interpreter works consistently: >>> int('0xaf') Traceback (most recent call last): File "", line 1, in ? int('0xaf') ValueError: invalid literal for int(): 0xaf >>> float('0xaf') Traceback (most recent call last): File "", line 1, in ? float('0xaf') ValueError: invalid literal for float(): 0xaf >>> int(0xaf) 175 >>> float(0xaf) 175.0 >>> Gregor ----- Original Message ----- From: "Lloyd Hugh Allen" To: "Huuuuuu" Cc: Sent: Tuesday, January 08, 2002 12:29 AM Subject: Re: [Tutor] built-in hex->int question > You can do long(float('0xaf')), if you want to...don't know if that > helps. > > Huuuuuu wrote: > > > > Hi Tutor, > > > > Why understands the float() function a string argument but not > > integer-cast-functions? > > > > >>> int('0xaf') > > Traceback (most recent call last): > > File "", line 1, in ? > > ValueError: invalid literal for int(): 0xaf > > >>> long('0xaf') > > Traceback (most recent call last): > > File "", line 1, in ? > > ValueError: invalid literal for long(): 0xaf > > >>> float('0xaf') > > 175.0 > > > > Thanks, > > willi > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From sheree@psouth.net Mon Jan 7 23:58:33 2002 From: sheree@psouth.net (Sheree Beaudette) Date: Mon, 7 Jan 2002 18:58:33 -0500 Subject: [Tutor] FW: Comparing variables Message-ID: <000001c197d7$37c98100$40de723f@u1v62> > I need some help!! I'm still new to Python but believe I'll need it here. > > > I have a form that sets the variable copyitem, a number from 1 to ... (an > integer) > > > > Once I submit the form > > I want copyitem to be compared with a sequence-number from a SQL query, > code as follows > > > > > do something true > > do something false > > > > > Since I've written these variables to the screen I know that they're > equal, yet they still do the 'do something false' . > > I hope it's something easy I've overlooked. I didn't know if there were > type differences that I need to convert. How do I convert these? Do I > need a python script? I'm new to Python so can you help??? > > Thanks in advance! From kalle@gnupung.net Tue Jan 8 00:18:27 2002 From: kalle@gnupung.net (Kalle Svensson) Date: Tue, 8 Jan 2002 01:18:27 +0100 Subject: [Tutor] built-in hex->int question In-Reply-To: <20020107232144Z43234-28926+7@mail.uni-paderborn.de> References: <20020107232144Z43234-28926+7@mail.uni-paderborn.de> Message-ID: <20020108011827.A23093@sandra.lysator.liu.se> [Huuuuuu] > Why understands the float() function a string argument but not > integer-cast-functions? You mean why does float() understand *hexadecimal* string arguments. I don't know the answer, but: >>> int("4") 4 >>> int("0xaf", 16) 175 >>> long("0xaf", 16) 175L Peace, Kalle -- Kalle Svensson (kalle@gnupung.net) - Laziness, impatience, hubris: Pick two! English: http://www.gnupung.net/ Svenska: http://www.lysator.liu.se/~kalle/ Stuff: ["http://www.%s.org/" % x for x in "gnu debian python emacs".split()] From lha2@columbia.edu Tue Jan 8 02:41:33 2002 From: lha2@columbia.edu (Lloyd Hugh Allen) Date: Mon, 07 Jan 2002 21:41:33 -0500 Subject: [Tutor] built-in hex->int question References: <20020107232144Z43234-28926+7@mail.uni-paderborn.de> <3C3A2F5C.A26EE9BE@mail.verizon.net> Message-ID: <3C3A5C5D.EA1CF702@mail.verizon.net> Forgot to read the doc strings: >>> print float.__doc__ float(x) -> floating point number Convert a string or number to a floating point number, if possible. >>> print long.__doc__ long(x) -> long integer long(x, base) -> long integer Convert a string or number to a long integer, if possible. A floating point argument will be truncated towards zero (this does not include a string representation of a floating point number!) When converting a string, use the given base. It is an error to supply a base when converting a non-string. >>> apparently float() is more forgiving than long(), or alternatively, long wants to be told ahead of time when it is given a string that is either not an integer or not base-10. Which makes sense, since number theorists (and other folks who deal in Z (integers)) tend to be like that too. No offense intended. Lloyd Hugh Allen wrote: > > You can do long(float('0xaf')), if you want to...don't know if that > helps. > > Huuuuuu wrote: > > > > Hi Tutor, > > > > Why understands the float() function a string argument but not > > integer-cast-functions? > > > > >>> int('0xaf') > > Traceback (most recent call last): > > File "", line 1, in ? > > ValueError: invalid literal for int(): 0xaf > > >>> long('0xaf') > > Traceback (most recent call last): > > File "", line 1, in ? > > ValueError: invalid literal for long(): 0xaf > > >>> float('0xaf') > > 175.0 > > > > Thanks, > > willi > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From karthikg@aztec.soft.net Tue Jan 8 05:57:23 2002 From: karthikg@aztec.soft.net (Karthik Gurumurthy) Date: Tue, 8 Jan 2002 11:27:23 +0530 Subject: [Tutor] FW: Comparing variables In-Reply-To: <000001c197d7$37c98100$40de723f@u1v62> Message-ID: is it something like you have numStr = "1" then you can get integer 1 by doing int(numStr) but it might throw an exception depending upon what came from web page so you might want to catch it though try: num = int(numStr) except: ValueError //do something here karthik. -----Original Message----- From: tutor-admin@python.org [mailto:tutor-admin@python.org]On Behalf Of Sheree Beaudette Sent: Tuesday, January 08, 2002 5:29 AM To: tutor@python.org Subject: [Tutor] FW: Comparing variables > I need some help!! I'm still new to Python but believe I'll need it here. > > > I have a form that sets the variable copyitem, a number from 1 to ... (an > integer) > > > > Once I submit the form > > I want copyitem to be compared with a sequence-number from a SQL query, > code as follows > > > > > do something true > > do something false > > > > > Since I've written these variables to the screen I know that they're > equal, yet they still do the 'do something false' . > > I hope it's something easy I've overlooked. I didn't know if there were > type differences that I need to convert. How do I convert these? Do I > need a python script? I'm new to Python so can you help??? > > Thanks in advance! _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From richert@upb.de Mon Jan 7 22:50:08 2002 From: richert@upb.de (Willi Richert) Date: Mon, 7 Jan 2002 23:50:08 +0100 Subject: [Tutor] How to assert a float? Message-ID: <20020107225020Z43721-9655+904@mail.uni-paderborn.de> Hi Tutor, How do you assert the following: ============================ import math def log2(x): return math.log(x)/math.log(2.0) assert 2**log2(5)==5.0 ============================ 2**log2(5) yields 4.9999999999999991 which is not 5.0 To round is also not very wise. Do you know how one can assert floats? Thanks willi From dyoo@hkn.eecs.berkeley.edu Tue Jan 8 07:24:34 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 7 Jan 2002 23:24:34 -0800 (PST) Subject: [Tutor] built-in hex->int question In-Reply-To: <20020107232144Z43234-28926+7@mail.uni-paderborn.de> Message-ID: On Tue, 8 Jan 2002, Huuuuuu wrote: > Why understands the float() function a string argument but not > integer-cast-functions? > > >>> int('0xaf') > Traceback (most recent call last): > File "", line 1, in ? > ValueError: invalid literal for int(): 0xaf How strange! ### >>> int('0xaf') Traceback (most recent call last): File "", line 1, in ? ValueError: invalid literal for int(): 0xaf >>> int('0xaf', 16) 175 ### Hmmm... So as long as Python knows which base it's working on, the conversion works. Time to look at the documentation: """ int(x[, radix]) Convert a string or number to a plain integer. If the argument is a string, it must contain a possibly signed decimal number representable as a Python integer, possibly embedded in whitespace; this behaves identical to string.atoi(x[, radix]). The radix parameter gives the base for the conversion and may be any integer in the range [2, 36], or zero. If radix is zero, the proper radix is guessed based on the contents of string; the interpretation is the same as for integer literals. If radix is specified and x is not a string, TypeError is raised. Otherwise, the argument may be a plain or long integer or a floating point number. Conversion of floating point numbers to integers truncates (towards zero).""" Ah! The documentation mentions that if the radix is zero, then Python will try to guess the way we expect it to: ### >>> int('0xaf', 0) 175 ### And that's probably what you're looking for. Apparently, the float() function will do this radix guessing thing for us, which is why: ### > >>> float('0xaf') > 175.0 ### worked for you before. Hope this helps! From idiot1@netzero.net Tue Jan 8 07:41:45 2002 From: idiot1@netzero.net (kirk Bailey) Date: Tue, 08 Jan 2002 02:41:45 -0500 Subject: [Tutor] I think it works... hello? (thumpthumpthump...) References: <20020107225020Z43721-9655+904@mail.uni-paderborn.de> Message-ID: <3C3AA2B9.C561A677@netzero.net> Well, holding it by the hand and feeding it the correct data after setting things up correctly, it did indeed process a return mail, extract data, find the pending in the pending file, and add me to testlist3. ok, I want to play with it some and see that it is really working, so gang, it is time. SCREW WITH ME. Really. (Shudder.) Here is the link to the web manager. http://www.howlermonkey.net/cgi-bin/TLwebmgr.py The list to screw around with is testlist3. Subscribe. UNsubscribe. Sendmessages while subscribed. Send them when subscribed. Just be nice, this is a testing exercise, not an invitation for a wholesale bording party to come alongside. Be advised that TL does not at this time send a confo message letting you know what was done regarding membership once it is done. Mayhaps I will install such a beast later, once the basic logic is right. I shudder to think it might, just MIGHT, be ready to hand out- maybe. Let's hammer on it some and see. Willi Richert wrote: > > Hi Tutor, > > How do you assert the following: > > ============================ > import math > > def log2(x): > return math.log(x)/math.log(2.0) > > assert 2**log2(5)==5.0 > ============================ > > 2**log2(5) yields 4.9999999999999991 which is not 5.0 > > To round is also not very wise. Do you know how one can assert floats? > > Thanks > willi > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- -Respectfully, -Kirk D Bailey end ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ |___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___| | _ \___ __ _ __| |_(_)_ _ __ _| |_| |_ ___ / __/ _ \| \| | | / _ Y _` (_-< _| | ' \/ _` | _| ' \/ -_) (_| (_) | .` |_ |_|_\___|__,_/__/\__|_|_||_\__, |\__|_||_\___|\___\___/|_|\_( ) |___/ |/ Kirk Bailey, consulting loose cannon www.howlermonkey.net highprimate@howlermonkey.net http://gipco.webjump.com idiot1@netzero.net _ _ _ _ ___ _ _ ___ _ _ _ _| |_ __ _| |_ __ _| |_(_)_ __ ___ / _ \ ' \/ -_) ' \ || | _/ _` | _/ _` | _| | ' \/ -_)_ \___/_||_\___|_||_\_,_|\__\__,_|\__\__,_|\__|_|_|_|_\___(_)_ ___ |___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___| ---------------------------------------------------- Sign Up for NetZero Platinum Today Only $9.95 per month! http://my.netzero.net/s/signup?r=platinum&refcd=PT97 From karthikg@aztec.soft.net Tue Jan 8 09:34:58 2002 From: karthikg@aztec.soft.net (Karthik Gurumurthy) Date: Tue, 8 Jan 2002 15:04:58 +0530 Subject: [Tutor] useful stuff for newbies In-Reply-To: <3C3A5C5D.EA1CF702@mail.verizon.net> Message-ID: hi newbies, in python 2.2 please take note of the help function. i know pydoc is there. the builtin help() is real cool! i guess it must be making use of pydoc internally..not sure though. >>help(obref.methodName) ==> prints the help >>help(module.methodName) ==> prints the help karthik. From scarblac@pino.selwerd.nl Tue Jan 8 09:41:39 2002 From: scarblac@pino.selwerd.nl (Remco Gerlich) Date: Tue, 8 Jan 2002 10:41:39 +0100 Subject: [Tutor] How to assert a float? In-Reply-To: <20020107225020Z43721-9655+904@mail.uni-paderborn.de>; from richert@upb.de on Mon, Jan 07, 2002 at 11:50:08PM +0100 References: <20020107225020Z43721-9655+904@mail.uni-paderborn.de> Message-ID: <20020108104139.A26295@pino.selwerd.nl> On 0, Willi Richert wrote: > Hi Tutor, > > How do you assert the following: > > ============================ > import math > > def log2(x): > return math.log(x)/math.log(2.0) > > assert 2**log2(5)==5.0 > ============================ > > 2**log2(5) yields 4.9999999999999991 which is not 5.0 > > To round is also not very wise. Do you know how one can assert floats? Well, what you did is correct - but the assert fails, of course, 2**log2(5) is not equal to 5.0 in Python. Everything is working as intended. What you should do instead depends a bit on what you need it for, but you could e.g. define a constant with an acceptable error margin: EPSILON = 0.00000000001 assert abs(2**log2(5) - 5.0) <= EPSILON -- Remco Gerlich From rashigupta77@hotmail.com Tue Jan 8 11:31:30 2002 From: rashigupta77@hotmail.com (rashi gupta) Date: Tue, 8 Jan 2002 17:01:30 +0530 Subject: [Tutor] SocketServer module not creating a TCP server References: Message-ID: While creating the client/server application using the SocketServer module, the server is handling just one request from a client. It is however, connecting to multiple clients at one time. Moreover the rfile.read() function makes both the client and the server go into a hang. I am not too sure whether the serve_forever method can handle multiple clients but single request from each or multiple requests from the same client. The server and client programs are as follows: #server program import SocketServer from time import sleep port=8888 class myR(SocketServer.StreamRequestHandler): def handle(self): print "connection from",self.client_address try: self.rfile.read() self.wfile.write("SocketServer works!") except IOError: print "Connection from the client ",self.client_address," closed" srvsocket=SocketServer.TCPServer(("",port),myR) print "the socket is listening to the port", port srvsocket.serve_forever() #client program from socket import * Hostname = 'localhost' PortNumber = 8888 Buffer = 500 ServerAddress = (Hostname, PortNumber) TCP_Client_Socket = socket(AF_INET, SOCK_STREAM) TCP_Client_Socket.connect(ServerAddress) while 1: print 'The client is conencted to the server' DataStr = raw_input('Enter data to send to the server: ') if not DataStr: print 'The client has entered nothing; hence the connection to the server is closed' break TCP_Client_Socket.send(DataStr) ServerData = TCP_Client_Socket.recv(Buffer) if not ServerData: print 'The server has sent nothing' break print 'The server has sent this data string: ', ServerData TCP_Client_Socket.close() From alan.gauld@bt.com Tue Jan 8 11:46:07 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Tue, 8 Jan 2002 11:46:07 -0000 Subject: [Tutor] Obfuscated Pythonic English Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C247@mbtlipnt02.btlabs.bt.co.uk> I've been reading about metaclasses recently and came across the following comment in an essay (by Guido?) which I thought deserved an airing. The sad thing is that it does make sense when you read it a few times... " In core Python there is only one meta-type, the type ``type'' (types.TypeType), which is the type of all type objects, even itself. " ;-) The whole essay is at: http://www.python.org/doc/essays/metaclasses/ Alan Gauld Solutions Designer BT computing partners Tel : 0141 220 8795 Fax : 0141 248 1284 From karthikg@aztec.soft.net Tue Jan 8 15:18:49 2002 From: karthikg@aztec.soft.net (Karthik Gurumurthy) Date: Tue, 8 Jan 2002 20:48:49 +0530 Subject: [Tutor] globals( ) and binding doubt (newbie) ! In-Reply-To: Message-ID: hi all, please take a look at python session dump: I have put comments at significant places. >>> def f1(): ... print 'f1' ... >>> def f2(): ... print 'f2' ... >>> def f3(): ... print 'f3' ... >>> l = [f1,f2,f3] >>> map(lambda f:f(),l) f1 f2 f3 [None, None, None] >>> def f1(a): ... print a ... >>> def f2(a): ... print a ... >>> def f3(a): ... print a ... >>> >>> >>> seq = [f1,f2,f3] ##### Here seq is filled with f1,f2 and f3 >>> >>> l = [1,2,3,4,5] >>> map(lambda i:map(lambda f:f(i),seq),l) 1 1 1 2 2 2 3 3 3 4 4 4 5 5 5 [[None, None, None], [None, None, None], [None, None, None], [None, None, None], [None, No ne, None]] >>> def f1(a): ##### changed the implementations of the functions ... print "f1 " + str(a) ##### now globals would have bound the names f1,f2 and f3 to the latest definitions ... >>> def f2(b): ... print "f2 " + str(b) ... >>> def f3(c): ... print "f3 " + str(c) ... >>> map(lambda i:map(lambda f:f(i),seq),l) ##### But this seems to have made the call on the earlier definition 1 ##### seq is the list which the methods 1 ##### did'nt work as expected 1 2 2 2 3 3 3 4 4 4 5 5 5 [[None, None, None], [None, None, None], [None, None, None], [None, None, None], [None, No ne, None]] >>> seq [, , ] >>> globals() {'test1': , 'f1': , 'f2': , 'f3': , 'seq': [, , ], '__builtins__': , '__name__': '__main__', '__doc__': None, 'l': [1, 2, 3, 4, 5]} >>> >>> >>> >>> seq = [f1,f2,f3] ##### I had to re-initialize the list with the same names again. >>> map(lambda i:map(lambda f:f(i),seq),l) f1 1 ##### Then things worked fine f2 1 f3 1 f1 2 f2 2 f3 2 f1 3 f2 3 f3 3 f1 4 f2 4 f3 4 f1 5 f2 5 f3 5 [[None, None, None], [None, None, None], [None, None, None], [None, None, None], [None, No ne, None]] >>> Can someone tell me why it did'nt use the correct versions of the functions earlier. When python comes across a name, it does look up in locals() or globals() and then executes the one mapped there? When i redefined f1 , f2 and f3, globals would have accepted these and overwritten the earlier one? thanks for your patience! karthik From urnerk@qwest.net Tue Jan 8 15:43:05 2002 From: urnerk@qwest.net (Kirby Urner) Date: Tue, 08 Jan 2002 07:43:05 -0800 Subject: [Tutor] globals( ) and binding doubt (newbie) ! In-Reply-To: References: Message-ID: <4.2.0.58.20020108074207.016dd100@pop3.norton.antivirus> > >thanks for your patience! >karthik Not exactly sure what's going on here, but note that if you don't explicity return a value from a function (print a doesn't count -- that's not returning), the the function returns None. In the examples you give, your functions behave as they were defined, by returning None. Kirby From karthikg@aztec.soft.net Tue Jan 8 16:33:48 2002 From: karthikg@aztec.soft.net (Karthik Gurumurthy) Date: Tue, 8 Jan 2002 22:03:48 +0530 Subject: [Tutor] globals( ) and binding doubt (newbie) ! In-Reply-To: <4.2.0.58.20020108074207.016dd100@pop3.norton.antivirus> Message-ID: for a moment i totally forgot about the reference semantics and got too drawn into globals and "name" look up and stuff like that :-) am doing quite a bit of python reading these days. a,b,c were refering to 3 objects i added them to a list then i made a,b and c point to different objects and expected the list to point to the ones initialized last which is wrong. I got confused because i was looking at the globals() which reflected the change. The earlier objects are obviously not garbage collected since the lists were holding on to references to them. uhhm. thanks karthik. -----Original Message----- From: Kirby Urner [mailto:urnerk@qwest.net] Sent: Tuesday, January 08, 2002 9:13 PM To: Karthik Gurumurthy Cc: tutor@python.org; python-list@python.org Subject: Re: [Tutor] globals( ) and binding doubt (newbie) ! Importance: High > >thanks for your patience! >karthik Not exactly sure what's going on here, but note that if you don't explicity return a value from a function (print a doesn't count -- that's not returning), the the function returns None. In the examples you give, your functions behave as they were defined, by returning None. Kirby From scarblac@pino.selwerd.nl Tue Jan 8 16:14:49 2002 From: scarblac@pino.selwerd.nl (Remco Gerlich) Date: Tue, 8 Jan 2002 17:14:49 +0100 Subject: [Tutor] globals( ) and binding doubt (newbie) ! In-Reply-To: ; from karthikg@aztec.soft.net on Tue, Jan 08, 2002 at 08:48:49PM +0530 References: Message-ID: <20020108171449.A26665@pino.selwerd.nl> On 0, Karthik Gurumurthy wrote: Hi! It looks like you are having fun, a newbie playing around with changing lists of functions - welcome to Python :-) (snip) > >>> seq = [f1,f2,f3] ##### I had to re-initialize the list with the > same names again. (snip) > Can someone tell me why it did'nt use the correct versions of the functions > earlier. > When python comes across a name, it does look up in locals() or globals() > and then executes the > one mapped there? (snip) > When i redefined f1 , f2 and f3, globals would have accepted these and > overwritten the earlier one? When you do def f1: pass The name 'f1' refers to a function object. After that, you do: seq = [f1] At the moment this assignment happens, the name 'f1' is looked up. 'seq' now refers to a list object, with one element in it, a reference to the function.* It doesn't hold the name, it holds the reference!* Now you do def f1: print "Whee!" Now 'f1' refers to the new function. But 'seq' wasn't changed, so it still holds the same reference as before, which refers to the old function. See? So therefore seq[0]() will still print nothing, until you do seq=[f1] again. Hope it's clearer now. Main thing to remember in Python: everything is a reference. -- Remco Gerlich From idiot1@netzero.net Tue Jan 8 17:26:24 2002 From: idiot1@netzero.net (kirk Bailey) Date: Tue, 08 Jan 2002 12:26:24 -0500 Subject: [Tutor] Re: FW: Returned mail: see transcript for details References: Message-ID: <3C3B2BC0.D68A7BB4@netzero.net> Yep, turns out that when run as a alias, it does not know where it is, so it cannot do relative addressing. odd. I will fix and invite a new round of gremlinfesting. Note the line pointing out a path error in line 204. The file is there. The problem is, it does not know where HERE is! './lists/pending' only works if you know the definition of '.'!!! John Precedo wrote: > > Bounce messages fowarded to you FYI. (I tried to subscribe to testlist3 as > you asked for in the message '[Tutor] I think it works... hello? > (thumpthumpthump...)' on the Python tutor mailing list). > > I know that 'subscribe' in the subject line isn't what it's expecting, but > shouldn't it silently shove it in the bit bucket rather than sending a > bounce message back? > > Regards, > John > > -- > John Precedo (johnp@reportlab.com) Developer > Reportlab Europe Ltd (http://www.reportlab.com) > > > -----Original Message----- > > From: Mail Delivery Subsystem [mailto:MAILER-DAEMON@ns.howlermonkey.net] > > Sent: 08 January 2002 15:18 > > To: johnp@reportlab.com > > Subject: Returned mail: see transcript for details > > > > > > The original message was received at Tue, 8 Jan 2002 10:18:24 -0500 (EST) > > from finch-post-10.mail.demon.net [194.217.242.38] > > > > ----- The following addresses had permanent fatal errors ----- > > "|/www/www.howlermonkey.net/cgi-bin/TLlistmaster.py" > > (reason: 1) > > (expanded from: ) > > > > ----- Transcript of session follows ----- > > From:= johnp@reportlab.com > > Subject field as extracted:='subscribe' > > CLEANED UP subject line='subscribe' > > command='subscribe' > > Traceback (innermost last): > > File "/www/www.howlermonkey.net/cgi-bin/TLlistmaster.py", line 178, in ? > > oldfrom=commandline[1] # extract > > the old FROM > > IndexError: list index out of range > > 554 5.3.0 "|/www/www.howlermonkey.net/cgi-bin/TLlistmaster.py"... > > unknown mailer error 1 > > > > ---------------------------------------------------------------------- > Name: ATT00015.dat > ATT00015.dat Type: DAT File (application/x-unknown-content-type-DAT_auto_file) > Encoding: 7bit > > Part 1.3 Type: Outlook Express Mail Message (message/rfc822) > Encoding: 7bit -- -Respectfully, -Kirk D Bailey end ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ |___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___| | _ \___ __ _ __| |_(_)_ _ __ _| |_| |_ ___ / __/ _ \| \| | | / _ Y _` (_-< _| | ' \/ _` | _| ' \/ -_) (_| (_) | .` |_ |_|_\___|__,_/__/\__|_|_||_\__, |\__|_||_\___|\___\___/|_|\_( ) |___/ |/ Kirk Bailey, consulting loose cannon www.howlermonkey.net highprimate@howlermonkey.net http://gipco.webjump.com idiot1@netzero.net _ _ _ _ ___ _ _ ___ _ _ _ _| |_ __ _| |_ __ _| |_(_)_ __ ___ / _ \ ' \/ -_) ' \ || | _/ _` | _/ _` | _| | ' \/ -_)_ \___/_||_\___|_||_\_,_|\__\__,_|\__\__,_|\__|_|_|_|_\___(_)_ ___ |___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___| ---------------------------------------------------- Sign Up for NetZero Platinum Today Only $9.95 per month! http://my.netzero.net/s/signup?r=platinum&refcd=PT97 From idiot1@netzero.net Tue Jan 8 17:52:45 2002 From: idiot1@netzero.net (kirk Bailey) Date: Tue, 08 Jan 2002 12:52:45 -0500 Subject: [Tutor] OK, LET A NEW ROUND of slamming begin! Message-ID: <3C3B31ED.97E1F329@netzero.net> ok, updated, try again. http://www.howlermonkey.net/cgi-bin/TLwebmgr.py the list to mess with is 'testlist3'. AT THIS TIME it will not reply with a message letting you know the results of the process; to test membership, simply send a message to testlist3. mailto:testlist3@howlermonkey.net?subject=Testing%20membership%20attempt&body=This%20is%20a%20test. -- -Respectfully, -Kirk D Bailey end ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ |___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___| | _ \___ __ _ __| |_(_)_ _ __ _| |_| |_ ___ / __/ _ \| \| | | / _ Y _` (_-< _| | ' \/ _` | _| ' \/ -_) (_| (_) | .` |_ |_|_\___|__,_/__/\__|_|_||_\__, |\__|_||_\___|\___\___/|_|\_( ) |___/ |/ Kirk Bailey, consulting loose cannon www.howlermonkey.net highprimate@howlermonkey.net http://gipco.webjump.com idiot1@netzero.net _ _ _ _ ___ _ _ ___ _ _ _ _| |_ __ _| |_ __ _| |_(_)_ __ ___ / _ \ ' \/ -_) ' \ || | _/ _` | _/ _` | _| | ' \/ -_)_ \___/_||_\___|_||_\_,_|\__\__,_|\__\__,_|\__|_|_|_|_\___(_)_ ___ |___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___| ---------------------------------------------------- Sign Up for NetZero Platinum Today Only $9.95 per month! http://my.netzero.net/s/signup?r=platinum&refcd=PT97 From idiot1@netzero.net Tue Jan 8 19:50:05 2002 From: idiot1@netzero.net (kirk Bailey) Date: Tue, 08 Jan 2002 14:50:05 -0500 Subject: [Tutor] odd bodkins and novel emissions Message-ID: <3C3B4D6D.24E15C96@netzero.net> OK, it emits thus: ns# ./TLlistmaster.py < testfile From:= idiot1@netzero.net Subject field as extracted:='Re: quit idiot1@netzero.net testlist3 1010514864' CLEANED UP subject line='quit idiot1@netzero.net testlist3 1010514864' command='quit' oldfrom='idiot1@netzero.net' listname='testlist3' Pending action='quit idiot1@netzero.net testlist3 1010514864' command='quit'! Listname= testlist3 Listing members of testlist3 follows: ----------------------------------- Member= 'quit idiot1@netzero.net testlist3 1010514864' Member= 'quit idiot1@netzero.net testlist3 1010514864' ----------------------------------- They are already not a member! Aborting! ns# Odd, when I list the pending file I only get this: ns# list ./lists/pending Listing of file ./lists/pending in directory:/www/www.howlermonkey.net/cgi-bin quit idiot1@netzero.net testlist3 1010514864 ns# And AFTER the above run, this is what is STILL in the pending file: ns# list ./lists/pending Listing of file ./lists/pending in directory:/www/www.howlermonkey.net/cgi-bin quit idiot1@netzero.net testlist3 1010514864 The current listing is at http://www.howlermonkey.net/TLlistmaster.shtml this is a ssi include and is instantly updated if I make a chenge. Anyone care to take a look and guess- or reason out- whyfor it do this? -- -Respectfully, -Kirk D Bailey end ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ |___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___| | _ \___ __ _ __| |_(_)_ _ __ _| |_| |_ ___ / __/ _ \| \| | | / _ Y _` (_-< _| | ' \/ _` | _| ' \/ -_) (_| (_) | .` |_ |_|_\___|__,_/__/\__|_|_||_\__, |\__|_||_\___|\___\___/|_|\_( ) |___/ |/ Kirk Bailey, consulting loose cannon www.howlermonkey.net highprimate@howlermonkey.net http://gipco.webjump.com idiot1@netzero.net _ _ _ _ ___ _ _ ___ _ _ _ _| |_ __ _| |_ __ _| |_(_)_ __ ___ / _ \ ' \/ -_) ' \ || | _/ _` | _/ _` | _| | ' \/ -_)_ \___/_||_\___|_||_\_,_|\__\__,_|\__\__,_|\__|_|_|_|_\___(_)_ ___ |___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___| ---------------------------------------------------- Sign Up for NetZero Platinum Today Only $9.95 per month! http://my.netzero.net/s/signup?r=platinum&refcd=PT97 From dyoo@hkn.eecs.berkeley.edu Tue Jan 8 21:04:23 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 8 Jan 2002 13:04:23 -0800 (PST) Subject: [Tutor] odd bodkins and novel emissions In-Reply-To: <3C3B4D6D.24E15C96@netzero.net> Message-ID: On Tue, 8 Jan 2002, kirk Bailey wrote: > OK, it emits thus: > > ns# ./TLlistmaster.py < testfile > From:= idiot1@netzero.net > Subject field as extracted:='Re: quit idiot1@netzero.net testlist3 > 1010514864' > CLEANED UP subject line='quit idiot1@netzero.net testlist3 > 1010514864' > command='quit' > oldfrom='idiot1@netzero.net' > listname='testlist3' > Pending action='quit idiot1@netzero.net testlist3 1010514864' > command='quit'! Listname= testlist3 > Listing members of testlist3 follows: > ----------------------------------- > Member= 'quit idiot1@netzero.net testlist3 1010514864' > Member= 'quit idiot1@netzero.net testlist3 1010514864' > ----------------------------------- > They are already not a member! Aborting! Question: what does your member list look like? Is it a list of email addresses, or a list of quitting commands? The reason I'm asking this is because I'm guessing that what comes from readmembers() is something like: ### membernow = ['quit foobar@baz.org testlist1 1010514864', 'quit balin@moria.org testlist2 2020202020'] ### which I'll call a list of quitting commands. Is this right? Your from_addr, on the other hand, is just an email address like "foobar@baz.org". Your code is doing a comparison: ### if from_addr not in membernow: print 'They are already not a member! Aborting!' ### so that's why I'm focusing on the contents of your members list. Good luck! From virketis@fas.harvard.edu Tue Jan 8 21:40:08 2002 From: virketis@fas.harvard.edu (Pijus Virketis) Date: Tue, 8 Jan 2002 16:40:08 -0500 Subject: [Tutor] Stern-Brocot tree: more fun math Message-ID: <00f901c1988d$0b429c50$dbadf78c@virketis2> This is a multi-part message in MIME format. ------=_NextPart_000_00F6_01C19863.225ED8B0 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Dear all, inspired by the thread about Continued Fractions and armed with the = reference to "Concrete Mathematics", I've written a few functions to = play around with another interesting mathematical construct, a = Stern-Brocot tree. For an introduction to SB trees, see = http://www.cut-the-knot.com/ctk/SB_tree.html. It can be show (by me, = even :)) that this tree is a representation of the Rational numbers = (i.e. a number system). Its nodes are only reduced fractions, and they = are ordered, so it is easy to make algorithms that traverse the tree. It = also suggests an interesting notation, because any fraction can be = unambiguously identified by listing how many left and right turns are = needed from the first node to get to it. So, 5/7 is L, R, R, L. So, = here's the code: # define the L and R matrices L =3D [[1,1],[0,1]] R =3D [[1,0],[1,1]] # some helper functions def median(S): """ Returns the median fraction from a State matrix """ return [S[1][0]+S[1][1],S[0][0]+S[0][1]] =20 def matrix_mult(A,B): """ Multiplies two 2x2 matrixes """ return ([[A[0][0]*B[0][0]+A[0][1]*B[1][0], = A[0][0]*B[0][1]+A[0][1]*B[1][1]], [A[1][0]*B[0][0]+A[1][1]*B[1][0], = A[1][0]*B[0][1]+A[1][1]*B[1][1]]]) =20 def frac2path(m,n): """ Returns the LR address of reduced fraction m/n """ path =3D [] =20 S =3D [[1,0],[0,1]] # we start = at the Identity node frac =3D float(m)/float(n) # this is = the fraction we wish to end up at while frac !=3D float(median(S)[0])/float(median(S)[1]): # while not = at the correct node if frac < float(median(S)[0])/float(median(S)[1]): # either turn = left path.append("L") # and output = "L" S =3D matrix_mult(S,L) # update = the State Matrix else: # or turn = right path.append("R") # output "R"=20 S =3D matrix_mult(S,R) # update = the State Matrix return path def path2frac(path_list): """ Returns the fraction corresponding to given ["L","R"] address """ S =3D [[1,0],[0,1]] # we start with Identity matrix for turn in path_list: # for each turn in the path list if turn =3D=3D "L": # if we turn left S =3D matrix_mult(S,L) # multiply the State matrix by the = Left matrix =20 else: # if we turn right =20 S =3D matrix_mult(S,R) # multiply the State matrix by the = Right matrix return median(S) # return the resulting fraction = (median of State matrix) =20 We can use this to estimate irrational numbers to arbitrary degree of = precision. Just as Kirby did in his post a month ago, I am going to take = a short at root 3. From highschool I remember that its something like = 1.73 ... Let's plug 173/100 into our function that gives back the path = to any fraction: >>> sternbrocot.frac2path(173,100) ['R', 'L', 'R', 'R', 'L', 'R', 'R', 'L', 'L', 'R', 'L'] Is there a pattern here? It seems that it might be R, L, R, R, L, R, R, = L, ... Irrationals always make patterns in SB representation. So, let's = make a longer list and try it to see if our conjecture was good: >>> root_list =3D ['R', 'L', 'R', 'R', 'L', 'R', 'R', 'L', 'R', 'R', = 'L', 'R', 'R', 'L', 'R', 'R', 'L', 'R', 'R', 'L', 'R', 'R', 'L', 'R', = 'R', 'L'] >>> sternbrocot.path2frac(root_list) [121635, 70226] >>> import math >>> math.sqrt(3) - 121635./70226 1.7560397580496101e-010 So, our estimation is pretty close to the one obtained from math.sqrt(). = Not bad. We can try it a few more steps further: >>> root_list =3D ['R', 'L', 'R', 'R', 'L', 'R', 'R', 'L', 'R', 'R', = 'L', 'R', 'R', 'L', 'R', 'R', 'L', 'R', 'R', 'L', 'R', 'R', 'L', 'R', = 'R', 'L', 'R', 'R', 'L', 'R', 'R', 'L', 'R', 'R', 'L', 'R', 'R', 'L', = 'R', 'R', 'L', 'R', 'R', 'L', 'R', 'R', 'L', 'R', 'R', 'L', 'R', 'R', = 'L'] >>> sternbrocot.path2frac(root_list) [17083879020L, 9863382151L] >>> math.sqrt(3) - 17083879020./9863382151 0.0 That's a pretty good estimate of the square root of three. The next = thing to do is to rewrite all of this as a generator, just to be trendy. = :) -PV=20 ------=_NextPart_000_00F6_01C19863.225ED8B0 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
Dear all,
 
inspired by the thread about Continued = Fractions=20 and armed with the reference to "Concrete Mathematics", I've written a = few=20 functions to play around with another interesting mathematical = construct, a=20 Stern-Brocot tree. For an introduction to SB trees, see http://www.cut-the-= knot.com/ctk/SB_tree.html.=20 It can be show (by me, even :)) that this tree is a representation of = the=20 Rational numbers (i.e. a number system). Its nodes are only reduced = fractions, and they are ordered, so it is easy to make algorithms that = traverse=20 the tree. It also suggests an interesting notation, because any fraction = can be=20 unambiguously identified by listing how many left and right turns are = needed=20 from the first node to get to it. So, 5/7 is L, R, R, L. So, here's the=20 code:
 
 # define the L and R = matrices
L =3D=20 [[1,1],[0,1]]
R =3D [[1,0],[1,1]]
 
# some helper functions
def=20 median(S):
    """
    Returns the = median=20 fraction from a State matrix
    = """
   =20 return [S[1][0]+S[1][1],S[0][0]+S[0][1]]
   
def=20 matrix_mult(A,B):
    """
    = Multiplies two=20 2x2 matrixes
    """
    return=20 ([[A[0][0]*B[0][0]+A[0][1]*B[1][0],=20 A[0][0]*B[0][1]+A[0][1]*B[1][1]],
      =      =20 [A[1][0]*B[0][0]+A[1][1]*B[1][0],=20 A[1][0]*B[0][1]+A[1][1]*B[1][1]]])
   
def=20 frac2path(m,n):
    """
    Returns = the LR=20 address of reduced fraction m/n
    = """
   =20 path =3D []          =20
    S =3D=20 [[1,0],[0,1]]          =             &= nbsp;           &n= bsp;  =20 # we start at the Identity node
    frac =3D=20 float(m)/float(n)         &n= bsp;           &nb= sp;        =20 # this is the fraction we wish to end up at
    while = frac !=3D=20 float(median(S)[0])/float(median(S)[1]): # while not at the correct=20 node
        if frac <=20 float(median(S)[0])/float(median(S)[1]): # either turn=20 left
           = ;=20 path.append("L")         &nb= sp;           &nbs= p;        =20 # and output=20 "L"
           = S =3D=20 matrix_mult(S,L)         &nb= sp;           &nbs= p;    =20 # update the State Matrix
       =20 else:           &n= bsp;           &nb= sp;           &nbs= p;         =20 # or turn=20 right
          &nbs= p;=20 path.append("R")         &nb= sp;           &nbs= p;        =20 # output "R"=20
            S = =3D=20 matrix_mult(S,R)         &nb= sp;           &nbs= p;    =20 # update the State Matrix
    return path
 
def = path2frac(path_list):
   =20 """
    Returns the fraction corresponding to given = ["L","R"]=20 address
    """
    S =3D=20 [[1,0],[0,1]]          =     =20 # we start with Identity matrix
    for turn in=20 path_list:          # for = each turn=20 in the path list
        if turn = =3D=3D=20 "L":           &nb= sp; #=20 if we turn=20 left
           = ; S =3D=20 matrix_mult(S,L)    # multiply the State matrix by the = Left=20 matrix       =20
       =20 else:           &n= bsp;          =20 # if we turn right   =20
            S = =3D=20 matrix_mult(S,R)    # multiply the State matrix by the = Right=20 matrix
    return=20 median(S)          &nbs= p;    =20 # return the resulting fraction (median of State = matrix)
   =20
We can use this to estimate irrational numbers to arbitrary degree = of=20 precision. Just as Kirby did in his post a month ago, I am going to take = a short=20 at root 3. From highschool I remember that its something like 1.73 ... = Let's=20 plug 173/100 into our function that gives back the path to any=20 fraction:
 
>>>=20 sternbrocot.frac2path(173,100)
['R', 'L', 'R', 'R', 'L', 'R', 'R', = 'L', 'L',=20 'R', 'L']
 
Is there a pattern here? It seems that = it might be=20 R, L, R, R, L, R, R, L, ... Irrationals always make patterns in SB=20 representation. So, let's make a longer list and try it to see if our = conjecture=20 was good:

>>> root_list =3D ['R', 'L', 'R', 'R', 'L', 'R', 'R', = 'L', 'R',=20 'R', 'L', 'R', 'R', 'L', 'R', 'R', 'L', 'R', 'R', 'L', 'R', 'R', 'L', = 'R', 'R',=20 'L']
>>> sternbrocot.path2frac(root_list)
[121635,=20 70226]
>>> import math
>>> math.sqrt(3) -=20 121635./70226
1.7560397580496101e-010
 
So, our estimation is pretty close to the one obtained from = math.sqrt().=20 Not bad. We can try it a few more steps further:

>>> root_list =3D ['R', 'L', 'R', 'R', 'L', 'R', 'R', = 'L', 'R',=20 'R', 'L', 'R', 'R', 'L', 'R', 'R', 'L', 'R', 'R', 'L', 'R', 'R', 'L', = 'R', 'R',=20 'L', 'R', 'R', 'L', 'R', 'R', 'L', 'R', 'R', 'L', 'R', 'R', 'L', 'R', = 'R', 'L',=20 'R', 'R', 'L', 'R', 'R', 'L', 'R', 'R', 'L', 'R', 'R', = 'L']
>>>=20 sternbrocot.path2frac(root_list)
[17083879020L, = 9863382151L]
>>>=20 math.sqrt(3) - 17083879020./9863382151
0.0
 
That's a pretty good estimate of the square root of = three. The=20 next thing to do is to rewrite all of this as a generator, just to be = trendy.=20 :)
 
-PV 
------=_NextPart_000_00F6_01C19863.225ED8B0-- From urnerk@qwest.net Tue Jan 8 23:04:40 2002 From: urnerk@qwest.net (Kirby Urner) Date: Tue, 08 Jan 2002 15:04:40 -0800 Subject: [Tutor] Stern-Brocot tree: more fun math In-Reply-To: <00f901c1988d$0b429c50$dbadf78c@virketis2> Message-ID: <4.2.0.58.20020108150400.00cb3770@pop3.norton.antivirus> Good stuff PV. This is how I like to learn/play with Python, by learning/playing with math (not exclusively, but it's certainly one way to go). Kirby From dsh8290@rit.edu Tue Jan 8 23:18:26 2002 From: dsh8290@rit.edu (dman) Date: Tue, 8 Jan 2002 18:18:26 -0500 Subject: [Tutor] How to assert a float? In-Reply-To: <20020107225020Z43721-9655+904@mail.uni-paderborn.de> References: <20020107225020Z43721-9655+904@mail.uni-paderborn.de> Message-ID: <20020108231826.GA5300@localhost> On Mon, Jan 07, 2002 at 11:50:08PM +0100, Willi Richert wrote: | 2**log2(5) yields 4.9999999999999991 which is not 5.0 Welcome to finite precision binary floating point. Try performing the operations in finite precision binary floating point. It is the same effect as doing 2/3 in finite precision decimal floating point (commonly just called "decimal"). The solution is to never check floats for equality -- they will more often (after some computations, of course) be close enough, but not equal, to what you wanted. -D -- Even youths grow tired and weary, and young men stumble and fall; but those who hope in the Lord will renew their strength. They will soar on wings like eagles; they will run and not grow weary, they will walk and not be faint. Isaiah 40:31 From kauphlyn@speakeasy.org Wed Jan 9 01:31:52 2002 From: kauphlyn@speakeasy.org (Daniel Coughlin) Date: Tue, 8 Jan 2002 17:31:52 -0800 (PST) Subject: [Tutor] Algorithm Question Message-ID: This isnt really a python question per se, but rather a question about a specific algorithm. I am no math wiz, and wondered if any of the math guru's on this list could help me sort this out, or at least point me in the right direction. I need to take in a variable quantity of integers (850,250,375,etc) and return a list of all the possible sums of the numbers in the list given when each of these is multiplied by say one through ten. To make it a little simpler I'll use a simpler example: input = (5, 10); output = (15,25,30,etc) all multiples of 5 up to 150. a similar algorithm would be to systematically generate all possible pin codes for a bank machine - given four fields (lets say you are only using two numbers, 1 and 0) find all possible arrangements : (0001,0010,0100,1000,1001,1011,1111,0000,0110,1010,0101,1100, etc) How does one go about solving these types of problems with some kind of efficiency? I hope this clear. Any help would be appreciated! Daniel From toodles@yifan.net Wed Jan 9 01:42:16 2002 From: toodles@yifan.net (Andy W) Date: Wed, 9 Jan 2002 09:42:16 +0800 Subject: [Tutor] odd bodkins and novel emissions References: <3C3B4D6D.24E15C96@netzero.net> Message-ID: <002701c198ae$e4231380$da00a8c0@Sun> Hiya > And AFTER the above run, this is what is STILL in the pending file: > > > ns# list ./lists/pending > Listing of file ./lists/pending in > directory:/www/www.howlermonkey.net/cgi-bin > > quit idiot1@netzero.net testlist3 1010514864 At the moment I'm looking at this block: #### if thecommand =="quit": print "command='quit'! Listname=", listname membernow=[] membernow=readmembers(listname) # read the specified list into members, print "Listing members of "+listname+" follows:" print "-----------------------------------" for X in membernow: print "Member= '"+x+"'" print "-----------------------------------" ... ### Maybe there's 2 errors, or maybe I'm crazy. Maybe both. For the first, "They are already not a member! Aborting!", I'd say Danny's guess sounds about right. But this wouldn't explain why the "quit" pending is still there would it? Or would it? Ack it's too early. If I'm not mistaken, the only way the pendings get cleared is whenl writependings() is called. But in the above code block, there's a lack of writependings() going on. In the handling of the "join" command, there is as follows: ### for x in members: print "members="+x writependings(subject, pendings) # write the pendings to the file MINUS the one specified. ### Should this be mirrored in the handling of quit? Or am I totally off the mark? HTH, Andy From Willem de Beer" <20020107022820.GA27042@localhost> Message-ID: <000501c198b3$d6005b00$fdcb36d2@renee123> Thanks for the info, although I still do not know what to do... :) I downloaded SciPy-0.1.win32-py2.1.exe and ran it. It installed to the directory c:\Python21. There is a multiarray.pyd file in the Python21\DLLs directory, but I do not know what to do with it. You asked: Where/How did you install Numeric? What is sys.path? Where is the dll it is looking for? On my (debian) system it is one of /usr/lib/python2.1/site-packages/Numeric/_numpy.so /usr/lib/python2.1/site-packages/Numeric/multiarray.so /usr/lib/python2.1/site-packages/Numeric/umath.so /usr/lib/python2.1/site-packages/Numeric/arrayfns.so Best regards Willem From glingl@aon.at Wed Jan 9 02:22:25 2002 From: glingl@aon.at (Gregor Lingl) Date: Wed, 9 Jan 2002 03:22:25 +0100 Subject: [Tutor] Stern-Brocot tree: more fun math References: <00f901c1988d$0b429c50$dbadf78c@virketis2> Message-ID: <008b01c198b4$7aba00b0$1664a8c0@mega> This is a multi-part message in MIME format. ------=_NextPart_000_0088_01C198BC.DC399780 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Dear all, inspired by PV's Stern-Brocot-program I thought this to be an ideal = opportunity to try out Kirby's fraction-objects. I produced a slightliy enhanced version of the F class in order to have 'big fractions' and to be able to compare them. Moreover I used the strange but convenient fact that this class allows the definition of the fraction 1/0. Then I developed another recursive solution (considering trees to be = naturally recursive data-structures) - may be it's mathematically less = pretentious, but=20 it works. Here is the code of the program: def median(l, r): return F(l.num+r.num, l.den+r.den) ### Stern-Brocot-tree-traversal back and forth trace =3D 0 def frac2path(f, path =3D [], left =3D F(0,1), right =3D F(1,0)): m =3D median(left,right) if trace: print m if f =3D=3D m: return path elif f < m: return frac2path(f, path+["L"], left, m) else: return frac2path(f, path+["R"], m, right) def path2frac(p, left =3D F(0,1), result =3D F(1,1), right =3D F(1,0)): if not p: return result if trace: print result if p[0]=3D=3D"L": return path2frac(p[1:], left, median(left,result), result) else: return path2frac(p[1:], result, median(result,right), right) =20 ### Kirby's fraction-class, slightly enhanced class F: def __init__(self,numer,denom): # reduce inputs to lowest terms numer =3D long(numer) # NEW: for 'big fractions' denom =3D long(denom) gcd =3D self.gcd(numer,denom) self.num =3D numer//gcd self.den =3D denom//gcd def __add__(self,other): # find lowest common multiple a,b =3D self.num, other.num comden =3D self.lcm(self.den, other.den) if comden !=3D self.den: a *=3D comden//self.den if comden !=3D other.den: b *=3D comden//other.den return F(a+b,comden) def __sub__(self,other): return self + (-other) def __neg__(self): return F(-self.num,self.den) def __lt__(self,other): # NEW: for comparison: m>> frac2path(F(173,100)) ['R', 'L', 'R', 'R', 'L', 'R', 'R', 'L', 'L', 'R', 'L'] >>> path2frac(['R', 'L', 'R', 'R', 'L', 'R', 'R', 'L', 'L', 'R', 'L']) (173/100) >>> trace =3D 1 >>> frac2path(F(173,100)) (1/1) (2/1) (3/2) (5/3) (7/4) (12/7) (19/11) (26/15) (45/26) (64/37) (109/63) (173/100) ['R', 'L', 'R', 'R', 'L', 'R', 'R', 'L', 'L', 'R', 'L'] >>> path2frac(['R', 'L', 'R', 'R', 'L', 'R', 'R', 'L', 'L', 'R', 'L']) (1/1) (2/1) (3/2) (5/3) (7/4) (12/7) (19/11) (26/15) (45/26) (64/37) (109/63) (173/100) >>>=20 ... >>> trace =3D 0 >>> path2frac(root_list) # the one of PV (17083879020/9863382151) >>>=20 Hope, you found this interesting Gregor -------------------------------------------------------------------------= - P.S.: In my eyes the lack of class-methods in Python is still=20 a little bit annoying. ------=_NextPart_000_0088_01C198BC.DC399780 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
Dear all,
 
inspired by PV's Stern-Brocot-program I = thought=20 this to be an ideal opportunity
to try out Kirby's = fraction-objects.
 
I produced a slightliy enhanced version = of the F=20 class in order
to have 'big fractions' and to be able = to compare=20 them.
Moreover I used the strange but = convenient fact=20 that this class allows
the definition of the fraction = 1/0.
 
Then I developed another recursive = solution=20 (considering trees to be naturally
recursive data-structures) - may be = it's=20 mathematically less pretentious, but
it works.
 
Here is the code of the = program:
 
def median(l, r):
    return F(l.num+r.num,=20 l.den+r.den)
 
### Stern-Brocot-tree-traversal back and forth
 
trace =3D 0
 
def frac2path(f, path =3D [], left =3D F(0,1), right =3D=20 F(1,0)):
    m =3D = median(left,right)
    if=20 trace: print m
    if f =3D=3D=20 m:
        return=20 path
    elif f <=20 m:
        return frac2path(f, = path+["L"],=20 left, m)
   =20 else:
        return frac2path(f,=20 path+["R"], m, right)
 
def path2frac(p, left =3D F(0,1), result =3D F(1,1), right =3D=20 F(1,0)):
    if not=20 p:
        return=20 result
    if trace: print = result
    if=20 p[0]=3D=3D"L":
        return = path2frac(p[1:],=20 left, median(left,result), result)
   =20 else:
        return = path2frac(p[1:],=20 result, median(result,right), right)
   
### = Kirby's=20 fraction-class, slightly enhanced
 
class F:
 
    def=20 __init__(self,numer,denom):
       = #=20 reduce inputs to lowest = terms
       =20 numer =3D long(numer)        # = NEW: for=20 'big fractions'
        denom =3D=20 long(denom)
        gcd =3D=20 self.gcd(numer,denom)
        = self.num =3D=20 numer//gcd
        self.den =3D=20 denom//gcd
 
    def=20 __add__(self,other):
        # = find lowest=20 common multiple
        a,b =3D = self.num,=20 other.num
        comden =3D=20 self.lcm(self.den, = other.den)
        if=20 comden !=3D=20 self.den:
          = a *=3D=20 comden//self.den
        if comden = !=3D=20 other.den:
          = ; b *=3D=20 comden//other.den
        return=20 F(a+b,comden)
 
    def=20 __sub__(self,other):
        = return self +=20 (-other)
 
    def=20 __neg__(self):
        return=20 F(-self.num,self.den)
 
    def=20 __lt__(self,other):      # NEW: for = comparison:=20 m<n
        return = (self.num*other.den)=20 < (other.num*self.den)
 
    def=20 __eq__(self,other):      # NEW: for = comparison:=20 m=3D=3Dn
        return = (self.num*other.den)=20 =3D=3D (other.num*self.den)
 
    def=20 gcd(self,a,b):
        # find = greatest=20 common divisor of a,b
        if = b=3D=3D0:=20 return a
        else: return=20 self.gcd(b,a%b)
 
    def=20 lcm(self,a,b):
        # find = lowest=20 common multiple of a,b
        = return=20 a*b//self.gcd(a,b)
 
    def=20 __repr__(self):
        # = represent as=20 (a/b)
        return "(%s/%s)" %=20 (self.num, self.den)
 
### And now a test - run:
 
>>> frac2path(F(173,100))
['R', 'L', 'R', 'R', 'L', = 'R', 'R',=20 'L', 'L', 'R', 'L']
>>> path2frac(['R', 'L', 'R', 'R', 'L', = 'R',=20 'R', 'L', 'L', 'R', 'L'])
(173/100)
>>> trace =3D = 1
>>>=20 frac2path(F(173,100))
(1/1)
(2/1)
(3/2)
(5/3)
(7/4)
(12= /7)
(19/11)
(26/15)
(45/26)
(64/37)
(109/63)
(173/100)<= BR>['R',=20 'L', 'R', 'R', 'L', 'R', 'R', 'L', 'L', 'R', 'L']
>>>=20 path2frac(['R', 'L', 'R', 'R', 'L', 'R', 'R', 'L', 'L', 'R',=20 'L'])
(1/1)
(2/1)
(3/2)
(5/3)
(7/4)
(12/7)
(19/11)(26/15)
(45/26)
(64/37)
(109/63)
(173/100)
>>> =
...
>>> trace =3D 0
>>> path2frac(root_list)   # the one of=20 PV
(17083879020/9863382151)
>>>
Hope, you found this interesting
Gregor
 
--------------------------------------------------------------------= ------
P.S.: In my eyes the lack of class-methods in Python is still =
a little bit annoying.
 
------=_NextPart_000_0088_01C198BC.DC399780-- From dsh8290@rit.edu Wed Jan 9 02:53:50 2002 From: dsh8290@rit.edu (dman) Date: Tue, 8 Jan 2002 21:53:50 -0500 Subject: [Tutor] Utter newbie question In-Reply-To: <000501c198b3$d6005b00$fdcb36d2@renee123> References: <003201c19718$df617540$9d6760cb@renee123> <20020107022820.GA27042@localhost> <000501c198b3$d6005b00$fdcb36d2@renee123> Message-ID: <20020109025350.GB7272@localhost> On Wed, Jan 09, 2002 at 03:17:48PM +1300, Willem de Beer wrote: | Thanks for the info, although I still do not know what to do... :) Ok. | I downloaded SciPy-0.1.win32-py2.1.exe and ran it. It installed to | the directory c:\Python21. There is a multiarray.pyd file in the | Python21\DLLs directory, but I do not know what to do with it. My guess is that that installer doesn't include Numeric with it, but requires you to get it for yourself (now don't you wish you had apt-get ;-)). Go get Numeric and install it, that should help. Can you post the output of dir c:\python21 dir c:\python21\dlls ? -D -- If your company is not involved in something called "ISO 9000" you probably have no idea what it is. If your company _is_ involved in ISO 9000 then you definitely have no idea what it is. (Scott Adams - The Dilbert principle) From virketis@fas.harvard.edu Wed Jan 9 02:54:32 2002 From: virketis@fas.harvard.edu (Pijus Virketis) Date: Tue, 8 Jan 2002 21:54:32 -0500 Subject: [Tutor] Stern-Brocot tree: more fun math References: <00f901c1988d$0b429c50$dbadf78c@virketis2> <008b01c198b4$7aba00b0$1664a8c0@mega> Message-ID: <013f01c198b8$f764d730$dbadf78c@virketis2> This is a multi-part message in MIME format. ------=_NextPart_000_013C_01C1988F.0E29F2E0 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable >Then I developed another recursive solution (considering trees to be = naturally >recursive data-structures) - may be it's mathematically less = pretentious, but=20 > it works. While I would love to be "mathematically pretentious", the iterative = algorithm I used is from "Concrete Mathematics", so I cannot claim that = wonderful descriptive for myself... :) Sure enough, Gregor's recursive = code is cool. The thing is, for some reason I always find it easier to = think iteratively. Maybe it's time to take a look at Lisp and break this = barrier ... >P.S.: In my eyes the lack of class-methods in Python is still=20 >a little bit annoying. How would they be useful?=20 Cheers,=20 Pijus ------=_NextPart_000_013C_01C1988F.0E29F2E0 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
>Then I developed = another recursive=20 solution (considering trees to be naturally
>recursive=20 data-structures) - may be it's mathematically less pretentious, but=20
> it=20 works.
 
While I would love to be = "mathematically=20 pretentious", the iterative algorithm I used is from "Concrete = Mathematics", so=20 I cannot claim that wonderful descriptive for myself... :) Sure enough, = Gregor's=20 recursive code is cool. The thing is, for some reason I always = find it=20 easier to think iteratively. Maybe it's time to take a look at Lisp and = break=20 this barrier ...
 
>P.S.: In my eyes the lack = of=20 class-methods in Python is still
>a little bit annoying.
 
How would they be useful?=20
 
Cheers,
 
Pijus
 
------=_NextPart_000_013C_01C1988F.0E29F2E0-- From urnerk@qwest.net Wed Jan 9 03:24:07 2002 From: urnerk@qwest.net (Kirby Urner) Date: Tue, 08 Jan 2002 19:24:07 -0800 Subject: [Tutor] Stern-Brocot tree: more fun math In-Reply-To: <013f01c198b8$f764d730$dbadf78c@virketis2> References: <00f901c1988d$0b429c50$dbadf78c@virketis2> <008b01c198b4$7aba00b0$1664a8c0@mega> Message-ID: <4.2.0.58.20020108192336.01a5e270@pop3.norton.antivirus> > > >P.S.: In my eyes the lack of class-methods in Python is still > >a little bit annoying. As of 2.2, I think we do have class methods -- no need for an instance in order for the method to work. Kirby From urnerk@qwest.net Wed Jan 9 03:44:12 2002 From: urnerk@qwest.net (Kirby Urner) Date: Tue, 08 Jan 2002 19:44:12 -0800 Subject: [Tutor] Algorithm Question In-Reply-To: Message-ID: <4.2.0.58.20020108192437.01a5ed90@pop3.norton.antivirus> > find all possible arrangements : >(0001,0010,0100,1000,1001,1011,1111,0000,0110,1010,0101,1100, etc) Don't forget 0000 (maybe not legal in bank world). In this case, doing binary, the simplest approach is to just increment in base 2. A lot of these permutation generators can be thought of as counting problems, where you have a sequence with a defined order, i.e. lowest to highest. If you can think of a rule which defines the increment, and repeat it... For example, if you wanted all permutations of 0,1,2,3,4, with 3 slots to fill, then you could just increment in base 5: def base(n,b): """ Convert n in base 10 to list of digits in some positive integral base b < 10 """ digits = [] while n>0: r = n%b n = n//b digits = [r] + digits return digits >>> ["".join(map(str,([0,0,0]+base(i,5)))[-3:]) for i in range(125)] will give: ['000', '001', '002', '003', '004', '010', '011', '012', '013', '014' <> '412', '413', '414', '420', '421', '422', '423', '424', '430', '431', '432', '433', '434', '440', '441', '442', '443', '444'] Kirby From idiot1@netzero.net Wed Jan 9 04:43:18 2002 From: idiot1@netzero.net (kirk Bailey) Date: Tue, 08 Jan 2002 23:43:18 -0500 Subject: [Tutor] odd bodkins and novel emissions References: Message-ID: <3C3BCA66.A6D8BB8D@netzero.net> Danny Yoo wrote: > > On Tue, 8 Jan 2002, kirk Bailey wrote: > > > OK, it emits thus: > > > > ns# ./TLlistmaster.py < testfile > > From:= idiot1@netzero.net > > Subject field as extracted:='Re: quit idiot1@netzero.net testlist3 1010514864' > > CLEANED UP subject line='quit idiot1@netzero.net testlist3 1010514864' > > command='quit' > > oldfrom='idiot1@netzero.net' > > listname='testlist3' > > Pending action='quit idiot1@netzero.net testlist3 1010514864' > > command='quit'! Listname= testlist3 > > Listing members of testlist3 follows: > > ----------------------------------- > > Member= 'quit idiot1@netzero.net testlist3 1010514864' > > Member= 'quit idiot1@netzero.net testlist3 1010514864' > > ----------------------------------- > > They are already not a member! Aborting! > > Question: what does your member list look like? Is it a list of email > addresses, or a list of quitting commands? Each list has it's own email list of members. This is EXACTLY the sort used in majordomo or in sendmail ':include:' baised email lists. You could convert one of those to a TL list in 9 heartbeats- if you can type a single alias into the aliases script and recompile it that quick- and yank the old alias out. as there is NO outgoing alias, unlike majordomo, it is IMPOSSIBLE to guess that transmission alias and spam a list. TL is SECURE! you not a mamber and ok2post, you're not hitting the net, no discussion, period. Now what is being listed there is not the subscriber file at all, for it does not contain that information. It is the PENDING file! But why is it reading THE WRONG FILE?!?!? WHERE DID I FAIL??? A subscriber file looks like a flat list of naked email addresses, as: me@here.com you@there.org her@thatplace.cc us@whynot.info nobody@noplace.foo > The reason I'm asking this is > because I'm guessing that what comes from readmembers() is something like: > > ### > membernow = ['quit foobar@baz.org testlist1 1010514864', > 'quit balin@moria.org testlist2 2020202020'] > ### > > which I'll call a list of quitting commands. Is this right? > The list is called 'pending' and is a list of unconfirmed commands. There are 2 commands that have to be confirmed by emai, join or quit. They are configured as: command email listname cookie The cookie is the output of time.time turned into an intiger, then that into a string. This strips off the numbers which are a decimal of a second. pendings are VERY secure. First, the included email address MUST match the SENDING email address. The list specified MUST match the pending list, and the time cookie MUST match. the program strips off the "Re:" part, and then strips off leading and trailing whitespace, so the normal replay "Re:" does not hurt things. > Your from_addr, on the other hand, is just an email address like > "foobar@baz.org". Your code is doing a comparison: Sure is. if the provided email, which is what the confo message was sent to, does not match the REPLYING email, it's bogus, or assumed so. This is partly a test that it is a real account, and partly a test to make sure that person really wants this to happen, so jokers cannot send in subscriptions for someone else. When everything else is done I will add a provision to calculate the time code dor 7 days, add that to the timestamp, and see if it is smaller than the NOW time at runtime. if it is, it timed out and we kill it. > > ### > if from_addr not in membernow: > print 'They are already not a member! Aborting!' > ### > > so that's why I'm focusing on the contents of your members list. > > Good luck! Members list? For testlist3? ok. ns# list ./lists/testlist3 Listing of file ./lists/testlist3 in directory:/www/www.howlermonkey.net/cgi-bin shalehperry@attbi.com idiot1@netzero.net ns# While we are at it, let's list 'pending': ns# list ./lists/pending Listing of file ./lists/pending in directory:/www/www.howlermonkey.net/cgi-bin quit idiot1@netzero.net testlist3 1010514864 ns# Again, you can view the current listing of the script at http://www.howlermonkey.net/TLlistmaster.shtml as this is a ssi include, it inherently instantly updates the page if I modify the script. -- -Respectfully, -Kirk D Bailey end ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ |___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___| | _ \___ __ _ __| |_(_)_ _ __ _| |_| |_ ___ / __/ _ \| \| | | / _ Y _` (_-< _| | ' \/ _` | _| ' \/ -_) (_| (_) | .` |_ |_|_\___|__,_/__/\__|_|_||_\__, |\__|_||_\___|\___\___/|_|\_( ) |___/ |/ Kirk Bailey, consulting loose cannon www.howlermonkey.net highprimate@howlermonkey.net http://gipco.webjump.com idiot1@netzero.net _ _ _ _ ___ _ _ ___ _ _ _ _| |_ __ _| |_ __ _| |_(_)_ __ ___ / _ \ ' \/ -_) ' \ || | _/ _` | _/ _` | _| | ' \/ -_)_ \___/_||_\___|_||_\_,_|\__\__,_|\__\__,_|\__|_|_|_|_\___(_)_ ___ |___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___| ---------------------------------------------------- Sign Up for NetZero Platinum Today Only $9.95 per month! http://my.netzero.net/s/signup?r=platinum&refcd=PT97 From idiot1@netzero.net Wed Jan 9 04:59:04 2002 From: idiot1@netzero.net (kirk Bailey) Date: Tue, 08 Jan 2002 23:59:04 -0500 Subject: [Tutor] my time skeds Message-ID: <3C3BCE18.BCA1BD06@netzero.net> I am home after 10:45pm EST, and away after 3pm EST, M-F, and in general daytime until about 5:30 saterdays. Work evenigns, so do not expect replys from me until late in evening. Sat evening and subdays are generally chaos events, take your best shot and assume poor odds. -- -Respectfully, -Kirk D Bailey end ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ |___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___| | _ \___ __ _ __| |_(_)_ _ __ _| |_| |_ ___ / __/ _ \| \| | | / _ Y _` (_-< _| | ' \/ _` | _| ' \/ -_) (_| (_) | .` |_ |_|_\___|__,_/__/\__|_|_||_\__, |\__|_||_\___|\___\___/|_|\_( ) |___/ |/ Kirk Bailey, consulting loose cannon www.howlermonkey.net highprimate@howlermonkey.net http://gipco.webjump.com idiot1@netzero.net _ _ _ _ ___ _ _ ___ _ _ _ _| |_ __ _| |_ __ _| |_(_)_ __ ___ / _ \ ' \/ -_) ' \ || | _/ _` | _/ _` | _| | ' \/ -_)_ \___/_||_\___|_||_\_,_|\__\__,_|\__\__,_|\__|_|_|_|_\___(_)_ ___ |___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___| ---------------------------------------------------- Sign Up for NetZero Platinum Today Only $9.95 per month! http://my.netzero.net/s/signup?r=platinum&refcd=PT97 From idiot1@netzero.net Wed Jan 9 06:27:59 2002 From: idiot1@netzero.net (kirk Bailey) Date: Wed, 09 Jan 2002 01:27:59 -0500 Subject: [Tutor] TLlistmaster Message-ID: <3C3BE2EF.8CAD21F5@netzero.net> OK, found a couple of easy to miss typos, and a set of added quotemarks which turned a variable name into a literal with devistating results- that strange list of all the pendings was because it was reading the actual pending file due to the added quotes, instead of referring to the CONTENT! Only got one bug showing now, and this appears to be either a file creation bug adding an extra CRLF to the subwcriber file, which confuses the membership test, or I made a mistake when editing the file- and I suspect it's the former, still chasing it down. -- -Respectfully, -Kirk D Bailey end ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ |___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___| | _ \___ __ _ __| |_(_)_ _ __ _| |_| |_ ___ / __/ _ \| \| | | / _ Y _` (_-< _| | ' \/ _` | _| ' \/ -_) (_| (_) | .` |_ |_|_\___|__,_/__/\__|_|_||_\__, |\__|_||_\___|\___\___/|_|\_( ) |___/ |/ Kirk Bailey, consulting loose cannon www.howlermonkey.net highprimate@howlermonkey.net http://gipco.webjump.com idiot1@netzero.net _ _ _ _ ___ _ _ ___ _ _ _ _| |_ __ _| |_ __ _| |_(_)_ __ ___ / _ \ ' \/ -_) ' \ || | _/ _` | _/ _` | _| | ' \/ -_)_ \___/_||_\___|_||_\_,_|\__\__,_|\__\__,_|\__|_|_|_|_\___(_)_ ___ |___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___| ---------------------------------------------------- Sign Up for NetZero Platinum Today Only $9.95 per month! http://my.netzero.net/s/signup?r=platinum&refcd=PT97 From idiot1@netzero.net Wed Jan 9 06:53:03 2002 From: idiot1@netzero.net (kirk Bailey) Date: Wed, 09 Jan 2002 01:53:03 -0500 Subject: [Tutor] oh, BTW- Message-ID: <3C3BE8CF.247B84C0@netzero.net> I want to make a variable global so it shoes up for functions (subroutines) without bothering to pass it to them- makes coding much easier, but I did not read how to do this. Either someone slip me a tip, or point me at the right part of themanual, ok? -- -Respectfully, -Kirk D Bailey end ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ |___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___| | _ \___ __ _ __| |_(_)_ _ __ _| |_| |_ ___ / __/ _ \| \| | | / _ Y _` (_-< _| | ' \/ _` | _| ' \/ -_) (_| (_) | .` |_ |_|_\___|__,_/__/\__|_|_||_\__, |\__|_||_\___|\___\___/|_|\_( ) |___/ |/ Kirk Bailey, consulting loose cannon www.howlermonkey.net highprimate@howlermonkey.net http://gipco.webjump.com idiot1@netzero.net _ _ _ _ ___ _ _ ___ _ _ _ _| |_ __ _| |_ __ _| |_(_)_ __ ___ / _ \ ' \/ -_) ' \ || | _/ _` | _/ _` | _| | ' \/ -_)_ \___/_||_\___|_||_\_,_|\__\__,_|\__\__,_|\__|_|_|_|_\___(_)_ ___ |___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___| ---------------------------------------------------- Sign Up for NetZero Platinum Today Only $9.95 per month! http://my.netzero.net/s/signup?r=platinum&refcd=PT97 From spray14@hotmail.com Wed Jan 9 07:01:56 2002 From: spray14@hotmail.com (james kellam) Date: Wed, 09 Jan 2002 02:01:56 -0500 Subject: [Tutor] obfusciated python Message-ID: Hey Alan, You just now seeing "the light"? I have a book in front of me called "Learn to Program Using Python". It's got the same mumbo jumbo : "You set it by opening C:\AUTOEXE.BAT in Notepad and addding the line SET..." Well the first time I read the above (pg.232) I thought well now , a notepad is not a notepad, it'a now a program to program computers with. Hey what do I need python for? I also must have the first edition because it's full of typos and errors, almost unusable. Lucky for me I found "How to think like..." on a website. This is my first post and I've made it up to filters and strings in my studies. Next will be objects. When I run into any python related trouble I'll post again. Later, james P.S. Ya'll got a killer site a useless! _________________________________________________________________ Join the world’s largest e-mail service with MSN Hotmail. http://www.hotmail.com From glingl@aon.at Wed Jan 9 07:25:37 2002 From: glingl@aon.at (Gregor Lingl) Date: Wed, 9 Jan 2002 08:25:37 +0100 Subject: [Tutor] Another aftermath (Stern-Brocot tree): References: <00f901c1988d$0b429c50$dbadf78c@virketis2> <008b01c198b4$7aba00b0$1664a8c0@mega> <4.2.0.58.20020108192336.01a5e270@pop3.norton.antivirus> Message-ID: <002301c198de$d589bce0$1664a8c0@mega> Some remarks: 1. During sleep this problem apparently worked in my brain, so when I woke up it was easy to rewrite the code as follows - to get an equivalent iterative solution: (First I added a trivial __ne__ - method to the class F) def frac2path(f): path = [] left, m, right = F(0,1), F(1,1), F(1,0) while f != m: if f < m: path.append("L") right = m else: path.append("R") left = m m = median(left,right) if trace: print m return path def path2frac(p): left, result, right = F(0,1), F(1,1), F(1,0) while p: if trace: print result if p[0]=="L": result, right = median(left,result), result else: left, result = result, median(result,right) del p[0] return result 2. So it turned out to me (why only now?) that this is nothing else than a special sort of binary search. 3. Could you please explain this remark a little bit: > As of 2.2, I think we do have class methods -- no need > for an instance in order for the method to work. Is the gcd in the F-class something like this? Even when using it inside F we need a self. ... to call ist. And could we call this from outside the class without an instance? ( F.gcd(..., ...) as one might expect if it were similar to Java, does not work. ) Sincerely Gregor From Willem de Beer" <20020107022820.GA27042@localhost> <000501c198b3$d6005b00$fdcb36d2@renee123> <20020109025350.GB7272@localhost> Message-ID: <001801c198df$bf86dc60$947937d2@renee123> From: dman > > Go get Numeric and install it, that should help. Did that - null result. Can you post the > output of > dir c:\python21 > dir c:\python21\dlls > ? Uhm... betraying my recent history: How do I "pipe" the output to a text file in Windows? Willem From toodles@yifan.net Wed Jan 9 08:09:56 2002 From: toodles@yifan.net (Andy W) Date: Wed, 9 Jan 2002 16:09:56 +0800 Subject: [Tutor] oh, BTW- References: <3C3BE8CF.247B84C0@netzero.net> Message-ID: <001701c198e5$0d2d4d50$da00a8c0@Sun> Hi > I want to make a variable global so it shoes up for functions > (subroutines) without bothering to pass it to them- makes coding much > easier, but I did not read how to do this. Either someone slip me a > tip, or point me at the right part of themanual, ok? Some time before referencing the variable within your function (preferably at the very start), write "global variablename". eg. def function_name(): global variable_name #... Andy > > -- > > > > -Respectfully, > -Kirk D Bailey > > > end > ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ > |___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___| > | _ \___ __ _ __| |_(_)_ _ __ _| |_| |_ ___ / __/ _ \| \| | > | / _ Y _` (_-< _| | ' \/ _` | _| ' \/ -_) (_| (_) | .` |_ > |_|_\___|__,_/__/\__|_|_||_\__, |\__|_||_\___|\___\___/|_|\_( ) > |___/ |/ > > Kirk Bailey, consulting loose cannon > > www.howlermonkey.net highprimate@howlermonkey.net > http://gipco.webjump.com idiot1@netzero.net > _ _ _ _ > ___ _ _ ___ _ _ _ _| |_ __ _| |_ __ _| |_(_)_ __ ___ > / _ \ ' \/ -_) ' \ || | _/ _` | _/ _` | _| | ' \/ -_)_ > \___/_||_\___|_||_\_,_|\__\__,_|\__\__,_|\__|_|_|_|_\___(_)_ ___ > |___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___| > ---------------------------------------------------- > Sign Up for NetZero Platinum Today > Only $9.95 per month! > http://my.netzero.net/s/signup?r=platinum&refcd=PT97 > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From wesc@yahoo.com Wed Jan 9 08:19:47 2002 From: wesc@yahoo.com (Wesley J. Chun) Date: Wed, 9 Jan 2002 00:19:47 -0800 (PST) Subject: [Tutor] Python course in Silicon Valley (1/28-3/25) Message-ID: <20020109081947.65433.qmail@web10008.mail.yahoo.com> After a 1 year hiatus, UC Santa Cruz Extension is once again offering a Python course, Python Programming (I). The course is 8 weeks in total, one night a week (Monday nights) from January 28 - March 25 (no class on Presidents' Day, Feb 18). The class is taught in Sunnyvale. The course description and enrollment information can be found below or by calling Mickal at 408-566-4534: http://instruction.ucsc-extension.edu/wesc/013e44cd.htm if all goes well, i may be teaching a new course in the Spring, Python Programming 2, which follows right after the 1st course. if enrollments are not high enough for the advanced class, then i will probably teach the 1st class again. i have also put in a proposal for a "completely new to programming" course for newbies, but that has yet to be approved. anyway, hope to see some of you in class later this month!! -wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall PTR, © 2001 http://starship.python.net/crew/wesc/cpp/ wesley.j.chun :: wesc@yahoo.com cyberweb.consulting :: cyberweb@rocketmail.com http://www.dnai.com/~wesc/cyberweb/ __________________________________________________ Do You Yahoo!? Send FREE video emails in Yahoo! Mail! http://promo.yahoo.com/videomail/ From dyoo@hkn.eecs.berkeley.edu Wed Jan 9 08:23:01 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 9 Jan 2002 00:23:01 -0800 (PST) Subject: [Tutor] oh, BTW- In-Reply-To: <001701c198e5$0d2d4d50$da00a8c0@Sun> Message-ID: On Wed, 9 Jan 2002, Andy W wrote: > > (subroutines) without bothering to pass it to them- makes coding much > > easier, but I did not read how to do this. Either someone slip me a > > tip, or point me at the right part of themanual, ok? > > Some time before referencing the variable within your function > (preferably at the very start), write "global variablename". eg. > > def function_name(): > global variable_name > #... But as a warning: be careful about doing this. You may want to consider passing the parameters explicitely; perhaps there's a better way to do what you're trying to do, without using globals. Global variables can be a nightmare during debugging, because you lose the ability to easily look at each piece of your program in isolation. From scarblac@pino.selwerd.nl Wed Jan 9 10:49:23 2002 From: scarblac@pino.selwerd.nl (Remco Gerlich) Date: Wed, 9 Jan 2002 11:49:23 +0100 Subject: [Tutor] Algorithm Question In-Reply-To: ; from kauphlyn@speakeasy.org on Tue, Jan 08, 2002 at 05:31:52PM -0800 References: Message-ID: <20020109114923.A27648@pino.selwerd.nl> On 0, Daniel Coughlin wrote: > > This isnt really a python question per se, but rather a question about a > specific algorithm. I am no math wiz, and wondered if any of the math guru's on > this list could help me sort this out, or at least point me in the right > direction. > > I need to take in a variable quantity of integers (850,250,375,etc) and return a > list of all the possible sums of the numbers in the list given when each of > these is multiplied by say one through ten. To make > it a little simpler I'll > use a simpler example: input = (5, 10); output = (15,25,30,etc) all multiples of > 5 up to 150. A simple recursive version should do - with lists of lengths 0 or 1 it's trivial, and with larger lists you can first compute the numbers for a smaller part of the list, then add the first number to each number in the result, in all the possible multiples. To avoid duplicates we'd use a dictionary to store temporary results: def sums(L): if len(L) == 0: return [] if len(L) == 1: return range(L[0], L[0]*11, L[0]) smaller = sums(L[1:]) temporary = {} for sum in smaller: for i in range(1,11): temporary[sum+i*L[0]] = 0 return temporary.keys() > How does one go about solving these types of problems with some kind of > efficiency? Well, this is some sort of efficient - who knows how efficient :) But it should work, although it's untested. Don't go looking for efficiency before you *know* that this part is a bottleneck and your program is too slow without a better version. And if you finally decide that it needs to be faster, consider how you're using these numbers. If you only use a few for further computation, look for an algorithm that computes only those that you actually use. Besides - the current version uses a dictionary, so it already rocks :) -- Remco Gerlich From pythontutor@venix.com Wed Jan 9 13:21:32 2002 From: pythontutor@venix.com (Lloyd Kvam) Date: Wed, 09 Jan 2002 08:21:32 -0500 Subject: [Tutor] A small math puzzle [recreational Python] References: <4.2.0.58.20020106175446.00d2d5d0@pop3.norton.antivirus> Message-ID: <3C3C43DC.6030807@venix.com> I pulled out my old copy of LIU from 1968. It's stamped $12.56 (new). (I have to confess that I never liked the book.) So there's been a fair amount of inflation over the years. Kirby Urner wrote: > >> >> Thanks for the recommendation! I just ordered it from Amazon. Do you >> have any other introductory math books you'd recommend for those who are >> interested in this sort of stuff? > > > Yikes, out of print and $71 for a used copy. > > Math books are expensive. Lots over $100. > > Kirby > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From urnerk@qwest.net Wed Jan 9 14:28:01 2002 From: urnerk@qwest.net (Kirby Urner) Date: Wed, 09 Jan 2002 06:28:01 -0800 Subject: [Tutor] Algorithm Question In-Reply-To: <20020109114923.A27648@pino.selwerd.nl> References: Message-ID: <4.2.0.58.20020109061251.01a5aed0@pop3.norton.antivirus> > >def sums(L): > if len(L) == 0: > return [] > if len(L) == 1: > return range(L[0], L[0]*11, L[0]) > > smaller = sums(L[1:]) > temporary = {} > for sum in smaller: > for i in range(1,11): > temporary[sum+i*L[0]] = 0 > > return temporary.keys() I modified this to sort the output, and gave it: >>> sums([5,11,15]) and got: [31, 36, 41, 42, 46, 47, 51, 52, 53, 56, 57, 58, 61, 62, 63, 64, 66, 67, 68, 69, 71, 72, etc. etc. but shouldn't 5 + 2*15 = 30 be on the list? I confess I never understood Daniel's description of what he needed very well. Kirby Modified code: def sums(L): if len(L) == 0: return [] if len(L) == 1: return range(L[0], L[0]*11, L[0]) smaller = sums(L[1:]) temporary = {} for sum in smaller: for i in range(1,11): temporary[sum+i*L[0]] = 0 t = temporary.keys() t.sort() return t From urnerk@qwest.net Wed Jan 9 14:33:08 2002 From: urnerk@qwest.net (Kirby Urner) Date: Wed, 09 Jan 2002 06:33:08 -0800 Subject: [Tutor] Utter newbie question In-Reply-To: <001801c198df$bf86dc60$947937d2@renee123> References: <003201c19718$df617540$9d6760cb@renee123> <20020107022820.GA27042@localhost> <000501c198b3$d6005b00$fdcb36d2@renee123> <20020109025350.GB7272@localhost> Message-ID: <4.2.0.58.20020109062944.01ae86c0@pop3.norton.antivirus> At 08:32 PM 1/9/2002 +1300, Willem de Beer wrote: >From: dman > > > > > Go get Numeric and install it, that should help. > >Did that - null result. > > Can you post the > > output of > > dir c:\python21 > > dir c:\python21\dlls > > ? > >Uhm... betraying my recent history: How do I "pipe" the output to a text >file in Windows? > >Willem > dir c:\python21 > filename1.txt dir c:\python21\dlls > filename2.txt You confirmed Numeric is installed correctly. At blank IDLE window (GUI shell) go >>> import Numeric you should get nothing back. >>> dir(Numeric) should get you a huge long list of stuff. Kirby From scarblac@pino.selwerd.nl Wed Jan 9 14:42:29 2002 From: scarblac@pino.selwerd.nl (Remco Gerlich) Date: Wed, 9 Jan 2002 15:42:29 +0100 Subject: [Tutor] Algorithm Question In-Reply-To: <4.2.0.58.20020109061251.01a5aed0@pop3.norton.antivirus>; from urnerk@qwest.net on Wed, Jan 09, 2002 at 06:28:01AM -0800 References: <20020109114923.A27648@pino.selwerd.nl> <4.2.0.58.20020109061251.01a5aed0@pop3.norton.antivirus> Message-ID: <20020109154229.A27955@pino.selwerd.nl> On 0, Kirby Urner wrote: > I modified this to sort the output, and gave it: > > >>> sums([5,11,15]) > > and got: > > [31, 36, 41, 42, 46, 47, 51, 52, 53, 56, 57, 58, 61, 62, > 63, 64, 66, 67, 68, 69, 71, 72, > > etc. etc. > > but shouldn't 5 + 2*15 = 30 be on the list? I confess > I never understood Daniel's description of what he needed > very well. My interpretation is that all numbers from the list must be present in the sum, since they can be multiplied by 1 to 10, not 0. Therefore the lowest number is 31=5+11+15. His own example with [5,10] started with 15, not 0, 5 or 10 (but those aren't sums). So it's not 100% clear. If they can be absent from the sum as well, both range() calls should start from 0, not L[0] or 1. -- Remco Gerlich From urnerk@qwest.net Wed Jan 9 14:51:11 2002 From: urnerk@qwest.net (Kirby Urner) Date: Wed, 09 Jan 2002 06:51:11 -0800 Subject: [Tutor] Re: Another aftermath (Stern-Brocot tree): In-Reply-To: <002301c198de$d589bce0$1664a8c0@mega> References: <00f901c1988d$0b429c50$dbadf78c@virketis2> <008b01c198b4$7aba00b0$1664a8c0@mega> <4.2.0.58.20020108192336.01a5e270@pop3.norton.antivirus> Message-ID: <4.2.0.58.20020109063400.01aef980@pop3.norton.antivirus> > >3. Could you please explain this remark a little bit: > > > As of 2.2, I think we do have class methods -- no need > > for an instance in order for the method to work. See below re staticmethod(). >Is the gcd in the F-class something like this? F-class could be rewritten this way. But since every F needs a self (has its own numerator and denominator), it's fine to not. All instances point back to the same code, so it's not like each instance internally has its own copy of the methods. However, ith gcd and lcm, you have the option to move them out of the F class altogether and just define them in the same module as the F-class. When the F-class uses them, it'll just say gcd(a,b) without the self.gcd(a,b) in front. This gives users direct access to lcm and gcd without needing to refer to any F. >Even when using it inside F we need a self. ... >to call ist. And could we call this from outside >the class without an instance? >( F.gcd(..., ...) as one might expect if it were similar >to Java, does not work. ) > >Sincerely >Gregor This'll work if we go: class F: def __init__(self,numer,denom): # reduce inputs to lowest terms gcd = F.gcd(numer,denom) self.num = numer//gcd self.den = denom//gcd def __add__(self,other): # find lowest common multiple a,b = self.num, other.num comden = F.lcm(self.den, other.den) if comden != self.den: a *= comden//self.den if comden != other.den: b *= comden//other.den return F(a+b,comden) def gcd(a,b): # find greatest common divisor of a,b if b==0: return a else: return F.gcd(b,a%b) def lcm(a,b): # find lowest common multiple of a,b return a*b//F.gcd(a,b) def __repr__(self): # represent as (a/b) return "(%s/%s)" % (self.num, self.den) gcd = staticmethod(gcd) lcm = staticmethod(lcm) With instances: >>> a = F(1,2) >>> b = F(2,3) >>> a+b (7/6) Without: >>> F.gcd(10,45) 5 >>> F.lcm(10,45) 90 Note, to make your F-class even more versatile, you could define how to multiply two fractions, and how to raise fractions to integral powers, i.e. define __mul__ and __pow__. You could also divide fractions by overriding __div__ -- which comes in handy of the integral power is negative i.e. (1/2)**-1 = 2/1 and (1/2)**-2 = [2/1]**2 i.e. (p/q)**(-n) = (q/p)**n. Kirby From urnerk@qwest.net Wed Jan 9 14:59:52 2002 From: urnerk@qwest.net (Kirby Urner) Date: Wed, 09 Jan 2002 06:59:52 -0800 Subject: [Tutor] Algorithm Question In-Reply-To: <20020109154229.A27955@pino.selwerd.nl> References: <4.2.0.58.20020109061251.01a5aed0@pop3.norton.antivirus> <20020109114923.A27648@pino.selwerd.nl> <4.2.0.58.20020109061251.01a5aed0@pop3.norton.antivirus> Message-ID: <4.2.0.58.20020109065844.01af7130@pop3.norton.antivirus> At 03:42 PM 1/9/2002 +0100, Remco Gerlich wrote: >On 0, Kirby Urner wrote: > > I modified this to sort the output, and gave it: > > > > >>> sums([5,11,15]) > > > > and got: > > > > [31, 36, 41, 42, 46, 47, 51, 52, 53, 56, 57, 58, 61, 62, > > 63, 64, 66, 67, 68, 69, 71, 72, > > > > etc. etc. > > > > but shouldn't 5 + 2*15 = 30 be on the list? I confess > > I never understood Daniel's description of what he needed > > very well. Sorry, I goofed, I meant 5 + 2*15 = 35. Shouldn't 35 be present? >My interpretation is that all numbers from the list must be present in the >sum, since they can be multiplied by 1 to 10, not 0. Therefore the lowest >number is 31=5+11+15. Kirby From urnerk@qwest.net Wed Jan 9 15:04:58 2002 From: urnerk@qwest.net (Kirby Urner) Date: Wed, 09 Jan 2002 07:04:58 -0800 Subject: [Tutor] Algorithm Question In-Reply-To: <4.2.0.58.20020109065844.01af7130@pop3.norton.antivirus> References: <20020109154229.A27955@pino.selwerd.nl> <4.2.0.58.20020109061251.01a5aed0@pop3.norton.antivirus> <20020109114923.A27648@pino.selwerd.nl> <4.2.0.58.20020109061251.01a5aed0@pop3.norton.antivirus> Message-ID: <4.2.0.58.20020109070344.01af7620@pop3.norton.antivirus> At 06:59 AM 1/9/2002 -0800, Kirby Urner wrote: >At 03:42 PM 1/9/2002 +0100, Remco Gerlich wrote: >>On 0, Kirby Urner wrote: >> > I modified this to sort the output, and gave it: >> > >> > >>> sums([5,11,15]) >> > >> > and got: >> > >> > [31, 36, 41, 42, 46, 47, 51, 52, 53, 56, 57, 58, 61, 62, >> > 63, 64, 66, 67, 68, 69, 71, 72, >> > >> > etc. etc. >> > >> > but shouldn't 5 + 2*15 = 30 be on the list? I confess >> > I never understood Daniel's description of what he needed >> > very well. > >Sorry, I goofed, I meant 5 + 2*15 = 35. Shouldn't 35 be >present? Nevermind, same answer -- you're saying 11 has to be there. OK. I got it now. I see what you're telling me. Kirby From dsh8290@rit.edu Wed Jan 9 15:14:36 2002 From: dsh8290@rit.edu (dman) Date: Wed, 9 Jan 2002 10:14:36 -0500 Subject: [Tutor] Utter newbie question In-Reply-To: <001801c198df$bf86dc60$947937d2@renee123> References: <003201c19718$df617540$9d6760cb@renee123> <20020107022820.GA27042@localhost> <000501c198b3$d6005b00$fdcb36d2@renee123> <20020109025350.GB7272@localhost> <001801c198df$bf86dc60$947937d2@renee123> Message-ID: <20020109151436.GD9355@localhost> On Wed, Jan 09, 2002 at 08:32:08PM +1300, Willem de Beer wrote: | Can you post the | > output of | > dir c:\python21 | > dir c:\python21\dlls | > ? | | Uhm... betraying my recent history: How do I "pipe" the output to a text | file in Windows? What Kirby said, or copy-n-paste from the output window. -D -- Pride goes before destruction, a haughty spirit before a fall. Proverbs 16:18 From dsh8290@rit.edu Wed Jan 9 15:17:56 2002 From: dsh8290@rit.edu (dman) Date: Wed, 9 Jan 2002 10:17:56 -0500 Subject: [Tutor] obfusciated python In-Reply-To: References: Message-ID: <20020109151756.GE9355@localhost> On Wed, Jan 09, 2002 at 02:01:56AM -0500, james kellam wrote: | Well the first time I read the above (pg.232) I thought | well now , a notepad is not a notepad, it'a now a program to program | computers with. Hey what do I need python for? Hehe. Sure, you can use notepad to create source files, but you'll still need the appropriate tools to convert that source into actual behavior :-). An if you think notepad is a good programmer's editor, take a look at things like nedit, gvim, or emacs. gvim is my preferred editor. nedit has a notepad-like interface but includes syntax highlighting, autoindenting, and tab expansion. I seem to think there's a windows build of it somewhere. -D -- The way of a fool seems right to him, but a wise man listens to advice. Proverbs 12:15 From karthikg@aztec.soft.net Wed Jan 9 15:34:53 2002 From: karthikg@aztec.soft.net (Karthik Gurumurthy) Date: Wed, 9 Jan 2002 21:04:53 +0530 Subject: [Tutor] desperately looking for xslt code example using pyxml In-Reply-To: <4.2.0.58.20020109065844.01af7130@pop3.norton.antivirus> Message-ID: hi all, Did anyone use PyXML0.7 release. It has xslt, xpath support built into it. I have a xsl file --> style.xsl from xml.xslt.Processor import * p = Processor() p.setStyleSheetReader(style.xsl) xmlDoc = getStringRep() p.runString(xmlDoc) --> this fails any help?? thanks, karthik. From alan.gauld@bt.com Wed Jan 9 15:17:56 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Wed, 9 Jan 2002 15:17:56 -0000 Subject: [Tutor] obfusciated python Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C258@mbtlipnt02.btlabs.bt.co.uk> > of me called "Learn to Program Using Python". It's got the > same mumbo jumbo : "You set it by opening C:\AUTOEXE.BAT > in Notepad and adding the line SET..." Yeah, but it also says a pre-requisite to read the book is that you know the basics of operating a computer and if not to look up things in your computer's manual... Setting environment variables comes under that heading. :-) > I also must have the first edition because it's full of > typos and errors, almost unusable. Hmm, I wouldn't go that far, most are simple spelling mistakes and minor layout errors during typesetting - Warning to wannabe authors: Python is much more sensitive to that than other programming languages because of not having block markers: int hello(){ printf('hello world\n'); return 0; } is a minor typo in a C book but the equivalent one-space error is a disaster in a Python book! :-( However the errata page at: http://www.freenetpages.co.uk/hp/alan.gauld/book/ Should list and fix most (all?) of them. > Lucky for me I found "How to think like..." on a website. Yes that's a good resource too although it doesn't cover as much material as my tutor does (especially the book version). > This is my first post and I've made it up to filters and > strings in my studies. Next will be objects. Feel free to ask questions we're all here to help. Alan g. Author of the 'Learning to Program' web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld@bt.com Wed Jan 9 15:21:32 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Wed, 9 Jan 2002 15:21:32 -0000 Subject: [Tutor] Utter newbie question Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C259@mbtlipnt02.btlabs.bt.co.uk> > Uhm... betraying my recent history: How do I "pipe" the > output to a text file in Windows? In a DOS box: C:\> dir c:\python21 > py21.txt C:\> dir c:\python21\dlls > dlls.txt Should do it, Alan G From alan.gauld@bt.com Wed Jan 9 15:36:29 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Wed, 9 Jan 2002 15:36:29 -0000 Subject: [Tutor] Re: Another aftermath (Stern-Brocot tree): Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C25A@mbtlipnt02.btlabs.bt.co.uk> > class F: > def gcd(a,b): > # find greatest common divisor of a,b > gcd = staticmethod(gcd) > > With instances: > >>> a = F(1,2) > >>> b = F(2,3) > >>> a+b > (7/6) > > Without: > >>> F.gcd(10,45) > 5 Which is a good enough demo of how to create and access the new static (aka class) methods but is not a good example of what a class method should be used for - they are normally methods that apply to all instances of the class or do things at the abstract class level like change the default timeout of a socket class for example, or get a list(or count) of all instances... Thus a string class method upper() could upper case all string instances say. Or a Fraction gcd() class method could find the gcd of all existing fraction instances... Constructors are often implemented as class methods too. The idea of using static methods to wrap up what should really be functions or procedures is a really bad idea from Java land IMHO. (Coz Java's broken object system offers no other way to do it!) Bah, humbug :-) Alan g. From urnerk@qwest.net Wed Jan 9 15:56:52 2002 From: urnerk@qwest.net (Kirby Urner) Date: Wed, 09 Jan 2002 07:56:52 -0800 Subject: [Tutor] Re: Another aftermath (Stern-Brocot tree): In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66C25A@mbtlipnt02.btlabs .bt.co.uk> Message-ID: <4.2.0.58.20020109075556.01ae6ea0@pop3.norton.antivirus> > >Which is a good enough demo of how to create and access >the new static (aka class) methods but is not a good >example of what a class method should be used for Agreed. And yes, Java forces us to do it this way because everything is in a class. Moving the likes of gcd and lcm out of the class and having them be free floating in the same module is a better approach in this case. Kirby From spray14@hotmail.com Wed Jan 9 16:04:44 2002 From: spray14@hotmail.com (james kellam) Date: Wed, 09 Jan 2002 11:04:44 -0500 Subject: [Tutor] Can gvim60win32 be used in pace of IDLE? Message-ID: Hello, I've had gvim for a while now, and it's a nice editor. I read in an earlier thread where dman mentions it. Does this mean you can use it instead of IDLE? This would be great since gvim is on my pop up when I right-click as an option; Edit with gvim I tried to post this question on the vim@vim.org website but all I've recieved is 7 delightfull exchanges of correspondence between me and a machine! So, I've about given up on that route. I'm confirmed as a member of the mail list, just no mail! Oh yeh, I got a lot of files from 'em filling up my junk folders. Just saw the thread and thought I'd ask. Later, james _________________________________________________________________ Get your FREE download of MSN Explorer at http://explorer.msn.com/intl.asp. From idiot1@netzero.net Wed Jan 9 16:24:51 2002 From: idiot1@netzero.net (kirk Bailey) Date: Wed, 09 Jan 2002 11:24:51 -0500 Subject: [Tutor] Re: TLlistmaster.py Message-ID: <3C3C6ED3.AF9ED28E@netzero.net> Ah, coffee. ok, me awake, me snakecharming, me here. let the gremlins begin their play! feel free to feel freely at TLlistmaster, and see how it twitches. -- -Respectfully, -Kirk D Bailey end ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ |___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___| | _ \___ __ _ __| |_(_)_ _ __ _| |_| |_ ___ / __/ _ \| \| | | / _ Y _` (_-< _| | ' \/ _` | _| ' \/ -_) (_| (_) | .` |_ |_|_\___|__,_/__/\__|_|_||_\__, |\__|_||_\___|\___\___/|_|\_( ) |___/ |/ Kirk Bailey, consulting loose cannon www.howlermonkey.net highprimate@howlermonkey.net http://gipco.webjump.com idiot1@netzero.net _ _ _ _ ___ _ _ ___ _ _ _ _| |_ __ _| |_ __ _| |_(_)_ __ ___ / _ \ ' \/ -_) ' \ || | _/ _` | _/ _` | _| | ' \/ -_)_ \___/_||_\___|_||_\_,_|\__\__,_|\__\__,_|\__|_|_|_|_\___(_)_ ___ |___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___| ---------------------------------------------------- Sign Up for NetZero Platinum Today Only $9.95 per month! http://my.netzero.net/s/signup?r=platinum&refcd=PT97 From urnerk@qwest.net Wed Jan 9 17:42:13 2002 From: urnerk@qwest.net (Kirby Urner) Date: Wed, 09 Jan 2002 09:42:13 -0800 Subject: [Tutor] Can gvim60win32 be used in pace of IDLE? In-Reply-To: Message-ID: <4.2.0.58.20020109093946.01a5c100@pop3.norton.antivirus> At 11:04 AM 1/9/2002 -0500, james kellam wrote: >Hello, > I've had gvim for a while now, and it's a nice editor. >I read in an earlier thread where dman mentions it. Does this mean you can >use it instead of IDLE? You can use it in place of IDLE's text editor, but not as a replacement for the interactive shell. Two windows open would be more the usual (Vim in one, IDLE shell in other). If in Windows, a 3rd DOS window for testing any modules with Tk.mainloop() would be likely as well. Some people don't believe in using Python interactively and just write scripts which execute from start to finish. That's alien to me, but if it's your style (to not test program fragments interactively in the shell), then yes, you don't need IDLE at all. Kirby From alan.gauld@bt.com Wed Jan 9 17:37:41 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Wed, 9 Jan 2002 17:37:41 -0000 Subject: [Tutor] Can gvim60win32 be used in pace of IDLE? Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C25E@mbtlipnt02.btlabs.bt.co.uk> > I've had gvim for a while now, and it's a nice editor. Yes, it's been my preferred editor on Windows for a long time, the latest release(v6.x) with folding etc is just great! > use it instead of IDLE? As an editor yes, it has a syntax mode to colorize the code. It won't run the programs like IDLE will you have to keep a Python box open(maybe IDLE) or just run the program from a DOS prompt: ie while editing foo.py in gvim have a DOS window open and use: C:\> python foo.py DOSKEY or F3 will recall the last line so you just keep hitting F3 and watch the results. Its actually my normal way of working for big programs and for any Tkinter work. > Edit with gvim Likewise and its really good to have the two edit options, one linked to IDLE and the other to vim. Alan G. From Michael.Baker@anchorgaming.com Wed Jan 9 18:10:44 2002 From: Michael.Baker@anchorgaming.com (Baker, Michael) Date: Wed, 9 Jan 2002 10:10:44 -0800 Subject: [Tutor] accessing dynamically created py objects Message-ID: <5A021171E87BD411AF7700508B6940D001E07A8D@anchorgaming.anchorgaming.com> i can make this function: >>> def maker(n=10): for a in range(n): exec "N%s=0" % a print dir() and then call it: >>> maker(10) ['N0', 'N1', 'N2', 'N3', 'N4', 'N5', 'N6', 'N7', 'N8', 'N9', 'a', 'n'] >>> maker(20) ['N0', 'N1', 'N10', 'N11', 'N12', 'N13', 'N14', 'N15', 'N16', 'N17', 'N18', 'N19', 'N2', 'N3', 'N4', 'N5', 'N6', 'N7', 'N8', 'N9', 'a', 'n'] >>> i'm trying to use something like this to track ranges of a random number generator. i need to access each object after it has been created to modify its value. running another exec statement in the above example doesn't work - exec "N%s=N%s+1" % n i'd like to then return a list containing the aggregate values stored in each object created when the function is run. how can i make this work?? thanks in advance mb From Willem de Beer" Message-ID: <001701c19942$731f31c0$36cc36d2@renee123> Scroll down for the dir c:\python21\dlls outout. Best regards Willem > > Uhm... betraying my recent history: How do I "pipe" the > > output to a text file in Windows? > > In a DOS box: > > C:\> dir c:\python21 > py21.txt > Volume in drive C has no label Volume Serial Number is 1360-14D9 Directory of C:\Python21 .
01-03-02 11:01a . .. 01-03-02 11:01a .. DOCUME~1 01-03-02 11:01a Documentation DOWNLO~1 01-03-02 11:01a Downloads WIN32C~1 01-03-02 11:01a win32comext LIB 01-03-02 11:01a Lib WIN32COM 01-03-02 11:01a win32com TOOLS 01-03-02 11:01a Tools WIN32 01-03-02 11:01a win32 PPM LOG 5 07-26-01 2:50p PPM.LOG TCL 01-03-02 11:01a tcl INCLUDE 01-03-02 11:01a include PYTHON~1 01-03-02 11:01a Pythonwin AS_PYDOC 01-03-02 11:01a as_pydoc LIBS 01-03-02 11:01a libs PPM 01-03-02 11:01a PPM PYC ICO 766 07-26-01 11:33a pyc.ico CHANGE~1 TXT 874 07-26-01 11:33a changes-ActivePython.txt PPD ICO 3,310 07-26-01 11:33a ppd.ico PYTHON EXE 20,566 07-26-01 11:39a python.exe DLLS 01-03-02 11:01a DLLs RELEAS~1 HTM 19,556 07-26-01 11:33a RELEASE.html LICENSE TXT 9,844 07-26-01 11:33a license.txt PYTHONW EXE 20,567 07-26-01 11:39a pythonw.exe W9XPOPEN EXE 16,384 07-26-01 11:39a w9xpopen.exe PPM PTH 3 07-26-01 11:33a PPM.pth PY ICO 766 07-26-01 11:33a py.ico SUPPORT 01-03-02 11:02a Support PYPPM PY 1,506 07-26-01 2:49p pyppm.py PYCON ICO 766 07-26-01 11:33a pycon.ico PYPPM BAT 290 07-26-01 11:33a pyppm.bat FFT 01-07-02 11:16a FFT MA 01-07-02 11:16a MA NUMERIC 01-07-02 11:16a Numeric RNG 01-07-02 11:16a RNG NUMERIC PTH 9 01-09-02 6:20p Numeric.pth SCIPY-~1 LOG 183,719 01-09-02 6:21p SciPy-wininst.log REMOVE~1 EXE 18,432 01-09-02 6:20p RemoveSciPy.exe GUI_TH~1 01-07-02 12:09p gui_thread SCIPY 01-07-02 12:09p scipy NUMERI~1 LOG 2,418 01-09-02 3:38p Numeric-wininst.log REMOVE~2 EXE 18,432 01-09-02 3:38p RemoveNumeric.exe 19 file(s) 318,213 bytes 23 dir(s) 695,775,232 bytes free > C:\> dir c:\python21\dlls > dlls.txt Volume in drive C has no label Volume Serial Number is 1360-14D9 Directory of C:\Python21\DLLs . 01-03-02 11:01a . .. 01-03-02 11:01a .. MMAP PYD 24,576 07-26-01 11:39a mmap.pyd PYEXPAT PYD 32,855 07-26-01 11:39a pyexpat.pyd UNICOD~1 PYD 212,992 07-26-01 11:39a unicodedata.pyd SELECT PYD 20,566 07-26-01 11:39a select.pyd _SRE PYD 49,236 07-26-01 11:39a _sre.pyd _TESTC~1 PYD 20,480 07-26-01 11:39a _testcapi.pyd PARSER PYD 41,046 07-26-01 11:39a parser.pyd TK83 DLL 950,272 07-26-01 11:37a tk83.dll XMLTOK DLL 81,920 07-26-01 11:33a xmltok.dll WINSOUND PYD 20,480 07-26-01 11:39a winsound.pyd _SYMTA~1 PYD 20,480 07-26-01 11:39a _symtable.pyd BSDDB PYD 82,005 07-26-01 11:39a bsddb.pyd _TKINTER PYD 28,760 07-26-01 11:39a _tkinter.pyd ZLIB PYD 61,524 07-26-01 11:39a zlib.pyd TCL83 DLL 483,328 07-26-01 11:35a tcl83.dll XMLPARSE DLL 53,248 07-26-01 11:33a xmlparse.dll _SOCKET PYD 36,951 07-26-01 11:39a _socket.pyd _WINREG PYD 36,864 07-26-01 11:39a _winreg.pyd MULTIA~1 PYD 32,768 10-30-00 10:21p multiarray.pyd 19 file(s) 2,290,351 bytes 2 dir(s) 695,771,136 bytes free From Willem de Beer" Message-ID: <001f01c19942$7bee7180$36cc36d2@renee123> Scroll down for the dir c:\python21\dlls outout. Best regards Willem > > Uhm... betraying my recent history: How do I "pipe" the > > output to a text file in Windows? > > In a DOS box: > > C:\> dir c:\python21 > py21.txt > Volume in drive C has no label Volume Serial Number is 1360-14D9 Directory of C:\Python21 . 01-03-02 11:01a . .. 01-03-02 11:01a .. DOCUME~1 01-03-02 11:01a Documentation DOWNLO~1 01-03-02 11:01a Downloads WIN32C~1 01-03-02 11:01a win32comext LIB 01-03-02 11:01a Lib WIN32COM 01-03-02 11:01a win32com TOOLS 01-03-02 11:01a Tools WIN32 01-03-02 11:01a win32 PPM LOG 5 07-26-01 2:50p PPM.LOG TCL 01-03-02 11:01a tcl INCLUDE 01-03-02 11:01a include PYTHON~1 01-03-02 11:01a Pythonwin AS_PYDOC 01-03-02 11:01a as_pydoc LIBS 01-03-02 11:01a libs PPM 01-03-02 11:01a PPM PYC ICO 766 07-26-01 11:33a pyc.ico CHANGE~1 TXT 874 07-26-01 11:33a changes-ActivePython.txt PPD ICO 3,310 07-26-01 11:33a ppd.ico PYTHON EXE 20,566 07-26-01 11:39a python.exe DLLS 01-03-02 11:01a DLLs RELEAS~1 HTM 19,556 07-26-01 11:33a RELEASE.html LICENSE TXT 9,844 07-26-01 11:33a license.txt PYTHONW EXE 20,567 07-26-01 11:39a pythonw.exe W9XPOPEN EXE 16,384 07-26-01 11:39a w9xpopen.exe PPM PTH 3 07-26-01 11:33a PPM.pth PY ICO 766 07-26-01 11:33a py.ico SUPPORT 01-03-02 11:02a Support PYPPM PY 1,506 07-26-01 2:49p pyppm.py PYCON ICO 766 07-26-01 11:33a pycon.ico PYPPM BAT 290 07-26-01 11:33a pyppm.bat FFT 01-07-02 11:16a FFT MA 01-07-02 11:16a MA NUMERIC 01-07-02 11:16a Numeric RNG 01-07-02 11:16a RNG NUMERIC PTH 9 01-09-02 6:20p Numeric.pth SCIPY-~1 LOG 183,719 01-09-02 6:21p SciPy-wininst.log REMOVE~1 EXE 18,432 01-09-02 6:20p RemoveSciPy.exe GUI_TH~1 01-07-02 12:09p gui_thread SCIPY 01-07-02 12:09p scipy NUMERI~1 LOG 2,418 01-09-02 3:38p Numeric-wininst.log REMOVE~2 EXE 18,432 01-09-02 3:38p RemoveNumeric.exe 19 file(s) 318,213 bytes 23 dir(s) 695,775,232 bytes free > C:\> dir c:\python21\dlls > dlls.txt Volume in drive C has no label Volume Serial Number is 1360-14D9 Directory of C:\Python21\DLLs . 01-03-02 11:01a . .. 01-03-02 11:01a .. MMAP PYD 24,576 07-26-01 11:39a mmap.pyd PYEXPAT PYD 32,855 07-26-01 11:39a pyexpat.pyd UNICOD~1 PYD 212,992 07-26-01 11:39a unicodedata.pyd SELECT PYD 20,566 07-26-01 11:39a select.pyd _SRE PYD 49,236 07-26-01 11:39a _sre.pyd _TESTC~1 PYD 20,480 07-26-01 11:39a _testcapi.pyd PARSER PYD 41,046 07-26-01 11:39a parser.pyd TK83 DLL 950,272 07-26-01 11:37a tk83.dll XMLTOK DLL 81,920 07-26-01 11:33a xmltok.dll WINSOUND PYD 20,480 07-26-01 11:39a winsound.pyd _SYMTA~1 PYD 20,480 07-26-01 11:39a _symtable.pyd BSDDB PYD 82,005 07-26-01 11:39a bsddb.pyd _TKINTER PYD 28,760 07-26-01 11:39a _tkinter.pyd ZLIB PYD 61,524 07-26-01 11:39a zlib.pyd TCL83 DLL 483,328 07-26-01 11:35a tcl83.dll XMLPARSE DLL 53,248 07-26-01 11:33a xmlparse.dll _SOCKET PYD 36,951 07-26-01 11:39a _socket.pyd _WINREG PYD 36,864 07-26-01 11:39a _winreg.pyd MULTIA~1 PYD 32,768 10-30-00 10:21p multiarray.pyd 19 file(s) 2,290,351 bytes 2 dir(s) 695,771,136 bytes free From urnerk@qwest.net Wed Jan 9 19:21:49 2002 From: urnerk@qwest.net (Kirby Urner) Date: Wed, 09 Jan 2002 11:21:49 -0800 Subject: [Tutor] accessing dynamically created py objects In-Reply-To: <5A021171E87BD411AF7700508B6940D001E07A8D@anchorgaming.anch orgaming.com> Message-ID: <4.2.0.58.20020109111503.01af3340@pop3.norton.antivirus> > >how can i make this work?? > >thanks in advance >mb To me, it makes more sense to create your N0..Nn as keys to a dictionary, and then use these to map to values. If you need multiple values, you could map to lists. e.g. >>> gens = {} >>> def maker(n): for i in range(n): gens["N"+str(i)]=[0,0] >>> maker(5) >>> gens {'N0': [0, 0], 'N1': [0, 0], 'N2': [0, 0], 'N3': [0, 0], 'N4': [0, 0]} Here each Nn is paired with [0,0] i.e. you could populate either or both elements. Now you can go: >>> gens['N4'][0] += 1 # increment 0th element of N4 list >>> gens {'N0': [0, 0], 'N1': [0, 0], 'N2': [0, 0], 'N3': [0, 0], 'N4': [1, 0]} It's easier to mass-create distinct entities using some data structure than to synthesize variables at the outermost (module) level. Kirby From Michael.Baker@anchorgaming.com Wed Jan 9 21:22:38 2002 From: Michael.Baker@anchorgaming.com (Baker, Michael) Date: Wed, 9 Jan 2002 13:22:38 -0800 Subject: [Tutor] accessing dynamically created py objects Message-ID: <5A021171E87BD411AF7700508B6940D001E07A90@anchorgaming.anchorgaming.com> yes thanks that'll do here's my code: def getStop(stops,awards,weightranges,iterations=1): t1=time() ran=random STOPS={} print "i'm workin..." for item in range(len(stops)): STOPS["STOP"+str(item)]=0.0 for a in range(iterations): r=ran()*weightranges[-1] for n in weightranges: if r<=n: #get slice index - NOT STOP NUMBER! st=weightranges.index(n) break stop=stops[st] award=awards[st] STOPS['STOP'+str(stop)]+=1 #sort print "...ok i'm done" for d in STOPS.keys(): STOPS[d]=STOPS[d]/iterations*100 print "process took ",time()-t1," seconds" return [stop,award,STOPS] >>> stops=[0,1,2,3,4,5,6,7,8,9] >>> awards=[2500,500,250,100,75,60,50,45,35,25] >>> weights=[1,3,8,14,22,32,62,132,482,812] >>> s=getStop(stops,awards,weights,1000000) i'm workin... ...ok i'm done 28.2400000095 seconds >>> s [7, 35, {'STOP2': 0.23540000000000003, 'STOP3': 40.566800000000001, 'STOP0': 0.1245, 'STOP1': 3.7212000000000001, 'STOP6': 0.97499999999999998, 'STOP7': 43.130600000000001, 'STOP4': 0.62319999999999998, 'STOP5': 8.6646000000000001, 'STOP8': 0.74390000000000001, 'STOP9': 1.2148000000000001}] -----Original Message----- From: Kirby Urner [mailto:urnerk@qwest.net] Sent: Wednesday, January 09, 2002 1:22 PM To: Baker, Michael Cc: 'tutor@python.org' Subject: Re: [Tutor] accessing dynamically created py objects > >how can i make this work?? > >thanks in advance >mb To me, it makes more sense to create your N0..Nn as keys to a dictionary, and then use these to map to values. If you need multiple values, you could map to lists. e.g. >>> gens = {} >>> def maker(n): for i in range(n): gens["N"+str(i)]=[0,0] >>> maker(5) >>> gens {'N0': [0, 0], 'N1': [0, 0], 'N2': [0, 0], 'N3': [0, 0], 'N4': [0, 0]} Here each Nn is paired with [0,0] i.e. you could populate either or both elements. Now you can go: >>> gens['N4'][0] += 1 # increment 0th element of N4 list >>> gens {'N0': [0, 0], 'N1': [0, 0], 'N2': [0, 0], 'N3': [0, 0], 'N4': [1, 0]} It's easier to mass-create distinct entities using some data structure than to synthesize variables at the outermost (module) level. Kirby From glingl@aon.at Wed Jan 9 23:05:15 2002 From: glingl@aon.at (Gregor Lingl) Date: Thu, 10 Jan 2002 00:05:15 +0100 Subject: [Tutor] Algorithm Question References: <4.2.0.58.20020108192437.01a5ed90@pop3.norton.antivirus> Message-ID: <009901c19962$199b7df0$1664a8c0@mega> > > For example, if you wanted all permutations of 0,1,2,3,4, > with 3 slots to fill, then you could just increment > in base 5: > > def base(n,b): > """ > Convert n in base 10 to list of digits > in some positive integral base b < 10 > """ > digits = [] > while n>0: > r = n%b > n = n//b > digits = [r] + digits > return digits > > >>> ["".join(map(str,([0,0,0]+base(i,5)))[-3:]) for i in range(125)] > > will give: > An alternate solution could be attained using a similar appraoch as to teresa: (yes, I know, soon it will be enough of this (albeit seemingly powerful) stuff) def codelist(chars, length): codes = [] makecodes(chars, length, '', codes) return codes def makecodes(chars, length, begin, codes): if length == 0: codes.append(begin) # this begin is now the end return for char in chars: makecodes(chars, length-1, begin + char, codes) >>> codelist('01', 3) ['000', '001', '010', '011', '100', '101', '110', '111'] >>> codelist('01', 4) ['0000', '0001', '0010', '0011', '0100', '0101', '0110', '0111', '1000', '1001', '1010', '1011', '1100', '1101', '1110', '1111'] >>> codelist('ABC', 3) ['AAA', 'AAB', 'AAC', 'ABA', 'ABB', 'ABC', 'ACA', 'ACB', 'ACC', 'BAA', 'BAB', 'BAC', 'BBA', 'BBB', 'BBC', 'BCA', 'BCB', 'BCC', 'CAA', 'CAB', 'CAC', 'CBA', 'CBB', 'CBC', 'CCA', 'CCB', 'CCC'] >>> codelist('wxyz', 2) ['ww', 'wx', 'wy', 'wz', 'xw', 'xx', 'xy', 'xz', 'yw', 'yx', 'yy', 'yz', 'zw', 'zx', 'zy', 'zz'] >>> Gregor From lha2@columbia.edu Wed Jan 9 23:09:31 2002 From: lha2@columbia.edu (Lloyd Hugh Allen) Date: Wed, 09 Jan 2002 18:09:31 -0500 Subject: [Tutor] Algorithm Question References: <20020109154229.A27955@pino.selwerd.nl> <4.2.0.58.20020109061251.01a5aed0@pop3.norton.antivirus> <20020109114923.A27648@pino.selwerd.nl> <4.2.0.58.20020109061251.01a5aed0@pop3.norton.antivirus> <4.2.0.58.20020109070344.01af7620@pop3.norton.antivirus> Message-ID: <3C3CCDAB.DA2DB74B@mail.verizon.net> It seems to me that we're looking for a variation on a multiplication table (only with addition, and with funny headings on the rows and columns). A vanilla multiplication table (so that you can see what's going on) can be generated by >>> thelist = [] >>> for count1 in range(11): thelist.append([]) for count2 in range(11): thelist[count1].append(count1*count2) to get an addition table, change the * to a +; to get what you want, give count1 and count2 a coefficient in the last line, as in thelist[count1].append(5*count1 + 2*count2) as a mathematician, I'm uncomfortable with getting rid of the entries generated by count1 being 0 and those generated by count2 being 0 (the generators should be in your answer list/matrix; to do otherwise makes my stomach twist for some reason). The exercise for the reader is to take this 2-dimensional list/matrix and flatten it into a one-dimensional list with no repeated entries. I had one lying around in lisp a second ago, and I guess it's not that hard to write a cdr() and car()... or you could leave out the line " thelist.append([])" and scratch the index from the last line, and then you only have to sort and kill repeated entries. I think it looks nicer as a table though. Aesthetics. Depends on what you need this for. Kirby Urner wrote: > > At 06:59 AM 1/9/2002 -0800, Kirby Urner wrote: > >At 03:42 PM 1/9/2002 +0100, Remco Gerlich wrote: > >>On 0, Kirby Urner wrote: > >> > I modified this to sort the output, and gave it: > >> > > >> > >>> sums([5,11,15]) > >> > > >> > and got: > >> > > >> > [31, 36, 41, 42, 46, 47, 51, 52, 53, 56, 57, 58, 61, 62, > >> > 63, 64, 66, 67, 68, 69, 71, 72, > >> > > >> > etc. etc. > >> > > >> > but shouldn't 5 + 2*15 = 30 be on the list? I confess > >> > I never understood Daniel's description of what he needed > >> > very well. > > > >Sorry, I goofed, I meant 5 + 2*15 = 35. Shouldn't 35 be > >present? > > Nevermind, same answer -- you're saying 11 has to be there. > OK. I got it now. I see what you're telling me. > > Kirby > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From urnerk@qwest.net Thu Jan 10 01:05:50 2002 From: urnerk@qwest.net (Kirby Urner) Date: Wed, 09 Jan 2002 17:05:50 -0800 Subject: [Tutor] Algorithm Question In-Reply-To: <009901c19962$199b7df0$1664a8c0@mega> References: <4.2.0.58.20020108192437.01a5ed90@pop3.norton.antivirus> Message-ID: <4.2.0.58.20020109170153.00c45a70@pop3.norton.antivirus> Note that these powerful algorithms by Gregor don't solve the teresa problem (are related) as they permit repetitions of elements in excess of the original number of same, e.g. xyz doesn't actually permute to xxx when defining permutation in the usual way. Kirby From flash1210@hotmail.com Thu Jan 10 03:14:15 2002 From: flash1210@hotmail.com (Frank Holmes) Date: Wed, 09 Jan 2002 19:14:15 -0800 Subject: [Tutor] getting keyboard input to dictionary (newbie ques) Message-ID: I am writing a simple phone number database type program. I am using dictionaries to handle variations in the way the names can be entered ie: jones:555-5555, Jones:555 5555, etc. I can get it to return names or quit in response to keyboard input from a menu, but cannot figure out how to add entries to the dictionary from there. Help! Def add_name(): print "enter name" n=raw_input() print "enter number" m=raw_input() d1[n]=m while 1: print "some greeting" print "type name to search" print "type 'add' to add names or 'quit' to exit" x=raw_input() if x=='quit': break d1={'a name':'1111', 'another name':'2222', 'A. Name':'1111'} if x in d1.keys(): print d1[x], x if x=='add': add_name() It will let me retrieve and quit, and when I enter 'add' it will print as if it is working but the entries are not added to the dict. I have tried converting the raw-input() value to a string using the str.() then using that identity in the d1[n]=m but still won't update. I'm missing something obvious... help. _________________________________________________________________ Chat with friends online, try MSN Messenger: http://messenger.msn.com From dyoo@hkn.eecs.berkeley.edu Thu Jan 10 05:52:27 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 9 Jan 2002 21:52:27 -0800 (PST) Subject: [Tutor] getting keyboard input to dictionary (newbie ques) In-Reply-To: Message-ID: On Wed, 9 Jan 2002, Frank Holmes wrote: > > I am writing a simple phone number database type program. I am using > dictionaries to handle variations in the way the names can be entered ie: > jones:555-5555, Jones:555 5555, etc. > I can get it to return names or quit in response to keyboard input from a > menu, but cannot figure out how to add entries to the dictionary from there. > Help! Hi Frank, let's take a look. > > Def add_name(): ^^^ You'll want to make that 'Def' lowercased, like this: ### def add_name(): print "enter name" n=raw_input() print "enter number" m=raw_input() d1[n]=m ### I can't think of any "technical" reasons why 'def' is case sensitive in the Python language. However, this case sensitivity is followed through everywhere in Python. Function names, variable names... heck, all names are case sensitive in Python! Perhaps for the sake of consistancy, all the Python keywords are also case sensitive. One other thing you may find will bite you initially is that variables in functions are "local" by default. You probably won't have problems with add_name(), but it's usually a good idea to label variables as "global" if their origin is from outside the function. Here's another version of add_name() that's a little safer: ### def add_name(): global d1 print "enter name" n=raw_input() print "enter number" m=raw_input() d1[n]=m ### A better approach might be to avoid the global thing altogether, but we can talk about that later. > while 1: > print "some greeting" > print "type name to search" > print "type 'add' to add names or 'quit' to exit" > x=raw_input() > if x=='quit': > break > d1={'a name':'1111', 'another name':'2222', 'A. Name':'1111'} > if x in d1.keys(): > print d1[x], x > if x=='add': > add_name() Looks ok. Ah, there's one thing you might want to change. You might want to move the assignment of d1 out of your while loop. Can you think of a reason why it might make a difference? ### ### Version 1 ### while 1: print "some greeting" print "type name to search" print "type 'add' to add names or 'quit' to exit" x=raw_input() if x=='quit': break d1={'a name':'1111', 'another name':'2222', 'A. Name':'1111'} if x in d1.keys(): print d1[x], x if x=='add': add_name() ### vs. ### ### Version 2 ### d1 = {'a name':'1111', 'another name':'2222', 'A. Name':'1111'} while 1: print "some greeting" print "type name to search" print "type 'add' to add names or 'quit' to exit" x=raw_input() if x=='quit': break if x in d1.keys(): print d1[x], x if x=='add': add_name() ### Please feel free to ask questions on Tutor, and we can talk about your program some more. Hope this helps! From paulsid@shaw.ca Thu Jan 10 05:59:40 2002 From: paulsid@shaw.ca (Paul Sidorsky) Date: Wed, 09 Jan 2002 22:59:40 -0700 Subject: [Tutor] getting keyboard input to dictionary (newbie ques) References: Message-ID: <3C3D2DCC.BBB7DADB@shaw.ca> Frank Holmes wrote: > while 1: > print "some greeting" > print "type name to search" > print "type 'add' to add names or 'quit' to exit" > x=raw_input() > if x=='quit': > break This looks like the problem: > d1={'a name':'1111', 'another name':'2222', 'A. Name':'1111'} Here the dictionary gets reassigned each time so you're undoing any modifications. Try moving this line out of the loop. > if x in d1.keys(): > print d1[x], x > if x=='add': > add_name() One other suggestion: Dictionaries would make managing commands easier. For example: commands = {"add": add_name, "delete": del_name} Then: if x in commands.keys(): commands[x]() For quitting it's probably easier to treat that as a special case (as you have it now), but for everything else it might be useful to do it this way. Good luck! -- ====================================================================== Paul Sidorsky Calgary, Canada paulsid@shaw.ca http://members.shaw.ca/paulsid/ From toodles@yifan.net Thu Jan 10 06:05:00 2002 From: toodles@yifan.net (Andy W) Date: Thu, 10 Jan 2002 14:05:00 +0800 Subject: [Tutor] getting keyboard input to dictionary (newbie ques) References: Message-ID: <001f01c1999c$c4775f70$da00a8c0@Sun> Hi > > I am writing a simple phone number database type program. I am using > dictionaries to handle variations in the way the names can be entered ie: > jones:555-5555, Jones:555 5555, etc. > I can get it to return names or quit in response to keyboard input from a > menu, but cannot figure out how to add entries to the dictionary from there. > Help! > > Def add_name(): > print "enter name" > n=raw_input() > print "enter number" > m=raw_input() > d1[n]=m > > while 1: > print "some greeting" > print "type name to search" > print "type 'add' to add names or 'quit' to exit" > x=raw_input() > if x=='quit': > break > d1={'a name':'1111', 'another name':'2222', 'A. Name':'1111'} ^^^^^^^^ Here you are initialising the dictionary each time you pass through the loop, therefore destroying that record you just input. To get around this, just put d1=... above the while loop, and it'll initialise it only once. > if x in d1.keys(): > print d1[x], x > if x=='add': > add_name() > > > It will let me retrieve and quit, and when I enter 'add' it will print > as if it is working but the entries are not added to the dict. > I have tried converting the raw-input() value to a string using the > str.() then using that identity in the d1[n]=m but still won't update. > I'm missing something obvious... help. > > > > > > _________________________________________________________________ > Chat with friends online, try MSN Messenger: http://messenger.msn.com > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From dajoy@operamail.com Thu Jan 10 07:10:24 2002 From: dajoy@operamail.com (Daniel Ajoy) Date: Thu, 10 Jan 2002 02:10:24 -0500 Subject: [Tutor] Algorithm Question Message-ID: <3C4177CD@operamail.com> someproc(3,[5 11 15]) 15 [5 5 5] 21 [5 5 11] 25 [5 5 15] 27 [5 11 11] 31 [5 11 15] 33 [11 11 11] 35 [5 15 15] 37 [11 11 15] 41 [11 15 15] 45 [15 15 15] someproc(4,[5 11 15]) 20 [5 5 5 5] 26 [5 5 5 11] 30 [5 5 5 15] 32 [5 5 11 11] 36 [5 5 11 15] 38 [5 11 11 11] 40 [5 5 15 15] 42 [5 11 11 15] 44 [11 11 11 11] 46 [5 11 15 15] 48 [11 11 11 15] 50 [5 15 15 15] 52 [11 11 15 15] 56 [11 15 15 15] 60 [15 15 15 15] someproc(5,[5 11 15]) 25 [5 5 5 5 5] 31 [5 5 5 5 11] 35 [5 5 5 5 15] 37 [5 5 5 11 11] 41 [5 5 5 11 15] 43 [5 5 11 11 11] 45 [5 5 5 15 15] 47 [5 5 11 11 15] 49 [5 11 11 11 11] 51 [5 5 11 15 15] 53 [5 11 11 11 15] 55 [5 5 15 15 15] <--- Notice 55 [11 11 11 11 11] <-- Notice 57 [5 11 11 15 15] 59 [11 11 11 11 15] 61 [5 11 15 15 15] 63 [11 11 11 15 15] 65 [5 15 15 15 15] 67 [11 11 15 15 15] 71 [11 15 15 15 15] 75 [15 15 15 15 15] From alan.gauld@bt.com Thu Jan 10 12:29:05 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Thu, 10 Jan 2002 12:29:05 -0000 Subject: [Tutor] getting keyboard input to dictionary (newbie ques) Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C261@mbtlipnt02.btlabs.bt.co.uk> > Def add_name(): > print "enter name" As Danny has pointed out that needs to be 'def' not 'Def'. Also you *must* indent the body lines: def add_name(): print 'enter name' # etc... How much is up to you but usually 2 or 3 spaces or a single tab are used. Just make sure its consistent. > while 1: > print "some greeting" > print "type name to search" > print "type 'add' to add names or 'quit' to exit" > x=raw_input() > if x=='quit': > break > d1={'a name':'1111', 'another name':'2222', 'A. Name':'1111'} Danny said you *might* want to move this. I say you *definitely* want to move this above the while... > as if it is working ... In that case your code must have the fubnction stuff defined OK. > ...but the entries are not added to the dict. They probably are being assigned but when you go round that while loop again... oops! > I have tried converting the raw-input() value to a string raw_input returns a string so no need for that. > I'm missing something obvious... help. Its easily done :-) Alan g. From clickron@webtv.net Thu Jan 10 19:36:36 2002 From: clickron@webtv.net (Ron) Date: Thu, 10 Jan 2002 14:36:36 -0500 (EST) Subject: [Tutor] write problem Message-ID: <3789-3C3DED44-1568@storefull-166.iap.bryant.webtv.net> Hereis the problem. Python 2.2 (#28, Dec 21 2001, 12:21:22) [MSC 32 bit (Intel)] on win32 Type "copyright", "credits" or "license" for more information. IDLE 0.8 -- press F1 for help >>> data = open("ron.txt","a") >>> data.write("help me!") >>> data.read() '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00 and it continues with the x00s. What am I doing wrong. I had a file with one line of text saved, and this is what I ended up with. Maybe it doesn't like my name Ron From dyoo@hkn.eecs.berkeley.edu Thu Jan 10 19:43:18 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 10 Jan 2002 11:43:18 -0800 (PST) Subject: [Tutor] write problem In-Reply-To: <3789-3C3DED44-1568@storefull-166.iap.bryant.webtv.net> Message-ID: On Thu, 10 Jan 2002, Ron wrote: > Python 2.2 (#28, Dec 21 2001, 12:21:22) [MSC 32 bit (Intel)] on win32 > Type "copyright", "credits" or "license" for more information. > IDLE 0.8 -- press F1 for help > >>> data = open("ron.txt","a") > >>> data.write("help me!") > >>> data.read() > '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00 Hi Ron, The file position is at the end of the file, so you won't be able to read what you've immediately written until you rewind the file. What you'll probably want to do is rewind or "seek()" back to the beginning of the file: ### data.seek(0) ### This will set the file position back to the very beginning. One other thing you may need to do is tell the system that you intend to both read and write on the file. 'a' mode is only meant for writing, and certain systems may not like it if you try reading from the file. Use "a+" mode instead: ### data = open("ron.txt", "a+") ### Hope this helps! From ericleary@pcisys.net Thu Jan 10 04:16:20 2002 From: ericleary@pcisys.net (Eric Leary) Date: Wed, 9 Jan 2002 21:16:20 -0700 Subject: [Tutor] tcl/tkinter on python 2.1 for mac os x Message-ID: In Oct 2001 I downloaded python 2.1 for mac os x. I am learning python from Gauld's book and Laningham's book. the download has a note where the tkinter modules should be saying they are not available yet. now on Apple OS X site tcl tkinter is appearing as a link to a file that can be downloaded does this mean I can get the tkinter modules for macpython on OS X? my own casting about has not turned them up. PS: There is kind of a gap between what's covered in the above cited books and the regular list of books. (lutz, chun, etc.) can someone cook up some useless but instructive exercises (with code listing) for simplified spreadsheet (dumber than dan bricklin visicalc) and flatfile database so that old farts like me who are learning to code as a cultural endeavor rather a productive one can get an idea of how these types of apps are made. (yes i know visicalc was not made with an OO language, still...) I can sort of think of a way to make a database with dictionarys and I can mostly wrap my head around how do do it with objects but I don't really get how to do the methods for a record object. (laningham has a database project but I need one a little simpler to start with) for real programmers this is stupid of course because they would just use one of the cool db api(s). maybe something that could also show the easier to implement ideas of relational dbs as well (although I assume there aren't any of those!) thanks ericleary@pcisys.net From Ravay@aol.com Thu Jan 10 22:43:12 2002 From: Ravay@aol.com (Ravay@aol.com) Date: Thu, 10 Jan 2002 17:43:12 EST Subject: [Tutor] Re: Tutor digest, Vol 1 #1326 - 12 msgs Message-ID: <3d.17747084.296f7300@aol.com> please remove me of mailing list From paulsid@shaw.ca Thu Jan 10 22:50:21 2002 From: paulsid@shaw.ca (Paul Sidorsky) Date: Thu, 10 Jan 2002 15:50:21 -0700 Subject: [Tutor] write problem References: Message-ID: <3C3E1AAD.C3EFA2F1@shaw.ca> Danny Yoo wrote: > The file position is at the end of the file, so you won't be able to read > what you've immediately written until you rewind the file. What you'll > probably want to do is rewind or "seek()" back to the beginning of the > file: > > ### > data.seek(0) > ### Furthermore, a seek should always be done before changing from reading to writing (or vice-versa) in any case. Some implementations of C (which Python is written in) will do unpredictable things if this isn't done. I'm not sure if Python insulates against this or not but it's probably a good idea not to take the chance. -- ====================================================================== Paul Sidorsky Calgary, Canada paulsid@shaw.ca http://members.shaw.ca/paulsid/ From grimmtoothtoo@yahoo.com Thu Jan 10 23:56:03 2002 From: grimmtoothtoo@yahoo.com (Grimmtooth) Date: Thu, 10 Jan 2002 18:56:03 -0500 Subject: [Tutor] write problem In-Reply-To: <3789-3C3DED44-1568@storefull-166.iap.bryant.webtv.net> Message-ID: > >>> data = open("ron.txt","a") > >>> data.write("help me!") > >>> data.read() > '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00 After writing the one line of text, you are at the END of the file. Any reads you do will be from there. You need to use the seek() method for the open file object. Here is the documentation: "Set the file's current position, like stdio's fseek(). The whence argument is optional and defaults to 0 (absolute file positioning); other values are 1 (seek relative to the current position) and 2 (seek relative to the file's end). There is no return value. Note that if the file is opened for appending (mode 'a' or 'a+'), any seek() operations will be undone at the next write. If the file is only opened for writing in append mode (mode 'a'), this method is essentially a no-op, but it remains useful for files opened in append mode with reading enabled (mode 'a+'). " So basically you need to add a line data.seek(0) just before the read. Note that after that, further writes will once again be at the END of the file (read above). _________________________________________________________ Do You Yahoo!? Get your free @yahoo.com address at http://mail.yahoo.com From dyoo@hkn.eecs.berkeley.edu Fri Jan 11 00:45:11 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 10 Jan 2002 16:45:11 -0800 (PST) Subject: [Tutor] [How to unsubscribe from Tutor] In-Reply-To: <3d.17747084.296f7300@aol.com> Message-ID: On Thu, 10 Jan 2002 Ravay@aol.com wrote: > please remove me of mailing list Hi Ravay, You can unsubscribe yourself by visiting the web site you used to subscribe to Tutor: http://mail.python.org/mailman/listinfo/tutor If you go down to the bottom of that page, you'll see something about "Edit Options". If you edit your own options, you'll be able to unsubscribe. If you have any problems while you unsubscribe, please feel free to email the mailing list administrators at "tutor-admin@python.org", and we'll get things fixed. Best of wishes to you. From dyoo@hkn.eecs.berkeley.edu Fri Jan 11 00:52:30 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 10 Jan 2002 16:52:30 -0800 (PST) Subject: [Tutor] tcl/tkinter on python 2.1 for mac os x In-Reply-To: Message-ID: On Wed, 9 Jan 2002, Eric Leary wrote: > In Oct 2001 I downloaded python 2.1 for mac os x. > > I am learning python from Gauld's book and Laningham's book. > > the download has a note where the tkinter modules should be saying they > are not available yet. > > now on Apple OS X site tcl tkinter is appearing as a link to a file > that can be downloaded Hi Eric, Hmmm! Ok, I checked up on this; it does look like Tkinter should work on Mac OS X finally. Take a look: http://www.cwi.nl/~jack/macpython.html If you download MacPython22, you should be able to use Tkinter. (Now that I'm starting to feel the need for a new computer, that new iMac does look pretty tempting... *grin*) I'm not so sure about MacPython 2.1 and Tkinter though. For Macintosh issues, you can talk with the MacPython folks: http://www.python.org/sigs/pythonmac-sig/ and they might know more about this. Let's talk about making a simple database application in another post; I think it's a great topic! From flash1210@hotmail.com Fri Jan 11 04:28:30 2002 From: flash1210@hotmail.com (Frank Holmes) Date: Thu, 10 Jan 2002 20:28:30 -0800 Subject: [Tutor] How do I save a dictionary to disk? (another newbie question) Message-ID: I am working on a simple program for recalling phone numbers. I am using a dictionary to deal with variations in spelling, etc. I took the dictionary out of the 'while' loop and the add_name() function works as planned.... except (duh..) when I quit the program and restart it the names I have added are no longer there. They exist only locally and are dumped when the program ends. I beat my head against this for a few hours today, went through my books and cannot figure out how to store the updated dictionary. I know this is probably easy stuff but I am completely stumped. I am using python on a windows98 system. def add_name(): print "Enter Name" n=raw_input() d1[n]=m d1={'name':'1111', 'a. name':'1111', 'different name':'2222'} while 1: print "A Greeting" print "Please enter name to search" print "Type 'add' to add entries or 'quit' to exit" x=raw_input() if x=='quit': break if x in d1.keys(): print d1[x], x if x=='add': add_name() _________________________________________________________________ Chat with friends online, try MSN Messenger: http://messenger.msn.com From clickron@webtv.net Fri Jan 11 04:30:46 2002 From: clickron@webtv.net (Ron) Date: Thu, 10 Jan 2002 23:30:46 -0500 (EST) Subject: [Tutor] write problem Message-ID: <3792-3C3E6A76-762@storefull-166.iap.bryant.webtv.net> Thanks for the help everybody. Sometimes when things don't work out like this I start to get discouraged. It's nice to have someplace to ask questions and know I'll get the answers I need to keep me moving forward Ron From toodles@yifan.net Fri Jan 11 05:11:49 2002 From: toodles@yifan.net (Andy W) Date: Fri, 11 Jan 2002 13:11:49 +0800 Subject: [Tutor] How do I save a dictionary to disk? (another newbie question) References: Message-ID: <003101c19a5e$7faad530$da00a8c0@Sun> Hi Frank, > I am working on a simple program for recalling phone numbers. I am using > a dictionary to deal with variations in spelling, etc. I took the dictionary > out of the 'while' loop and the add_name() function works as planned.... Goody :) > except (duh..) when I quit the program and restart it the names I have added > are no longer there. They exist only locally and are dumped when the program > ends. > I beat my head against this for a few hours today, went through my books > and cannot figure out how to store the updated dictionary. > I know this is probably easy stuff but I am completely stumped. It is as long as you have a lot of spare time and use it to go through the Python Library Reference ;) Ah i'm such a nerd. You'll want to look at the "shelve" module, I think you'll find it perfect for your case. Basically it's an emulation of a dictionary, but with persistence added. http://www.python.org/doc/current/lib/module-shelve.html > > I am using python on a windows98 system. > > def add_name(): > print "Enter Name" > n=raw_input() > d1[n]=m > > d1={'name':'1111', 'a. name':'1111', 'different name':'2222'} > while 1: > print "A Greeting" > print "Please enter name to search" > print "Type 'add' to add entries or 'quit' to exit" > x=raw_input() > if x=='quit': > break > if x in d1.keys(): > print d1[x], x > if x=='add': > add_name() > > > _________________________________________________________________ > Chat with friends online, try MSN Messenger: http://messenger.msn.com > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From virketis@fas.harvard.edu Fri Jan 11 05:19:21 2002 From: virketis@fas.harvard.edu (Pijus Virketis) Date: Fri, 11 Jan 2002 00:19:21 -0500 Subject: [Tutor] How do I save a dictionary to disk? (another newbie question) References: <003101c19a5e$7faad530$da00a8c0@Sun> Message-ID: <016c01c19a5f$86c40b10$dbadf78c@virketis2> > > I beat my head against this for a few hours today, went through my > books > > and cannot figure out how to store the updated dictionary. > > I know this is probably easy stuff but I am completely stumped. > > It is as long as you have a lot of spare time and use it to go through the > Python Library Reference ;) Ah i'm such a nerd. > You'll want to look at the "shelve" module, I think you'll find it perfect > for your case. Basically it's an emulation of a dictionary, but with > persistence added. > http://www.python.org/doc/current/lib/module-shelve.html > Check out the pickle module. That's how you take Python objects and convert them into byte streams, ready for saving. -PV From karthikg@aztec.soft.net Fri Jan 11 05:39:44 2002 From: karthikg@aztec.soft.net (Karthik Gurumurthy) Date: Fri, 11 Jan 2002 11:09:44 +0530 Subject: [Tutor] How do I save a dictionary to disk? (another newbie question) In-Reply-To: <003101c19a5e$7faad530$da00a8c0@Sun> Message-ID: hi!, i realize that there are atleast 4 ways for achieving persistence after having a look at the reference. 1.marshal 2.shelve 3.pickle 4.DBM what are the differences between these modules. it says pickle is probably more powerful than marshal. I took a look at the anydbm module and played around with it. It also creates a file and allows us to handle stuff as if we are using dictionaries. But then i could'nt set an integer against a key. it took only strings. I have used ConfigParser before even there you add a section. then set values against a name. Then we can read it back from the section. Yeah it's meant to be used as a properties file. But how different it is from using DBM files. I know am missing something atleast wrt DBM. Probably it is capable of more? thanks, karthik -----Original Message----- From: tutor-admin@python.org [mailto:tutor-admin@python.org]On Behalf Of Andy W Sent: Friday, January 11, 2002 10:42 AM To: Frank Holmes; tutor@python.org Subject: Re: [Tutor] How do I save a dictionary to disk? (another newbie question) Hi Frank, > I am working on a simple program for recalling phone numbers. I am using > a dictionary to deal with variations in spelling, etc. I took the dictionary > out of the 'while' loop and the add_name() function works as planned.... Goody :) > except (duh..) when I quit the program and restart it the names I have added > are no longer there. They exist only locally and are dumped when the program > ends. > I beat my head against this for a few hours today, went through my books > and cannot figure out how to store the updated dictionary. > I know this is probably easy stuff but I am completely stumped. It is as long as you have a lot of spare time and use it to go through the Python Library Reference ;) Ah i'm such a nerd. You'll want to look at the "shelve" module, I think you'll find it perfect for your case. Basically it's an emulation of a dictionary, but with persistence added. http://www.python.org/doc/current/lib/module-shelve.html > > I am using python on a windows98 system. > > def add_name(): > print "Enter Name" > n=raw_input() > d1[n]=m > > d1={'name':'1111', 'a. name':'1111', 'different name':'2222'} > while 1: > print "A Greeting" > print "Please enter name to search" > print "Type 'add' to add entries or 'quit' to exit" > x=raw_input() > if x=='quit': > break > if x in d1.keys(): > print d1[x], x > if x=='add': > add_name() > > > _________________________________________________________________ > Chat with friends online, try MSN Messenger: http://messenger.msn.com > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From urnerk@qwest.net Fri Jan 11 06:35:40 2002 From: urnerk@qwest.net (Kirby Urner) Date: Thu, 10 Jan 2002 22:35:40 -0800 Subject: [Tutor] Basic number theory w/ Python Message-ID: <4.2.0.58.20020110221617.015c4740@pop3.norton.antivirus> A result of number theory is any positive integer is the sum of the totients of its factors. What does that mean? The totient of n is the number of positives less than n, including 1, and which are relatively prime to n, i.e. have no factors in common with n other than 1. So, for example, 28 has no factors in common, other than 1, with the following positive numbers < 28: [1, 3, 5, 9, 11, 13, 15, 17, 19, 23, 25, 27] The number of such numbers is the totient of n, and is simply the length of this list, i.e. 12. So totient(28)==12. Defining totient(n) is easy (for small n) if we have a way to assure gcd(i,n)==1, 0>> factors(28) [1, 2, 4, 7, 14, 28] >>> map(totient,factors(28)) [1, 1, 2, 6, 6, 12] >>> 1+1+2+6+6+12 28 Here are some functions to check this out for low (small) positive integers: from operator import add def gcd(a,b): "greatest common divisor of a,b" while b: a, b = b, a%b return a def factors(n): "return list of factors of n" return [i for i in range(1,n+1) if n%i==0] def sumtots(n): "sum the totients of n's factors" return reduce(add,[totient(i) for i in factors(n)]) Usage: >>> sumtots(28) 28 >>> sumtots(100) 100 >>> sumtots(120383) 120383 Kirby [1] my recollection is this simple Pythonic form of Euclid's Algorithm was first presented by Guido himself -- is this correct? From urnerk@qwest.net Fri Jan 11 07:00:49 2002 From: urnerk@qwest.net (Kirby Urner) Date: Thu, 10 Jan 2002 23:00:49 -0800 Subject: [Tutor] How do I save a dictionary to disk? (another newbie question) In-Reply-To: Message-ID: <4.2.0.58.20020110224055.015da650@pop3.norton.antivirus> >def add_name(): > print "Enter Name" > n=raw_input() > d1[n]=m ^ This can't work as written as m is nowhere defined. If you want the dictionary to persist, you need to save it as a file after the user quits. Probably best to save it as a human readable file. Lots of ways to parse it out and back in. Note: d1.items() spits out a list of (key,value) pairs. try: f = open("output.txt","w") for i in d1.items(): f.write("%s,%s\n" % (i[0],i[1])) finally: f.close() would create: name,1111 different name,2222 a. name,1111 or whatever else was in the dictionary, as a text file with line feeds between key,value pairs. try: f=open("test.txt","r") dlist=[j.split(",") for j in f.readlines()] finally: f.close() d1={} for pair in dlist: d1[pair[0]] = pair[1][:-1] would recreate the dictionary from the saved file, if included at the top of your module. Kirby From urnerk@qwest.net Fri Jan 11 07:19:02 2002 From: urnerk@qwest.net (Kirby Urner) Date: Thu, 10 Jan 2002 23:19:02 -0800 Subject: [Tutor] How do I save a dictionary to disk? (another newbie question) In-Reply-To: <4.2.0.58.20020110224055.015da650@pop3.norton.antivirus> References: Message-ID: <4.2.0.58.20020110230759.015ca550@pop3.norton.antivirus> > > >try: > f=open("test.txt","r") ^^^^^^^^ oops, I called it output.txt above. I like the shelve option mentioned by PV, but be forewarned that a shelved dictionary doesn't have all the functionality of a real dictionary. Here's some playing around with that object: Create a shelve object, populate it, close it, and remove it from the module: >>> import shelve >>> d= shelve.open("text.sh") >>> d['a']=10 >>> d['b']=90 >>> d.close() >>> del d Reopen as newd, check it for contents: >>> newd = shelve.open("text.sh") >>> newd >>> newd.items() Traceback (most recent call last): File "", line 1, in ? newd.items() AttributeError: DbfilenameShelf instance has no attribute 'items' Not as powerful as a real dictionary! >>> newd.keys() # OK, good, the keys are there ['b', 'a'] >>> newd.values Traceback (most recent call last): File "", line 1, in ? newd.values AttributeError: DbfilenameShelf instance has no attribute 'values' Yeah well, we can get 'em one at a time. Compare what a shelve dictionary gives you, versus a real dictionary: >>> dir(newd) ['__del__', '__delitem__', '__doc__', '__getitem__', '__init__', '__len__', '__module__', '__setitem__', 'close', 'dict', 'get', 'has_key', 'keys', 'sync'] >>> dir({}) ['__class__', '__cmp__', '__contains__', '__delattr__', '__delitem__', '__eq__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__repr__', '__setattr__', '__setitem__', '__str__', 'clear', 'copy', 'get', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues', 'keys', 'popitem', 'setdefault', 'update', 'values'] I still think just writing a human readable file, and parsing that back in as a dictionary, is probably the best thing. You never know when you might want the same info in some other program (not even Python). Text is way more universal than some pickle or anydbm format. Kirby From alan.gauld@bt.com Fri Jan 11 11:33:41 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Fri, 11 Jan 2002 11:33:41 -0000 Subject: [Tutor] tcl/tkinter on python 2.1 for mac os x Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C267@mbtlipnt02.btlabs.bt.co.uk> > I am learning python from Gauld's book and Laningham's book. Excellent choice both ;-) > the download has a note where the tkinter modules should be > saying they are not available yet. I'm not sure what you mean by this bit and will rely on some Mac users helping out - Macs are a mystery to me... > PS: There is kind of a gap between what's covered in > the above cited books and the regular list of books. My book is intended to get you up to the point where the other books and online resources make sense! > simplified spreadsheet (dumber than dan bricklin visicalc) First try a text based 4 function calculator. Define a language to enter sums: A session might look like: >>> import calculator >>> calculator.calculate() Calc: + 4 4 Res = 8 Calc: * 2 9 Res = 18 Calc: Q Quitting calculator >>> (A Spreadsheet at the dumb level is just a two dimensional array of such calculators! with some variable storage and cross referencing capabilities) > and flatfile database so that old farts like me who > are learning to code as a cultural endeavor rather > a productive one can get an idea of how these > types of apps are made. Starting from first principles get an object to read/write its attributes to a file. Now get a list of such objets to do the same. Now figure out how to search for/insert/delete entries from the list You've now got a very inefficient database system :-) Now learn to use the python shelve module to do the same job - you now have a more efficient database Now move onto the db modules for real power. > objects but I don't really get how to do the methods > for a record object. Initially just write each attribute into a single line using a format string. For more complex things(like embedded lists you can use a formatting language (XML seeems a good place to start...) > that could also show the easier to implement ideas of > relational dbs as well Implementing relational capability from scratch is harder and IMHO not worth the pain. Once you understand how to store simple objects and objects with internal lists of values jump straight to a proper database like mySQL and the db modules. HTH, Any other questions feel free to ask thats what we're here for. Alan g. Author of the 'Learning to Program' web site http://www.freenetpages.co.uk/hp/alan.gauld From arcege@speakeasy.net Fri Jan 11 13:57:00 2002 From: arcege@speakeasy.net (Michael P. Reilly) Date: Fri, 11 Jan 2002 08:57:00 -0500 Subject: [Tutor] How do I save a dictionary to disk? (another newbie question) In-Reply-To: <016c01c19a5f$86c40b10$dbadf78c@virketis2>; from virketis@fas.harvard.edu on Fri, Jan 11, 2002 at 12:19:21AM -0500 References: <003101c19a5e$7faad530$da00a8c0@Sun> <016c01c19a5f$86c40b10$dbadf78c@virketis2> Message-ID: <20020111085700.A895@speakeasy.net> On Fri, Jan 11, 2002 at 12:19:21AM -0500, Pijus Virketis wrote: > > > I beat my head against this for a few hours today, went through my > > books > > > and cannot figure out how to store the updated dictionary. > > > I know this is probably easy stuff but I am completely stumped. > > > > It is as long as you have a lot of spare time and use it to go through the > > Python Library Reference ;) Ah i'm such a nerd. > > You'll want to look at the "shelve" module, I think you'll find it perfect > > for your case. Basically it's an emulation of a dictionary, but with > > persistence added. > > http://www.python.org/doc/current/lib/module-shelve.html > > > > Check out the pickle module. That's how you take Python objects and convert > them into byte streams, ready for saving. FYI, The shelve module is a combination of the pickle and anydbm modules. Using the shelve module, Python objects are pickled and can then be written to disk with a key, as a dictionary. import pickle, shelve d = {'a': 1, 'b': 4, 'c': 9} n = 99 f = open('pickledspam', 'w') pickle.dump(n, f) # we'll right the number first pickle.dump(d, f) # then the dictionary f.close() f = open('pickledspam', 'r') # now we want to get the dictionary back p_n = pickle.load(f) # first we need to get the number p_d = pickle.load(f) # then the dictionary f.close() s = shelve.open('shelvedspam') s['n'] = n # save the number to the 'shelf' s['d'] = d # and the dictionary s.close() # reopening for consistancy of use s = shelve.open('shelvedspam') # getting back values s_d = s['d'] # we don't need to get the number first s.close() The shelve, if it is appropriate, can be more useful. But it is not always appropriate. -Arcege From tbost@ifarm.com Fri Jan 11 14:14:12 2002 From: tbost@ifarm.com (Tracy Bost) Date: Fri, 11 Jan 2002 08:14:12 -0600 (CST) Subject: [Tutor] Writing queries to a database Message-ID: <1010758452.3c3ef33472c1c@mail.ifarm.com> I searched the python.org site, but I guess I'm just missing it. I'm looking for a module that allows python to send queries to a database via odbc and return the results. Thanks for any help in pointing me in the right direction . ------------------------------------------------------------------------------ Visit "The Most Powerful Tool on the Farm" at http://www.ifarm.com Get the latest on Ag News, Market Reports, FREE email, and much more. From pythontutor@venix.com Fri Jan 11 14:44:09 2002 From: pythontutor@venix.com (Lloyd Kvam) Date: Fri, 11 Jan 2002 09:44:09 -0500 Subject: [Tutor] Writing queries to a database References: <1010758452.3c3ef33472c1c@mail.ifarm.com> Message-ID: <3C3EFA39.2080909@venix.com> I have been using the mxODBC package. The license terms on their web site have changed, so make sure that fits your needs. I have been quite happy with the package. Tracy Bost wrote: > > I searched the python.org site, but I guess I'm just missing it. > I'm looking for a module that allows python to send queries to a database > via odbc and return the results. Thanks for any help in pointing me in the > right direction . > > ------------------------------------------------------------------------------ > Visit "The Most Powerful Tool on the Farm" at http://www.ifarm.com > Get the latest on Ag News, Market Reports, FREE email, and much more. > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From idiot1@netzero.net Fri Jan 11 16:29:59 2002 From: idiot1@netzero.net (kirk Bailey) Date: Fri, 11 Jan 2002 11:29:59 -0500 Subject: [Tutor] ethics in programming Message-ID: <3C3F1307.68242321@netzero.net> Working on TinyList, I realized that for security reasons I am using TL's ability to talk to the smtp engine to send out the email, one envlope per recipient. Good, avoids security issues with many recipients per envlope. But this does slow down transmisson a little, mabe more than a little when we are talking LARGE lists. A way used in majordomo to send lists is to feed ONE copy of the letter to a special alias and take advantage of the :include: command to invoke the subscriber file. such a list alias looks like: listname-outgoing::include:/path/subscriberfilename # no spaces in the definition PLEASE! And the Mail Transmission Agent(hereafter MTA, usually sendmail) reads that file and sends a copy of the letter to each person on it. THERE IS NO OTHER SERVICE. *ANY* letter landing on that email alais goes out. Very spam friendly alas. And this is a Very Bad Thing. Of course, the idea is the name of alias is a secret, and is fed by a program, in this case majordomo. The manual uses listname-outgoing as an example, but you are supposed to pick some random name so as to safeguard the list. THAT alias may be made public, as it feeds into some kind of security program. listname:"|/www/cgi-bin/guardian listname" # doublequotes required if there is a space in the definition! Such a list lends itself to quick and efficent service of a LARGE subscriber base, like for instance the managers of every local depo in the coca-cola universe, all the gas stationmanagers of Chevron, etc. It needs a guardian of some sort to protect against spam. Although a headache, majordomo does this. For a simpler service, I wrote a program called Guardian. For LARGE lists, it receives *1* email, and feeds it out through the MTA to the entire list of subscribers. This can be stand alone, or work with TinyList for large list servicing; simply have only one subscriber in TL, the outbound list guardian, and let it hand the compiled message over to sendmail for massive transmission. BTW, the subscriber file for guardian can be the OK2POST file for TinyList, so only on person can post (only members can post) and only one copy goes out (the subscriber file contaions only one email, that of the outbound alias) but EVERYONE is in the ok2port file fot eh list if you like. don't have to, but I realized you can if you like. DO NOT put 50,000 names in the TL subscriber file or it will send it out itself,and talke quite a while to do so. Guardian extends the abilities of TL to handle LARGE lists conviently; hundreds of thousands of recipeints are practical and handled with dispatch (pardon the pun). This also makes it practical and convient for people to use TL to send out massive spam. THIS is why I am suspending release of Guardian; I HATE spam. Now I want to empower LEGITIMATE use, but hamper ILLIGITIMATE use of TL. Therefore, I encourage discussion of spam, how to hamper it, and any bright ideas that we can implement in the code of guardian to make spam easier to fight and punish. -- -Respectfully, -Kirk D Bailey end ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ |___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___| | _ \___ __ _ __| |_(_)_ _ __ _| |_| |_ ___ / __/ _ \| \| | | / _ Y _` (_-< _| | ' \/ _` | _| ' \/ -_) (_| (_) | .` |_ |_|_\___|__,_/__/\__|_|_||_\__, |\__|_||_\___|\___\___/|_|\_( ) |___/ |/ Kirk Bailey, consulting loose cannon www.howlermonkey.net highprimate@howlermonkey.net http://gipco.webjump.com idiot1@netzero.net _ _ _ _ ___ _ _ ___ _ _ _ _| |_ __ _| |_ __ _| |_(_)_ __ ___ / _ \ ' \/ -_) ' \ || | _/ _` | _/ _` | _| | ' \/ -_)_ \___/_||_\___|_||_\_,_|\__\__,_|\__\__,_|\__|_|_|_|_\___(_)_ ___ |___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___| ---------------------------------------------------- Sign Up for NetZero Platinum Today Only $9.95 per month! http://my.netzero.net/s/signup?r=platinum&refcd=PT97 From idiot1@netzero.net Fri Jan 11 17:57:07 2002 From: idiot1@netzero.net (kirk Bailey) Date: Fri, 11 Jan 2002 12:57:07 -0500 Subject: [Tutor] ethics in programming References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C26D@mbtlipnt02.btlabs.bt.co.uk> Message-ID: <3C3F2773.8F21CF16@netzero.net> Well, well, a pithy question. Nobody asked me this one before. Deserves an answer. Alan, I am postmaster at howlermonkey.net, which I own. I have wanted to offer list services for some time. Until now, all solutions offered dissapointed me for one of several reasons. I actually considered mailman, but at the time did not understand python, and it did not allow me to append a ADVERTISEMENT to the message which helps pay the rent on the cohosting bill. Sigh... would have used it if it did. Inhaling the O'Reily book managing mailing lists, I decided to go with majordomo. Heacaches, clumbersome, COMPLEX alias structure, clunky config file. And majorcool. ULCERS. so I looked around some more. And found Minorfish, which has it's own web interface, and lets you include dynamic content in the footers with tags, effectively applying ssi to email- and I ADORE ssi. And it has a few problems, including a personality problem with a devloper who is intolerant of newbies. Worst problem is it feeds ONE letter to sendmail directly with ALL the recipients in the envlope TO field. This is BAD practice, as to help fight spam, many services (including us) limit recipients per envlope to a low number, 10 in my case. Also, to help pay the cohosting bill, I want to place a text ad on the end of each letter, and mister personality refused to assist modifying the program to do this- telling me to route it to an external program to handle it. At this time, i could not program in python- I *STILL* cannot comprehend perl, which the fish was written in. So I decided to write what I wanted. Having looked at python, and being impressed with it's accessability, I decided to write it in python, learning as I went. I made the committment, and weeks of work followed. IT WORKS. TL is now a flexible modular suite, web manager, several nice optional features. And it sparkplugged several other cgi-email ideas I may explore later. Now, there is a product for the small user, written in a very easy to learn and modify language, with many features andoptions- CHOICES, our watchword and slogan. Afraid that someone would seize it if placed in the public domain, I chose to employ the GNU GPL to safeguard it and empower others wishing to use it, my gift to the email providing and using community. Payforward ROCKS. I intend to found a site (my box cohosts several small sites, and tinylist.org will soon be one of them) to support and offer TL. Recently, I realized there was a need for a way to send LARGE lists out efficently when reviewing how TL sends out list traffic. Being familiar with the methods of several list engines, I decided that the method used by majordomo is a good one, if well safeguarded. Guardian does this. It can work alone, or receive the output of TinyList, in effect turning TL into a message processor, but not using it for actual per recipient processing. This speeds up the delivery of large lists such as newsletters. However, it also empowers spam. I am a postmaster. I ***HATE*** spam. therefore, the post you replyed to. How to impede spam, yet enable legitimate large lists? As this reply is not of a sensitive personal nature, and is of intrest to others following the TL thread(s), I am taking the liberty of posting this to tutor list, please forgive me if this troubles you (and let me know so I will not do it again). alan.gauld@bt.com wrote: > > Kirk, > > As your mailer gets more sophisticated I wonder if > you looked at Mailman? It's a competitor to majordomo > etc but written in Python. > > I originally assumed you just wanted a project to > learn Python but its obviously becoming bigger than > that. It might be easier to add features to an > already complete and tested mail tool than to > work from scratch > > (FWIW, Python tutor is managed by mailman - naturally! :-) > > Also, for very secure email handling(can do PGP signing > etc), there is a sourceforge project called Shibboleth > - written in Perl. Last I looked they were very > close to a public release. > > Just some thoughts, but maybe you are enjoying the chase... > > Alan G. -- -Respectfully, -Kirk D Bailey end ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ |___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___| | _ \___ __ _ __| |_(_)_ _ __ _| |_| |_ ___ / __/ _ \| \| | | / _ Y _` (_-< _| | ' \/ _` | _| ' \/ -_) (_| (_) | .` |_ |_|_\___|__,_/__/\__|_|_||_\__, |\__|_||_\___|\___\___/|_|\_( ) |___/ |/ Kirk Bailey, consulting loose cannon www.howlermonkey.net highprimate@howlermonkey.net http://gipco.webjump.com idiot1@netzero.net _ _ _ _ ___ _ _ ___ _ _ _ _| |_ __ _| |_ __ _| |_(_)_ __ ___ / _ \ ' \/ -_) ' \ || | _/ _` | _/ _` | _| | ' \/ -_)_ \___/_||_\___|_||_\_,_|\__\__,_|\__\__,_|\__|_|_|_|_\___(_)_ ___ |___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___| ---------------------------------------------------- Sign Up for NetZero Platinum Today Only $9.95 per month! http://my.netzero.net/s/signup?r=platinum&refcd=PT97 From dyoo@hkn.eecs.berkeley.edu Fri Jan 11 18:10:52 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 11 Jan 2002 10:10:52 -0800 (PST) Subject: [Tutor] Writing queries to a database In-Reply-To: <3C3EFA39.2080909@venix.com> Message-ID: On Fri, 11 Jan 2002, Lloyd Kvam wrote: > I have been using the mxODBC package. The license terms on their web > site have changed, so make sure that fits your needs. I have been > quite happy with the package. > > Tracy Bost wrote: > > > > > I searched the python.org site, but I guess I'm just missing it. > > I'm looking for a module that allows python to send queries to a database > > via odbc and return the results. Thanks for any help in pointing me in the > > right direction . mxODBC can be found here: http://www.lemburg.com/files/python/mxODBC.html You may want to look at: http://www.python.org/topics/database/DatabaseAPI-2.0.html for more information of Python's Database API. If you have more questions, please feel free to ask! From idiot1@netzero.net Fri Jan 11 18:23:28 2002 From: idiot1@netzero.net (kirk Bailey) Date: Fri, 11 Jan 2002 13:23:28 -0500 Subject: [Tutor] TinyList Message-ID: <3C3F2DA0.9F4BD90B@netzero.net> OK, last bug fixed, thankyou alan for some excellent birdspotting. Dug up some buried treasure, and added a missing "+CRLF" where it rewrites the subscriber file minus the removed person. I beleive the entire suite is now complete and ready to offer people with web management. -- -Respectfully, -Kirk D Bailey end ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ |___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___| | _ \___ __ _ __| |_(_)_ _ __ _| |_| |_ ___ / __/ _ \| \| | | / _ Y _` (_-< _| | ' \/ _` | _| ' \/ -_) (_| (_) | .` |_ |_|_\___|__,_/__/\__|_|_||_\__, |\__|_||_\___|\___\___/|_|\_( ) |___/ |/ Kirk Bailey, consulting loose cannon www.howlermonkey.net highprimate@howlermonkey.net http://gipco.webjump.com idiot1@netzero.net _ _ _ _ ___ _ _ ___ _ _ _ _| |_ __ _| |_ __ _| |_(_)_ __ ___ / _ \ ' \/ -_) ' \ || | _/ _` | _/ _` | _| | ' \/ -_)_ \___/_||_\___|_||_\_,_|\__\__,_|\__\__,_|\__|_|_|_|_\___(_)_ ___ |___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___| ---------------------------------------------------- Sign Up for NetZero Platinum Today Only $9.95 per month! http://my.netzero.net/s/signup?r=platinum&refcd=PT97 From printers@sendme.cz Fri Jan 11 21:06:57 2002 From: printers@sendme.cz (A) Date: Fri, 11 Jan 2002 22:06:57 +0100 Subject: [Tutor] How to update file? Message-ID: <3C3F6201.14916.61F766@localhost> Hello, I need to update a local file from a web server if the file on this web server is newer then that on my local hard disk. Do you have any idea how it can be done? thank you. Ladislav From dyoo@hkn.eecs.berkeley.edu Sat Jan 12 04:52:52 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 11 Jan 2002 20:52:52 -0800 (PST) Subject: [Tutor] How to update file? In-Reply-To: <3C3F6201.14916.61F766@localhost> Message-ID: On Fri, 11 Jan 2002, A wrote: > I need to update a local file from a web server if the file on this > web server is newer then that on my local hard disk. Do you have any > idea how it can be done? I'm not sure if one can get a guaranteed 'last-modified' time of a web page. I did a quick search, and found something: http://www.xav.com/scripts/search/help/1068.html The page suggests that we look at the file itself, and see if it has a 'last-modified' META header. But that's a somewhat sketchy way of doing it... *grin* Alternatively, we can try to look at the "last-modified" header that gets sent to us by the web server. There's a description of this optional header from the W3 folks: http://www.w3.org/Protocols/HTTP/Object_Headers.html#last-modified We can use the 'httplib' module to grab at this header. Here's a small program that'll get the last-modified header if the web server supports it: ### import httplib import urlparse def getLastModifiedDate(url): url_pieces = urlparse.urlparse(url) base, path = url_pieces[1], url_pieces[2] ## this can be ## improved... conn = httplib.HTTPConnection(base) conn.request("GET", path) response = conn.getresponse() return response.getheader('last-modified') ### We'd better test this, just to make sure it works! *grin* ### >>> getLastModifiedDate("http://python.org") 'Fri, 11 Jan 2002 03:49:53 GMT ### However, maybe a simpler approach might work: how about just checking if your local file is different from what's on the web server? Hope this helps! From idiot1@netzero.net Sat Jan 12 07:29:22 2002 From: idiot1@netzero.net (kirk Bailey) Date: Sat, 12 Jan 2002 02:29:22 -0500 Subject: [Tutor] tinylist.1.0.0.tar.gz Message-ID: <3C3FE5D2.324A1885@netzero.net> Well, I think I did it right. Got the docs together, wapped into a tarball, crunced with gzip, made ~.tar.gz file. As working with tar and gzip are rather new to me ( I tend to use pkzip/unzip for widows) anyone ant a copy? Email me off list and I will send it direct. Registered the name tinylist.org, have the basic domain structure set up on the server. Waiting for the name to infect nameserver space, then will be able to offer support and sources on site. EVERY ONE OF YOU who helped this effort is thanked, and ALL of you are welcome. -- -Respectfully, -Kirk D Bailey end ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ |___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___| | _ \___ __ _ __| |_(_)_ _ __ _| |_| |_ ___ / __/ _ \| \| | | / _ Y _` (_-< _| | ' \/ _` | _| ' \/ -_) (_| (_) | .` |_ |_|_\___|__,_/__/\__|_|_||_\__, |\__|_||_\___|\___\___/|_|\_( ) |___/ |/ Kirk Bailey, consulting loose cannon www.howlermonkey.net highprimate@howlermonkey.net http://gipco.webjump.com idiot1@netzero.net _ _ _ _ ___ _ _ ___ _ _ _ _| |_ __ _| |_ __ _| |_(_)_ __ ___ / _ \ ' \/ -_) ' \ || | _/ _` | _/ _` | _| | ' \/ -_)_ \___/_||_\___|_||_\_,_|\__\__,_|\__\__,_|\__|_|_|_|_\___(_)_ ___ |___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___| ---------------------------------------------------- Sign Up for NetZero Platinum Today Only $9.95 per month! http://my.netzero.net/s/signup?r=platinum&refcd=PT97 From printers@sendme.cz Sat Jan 12 13:06:35 2002 From: printers@sendme.cz (A) Date: Sat, 12 Jan 2002 14:06:35 +0100 Subject: [Tutor] HTTPLib and POST problem with '?' Message-ID: <3C4042EB.30208.167FD1B@localhost> Hi, If I use example from Python doc like this #################### import httplib, urllib params = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0}) h = httplib.HTTP("www.musi-cal.com:80") h.putrequest("POST", "/cgi-bin/script.cgi") h.putheader("Content-type", "application/x-www-form-urlencoded") h.putheader("Content-length", "%d" % len(params)) h.putheader('Accept', 'text/plain') h.putheader('Host', 'www.musi-cal.com') h.endheaders() h.send(params) reply, msg, hdrs = h.getreply() print reply # should be 200 data = h.getfile().read() # get the raw HTML ################ it works well but only if the script is like http://www.musi-cal.com/cgi-bin/script.cgi but if the script is like http://www.musi-cal.com/cgi-bin/script.cgi?name=Paul (note a part after ? ) it means that PUTREQUEST should be h.putrequest("POST", "/cgi-bin/script.cgi?name=Paul") but httplib ignores everything after '?' and sends only /cgi-bin/script.cgi again Does anyone have any idea how it can be change to be ? sent the complete path(script)? Thanks. Ladislav From arcege@speakeasy.net Sat Jan 12 14:43:06 2002 From: arcege@speakeasy.net (Michael P. Reilly) Date: Sat, 12 Jan 2002 09:43:06 -0500 Subject: [Tutor] How to update file? In-Reply-To: ; from dyoo@hkn.eecs.berkeley.edu on Fri, Jan 11, 2002 at 08:52:52PM -0800 References: <3C3F6201.14916.61F766@localhost> Message-ID: <20020112094306.A4560@speakeasy.net> On Fri, Jan 11, 2002 at 08:52:52PM -0800, Danny Yoo wrote: [Preceding snipped] > Here's a small program that'll get the last-modified header if the web > server supports it: > > ### > import httplib > import urlparse > > def getLastModifiedDate(url): > url_pieces = urlparse.urlparse(url) > base, path = url_pieces[1], url_pieces[2] ## this can be > ## improved... > conn = httplib.HTTPConnection(base) > conn.request("GET", path) > response = conn.getresponse() > return response.getheader('last-modified') > ### Additionally, web servers accept a HEAD request which will not retreive the data, but just the headers, including the Last-Modified (if sent at all). If the file is large, it saves on work for the server. -Arcege From karshi.hasanov@utoronto.ca Sat Jan 12 17:48:33 2002 From: karshi.hasanov@utoronto.ca (Karshi) Date: Sat, 12 Jan 2002 12:48:33 -0500 Subject: [Tutor] Tk_help Message-ID: <20020112174906Z234715-19439+2@bureau8.utcc.utoronto.ca> Hi all, I have the following code in my program: -------------------------------------- class MyFrame(Frame): def __init__(self,parent=None ): Frame.__init__(self, parent,relief=RAISED, borderwidth=2) self.pack(fill=X) Command = makeCommandMenu(self) self.tk_menuBar(Command) def func(self): print " This will keep printing...." def makeCommandMenu(self): Command = Menubutton(self, text= ' Buttons', underline=0) Command.pack(side=LEFT, padx="2m") Command.menu = Menu(Command) Command.menu.add_command(label="Undo") Command.menu.entryconfig(0, state=DISABLED) Command.menu.add_command(label="New...", underline=0, command=self.func ) Command.menu.add_command(label="Open...", underline=0) Command.menu.add('separator') Command.menu.add_command(label='Quit', background='white', activebackground='green', command=Command.quit) Command['menu'] = Command.menu return Command -------------------------------------- which works fine. I am wondering about the line: "Command['menu'] = Command.menu" Can you explain me what this command does? Thanks From dyoo@hkn.eecs.berkeley.edu Sat Jan 12 20:01:36 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 12 Jan 2002 12:01:36 -0800 (PST) Subject: [Tutor] How to update file? (fwd) Message-ID: Let me forward this to Tutor; I'll try answering later today, but perhaps someone on Tutor can help. ---------- Forwarded message ---------- Date: Sat, 12 Jan 2002 14:06:35 +0100 From: A Reply-To: discuss@sendme.cz To: Danny Yoo Subject: Re: [Tutor] How to update file? On 11 Jan 2002, at 20:52, Danny Yoo wrote: > On Fri, 11 Jan 2002, A wrote: > > > I need to update a local file from a web server if the file on this > > web server is newer then that on my local hard disk. Do you have any > > idea how it can be done? > > I'm not sure if one can get a guaranteed 'last-modified' time of a web > page. I did a quick search, and found something: > > http://www.xav.com/scripts/search/help/1068.html > > The page suggests that we look at the file itself, and see if it has a > 'last-modified' META header. But that's a somewhat sketchy way of doing > it... *grin* > > Alternatively, we can try to look at the "last-modified" header that gets > sent to us by the web server. There's a description of this optional > header from the W3 folks: > > http://www.w3.org/Protocols/HTTP/Object_Headers.html#last-modified > > We can use the 'httplib' module to grab at this header. > > > Here's a small program that'll get the last-modified header if the web > server supports it: > > ### > import httplib > import urlparse > > def getLastModifiedDate(url): > url_pieces = urlparse.urlparse(url) > base, path = url_pieces[1], url_pieces[2] ## this can be > ## improved... > conn = httplib.HTTPConnection(base) > conn.request("GET", path) > response = conn.getresponse() > return response.getheader('last-modified') > ### > > > We'd better test this, just to make sure it works! *grin* > > ### > >>> getLastModifiedDate("http://python.org") > 'Fri, 11 Jan 2002 03:49:53 GMT > ### > Dear Danny, Thank you for your email > > However, maybe a simpler approach might work: how about just >checking if > your local file is different from what's on the web server? How can I check whether my local file is not older than that on web server and if it is then download it with all file attributes like the file on the web server? I tried using os.stat but I was not able to get good results. Best regards, Ladislav From skip@pobox.com Sat Jan 12 15:13:34 2002 From: skip@pobox.com (Skip Montanaro) Date: Sat, 12 Jan 2002 09:13:34 -0600 Subject: [Tutor] Re: HTTPLib and POST problem with '?' In-Reply-To: <3C4042EB.30208.167FD1B@localhost> References: <3C4042EB.30208.167FD1B@localhost> Message-ID: <15424.21150.57394.74837@12-248-41-177.client.attbi.com> Ladislav> If I use example from Python doc like this Ladislav> #################### Ladislav> import httplib, urllib Ladislav> params = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0}) Ladislav> h = httplib.HTTP("www.musi-cal.com:80") Ladislav> h.putrequest("POST", "/cgi-bin/script.cgi") ... Ladislav> ################ Ladislav> it works well but only if the script is like Ladislav> http://www.musi-cal.com/cgi-bin/script.cgi Ladislav> but if the script is like Ladislav> http://www.musi-cal.com/cgi-bin/script.cgi?name=Paul Ladislav> (note a part after ? ) it means that PUTREQUEST should be Ladislav> h.putrequest("POST", "/cgi-bin/script.cgi?name=Paul") Ladislav> but httplib ignores everything after '?' and sends only Ladislav> /cgi-bin/script.cgi Ladislav> again You can change things a couple ways: * If you want to use the POST method, you must always send the parameters using a call to the send() method of the HTTP object. In this case, you had params = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0}) ... h.send(params) If you want the parameter to be "name" with a value of "Paul", change the call that sets params to params = urllib.urlencode({'name': 'Paul'}) * Use the GET method instead of the POST method: h = httplib.HTTP("www.musi-cal.com:80") h.putrequest("GET", "/cgi-bin/script.cgi?name=Paul") h.putheader('Accept', 'text/plain') h.putheader('Host', 'www.musi-cal.com') h.endheaders() reply, msg, hdrs = h.getreply() In any case, make sure when you test your code you are communicating with a web server that you know and that actually has the URL you are interested in. As the webmaster of www.musi-cal.com I can tell you with a fair degree of certainty there is no CGI script here named "script.cgi". -- Skip Montanaro (skip@pobox.com - http://www.mojam.com/) From dyoo@hkn.eecs.berkeley.edu Sat Jan 12 20:07:10 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 12 Jan 2002 12:07:10 -0800 (PST) Subject: [Tutor] How to update file? In-Reply-To: Message-ID: On Sat, 12 Jan 2002, [iso-8859-1] Gustavo C=F3rdova Avila wrote: > > Here's a small program that'll get the last-modified header if the web > > server supports it: > >=20 > > ### > > import httplib > > import urlparse > >=20 > > def getLastModifiedDate(url): > > url_pieces =3D urlparse.urlparse(url) > > base, path =3D url_pieces[1], url_pieces[2] ## this can be > > ## improved... > > conn =3D httplib.HTTPConnection(base) > > conn.request("GET", path) > > response =3D conn.getresponse() > > return response.getheader('last-modified') > > ### >=20 > If you're gonna check the date on the remote file (which is on the web > server), I'd really recommend you use the HEAD method instead of the > GET method, because GET will bring you the whole file's contents, and > HEAD won't return the file contents, only the request's HTTP headers, > which is where the last modification date is. Thank you! I had completely forgotten about HEAD. From dsh8290@rit.edu Sat Jan 12 20:33:35 2002 From: dsh8290@rit.edu (dman) Date: Sat, 12 Jan 2002 15:33:35 -0500 Subject: [Tutor] ethics in programming In-Reply-To: <3C3F1307.68242321@netzero.net> References: <3C3F1307.68242321@netzero.net> Message-ID: <20020112203335.GA3292@localhost> On Fri, Jan 11, 2002 at 11:29:59AM -0500, kirk Bailey wrote: | Working on TinyList, I realized that for security reasons I am using | TL's ability to talk to the smtp engine to send out the email, one | envlope per recipient. I think it is better to pipe the message to the mail system (eg exim, postfix, or sendmail). Are you prepared to properly handle all error repsones from the SMTP server and retry delivery or return a bounce message as appropriate? SMTP seems trivial, but there are many things to get right for a robust system. Piping _is_ quite trivial and it gets the message off of your hands quickly. | Good, avoids security issues with many recipients per envlope. But | this does slow down transmisson a little, mabe more than a little | when we are talking LARGE lists. Right -- you need to send the DATA section once for each recipient. If you pipe it to exim I believe you will be able to specify all recipients at once and let exim deal with delivering it to the destination. I do know for a fact that if I put 2 addresses in To: or Cc: headers (using my mua) then exim makes two separate passes over the "routers" and delivers the message separately for each destination. | A way used in majordomo to send lists is to feed ONE copy of the | letter to a special alias and take advantage of the :include: command | to invoke the subscriber file. such a list alias looks like: | | listname-outgoing::include:/path/subscriberfilename # no spaces in the | definition PLEASE! | | And the Mail Transmission Agent(hereafter MTA, usually sendmail) reads | that file and sends a copy of the letter to each person on it. THERE | IS NO OTHER SERVICE. *ANY* letter landing on that email alais goes | out. Very spam friendly alas. And this is a Very Bad Thing. | | Of course, the idea is the name of alias is a secret, Security through obscurity doesn't work. Look at what happens with MS systems as opposed to Linux or *BSD systems. One is obscure (no source available) the other isn't. | and is fed by a | program, in this case majordomo. The manual uses listname-outgoing as | an example, but you are supposed to pick some random name so as to | safeguard the list. THAT alias may be made public, as it feeds into | some kind of security program. I haven't read the mailing list part of the exim manual yet, and I haven't read any manuals on MailMan. However I do know a bit about receiving mail (with exim as the MTA) and how it can be run through several different layers and forms of spam detection and rejection. When someone posts a message to the list address you will (should) run it through some checks (I've heard good things about "spamassassin" and "vipul's razor") to determine whether or not to accept or reject it. If it is accepted as not being spam you will then rewrite the envelope recipient to be all the list members and continue processing (send it to the new recipients). The list->subscribers expansion can be done by exim itself (without creating new, unchecked, aliases as it sounds like majordomo wants) or by an external program (such as MailMan) and the recipients list specified as the message is handed back to the MTA (this still works without an new alias). HTH, -D -- I can do all things through Christ who strengthens me. Philippians 4:13 From arcege@speakeasy.net Sat Jan 12 21:04:59 2002 From: arcege@speakeasy.net (Michael P. Reilly) Date: Sat, 12 Jan 2002 16:04:59 -0500 Subject: [Tutor] Tk_help In-Reply-To: <20020112174906Z234715-19439+2@bureau8.utcc.utoronto.ca>; from karshi.hasanov@utoronto.ca on Sat, Jan 12, 2002 at 12:48:33PM -0500 References: <20020112174906Z234715-19439+2@bureau8.utcc.utoronto.ca> Message-ID: <20020112160459.A5064@speakeasy.net> On Sat, Jan 12, 2002 at 12:48:33PM -0500, Karshi wrote: > I have the following code in my program: > -------------------------------------- > class MyFrame(Frame): > def __init__(self,parent=None ): > Frame.__init__(self, parent,relief=RAISED, borderwidth=2) > self.pack(fill=X) > Command = makeCommandMenu(self) > > self.tk_menuBar(Command) > def func(self): > print " This will keep printing...." > > def makeCommandMenu(self): > > Command = Menubutton(self, text= ' Buttons', underline=0) > Command.pack(side=LEFT, padx="2m") > Command.menu = Menu(Command) > > Command.menu.add_command(label="Undo") > Command.menu.entryconfig(0, state=DISABLED) > > Command.menu.add_command(label="New...", underline=0, command=self.func ) > Command.menu.add_command(label="Open...", underline=0) > > Command.menu.add('separator') > Command.menu.add_command(label='Quit', background='white', > activebackground='green', command=Command.quit) > > Command['menu'] = Command.menu > return Command > -------------------------------------- > which works fine. > I am wondering about the line: > "Command['menu'] = Command.menu" > Can you explain me what this command does? > Thanks It sounds confusing, but with Tkinter widgets, the statement widget['name'] = value is the equivalent to widget.config(name = value) A new Menu widget is created, and you need to tell the Menubutton what the pop-up menu is through either 'widget["menu"]' or 'widget.config(menu=)'. The new Menu widget also happens to be stored as an attribute of the Menubutton with 'widget.attr = value' (in this case 'Command.menu = Menu(Command)'). It might help if you change it to: Command.menu_subwidget = Menu(Command) ... Command.config(menu = Command.menu_subwidget) Better? :) -Arcege From idiot1@netzero.net Sat Jan 12 22:01:33 2002 From: idiot1@netzero.net (kirk Bailey) Date: Sat, 12 Jan 2002 17:01:33 -0500 Subject: [Tutor] ethics in programming References: <3C3F1307.68242321@netzero.net> <20020112203335.GA3292@localhost> Message-ID: <3C40B23D.467D03C@netzero.net> dman wrote: > > On Fri, Jan 11, 2002 at 11:29:59AM -0500, kirk Bailey wrote: > | Working on TinyList, I realized that for security reasons I am using > | TL's ability to talk to the smtp engine to send out the email, one > | envlope per recipient. > > I think it is better to pipe the message to the mail system (eg exim, > postfix, or sendmail). Are you prepared to properly handle all error > repsones from the SMTP server and retry delivery or return a bounce > message as appropriate? SMTP seems trivial, but there are many things > to get right for a robust system. Piping _is_ quite trivial and it > gets the message off of your hands quickly. Not familiar with the concept as you use it, possibly this is a linguistics issue, and I already use it by another name. > > | Good, avoids security issues with many recipients per envlope. But > | this does slow down transmisson a little, mabe more than a little > | when we are talking LARGE lists. > > Right -- you need to send the DATA section once for each recipient. Well, another program (minorfish) does exactly that! But we limit max recipients per envlope to 10 to make spam more difficult, so that immediately encounters a security precaution conflict. But this itself is a by the aay, not the REAL major problem. > If you pipe it to exim I believe you will be able to specify all > recipients at once and let exim deal with delivering it to the > destination. I do know for a fact that if I put 2 addresses in To: or > Cc: headers (using my mua) then exim makes two separate passes over > the "routers" and delivers the message separately for each > destination. > > | A way used in majordomo to send lists is to feed ONE copy of the > | letter to a special alias and take advantage of the :include: command > | to invoke the subscriber file. such a list alias looks like: > | > | listname-outgoing::include:/path/subscriberfilename # no spaces in the > | definition PLEASE! > | > | And the Mail Transmission Agent(hereafter MTA, usually sendmail) reads > | that file and sends a copy of the letter to each person on it. THERE > | IS NO OTHER SERVICE. *ANY* letter landing on that email alais goes > | out. Very spam friendly alas. And this is a Very Bad Thing. > | > | Of course, the idea is the name of alias is a secret, > > Security through obscurity doesn't work. Look at what happens with MS > systems as opposed to Linux or *BSD systems. One is obscure (no > source available) the other isn't. True, once someone figures out the nam of the outbound alias on a majordomo list system, they can spam it at convience, and there is NOT ONE DAMN THING YOU CAN DO TO STOP THEM except change the name of the outbound alias. If they discovered it once, they can discover it again. I blush to admit that I can TELL YOU the aliases for every list in tinylist, and it will avail you NOTHING. THIS is a much more secure setup, and does not conflict with other security precautions. SO until I throughly understand other methods and can implement them reliably in MANY servers, without requiring special transmission agents, I think I will retain it. But if the list is LARGE, it calls for a helper program. considering this issue, I began to realize that such a program could offer security holes, and be vulnerable to being spammed; also, it made it practical to send spam in and of itself, for free, whereas current spambots cost LONG BUCK$. so having written a program I think will handle the task, I buried it. > > | and is fed by a > | program, in this case majordomo. The manual uses listname-outgoing as > | an example, but you are supposed to pick some random name so as to > | safeguard the list. THAT alias may be made public, as it feeds into > | some kind of security program. > > I haven't read the mailing list part of the exim manual yet, and I > haven't read any manuals on MailMan. However I do know a bit about > receiving mail (with exim as the MTA) and how it can be run through > several different layers and forms of spam detection and rejection. > That's good. Now what if a would be spamhouse get's their hands on some FREE software to do this sort of thing? So far, software to handle sending out bulk mail costs som bucks. If I start writing and releasing GNU GPL software to do so, LOTS of woodbe spamhauses will suddenly have the CAPITAL barrier removed. You think spam is bad now? THIS is the ethics issue this thread is about. That other stuff is a TECHNIQUE issue, this is an ETHICS issue I am raising. > When someone posts a message to the list address you will (should) run > it through some checks (I've heard good things about "spamassassin" > and "vipul's razor") to determine whether or not to accept or reject > it. If it is accepted as not being spam you will then rewrite the > envelope recipient to be all the list members and continue processing > (send it to the new recipients). The list->subscribers expansion can > be done by exim itself (without creating new, unchecked, aliases as it > sounds like majordomo wants) or by an external program (such as > MailMan) and the recipients list specified as the message is handed > back to the MTA (this still works without an new alias). > I must admit exim sounds like a MTA worth examining in greater detail. Although mature and powerful, sendmail is a tad creaky and there are many other MTA's available now with additional features. My problem as a programmer is that I can count on something that will accept sendmail commands, but sendmail will not reliably do for the user what exim will accept. > HTH, > -D > > -- > > I can do all things through Christ who strengthens me. > Philippians 4:13 > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- -Respectfully, -Kirk D Bailey end ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ |___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___| | _ \___ __ _ __| |_(_)_ _ __ _| |_| |_ ___ / __/ _ \| \| | | / _ Y _` (_-< _| | ' \/ _` | _| ' \/ -_) (_| (_) | .` |_ |_|_\___|__,_/__/\__|_|_||_\__, |\__|_||_\___|\___\___/|_|\_( ) |___/ |/ Kirk Bailey, consulting loose cannon www.howlermonkey.net highprimate@howlermonkey.net http://gipco.webjump.com idiot1@netzero.net _ _ _ _ ___ _ _ ___ _ _ _ _| |_ __ _| |_ __ _| |_(_)_ __ ___ / _ \ ' \/ -_) ' \ || | _/ _` | _/ _` | _| | ' \/ -_)_ \___/_||_\___|_||_\_,_|\__\__,_|\__\__,_|\__|_|_|_|_\___(_)_ ___ |___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___| ---------------------------------------------------- Sign Up for NetZero Platinum Today Only $9.95 per month! http://my.netzero.net/s/signup?r=platinum&refcd=PT97 From dsh8290@rit.edu Sat Jan 12 22:33:42 2002 From: dsh8290@rit.edu (dman) Date: Sat, 12 Jan 2002 17:33:42 -0500 Subject: [Tutor] ethics in programming In-Reply-To: <3C40B23D.467D03C@netzero.net> References: <3C3F1307.68242321@netzero.net> <20020112203335.GA3292@localhost> <3C40B23D.467D03C@netzero.net> Message-ID: <20020112223342.GA3956@localhost> On Sat, Jan 12, 2002 at 05:01:33PM -0500, kirk Bailey wrote: | dman wrote: | > | > On Fri, Jan 11, 2002 at 11:29:59AM -0500, kirk Bailey wrote: | > | Working on TinyList, I realized that for security reasons I am using | > | TL's ability to talk to the smtp engine to send out the email, one | > | envlope per recipient. | > | > I think it is better to pipe the message to the mail system (eg exim, | > postfix, or sendmail). Are you prepared to properly handle all error | > repsones from the SMTP server and retry delivery or return a bounce | > message as appropriate? SMTP seems trivial, but there are many things | > to get right for a robust system. Piping _is_ quite trivial and it | > gets the message off of your hands quickly. | | Not familiar with the concept as you use it, possibly this is a | linguistics issue, and I already use it by another name. Are you familiar with Unix? $ sendmail idiot1@netzero.net << EOF From: dman Subject: Hi Kirk. Date: today (obviously this is syntactically incorrect) To: Kirk Hi Kirk. This is the body of a message. This message was not created with a a MUA :-). EOF $ There is no SMTP involved in what I did. I ran exim, gave it the recipients on the command line and gave it the message itself (not quite conforming to RFC2822 but you get the idea) on stdin. I don't need to worry about SMTP errors or networking or anything. The only two possible errors is that the pipe is closed before I'm done writing or that exim returns non-zero exit status. Your TinyList program would use f = os.popen( "sendmail %s" % recipients ) f.write( message ) f.close() (BTW exim answers to the name sendmail if you make a symlink to the binary. It also behaves very compatibly, a drop-in replacement.) | > | Good, avoids security issues with many recipients per envlope. But | > | this does slow down transmisson a little, mabe more than a little | > | when we are talking LARGE lists. | > | > Right -- you need to send the DATA section once for each recipient. | | Well, another program (minorfish) does exactly that! But we limit | max recipients per envlope to 10 to make spam more difficult, so | that immediately encounters a security precaution conflict. But this | itself is a by the aay, not the REAL major problem. I was explicitly giving the reason for the performance degradation. | > If you pipe it to exim I believe you will be able to specify all | > recipients at once and let exim deal with delivering it to the | > destination. I do know for a fact that if I put 2 addresses in To: or | > Cc: headers (using my mua) then exim makes two separate passes over | > the "routers" and delivers the message separately for each | > destination. | > | > | A way used in majordomo to send lists is to feed ONE copy of the | > | letter to a special alias and take advantage of the :include: command | > | to invoke the subscriber file. such a list alias looks like: | > | | > | listname-outgoing::include:/path/subscriberfilename # no spaces in the | > | definition PLEASE! | > | | > | And the Mail Transmission Agent(hereafter MTA, usually sendmail) reads | > | that file and sends a copy of the letter to each person on it. THERE | > | IS NO OTHER SERVICE. *ANY* letter landing on that email alais goes | > | out. Very spam friendly alas. And this is a Very Bad Thing. | > | | > | Of course, the idea is the name of alias is a secret, | > | > Security through obscurity doesn't work. Look at what happens with MS | > systems as opposed to Linux or *BSD systems. One is obscure (no | > source available) the other isn't. | | True, once someone figures out the nam of the outbound alias on a | majordomo list system, they can spam it at convience, and there is | NOT ONE DAMN THING YOU CAN DO TO STOP THEM except change the name of | the outbound alias. If they discovered it once, they can discover it | again. | | I blush to admit that I can TELL YOU the aliases for every list in | tinylist, and it will avail you NOTHING. | THIS is a much more secure setup, and does not conflict with other | security precautions. SO until I throughly understand other methods | and can implement them reliably in MANY servers, without requiring | special transmission agents, I think I will retain it. But if the list | is LARGE, it calls for a helper program. considering this issue, I | began to realize that such a program could offer security holes, and | be vulnerable to being spammed; also, it made it practical to send | spam in and of itself, for free, whereas current spambots cost LONG | BUCK$. so having written a program I think will handle the task, I | buried it. | | > | and is fed by a | > | program, in this case majordomo. The manual uses listname-outgoing as | > | an example, but you are supposed to pick some random name so as to | > | safeguard the list. THAT alias may be made public, as it feeds into | > | some kind of security program. | > | > I haven't read the mailing list part of the exim manual yet, and I | > haven't read any manuals on MailMan. However I do know a bit about | > receiving mail (with exim as the MTA) and how it can be run through | > several different layers and forms of spam detection and rejection. | | That's good. | | Now what if a would be spamhouse get's their hands on some FREE | software to do this sort of thing? | | So far, software to handle sending out bulk mail costs som bucks. Umm, try this. Put an RFC2822 conformant message in my_spam_message.txt. Now use this shell script, feed it a list of addresses in the argument list. #!/bin/sh for ADDR in "$@" ; do cat my_spam_message.txt | sendmail $ADDR done Who charges big bucks for this? This technique will get past your 10 recipient check since it only has one recipient. It wouldn't be hard to add a little sed to make the To: header match the RCPT TO: command and pass a few more spam checks. Ok, so writing a bot to crawl through USENET and mailing list archives to harvest the addresses may not be trivial. The other problem is that your IP gets added to the RBL and many sites will reject it then. The only remaining technique that one needs is locating the open relays out there to bypass RBL checks. | If I start writing and releasing GNU GPL software to do so, LOTS of | woodbe spamhauses will suddenly have the CAPITAL barrier removed. | You think spam is bad now? THIS is the ethics issue this thread is | about. That other stuff is a TECHNIQUE issue, this is an ETHICS | issue I am raising. Yeah, spam is an ethics issue, but so is licenses and just about every other law and policy in this world. Only two laws are necessary, if people would actually follow them 1) Love the Lord your God with all your heart, mind, and soul, and 2) love your neighbor as yourself. If people followed these commands, then there would be no spam or stealing or ... | > When someone posts a message to the list address you will (should) run | > it through some checks (I've heard good things about "spamassassin" | > and "vipul's razor") to determine whether or not to accept or reject | > it. If it is accepted as not being spam you will then rewrite the | > envelope recipient to be all the list members and continue processing | > (send it to the new recipients). The list->subscribers expansion can | > be done by exim itself (without creating new, unchecked, aliases as it | > sounds like majordomo wants) or by an external program (such as | > MailMan) and the recipients list specified as the message is handed | > back to the MTA (this still works without an new alias). | | I must admit exim sounds like a MTA worth examining in greater detail. It is :-). It is easy to configure too. -D -- Micros~1 : For when quality, reliability and security just aren't that important! From idiot1@netzero.net Sat Jan 12 22:37:24 2002 From: idiot1@netzero.net (kirk Bailey) Date: Sat, 12 Jan 2002 17:37:24 -0500 Subject: [Tutor] ethics in programming References: <3C3F1307.68242321@netzero.net> <20020112203335.GA3292@localhost> <3C40B23D.467D03C@netzero.net> <20020112223342.GA3956@localhost> Message-ID: <3C40BAA4.55A3E6D5@netzero.net> dman wrote: > > On Sat, Jan 12, 2002 at 05:01:33PM -0500, kirk Bailey wrote: > | dman wrote: > | > > | > On Fri, Jan 11, 2002 at 11:29:59AM -0500, kirk Bailey wrote: > | > | Working on TinyList, I realized that for security reasons I am using > | > | TL's ability to talk to the smtp engine to send out the email, one > | > | envlope per recipient. > | > > | > I think it is better to pipe the message to the mail system (eg exim, > | > postfix, or sendmail). Are you prepared to properly handle all error > | > repsones from the SMTP server and retry delivery or return a bounce > | > message as appropriate? SMTP seems trivial, but there are many things > | > to get right for a robust system. Piping _is_ quite trivial and it > | > gets the message off of your hands quickly. > | > | Not familiar with the concept as you use it, possibly this is a > | linguistics issue, and I already use it by another name. > > Are you familiar with Unix? > some, I blush to admit some, but always somethign new to learn. > $ sendmail idiot1@netzero.net << EOF > From: dman > Subject: Hi Kirk. > Date: today (obviously this is syntactically incorrect) > To: Kirk > > Hi Kirk. This is the body of a message. This message was not created > with a a MUA :-). > > EOF > > $ > Just tried it, worked fine. > There is no SMTP involved in what I did. I ran exim, gave it the > recipients on the command line and gave it the message itself (not > quite conforming to RFC2822 but you get the idea) on stdin. I don't > need to worry about SMTP errors or networking or anything. The only > two possible errors is that the pipe is closed before I'm done writing > or that exim returns non-zero exit status. > > Your TinyList program would use > f = os.popen( "sendmail %s" % recipients ) > f.write( message ) > f.close() > > (BTW exim answers to the name sendmail if you make a symlink to the > binary. It also behaves very compatibly, a drop-in replacement.) > > | > | Good, avoids security issues with many recipients per envlope. But > | > | this does slow down transmisson a little, mabe more than a little > | > | when we are talking LARGE lists. > | > > | > Right -- you need to send the DATA section once for each recipient. > | > | Well, another program (minorfish) does exactly that! But we limit > | max recipients per envlope to 10 to make spam more difficult, so > | that immediately encounters a security precaution conflict. But this > | itself is a by the aay, not the REAL major problem. > > I was explicitly giving the reason for the performance degradation. > > | > If you pipe it to exim I believe you will be able to specify all > | > recipients at once and let exim deal with delivering it to the > | > destination. I do know for a fact that if I put 2 addresses in To: or > | > Cc: headers (using my mua) then exim makes two separate passes over > | > the "routers" and delivers the message separately for each > | > destination. > | > > | > | A way used in majordomo to send lists is to feed ONE copy of the > | > | letter to a special alias and take advantage of the :include: command > | > | to invoke the subscriber file. such a list alias looks like: > | > | > | > | listname-outgoing::include:/path/subscriberfilename # no spaces in the > | > | definition PLEASE! > | > | > | > | And the Mail Transmission Agent(hereafter MTA, usually sendmail) reads > | > | that file and sends a copy of the letter to each person on it. THERE > | > | IS NO OTHER SERVICE. *ANY* letter landing on that email alais goes > | > | out. Very spam friendly alas. And this is a Very Bad Thing. > | > | > | > | Of course, the idea is the name of alias is a secret, > | > > | > Security through obscurity doesn't work. Look at what happens with MS > | > systems as opposed to Linux or *BSD systems. One is obscure (no > | > source available) the other isn't. > | > | True, once someone figures out the nam of the outbound alias on a > | majordomo list system, they can spam it at convience, and there is > | NOT ONE DAMN THING YOU CAN DO TO STOP THEM except change the name of > | the outbound alias. If they discovered it once, they can discover it > | again. > | > | I blush to admit that I can TELL YOU the aliases for every list in > | tinylist, and it will avail you NOTHING. > | THIS is a much more secure setup, and does not conflict with other > | security precautions. SO until I throughly understand other methods > | and can implement them reliably in MANY servers, without requiring > | special transmission agents, I think I will retain it. But if the list > | is LARGE, it calls for a helper program. considering this issue, I > | began to realize that such a program could offer security holes, and > | be vulnerable to being spammed; also, it made it practical to send > | spam in and of itself, for free, whereas current spambots cost LONG > | BUCK$. so having written a program I think will handle the task, I > | buried it. > | > | > | and is fed by a > | > | program, in this case majordomo. The manual uses listname-outgoing as > | > | an example, but you are supposed to pick some random name so as to > | > | safeguard the list. THAT alias may be made public, as it feeds into > | > | some kind of security program. > | > > | > I haven't read the mailing list part of the exim manual yet, and I > | > haven't read any manuals on MailMan. However I do know a bit about > | > receiving mail (with exim as the MTA) and how it can be run through > | > several different layers and forms of spam detection and rejection. > | > | That's good. > | > | Now what if a would be spamhouse get's their hands on some FREE > | software to do this sort of thing? > | > | So far, software to handle sending out bulk mail costs som bucks. > > Umm, try this. Put an RFC2822 conformant message in > my_spam_message.txt. Now use this shell script, feed it a list of > addresses in the argument list. > > #!/bin/sh > > for ADDR in "$@" ; > do > cat my_spam_message.txt | sendmail $ADDR > done > > Who charges big bucks for this? This technique will get past your 10 > recipient check since it only has one recipient. It wouldn't be hard > to add a little sed to make the To: header match the RCPT TO: command > and pass a few more spam checks. > > Ok, so writing a bot to crawl through USENET and mailing list archives > to harvest the addresses may not be trivial. The other problem is > that your IP gets added to the RBL and many sites will reject it then. > The only remaining technique that one needs is locating the open > relays out there to bypass RBL checks. > > | If I start writing and releasing GNU GPL software to do so, LOTS of > | woodbe spamhauses will suddenly have the CAPITAL barrier removed. > | You think spam is bad now? THIS is the ethics issue this thread is > | about. That other stuff is a TECHNIQUE issue, this is an ETHICS > | issue I am raising. > > Yeah, spam is an ethics issue, but so is licenses and just about every > other law and policy in this world. Only two laws are necessary, if > people would actually follow them > > 1) Love the Lord your God with all your heart, mind, and soul, > and > 2) love your neighbor as yourself. > > If people followed these commands, then there would be no spam or > stealing or ... > > | > When someone posts a message to the list address you will (should) run > | > it through some checks (I've heard good things about "spamassassin" > | > and "vipul's razor") to determine whether or not to accept or reject > | > it. If it is accepted as not being spam you will then rewrite the > | > envelope recipient to be all the list members and continue processing > | > (send it to the new recipients). The list->subscribers expansion can > | > be done by exim itself (without creating new, unchecked, aliases as it > | > sounds like majordomo wants) or by an external program (such as > | > MailMan) and the recipients list specified as the message is handed > | > back to the MTA (this still works without an new alias). > | > | I must admit exim sounds like a MTA worth examining in greater detail. > > It is :-). It is easy to configure too. > > -D > Dman, I must compliment you; You really display a comprehension of the technical and other issues. Would you like to be added to the tinylist-devlopers discussion list? > -- > > Micros~1 : > For when quality, reliability > and security just aren't > that important! > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- -Respectfully, -Kirk D Bailey Consulting Loose Cannon end www.howlermonkey.net highprimate@howlermonkey.net www.sacredelectron.org idiot1@netzero.net www.tinylist.org grumpy@tinylist.org ---------------------------------------------------- Sign Up for NetZero Platinum Today Only $9.95 per month! http://my.netzero.net/s/signup?r=platinum&refcd=PT97 From srichter@cbu.edu Sat Jan 12 22:56:48 2002 From: srichter@cbu.edu (Stephan Richter) Date: Sat, 12 Jan 2002 16:56:48 -0600 Subject: [Tutor] ethics in programming In-Reply-To: <3C40BAA4.55A3E6D5@netzero.net> References: <3C3F1307.68242321@netzero.net> <20020112203335.GA3292@localhost> <3C40B23D.467D03C@netzero.net> <20020112223342.GA3956@localhost> Message-ID: <5.1.0.14.2.20020112165334.03babdf8@mercury-1.cbu.edu> Okay, I have read enough. Maybe I missed a mail or so, but why in the world would you not want to use Mailman? It is written in Python and it has a good API. If Mailman does not have a feature that you require, then implement it for Mailman. This way many others will profit from the code. And btw, Barry (Warsaw) is a very nice guy and is very open to new features. Regards, Stephan -- Stephan Richter CBU - Physics and Chemistry Student Web2k - Web Design/Development & Technical Project Management From idiot1@netzero.net Sat Jan 12 23:10:34 2002 From: idiot1@netzero.net (kirk Bailey) Date: Sat, 12 Jan 2002 18:10:34 -0500 Subject: [Tutor] ethics in programming References: <3C3F1307.68242321@netzero.net> <20020112203335.GA3292@localhost> <3C40B23D.467D03C@netzero.net> <20020112223342.GA3956@localhost> <5.1.0.14.2.20020112165334.03babdf8@mercury-1.cbu.edu> Message-ID: <3C40C26A.F674E4CD@netzero.net> This is a fair question, and deserves an answer. Mailman cannot append advertisements, nor manage the rotation of them. If you want your list service to earn enough money to pay for itself, it has toeither SELL list service, or earn revenues from advertisements appended to the traffic passing through it. Stephan Richter wrote: > > Okay, > > I have read enough. Maybe I missed a mail or so, but why in the world would > you not want to use Mailman? It is written in Python and it has a good API. > If Mailman does not have a feature that you require, then implement it for > Mailman. This way many others will profit from the code. And btw, Barry > (Warsaw) is a very nice guy and is very open to new features. > I am glad to hear this! My experience with another product which ALMOST did what I wanted was far less satisfying. Also, when I started, I could not program python- or perl. I tried to learn perl, and it left me confused. The python language seemed to me more accessable, and the tutor list was VERY friendly and forthcoming with good advice, and QUITE tolerant of a python newbie- a trait sadly lacking elsewhere in other languages I considered. Again, I must compliment the tutor list community. And, as a high level language, it could handle doing this simply, whereas doing this in C would be a long and arduous task, and I would have to learn C. This is not something to accomplish in 3 weeks. And, As I needed a scripting language for 'glue' and cgi scripting anyway, I took it on myself to learn the best language for the task. PYTHON. Although there are still plenty of things to learn, I am well on my way. And, building from the ground up, I had complete control of how it worked, and could insure it did what I wanted, the way I wanted, and when done I would have DEEP understanding of it, how it worked, why it worked, and why it was that way. This also translates later into a marketable skill- building a list server for others. And, having had a distasteful experience with a product controled by someone else, by creating a tool myself I could insure I could always change it, and not have a problem with a primadonna messing up my goals withhis/her ego. That STILL leaves a bad taste in my mouth, 3 months later. Abnd, it meant giving the community a new tool for this sort of task. And payforward being what it is, it is only proper that I make it available freely under the GNU GPL. But thanks for asking, I welcome the opportunity to clarify things. Always feel free to ask me anything you like. > Regards, > Stephan > > -- > Stephan Richter > CBU - Physics and Chemistry Student > Web2k - Web Design/Development & Technical Project Management -- -Respectfully, -Kirk D Bailey Consulting Loose Cannon end www.howlermonkey.net highprimate@howlermonkey.net www.sacredelectron.org idiot1@netzero.net www.tinylist.org grumpy@tinylist.org ---------------------------------------------------- Sign Up for NetZero Platinum Today Only $9.95 per month! http://my.netzero.net/s/signup?r=platinum&refcd=PT97 From virketis@fas.harvard.edu Sat Jan 12 23:59:20 2002 From: virketis@fas.harvard.edu (Pijus Virketis) Date: Sat, 12 Jan 2002 18:59:20 -0500 Subject: [Tutor] ethics in programming References: <3C3F1307.68242321@netzero.net> <20020112203335.GA3292@localhost> <3C40B23D.467D03C@netzero.net> <20020112223342.GA3956@localhost> <5.1.0.14.2.20020112165334.03babdf8@mercury-1.cbu.edu> <3C40C26A.F674E4CD@netzero.net> Message-ID: <001501c19bc5$26daf170$dbadf78c@virketis2> > Mailman cannot append advertisements, nor manage the rotation of them. > > If you want your list service to earn enough money to pay for itself, > it has toeither SELL list service, or earn revenues from > advertisements appended to the traffic passing through it. Kirk, I think Stephan's point was that even if Mailman is missing some feature you need, it would be easier and more beneficial to the whole community to add it, rather than forking your own list manager. I hope you will agree that more people would be able to share the fruits of your hard work, if you modified an established program, like Mailman. Cheers, Pijus From grimmtoothtoo@yahoo.com Sun Jan 13 00:36:38 2002 From: grimmtoothtoo@yahoo.com (Grimmtooth) Date: Sat, 12 Jan 2002 19:36:38 -0500 Subject: [Tutor] ethics in programming In-Reply-To: <001501c19bc5$26daf170$dbadf78c@virketis2> Message-ID: What, and miss the learning experience? Tut! :-) > more people would be able to share the fruits of your hard work, if you > modified an established program, like Mailman. _________________________________________________________ Do You Yahoo!? Get your free @yahoo.com address at http://mail.yahoo.com From flash1210@hotmail.com Sun Jan 13 01:00:42 2002 From: flash1210@hotmail.com (Frank Holmes) Date: Sat, 12 Jan 2002 17:00:42 -0800 Subject: [Tutor] clearscreen command Message-ID: does python have the equivalent of a clearscreen command? _________________________________________________________________ Get your FREE download of MSN Explorer at http://explorer.msn.com/intl.asp. From rufmetal@rogers.com Sun Jan 13 01:24:22 2002 From: rufmetal@rogers.com (Chris Keelan) Date: Sat, 12 Jan 2002 20:24:22 -0500 Subject: [Tutor] clearscreen command In-Reply-To: References: Message-ID: <20020113012705.DAOV183570.fep03-mail.bloor.is.net.cable.rogers.com@there> On Saturday 12 January 2002 08:00 pm, Frank Holmes wrote: > does python have the equivalent of a clearscreen command? In a *nix environment: import os os.cmd('clear') I have no idea how to do this in Windows: maybe os.cmd('cls') ? - C From dsh8290@rit.edu Sun Jan 13 01:39:33 2002 From: dsh8290@rit.edu (dman) Date: Sat, 12 Jan 2002 20:39:33 -0500 Subject: [Tutor] clearscreen command In-Reply-To: References: Message-ID: <20020113013933.GA4924@localhost> On Sat, Jan 12, 2002 at 05:00:42PM -0800, Frank Holmes wrote: | does python have the equivalent of a clearscreen command? Python doesn't have "screens" so it can't clear them. Screens are part of the OS you're using. If you use the ncurses library you can clear the screen (Unix and Cygwin only). If you assume the terminal has no more than 30 lines print "\n"*30 will have the same effect. Alternatively you can try and figure out which escape codes various shells/terminals use to clear the screen. -D -- Religion that God our Father accepts as pure and faultless is this: to look after orphans and widows in their distress and to keep oneself from being polluted by the world. James 1:27 From ak@silmarill.org Sun Jan 13 01:38:49 2002 From: ak@silmarill.org (Andrei Kulakov) Date: Sat, 12 Jan 2002 20:38:49 -0500 Subject: [Tutor] ethics in programming In-Reply-To: ; from grimmtoothtoo@yahoo.com on Sat, Jan 12, 2002 at 07:36:38PM -0500 References: <001501c19bc5$26daf170$dbadf78c@virketis2> Message-ID: <20020112203849.A12856@silmarill.org> On Sat, Jan 12, 2002 at 07:36:38PM -0500, Grimmtooth wrote: > What, and miss the learning experience? Tut! :-) That's what the thread is about - someone told kirk that TL is fine as a learning experiment, but if he wants to have a full fledged list manager with the features he wants, he's better off modifying Mailman. I think that's true.. If all you want is a few new features, change existing program(s). Only make a new one if you think existing systems have an inherently flawed architecture or if you want to use a completely different approach.. > > > more people would be able to share the fruits of your hard work, if you > > modified an established program, like Mailman. > > > > _________________________________________________________ > Do You Yahoo!? > Get your free @yahoo.com address at http://mail.yahoo.com > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: cy.silmarill.org From grimmtoothtoo@yahoo.com Sun Jan 13 03:30:40 2002 From: grimmtoothtoo@yahoo.com (Grimmtooth) Date: Sat, 12 Jan 2002 22:30:40 -0500 Subject: [Tutor] ethics in programming In-Reply-To: <20020112203849.A12856@silmarill.org> Message-ID: > I think that's true.. If all you want is a few new features, change > existing program(s). Only make a new one if you think existing systems > have an inherently flawed architecture or if you want to use a > completely different approach.. Nothing wrong with a fresh approach and/or a multitude of choices. That is one of the cornerstones of open source development, or so I hear. And of course, there's nothing more satisfying than seeing it through from start to finish. _________________________________________________________ Do You Yahoo!? Get your free @yahoo.com address at http://mail.yahoo.com From idiot1@netzero.net Sun Jan 13 05:52:06 2002 From: idiot1@netzero.net (kirk Bailey) Date: Sun, 13 Jan 2002 00:52:06 -0500 Subject: [Tutor] TLmakelist Message-ID: <3C412085.72FD9EA@netzero.net> TLmakelist is ready. It is a 'sh' shell script, and it works; I have used it to create 2 lists flawlessly. It will receive input as command line input, or as prompted console input if none is fed to it from the command line. With a Python cgi script it can be fed that command line input, and let that webscript filter out agressive code. THAT script is not written yet. Anyone who wants a copy email me off list and I shall provide it direct. -- -Respectfully, -Kirk D Bailey Consulting Loose Cannon end www.howlermonkey.net highprimate@howlermonkey.net www.sacredelectron.org idiot1@netzero.net www.tinylist.org grumpy@tinylist.org ---------------------------------------------------- Sign Up for NetZero Platinum Today Only $9.95 per month! http://my.netzero.net/s/signup?r=platinum&refcd=PT97 From idiot1@netzero.net Sun Jan 13 05:57:34 2002 From: idiot1@netzero.net (kirk Bailey) Date: Sun, 13 Jan 2002 00:57:34 -0500 Subject: [Tutor] ethics in programming Message-ID: <3C4121CE.9709323C@netzero.net> I read the mailman stuff, and did not know enough to modify it. Also I seem to have gotten the impression that a few parts were modularm, and in C. I do not grok C. As I had to learn something anyhow, why not start off simple and build and learn? And sometimes, a hard task raises a man to the challenge, where a easier one is also easier to lay down. I made a comittment to undertake a hard task. But concentrate all my effort on ONE language, not two. Besides, I feel uncofortable altering someone elses work, all the more so having walked away from a situation with a man who did not like me wanting to do exactly that with a different gnu gpl product. He disliked my desired directions, desired function, and in the end, me. BTW, the feeling is mutual. I shall not name him. He is not on this list. Andrei Kulakov wrote: > > On Sat, Jan 12, 2002 at 07:36:38PM -0500, Grimmtooth wrote: > > What, and miss the learning experience? Tut! :-) > > That's what the thread is about - someone told kirk that TL is fine as a > learning experiment, but if he wants to have a full fledged list manager > with the features he wants, he's better off modifying Mailman. > > I think that's true.. If all you want is a few new features, change > existing program(s). Only make a new one if you think existing systems > have an inherently flawed architecture or if you want to use a > completely different approach. > > > > > > more people would be able to share the fruits of your hard work, if you > > > modified an established program, like Mailman. > > I cannot judge this issue. -- -Respectfully, -Kirk D Bailey Consulting Loose Cannon end www.howlermonkey.net highprimate@howlermonkey.net www.sacredelectron.org idiot1@netzero.net www.tinylist.org grumpy@tinylist.org ---------------------------------------------------- Sign Up for NetZero Platinum Today Only $9.95 per month! http://my.netzero.net/s/signup?r=platinum&refcd=PT97 -- -Respectfully, -Kirk D Bailey Consulting Loose Cannon end www.howlermonkey.net highprimate@howlermonkey.net www.sacredelectron.org idiot1@netzero.net www.tinylist.org grumpy@tinylist.org ---------------------------------------------------- Sign Up for NetZero Platinum Today Only $9.95 per month! http://my.netzero.net/s/signup?r=platinum&refcd=PT97 From idiot1@netzero.net Sun Jan 13 06:01:35 2002 From: idiot1@netzero.net (kirk Bailey) Date: Sun, 13 Jan 2002 01:01:35 -0500 Subject: [Tutor] tinylist.org Message-ID: <3C4122BF.4E52627B@netzero.net> tinylist.org is up. http://www.tinylist.org/ -- -Respectfully, -Kirk D Bailey Consulting Loose Cannon end www.howlermonkey.net highprimate@howlermonkey.net www.sacredelectron.org idiot1@netzero.net www.tinylist.org grumpy@tinylist.org ---------------------------------------------------- Sign Up for NetZero Platinum Today Only $9.95 per month! http://my.netzero.net/s/signup?r=platinum&refcd=PT97 From srichter@cbu.edu Sun Jan 13 07:40:40 2002 From: srichter@cbu.edu (Stephan Richter) Date: Sun, 13 Jan 2002 01:40:40 -0600 Subject: [Tutor] ethics in programming In-Reply-To: <3C40C26A.F674E4CD@netzero.net> References: <3C3F1307.68242321@netzero.net> <20020112203335.GA3292@localhost> <3C40B23D.467D03C@netzero.net> <20020112223342.GA3956@localhost> <5.1.0.14.2.20020112165334.03babdf8@mercury-1.cbu.edu> Message-ID: <5.1.0.14.2.20020113013121.029e4410@mercury-1.cbu.edu> At 06:10 PM 1/12/2002 -0500, kirk Bailey wrote: >This is a fair question, and deserves an answer. > >Mailman cannot append advertisements, nor manage the rotation of them. > >If you want your list service to earn enough money to pay for itself, >it has toeither SELL list service, or earn revenues from >advertisements appended to the traffic passing through it. Well, that might be a nice feature to have. :-) >And, As I needed a scripting language for 'glue' and cgi scripting >anyway, I took it on myself to learn the best language for the task. >PYTHON. Although there are still plenty of things to learn, I am well >on my way. Well, now you are touching on something that I have been working on for Mailman. While Mailman comes with a native Web interface, I developed a product for Zope (www.zope.org) that allows you to manage and handle mailing list straight from Zope. You can develop an entire Web application and integrate Mailman in it. >And, building from the ground up, I had complete control of how it >worked, and could insure it did what I wanted, the way I wanted, and >when done I would have DEEP understanding of it, how it worked, why it >worked, and why it was that way. This also translates later into a >marketable skill- building a list server for others. Well, I used to think like that too. But at one point you realize that reinventing the wheel is not as cool as inventing it. So actually providing a new component reach many more people, due to the established community. And one more thing, often specialists of various areas working on these open projects, having knowledge that you might not have the time for to acquire. >And, having had a distasteful experience with a product controled by >someone else, by creating a tool myself I could insure I could always >change it, and not have a problem with a primadonna messing up my >goals withhis/her ego. That STILL leaves a bad taste in my mouth, 3 >months later. Well, I think that is the cool thing about Open Source. One can do whatever he likes. A lot of my products for Zope will never make it in the core, but still many people install them, because they are helpful. >But thanks for asking, I welcome the opportunity to clarify things. >Always feel free to ask me anything you like. Well, then I would like to ask you to look into an integration with Mailman. OR, since I will meet with Barry next week about Mailman, send me a detailed list of features you need and I will address them for you. Regards, Stephan -- Stephan Richter CBU - Physics and Chemistry Student Web2k - Web Design/Development & Technical Project Management From srichter@cbu.edu Sun Jan 13 07:43:39 2002 From: srichter@cbu.edu (Stephan Richter) Date: Sun, 13 Jan 2002 01:43:39 -0600 Subject: [Tutor] ethics in programming In-Reply-To: <3C4121CE.9709323C@netzero.net> Message-ID: <5.1.0.14.2.20020113014053.0281a610@mercury-1.cbu.edu> At 12:57 AM 1/13/2002 -0500, kirk Bailey wrote: >I read the mailman stuff, and did not know enough to modify it. Also I >seem to have gotten the impression that a few parts were modularm, and >in C. I do not grok C. As I had to learn something anyhow, why not >start off simple and build and learn? And sometimes, a hard task >raises a man to the challenge, where a easier one is also easier to >lay down. I made a comittment to undertake a hard task. But >concentrate all my effort on ONE language, not two. No, no. Mailman has minimal C code; it is only there, so that the wrapper can answer the MTA fast enough, since you would get an error from the MTA otherwise. Since I am coding with Mailman I never hit a C component and probably never will! >Besides, I feel uncofortable altering someone elses work, all the more >so having walked away from a situation with a man who did not like me >wanting to do exactly that with a different gnu gpl product. He >disliked my desired directions, desired function, and in the end, me. Well, I do not think that will be the case here. :-) Regards, Stephan -- Stephan Richter CBU - Physics and Chemistry Student Web2k - Web Design/Development & Technical Project Management From ak@silmarill.org Sun Jan 13 03:42:41 2002 From: ak@silmarill.org (Andrei Kulakov) Date: Sat, 12 Jan 2002 22:42:41 -0500 Subject: [Tutor] ethics in programming In-Reply-To: ; from grimmtoothtoo@yahoo.com on Sat, Jan 12, 2002 at 10:30:40PM -0500 References: <20020112203849.A12856@silmarill.org> Message-ID: <20020112224241.A13489@silmarill.org> On Sat, Jan 12, 2002 at 10:30:40PM -0500, Grimmtooth wrote: > > > I think that's true.. If all you want is a few new features, change > > existing program(s). Only make a new one if you think existing systems > > have an inherently flawed architecture or if you want to use a > > completely different approach.. > > Nothing wrong with a fresh approach and/or a multitude of choices. That is > one of the cornerstones of open source development, or so I hear. > > And of course, there's nothing more satisfying than seeing it through from > start to finish. Yeah, I agree. We shouldn't forget, though, that effort spent remaking something that's already there could be spent more wisely on something nobody made yet. But, of course, it's up to the dude. > > > _________________________________________________________ > Do You Yahoo!? > Get your free @yahoo.com address at http://mail.yahoo.com > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: cy.silmarill.org From toodles@yifan.net Sun Jan 13 11:54:22 2002 From: toodles@yifan.net (Andy W) Date: Sun, 13 Jan 2002 19:54:22 +0800 Subject: [Tutor] String formatting Message-ID: <000e01c19c29$0e6b26a0$da00a8c0@Sun> Hi folks, Is there a way in which I can format a string, but escape a particular "%"? For example, take the following case: # val_dict={'score':100} print "You scored %(score)%."%val_dict # What I want as the output is "You scored 100%.", but this will not work due to "incomplete formatting". Of course I can always use a character that won't be present (NUL), and replace it with "%", but I'd like to know if there's a cleaner, more Pythonic solution. Andy From srichter@cbu.edu Sun Jan 13 12:02:11 2002 From: srichter@cbu.edu (Stephan Richter) Date: Sun, 13 Jan 2002 06:02:11 -0600 Subject: [Tutor] String formatting In-Reply-To: <000e01c19c29$0e6b26a0$da00a8c0@Sun> Message-ID: <5.1.0.14.2.20020113060101.035910a8@mercury-1.cbu.edu> At 07:54 PM 1/13/2002 +0800, Andy W wrote: >Hi folks, > >Is there a way in which I can format a string, but escape a particular "%"? Yep. You simply double your %. Try: >val_dict={'score':100} >print "You scored %(score)i%%."%val_dict Regards, Stephan -- Stephan Richter CBU - Physics and Chemistry Student Web2k - Web Design/Development & Technical Project Management From barry@zope.com Sun Jan 13 16:27:18 2002 From: barry@zope.com (Barry A. Warsaw) Date: Sun, 13 Jan 2002 11:27:18 -0500 Subject: [Tutor] ethics in programming References: <3C3F1307.68242321@netzero.net> <20020112203335.GA3292@localhost> <3C40B23D.467D03C@netzero.net> <20020112223342.GA3956@localhost> <5.1.0.14.2.20020112165334.03babdf8@mercury-1.cbu.edu> <5.1.0.14.2.20020113013121.029e4410@mercury-1.cbu.edu> Message-ID: <15425.46438.761886.896226@anthem.wooz.org> [Coming in on the middle of this thread, and I'm not sure of the relevancy to the tutor list. -BAW] >>>>> "SR" == Stephan Richter writes: SR> At 06:10 PM 1/12/2002 -0500, kirk Bailey wrote: >> This is a fair question, and deserves an answer. Mailman >> cannot append advertisements, nor manage the rotation of them. >> If you want your list service to earn enough money to pay for >> itself, it has toeither SELL list service, or earn revenues >> from advertisements appended to the traffic passing through it. SR> Well, that might be a nice feature to have. :-) Sure, and it would't be hard to add. It's just not something I'm interested in, nor has even had a single developer requested that Mailman be able do this. Mailman's community isn't primarily listserve providers, and most who do provide list services do so as part of a wider menu of offerings. >> And, building from the ground up, I had complete control of how >> it worked, and could insure it did what I wanted, the way I >> wanted, and when done I would have DEEP understanding of it, >> how it worked, why it worked, and why it was that way. This >> also translates later into a marketable skill- building a list >> server for others. SR> Well, I used to think like that too. But at one point you SR> realize that reinventing the wheel is not as cool as inventing SR> it. The open source and free software communities have a rich and long tradition of reinvention. Well, all of software development does, but we probably don't hear about 95% of commercial software re-invention. :) Mailman exists because the alternatives were non-existant, non-functional, unmaintained, or inadequate at the time. We've done a good job, but of course we learned /a lot/ along the way. >> And, having had a distasteful experience with a product >> controled by someone else, by creating a tool myself I could >> insure I could always change it, and not have a problem with a >> primadonna messing up my goals withhis/her ego. That STILL >> leaves a bad taste in my mouth, 3 months later. SR> Well, I think that is the cool thing about Open Source. One SR> can do whatever he likes. A lot of my products for Zope will SR> never make it in the core, but still many people install them, SR> because they are helpful. One of Mailman's design principles is to be extensible in controlled ways. I'd like to think it inherits this principle from Python. Mailman -- or any software -- will never do everything that every user wants it to do. But I think a lot can be accomplished by providing a solid core functionality, and lots of principled hooks for users to extend or exchange parts. Think Zope components. That's just good architecture IMHO. Much of what Stephan and I will be talking about next week will be moving more of the legacy bits of Mailman to a more well designed, abstracted and extensible architcture. -Barry From mikalzet@libero.it Sun Jan 13 13:20:19 2002 From: mikalzet@libero.it (mikalzet@libero.it) Date: Sun, 13 Jan 2002 14:20:19 +0100 (CET) Subject: [Tutor] very elementary help ... for total analphabet In-Reply-To: <20020112174906Z234715-19439+2@bureau8.utcc.utoronto.ca> Message-ID: The following code is taken from "Learning to think like a Computer Scientist with Python": class Node: def __init__(self, cargo=None, next=None): self.cargo=cargo self.next = next def __str__(self): return str(self.cargo) def printBackward(list): if list == None: return head = list tail = list.next printBackward(tail) print head, node1 = Node(1) node2 = Node(2) node3 = Node(3) node1.next = node2 node2.next = node3 printBackward(node1) The output is: 3 2 1 Now for the question: I have tried to look at the stack diagram and I've tried adding print head and print tail commands in various points of printBackward to see how it works. It seems that: head = 1 tail = 2 then head = 2 tail = 3 then head = 3 tail = None. now the 'return' makes the loop exit and "print head" is executed. (And this already puzzles me, I would have thought return to cause the whole printBackward() to terminate - therefore no output at all). This granted, I would expect as output 3 What happens here ? "print head" seems to be executed several times ( why ?) printing the succession of values attributed to head in a first-in-last-out manner, as if it were a stack .... ? If I don't understand this behaviour I will never be able to use it or change it. I obviously have a deep misunderstanding of the workings of recursive functions. Anybody kind enough to explain this example better ? -- Michele Alzetta From tim-ward@home.com Sun Jan 13 19:53:36 2002 From: tim-ward@home.com (Tim Ward) Date: Sun, 13 Jan 2002 11:53:36 -0800 Subject: [Tutor] executing notepad txt files Message-ID: <000801c19c6b$fd7017a0$b3c70641@lusvil1.ky.home.com> This is a multi-part message in MIME format. ------=_NextPart_000_0005_01C19C28.EEE08140 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Hello, I've wrote a program using notepad. How do I get Python to execute it? Thanx, Tim ------=_NextPart_000_0005_01C19C28.EEE08140 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
Hello,
 
I've wrote a program using = notepad.
How do I get Python to execute = it?
 
Thanx,
Tim
------=_NextPart_000_0005_01C19C28.EEE08140-- From dyoo@hkn.eecs.berkeley.edu Sun Jan 13 21:31:27 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 13 Jan 2002 13:31:27 -0800 (PST) Subject: [Tutor] very elementary help ... for total analphabet [recursion!] In-Reply-To: Message-ID: On Sun, 13 Jan 2002 mikalzet@libero.it wrote: > The following code is taken from "Learning to think like a Computer > Scientist with Python": Hi mikalzet, nice to meet you. Ok, let's take a look: > class Node: > def __init__(self, cargo=None, next=None): > self.cargo=cargo > self.next = next > def __str__(self): > return str(self.cargo) Ah, I see, so this is a Node for a linked list. > def printBackward(list): > if list == None: return > head = list > tail = list.next > printBackward(tail) > print head, Ah, a recursive definition! This stuff is actually not "elementary". That is, it's not particularly "hard", but it is demented and strange enough that you may need to see some concrete examples of it in action before it starts making some sense. > Now for the question: I have tried to look at the stack diagram and > I've tried adding print head and print tail commands in various points > of printBackward to see how it works. It seems that: > > head = 1 tail = 2 > then head = 2 tail = 3 > then head = 3 tail = None. > now the 'return' makes the loop exit and "print head" is executed. > > (And this already puzzles me, I would have thought return to cause the > whole printBackward() to terminate - therefore no output at all). > > This granted, I would expect as output > 3 > > What happens here ? > printBackward() is a 'recursive' definition, so it'll feel a little backwards at first. Let's detail the trace a little more, and it might make more sense: ### In evaluating printBackward([node1, node2, node3]): head = node1, tail = node2 We need to evaluate printBackward([node2, node3]). In evaluating printBackward([node2, node3]): head = node2, tail = node3 We need to evaluate printBackward([node3]). In evaluating printBackward([node3]): head = node3, tail = None We need to evaluate printBackward(None) In evaluating printBackward(None): We hit the base case, so we return without doing anything. Print head, which is node3. Return. Print head, which is node2. Return. Print head, which is node1. Return. ### I'm using indentation here to emphasize the fact that printBackward() is calling other helper functions, and can continue on only after the helper is done. The strange part is that printBackward() is using itself to help itself. *grin* Let's take a look at the definition again: ### > def printBackward(list): > if list == None: return > head = list > tail = list.next > printBackward(tail) > print head, ### Tracing recursive functions can be a little tedious. It might be easier to think of it this way: Recursion depends on the fact that the function works on small things, and can use itself on smaller things to do the right thing. *grin* Pretend for the moment that printBackward() works --- that is, let's imagine that if we give it a list like [2, 3], it will go off and print: ### 3 2 ### If this works, then to printBackward() of [1, 2, 3], what we can do is say "Ok, we can pretend that printBackward() will work on a smaller chunk of this list. Let's tell printBackward() to do its work on the tail of our list, and then print out the head. If we do that, then we end up printing the list in backwards order." Here's another example of a recursive function: let's say that we had a linked list of numbers, and we wanted to add them all together to get their sum. How can we do this? ### def getSum(list): ## Base case --- if we're given no numbers, then their sum ## must be zero. if list == None: return 0 first, rest = list, list.next ## Otherwise, we can getSum() of the rest of the numbers, and add ## the first number to that. return first + getSum(rest) ### > "print head" seems to be executed several times ( why ?) printing the > succession of values attributed to head in a first-in-last-out manner, as > if it were a stack .... ? There is a stack involved, and it's one that Python maintains to keep track of function calls. When functions call other functions, the called function needs to "return" back to its caller. In a concrete example: ### def square(x): return x * x def hypotenuse(a, b): return math.sqrt(square(x) + square(y)) ### The hypotenuse function calls on square(x) to do it's work. square() itself does its thing, and then passes that result back to its caller. And that's where a stack is involved. We can break down square() like this: ### def square(x): return multiply(x, x) def multiply(a, b): if b == 0: return 0 return a + multiply(a, b-1) ### Hey look! The multiply() function here is itself "recursive", and it's probably something you've seen in elementary school: a * b = a * 1 + a * (b-1) The big thing about recursion is that you probably already have some experience with it in the real world, but you just need to recognize it as "recursion". Think about russian dolls, and how they are layered within each other. Or the poster of the movie "Memento", with photo images embedded within photo images. Please feel free to ask more questions on this; recursion is a lot of fun to talk about. Anyway, hope this helps! From rufmetal@rogers.com Sun Jan 13 22:29:15 2002 From: rufmetal@rogers.com (Chris Keelan) Date: Sun, 13 Jan 2002 17:29:15 -0500 Subject: [Tutor] clearscreen command In-Reply-To: <20020113012705.DAOV183570.fep03-mail.bloor.is.net.cable.rogers.com@there> References: <20020113012705.DAOV183570.fep03-mail.bloor.is.net.cable.rogers.com@there> Message-ID: <20020113223159.RLQM193413.fep04-mail.bloor.is.net.cable.rogers.com@there> On Saturday 12 January 2002 08:24 pm, Chris Keelan wrote: > On Saturday 12 January 2002 08:00 pm, Frank Holmes wrote: > > does python have the equivalent of a clearscreen command? > > In a *nix environment: > > import os > > os.cmd('clear') Of course, you know I meant: os.system('clear') or os.system('cls') didncha? - C From dyoo@hkn.eecs.berkeley.edu Sun Jan 13 22:32:28 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 13 Jan 2002 14:32:28 -0800 (PST) Subject: [Tutor] ethics in programming [modifying preexisting code] In-Reply-To: Message-ID: On Sat, 12 Jan 2002, Grimmtooth wrote: > What, and miss the learning experience? Tut! :-) > > > more people would be able to share the fruits of your hard work, if you > > modified an established program, like Mailman. Richard Feymann does talk about the very good value of reinventing the wheel for the sake of learning; I remember reading something about this in his book "What Do You Care What Other People Think?", but don't have the book handy to pull his quote out. On the other hand, Stephen Jay Gould argues that, taken to a hard extreme, this reinvention can be very counterproductive: http://www.eiu.edu/~scienced/what/what_3.html I say, let's do both. *grin* It might be good to talk about how to modify a preexisting software package to add some additional feature (like adding a chunk of text to the bottom of every message). Something like this already exists in Mailman; all messages are "decorated" so that they have an appropriate "header" and "footer". That is, there's already a bit of code that's responsible for adding the """ --------------------------------------------- Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor """ chunk to every message on Tutor. I did a quick check in the Mailman source code, and it looks like the 'Mailman/Handlers/Decorate.py' file is responsible for this. Here's the jist of the code: ### def process(mlist, msg, msgdata): ## [A lot of code cut...] msg.body = header + msg.body + footer ### This basically does what we'd expect it to, plus or minus a few issues that I've edited out of the code. *grin* But it doesn't look like it would take too much work to hardcode something here that does what Kirk wants. (It's another question of writing the code so that it "fits" well with the rest of Mailman's architecture. *grin*) Hope this helps! From dyoo@hkn.eecs.berkeley.edu Sun Jan 13 22:34:50 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 13 Jan 2002 14:34:50 -0800 (PST) Subject: [Tutor] executing notepad txt files In-Reply-To: <000801c19c6b$fd7017a0$b3c70641@lusvil1.ky.home.com> Message-ID: On Sun, 13 Jan 2002, Tim Ward wrote: > I've wrote a program using notepad. How do I get Python to execute it? Hi Tim, One of the easier ways to do this is to run your program though IDLE --- IDLE is a text editor that's like notepad, but is Python specific. There's a menu option in IDLE that's called "Run Script", and that should work for you. I have a small visual tutorial on IDLE here: http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro that tries to show how to use it. Try it out, and see if it works ok for you. If you have questions, please feel free to ask on Tutor! Good luck to you. From e.kotyk@shaw.ca Sun Jan 13 10:46:07 2002 From: e.kotyk@shaw.ca (Eve Kotyk) Date: Sun, 13 Jan 2002 10:46:07 +0000 Subject: [Tutor] executing notepad txt files References: Message-ID: <3C41656F.1466262B@shaw.ca> Danny Yoo wrote: > > On Sun, 13 Jan 2002, Tim Ward wrote: > > > I've wrote a program using notepad. How do I get Python to execute it? I generally write my Python code in Idle or VIM on a Linux machine and then envoke it by typing: python file_name.py. This works very well but I recently put the Python interpreter on my tiny Compaq Lite LTE notebook. I can enter code into the interpreter but if I write a file (like Tim) I can't execute it. Idle didn't come with the Win 3.1 version of Python. Any other suggestions. E From idiot1@netzero.net Sun Jan 13 23:04:07 2002 From: idiot1@netzero.net (kirk Bailey) Date: Sun, 13 Jan 2002 18:04:07 -0500 Subject: [Tutor] Revision codes Message-ID: <3C421267.A21DADAB@netzero.net> Defining revision codes, how when and whyfore. version #.#.# major/significant/minor, hugher numbers being newer than smaller ones. Start with 1.0.0; So if we do a minor tidying up, maybe a slight cosmetic update, we call this 1.0.1; Find a bug and fix it, this is 1.1.0; later make another cosmetic change, it is 1.1.1; And when we issue a serious upgrade, rewriting significant portions, adding new misfeatures, we then referr to this disaster as 2.0.0, yes? My, that was a long sentance; Uncle Phil Chanchuli would be SO distressed. (my english teacher, don't blaime him.) -- -Respectfully, -Kirk D Bailey Consulting Loose Cannon end www.howlermonkey.net highprimate@howlermonkey.net www.sacredelectron.org idiot1@netzero.net www.tinylist.org grumpy@tinylist.org ---------------------------------------------------- Sign Up for NetZero Platinum Today Only $9.95 per month! http://my.netzero.net/s/signup?r=platinum&refcd=PT97 From alan.gauld@bt.com Sun Jan 13 23:14:06 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Sun, 13 Jan 2002 23:14:06 -0000 Subject: [Tutor] tinylist.1.0.0.tar.gz Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C270@mbtlipnt02.btlabs.bt.co.uk> Kirk, > Registered the name tinylist.org, have the basic domain structure set > up on the server. Waiting for the name to infect nameserver space, > then will be able to offer support and sources on site. Well done! To come from a beginner in Python to writing a mail list server - regardless of how small or otherwise - in a few weeks is a fantasic achievement. I know you've had a lot of help from this list but you have done most of it yourself and I for one am impressed. Congratulations. Now all you need to do is document the design so you know how to fix it in 6 months time :-) Alan g From dsh8290@rit.edu Sun Jan 13 23:49:04 2002 From: dsh8290@rit.edu (dman) Date: Sun, 13 Jan 2002 18:49:04 -0500 Subject: [Tutor] executing notepad txt files In-Reply-To: <3C41656F.1466262B@shaw.ca> References: <3C41656F.1466262B@shaw.ca> Message-ID: <20020113234904.GA5905@localhost> On Sun, Jan 13, 2002 at 10:46:07AM +0000, Eve Kotyk wrote: | Danny Yoo wrote: | > | > On Sun, 13 Jan 2002, Tim Ward wrote: | > | > > I've wrote a program using notepad. How do I get Python to execute it? | | I generally write my Python code in Idle or VIM on a Linux machine and | then envoke it by typing: python file_name.py. This works very well but This is what I do. I often start the file with #!. | I recently put the Python interpreter on my tiny Compaq Lite LTE | notebook. I can enter code into the interpreter but if I write a file | (like Tim) I can't execute it. Error message? I can't guess that well. | Idle didn't come with the Win 3.1 version of Python. Any other | suggestions. Is python.exe in %PATH%? -D -- In the way of righteousness there is life; along that path is immortality. Proverbs 12:28 From idiot1@netzero.net Sun Jan 13 23:45:33 2002 From: idiot1@netzero.net (kirk Bailey) Date: Sun, 13 Jan 2002 18:45:33 -0500 Subject: [Tutor] tinylist.1.0.0.tar.gz References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C270@mbtlipnt02.btlabs.bt.co.uk> Message-ID: <3C421C1D.420619D6@netzero.net> BTW, my box does a few domains besides howlermonkey; I am preparing to move this list over to www.tinylist.org. Same tin, different label. Critter wears many hats. alan.gauld@bt.com wrote: > > Kirk, > > > Registered the name tinylist.org, have the basic domain structure set > > up on the server. Waiting for the name to infect nameserver space, > > then will be able to offer support and sources on site. > > Well done! > To come from a beginner in Python to writing a mail list server > - regardless of how small or otherwise - in a few weeks is > a fantasic achievement. > > I know you've had a lot of help from this list but you have > done most of it yourself and I for one am impressed. > > Congratulations. Now all you need to do is document the > design so you know how to fix it in 6 months time :-) > > Alan g > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- -Respectfully, -Kirk D Bailey Consulting Loose Cannon end www.howlermonkey.net highprimate@howlermonkey.net www.sacredelectron.org idiot1@netzero.net www.tinylist.org grumpy@tinylist.org ---------------------------------------------------- Sign Up for NetZero Platinum Today Only $9.95 per month! http://my.netzero.net/s/signup?r=platinum&refcd=PT97 From idiot1@netzero.net Mon Jan 14 00:14:15 2002 From: idiot1@netzero.net (kirk Bailey) Date: Sun, 13 Jan 2002 19:14:15 -0500 Subject: [Tutor] Permissions oddness Message-ID: <3C4222D7.A67B20BF@netzero.net> ok, here we go. Found out why the menu did not want to work in the tinylist.org domain. Permissions. dir 'kists' must be 7xx or the function listing all the .info files craps out. Of course, it has to read and write to those files in there, so the dir also must be 666 or better; therefore, 766 is the LOWEST permission that will work for the lists dir! Apparently when it tries to do a system dir related function, it has to run with the permissions of the dir being examined, not the dir where the system command lives! odd... -- -Respectfully, -Kirk D Bailey Consulting Loose Cannon end www.howlermonkey.net highprimate@howlermonkey.net www.sacredelectron.org idiot1@netzero.net www.tinylist.org grumpy@tinylist.org ---------------------------------------------------- Sign Up for NetZero Platinum Today Only $9.95 per month! http://my.netzero.net/s/signup?r=platinum&refcd=PT97 From grimmtoothtoo@yahoo.com Mon Jan 14 00:20:59 2002 From: grimmtoothtoo@yahoo.com (Grimmtooth) Date: Sun, 13 Jan 2002 19:20:59 -0500 Subject: [Tutor] Revision codes In-Reply-To: <3C421267.A21DADAB@netzero.net> Message-ID: > Defining revision codes, how when and whyfore. > > version #.#.# > major/significant/minor, hugher numbers being newer than smaller ones. I have no idea what the /de facto/ standard in opensourceworld is, but within my workplace, we use the following: > Start with 1.0.0; We call the three major.minor.revision Revisions are bumped for bugfixes of a release. Therefore, we release 1.00.00, we fix a bug we bump to 1.00.01. Minors are bumped when changes to the software require revision of the documentation. Add a new menu to the software, bump the minor. Thus going from 1.00.01 and adding a new menu, we go to 1.01.00. Majors are bumped arbitrarilly, but generally reflect a major design change. For example, if we add a new peripheral type to the software, we go from 1.01.00 to 2.00.00. Or if we add a new platform, we also bump the major. I have also seen the use of two-digit to be literal: i.e. 2.1 is not the same as 2.10. So be sure to fix yourself on one right away. _________________________________________________________ Do You Yahoo!? Get your free @yahoo.com address at http://mail.yahoo.com From dsh8290@rit.edu Mon Jan 14 01:08:51 2002 From: dsh8290@rit.edu (dman) Date: Sun, 13 Jan 2002 20:08:51 -0500 Subject: [Tutor] Revision codes In-Reply-To: References: <3C421267.A21DADAB@netzero.net> Message-ID: <20020114010851.GA6227@localhost> On Sun, Jan 13, 2002 at 07:20:59PM -0500, Grimmtooth wrote: | > Defining revision codes, how when and whyfore. | > | > version #.#.# | > major/significant/minor, hugher numbers being newer than smaller ones. | | | I have no idea what the /de facto/ standard in opensourceworld is, but | within my workplace, we use the following: | | > Start with 1.0.0; | | We call the three major.minor.revision major.minor.micro (at least, that's what 'configure' scripts call the variables. | Revisions are bumped for bugfixes of a release. Therefore, we release | 1.00.00, we fix a bug we bump to 1.00.01. | | Minors are bumped when changes to the software require revision of the | documentation. Add a new menu to the software, bump the minor. Thus going | from 1.00.01 and adding a new menu, we go to 1.01.00. | | Majors are bumped arbitrarilly, but generally reflect a major design change. | For example, if we add a new peripheral type to the software, we go from | 1.01.00 to 2.00.00. Or if we add a new platform, we also bump the major. Right. | I have also seen the use of two-digit to be literal: i.e. 2.1 is not the | same as 2.10. So be sure to fix yourself on one right away. Of course : 1 != 10 :-). You're allowed more than ten releases. -D -- Through love and faithfulness sin is atoned for; through the fear of the Lord a man avoids evil. Proverbs 16:6 From dsh8290@rit.edu Mon Jan 14 01:14:18 2002 From: dsh8290@rit.edu (dman) Date: Sun, 13 Jan 2002 20:14:18 -0500 Subject: [Tutor] Permissions oddness In-Reply-To: <3C4222D7.A67B20BF@netzero.net> References: <3C4222D7.A67B20BF@netzero.net> Message-ID: <20020114011418.GB6227@localhost> On Sun, Jan 13, 2002 at 07:14:15PM -0500, kirk Bailey wrote: | ok, here we go. Found out why the menu did not want to work in the | tinylist.org domain. | | Permissions. dir 'kists' must be 7xx or the function listing all the | .info files craps out. For directories : Read means you can list the contents. Write means you can modify the contents. Execute means you can 'cd' to the directory. Each operation is independent of the others, if you know what you want to do. Of course, if you can only do one of the latter two, you're working blind. | Of course, it has to read and write to those files in there, so the | dir also must be 666 or better; therefore, 766 is the LOWEST | permission that will work for the lists dir! Is it ever run as a user that doesn't own the dir? If not then 700 is good. | Apparently when it tries to do a system dir related function, it has | to run with the permissions of the dir being examined, not the dir | where the system command lives! odd... Take your editor, for example. $ ls -ld ~/. ~/.bashrc drwx--x--x 77 dman dman 4096 Jan 13 20:13 /home/dman/. -rw-r--r-- 1 dman dman 1990 Dec 30 22:09 /home/dman/.bashrc I own ~/.bashrc. Only the owner (me) has write permission. If you want to write to it, you must be me (or root). $ ls -ld /usr/bin/ drwxr-xr-x 2 root root 36864 Jan 12 23:26 /usr/bin/ Root owns the directory where vim is, but what does that matter? It means only root can write to it (modify the binaries or something), but it has no bearing on whether or not you can edit my stuff. -D -- Even youths grow tired and weary, and young men stumble and fall; but those who hope in the Lord will renew their strength. They will soar on wings like eagles; they will run and not grow weary, they will walk and not be faint. Isaiah 40:31 From arcege@speakeasy.net Mon Jan 14 02:13:15 2002 From: arcege@speakeasy.net (Michael P. Reilly) Date: Sun, 13 Jan 2002 21:13:15 -0500 Subject: [Tutor] Permissions oddness In-Reply-To: <20020114011418.GB6227@localhost>; from dsh8290@rit.edu on Sun, Jan 13, 2002 at 08:14:18PM -0500 References: <3C4222D7.A67B20BF@netzero.net> <20020114011418.GB6227@localhost> Message-ID: <20020113211315.E5064@speakeasy.net> On Sun, Jan 13, 2002 at 08:14:18PM -0500, dman wrote: > For directories : > Read means you can list the contents. > Write means you can modify the contents. > Execute means you can 'cd' to the directory. FYI, the execute bit on a directory means more than just 'can you cd'. It allows a program to traverse into the directory to open files. Try this: import os os.mkdir('trythis', 0777) open('trythis/test.txt', 'w').write('hi there\n') os.chmod('trythis', 0666) f = open('trythis/test.txt', 'r') At this point, you'll get an exception of "Permission denied". We're not changing the current directory, just trying to access a file in it. -Arcege From idiot1@netzero.net Mon Jan 14 03:39:03 2002 From: idiot1@netzero.net (kirk Bailey) Date: Sun, 13 Jan 2002 22:39:03 -0500 Subject: [Tutor] manual, an overview of how it all works Message-ID: <3C4252D7.74A38AF5@netzero.net> Is ready. Viddy at convience http://www.tinylist.org/manual.shtml Note the footer. All that is ssi, most if it actually in the file invoked by the ssi include. SSI can be very handy to have around if you don't want to go whole hog and bang the netire page from 1+ scripts. -- -Respectfully, -Kirk D Bailey Consulting Loose Cannon end www.howlermonkey.net highprimate@howlermonkey.net www.sacredelectron.org idiot1@netzero.net www.tinylist.org grumpy@tinylist.org ---------------------------------------------------- Sign Up for NetZero Platinum Today Only $9.95 per month! http://my.netzero.net/s/signup?r=platinum&refcd=PT97 From dsh8290@rit.edu Mon Jan 14 04:39:23 2002 From: dsh8290@rit.edu (dman) Date: Sun, 13 Jan 2002 23:39:23 -0500 Subject: [Tutor] Permissions oddness In-Reply-To: <20020113211315.E5064@speakeasy.net> References: <3C4222D7.A67B20BF@netzero.net> <20020114011418.GB6227@localhost> <20020113211315.E5064@speakeasy.net> Message-ID: <20020114043923.GA7970@localhost> On Sun, Jan 13, 2002 at 09:13:15PM -0500, Michael P. Reilly wrote: | On Sun, Jan 13, 2002 at 08:14:18PM -0500, dman wrote: | > For directories : | > Read means you can list the contents. | > Write means you can modify the contents. | > Execute means you can 'cd' to the directory. | | FYI, the execute bit on a directory means more than just 'can you cd'. | It allows a program to traverse into the directory to open files. | Try this: | | import os | os.mkdir('trythis', 0777) | open('trythis/test.txt', 'w').write('hi there\n') | | os.chmod('trythis', 0666) | f = open('trythis/test.txt', 'r') | | At this point, you'll get an exception of "Permission denied". We're not | changing the current directory, just trying to access a file in it. Ok, right, you're trying to descend into the directory. I guess that's a better way to phrase it. -D -- "...the word HACK is used as a verb to indicate a massive amount of nerd-like effort." -Harley Hahn, A Student's Guide to Unix From printers@sendme.cz Mon Jan 14 06:00:03 2002 From: printers@sendme.cz (A) Date: Mon, 14 Jan 2002 07:00:03 +0100 Subject: [Tutor] RE: HTTPLib and POST problem with '?' Message-ID: <3C4281F3.16845.1A0EEF@localhost> >In the light of the meta-principle "be conservative in what you generate, and >liberal in what you accept", I think a server should probably accept a >(probably-incorrect) mix of both, and try to do something sensible; but a >client (e.g., httplib) should never generate the mix. I would like to thank you all who tried to answer my question but yet I did not receive any good solution. If you use a client like MS Explorer and use a sniffer you can see that this client also sends posting script in a form "/cgi-bin/script.cgi?name=Paul. The same is true about PERL( LWP module). Does it mean PERL is better?? And as an example you can check http://www.globaltradeweb.com/default.asp?w=fbjm You will not be probably post successfully if you send form like /cgi-bin/script.cgi that is without '?' ANd this is not the only example So, Can anyone help me? Ladislav From idiot1@netzero.net Mon Jan 14 06:12:44 2002 From: idiot1@netzero.net (kirk Bailey) Date: Mon, 14 Jan 2002 01:12:44 -0500 Subject: [Tutor] TLreading Message-ID: <3C4276DC.8961147@netzero.net> I have several of the doc files online now. http://www.tinylist.org One of them gives a pretty supersimplified explaination of the cgi process, how it works, etc. -- -Respectfully, -Kirk D Bailey Consulting Loose Cannon end www.howlermonkey.net highprimate@howlermonkey.net www.sacredelectron.org idiot1@netzero.net www.tinylist.org grumpy@tinylist.org ---------------------------------------------------- Sign Up for NetZero Platinum Today Only $9.95 per month! http://my.netzero.net/s/signup?r=platinum&refcd=PT97 From p.hartley@spitech.com Mon Jan 14 09:25:47 2002 From: p.hartley@spitech.com (Paul Hartley) Date: Mon, 14 Jan 2002 17:25:47 +0800 Subject: [Tutor] Idle Message-ID: <008401c19cdd$a6bb9020$ebe710ac@pc7345> This is a multi-part message in MIME format. ------=_NextPart_000_007B_01C19D20.81147380 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable I have just started to use Idle and have prited out the manual. Looking = at using the debugger it says type in the module called dvtest.py save = it as a file and then import it. Now I did that but saved the file dvtest.py somewhere more convenient = for my source code, not in the python directories, now when I type = import dvtest.py it cannot find the module. It will not let me type in = import c:\source\python etc. so how do I get python (or idle) to look = elsewhere for the module? (I have looked at the documentation for import = and it talks about sys.path, so maybe I could add directories to = sys.path in Idle? Paul ------=_NextPart_000_007B_01C19D20.81147380 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
I have just started to use Idle and = have prited out=20 the manual. Looking at using the debugger it says type in the module = called=20 dvtest.py save it as a file and then import it.
 
Now I did that but saved the file = dvtest.py=20 somewhere more convenient for my source code, not in the python = directories, now=20 when I type import dvtest.py it cannot find the module. It will not let = me type=20 in import c:\source\python etc. so how do I get python (or idle) to look = elsewhere for the module? (I have looked at the documentation for import = and it=20 talks about sys.path, so maybe I could add directories to sys.path in=20 Idle?
 
Paul
------=_NextPart_000_007B_01C19D20.81147380-- From toodles@yifan.net Mon Jan 14 09:57:12 2002 From: toodles@yifan.net (Andy W) Date: Mon, 14 Jan 2002 17:57:12 +0800 Subject: [Tutor] Idle References: <008401c19cdd$a6bb9020$ebe710ac@pc7345> Message-ID: <000601c19ce1$da45d9b0$da00a8c0@Sun> Hi Paul, >> (I have looked at the documentation for import and it talks about sys.path, so maybe I could add directories to sys.path in Idle? Yes, you could indeed. Just do this: ### import sys sys.path.append("C:\\source\\python\\") ### And you should now be able to import dvtest.py. Andy ----- Original Message ----- From: Paul Hartley To: tutor@python.org Sent: Monday, January 14, 2002 5:25 PM Subject: [Tutor] Idle I have just started to use Idle and have prited out the manual. Looking at using the debugger it says type in the module called dvtest.py save it as a file and then import it. Now I did that but saved the file dvtest.py somewhere more convenient for my source code, not in the python directories, now when I type import dvtest.py it cannot find the module. It will not let me type in import c:\source\python etc. so how do I get python (or idle) to look elsewhere for the module? Paul From dyoo@hkn.eecs.berkeley.edu Mon Jan 14 10:20:22 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 14 Jan 2002 02:20:22 -0800 (PST) Subject: [Tutor] RE: HTTPLib and POST problem ["100 continue" problem redux?] In-Reply-To: <3C4281F3.16845.1A0EEF@localhost> Message-ID: > The same is true about PERL( LWP module). Does it mean PERL is > better?? > > And as an example you can check > http://www.globaltradeweb.com/default.asp?w=fbjm > > You will not be probably post successfully if you send > form like > /cgi-bin/script.cgi As soon as I heard the word "PERL" and "better", I knew I had to step in. *grin* There's actually a very strange problem here: apparently, 'httplib' isn't handling the '100 continue' server response gracefully. Your server is telling httplib that it's ok to pass more headers, but apparently, httplib isn't prepared for this! I did some research, and found a kludgy hack to make things work. http://mail.python.org/pipermail/python-list/2000-December/023204.html The following source code should do what you want: ### import httplib, urlparse def doPost(url): """An simplified interface to do an HTTP post. Just pass an URL.""" scheme, location, path, parameters, query, fragment = \ urlparse.urlparse(url) headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"} conn = httplib.HTTPConnection(location) conn.request("POST", path, query, headers) response = safe_getresponse(conn) data = response.read() conn.close() return data def safe_getresponse(conn): ## This is an ugly kludge! We need to talk with the ## comp.lang.python folks! See: ## http://mail.python.org/pipermail/ ## python-list/2000-December/023204.html ## for a reference to this fix. while 1: response = conn.getresponse() if response.status != 100: break conn._HTTPConnection__state = httplib._CS_REQ_SENT conn._HTTPConnection__response = None return response if __name__ == '__main__': url = "http://www.globaltradeweb.com/default.asp?w=fbjm" print doPost(url) ### The code above (crossing my fingers) should let the POST finally work for you. I have to admit, thought, that I feel very naughty about this code. I feel this is a bug in httplib; does anyone know more about this? From alan.gauld@bt.com Mon Jan 14 10:55:45 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon, 14 Jan 2002 10:55:45 -0000 Subject: [Tutor] very elementary help ... for total analphabet Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C272@mbtlipnt02.btlabs.bt.co.uk> > The following code is taken from "Learning to think like a Computer > Scientist with Python": > > class Node: ... > def printBackward(list): > if list == None: return > head = list > tail = list.next > printBackward(tail) ## CALLS ITSELF - THIS IS "RECURSION" > print head, The problem you have is that the function calls itself. This is known technically as recursion. You might find an alternative explanation of the concept helps, in which case take a look at my web page on it at: http://www.freenetpages.co.uk/hp/alan.gauld/ Go down to Advanced topics|Recursion in the table of contents. > (And this already puzzles me, I would have thought return to cause the > whole printBackward() to terminate - therefore no output at all). It does cause the whole *current version* of printBackwards to terminate so the program then executes the next line which is print head. Its a bit like one of those Russian dolls - each call nested within another. Once you get to the bottom level - the empty list, you start putting them back together again. Don't worry if this takes a while to sink in, you won't be the first to struggle with the concept. But once you do get it, its extremely powerful. Alan g. Author of the 'Learning to Program' web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld@bt.com Mon Jan 14 11:02:17 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon, 14 Jan 2002 11:02:17 -0000 Subject: [Tutor] executing notepad txt files Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C273@mbtlipnt02.btlabs.bt.co.uk> > > On Sun, 13 Jan 2002, Tim Ward wrote: > > > I've wrote a program using notepad. How do I get Python > to execute it? > I recently put the Python interpreter on my tiny Compaq Lite LTE > notebook. I can enter code into the interpreter but if I write a file > (like Tim) I can't execute it. In both cases start an MS DOS box and CD to the folder containing your python script created in notepad or some other editor... Then execute the python interpreter with the file as an argument: C:\SomeFolder>python myfile.py You could just double click the file in explorer (assuming you called it foo.py or whatever - the .py associates it with python) But unless you did something to pause it, it will execute so fast you hardly see it! Thats why a DOS box is best initially. > Idle didn't come with the Win 3.1 > version of Python. Any other suggestions. You don't need IDLE you can just run python directly as described above. Alan G. From alan.gauld@bt.com Mon Jan 14 17:23:40 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon, 14 Jan 2002 17:23:40 -0000 Subject: [Tutor] Idle Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C27D@mbtlipnt02.btlabs.bt.co.uk> > >> (I have looked at the documentation for import and it talks about > sys.path, so maybe I could add directories to sys.path in Idle? > > Yes, you could indeed. Just do this: > > ### > import sys > sys.path.append("C:\\source\\python\\") > ### Or set the PYTHONPATH environment variable. > > And you should now be able to import dvtest.py. But note that you do so by writing: import dvtest ie you don't include the file extension '.py' Alan g. Author of the 'Learning to Program' web site http://www.freenetpages.co.uk/hp/alan.gauld From mikalzet@libero.it Mon Jan 14 14:58:38 2002 From: mikalzet@libero.it (mikalzet@libero.it) Date: Mon, 14 Jan 2002 15:58:38 +0100 (CET) Subject: [Tutor] very elementary help ... [recursion!] In-Reply-To: Message-ID: On Sun, 13 Jan 2002, Danny Yoo wrote: > ### > In evaluating printBackward([node1, node2, node3]): > head = node1, tail = node2 > We need to evaluate printBackward([node2, node3]). > > In evaluating printBackward([node2, node3]): > head = node2, tail = node3 > We need to evaluate printBackward([node3]). > > In evaluating printBackward([node3]): > head = node3, tail = None > We need to evaluate printBackward(None) > > In evaluating printBackward(None): > We hit the base case, so we return without doing anything. > > Print head, which is node3. Return. > > Print head, which is node2. Return. > > Print head, which is node1. Return. > ### > > I'm using indentation here to emphasize the fact that printBackward() is > calling other helper functions, and can continue on only after the helper > is done. The strange part is that printBackward() is using itself to help > itself. *grin* ... mumble ... "...and can continue on only after the helper is done ..." EUREKA !! OK, very simple actually once one starts thinking the right way: my printBackward() function is called various times; my error was in thinking of it as ONE flow of execution (I have never programmed but I suppose the way I was thinking of it would be like a Basic "goto previous line"); whereas each call to printBackward() is independent and prints head as soon as it can ... i.e. as soon as the work done by the functions called inside it is finished. They just happen to be new instances of the same function. > Please feel free to ask more questions on this; recursion is a lot of fun > to talk about. Anyway, hope this helps! It did indeed. Thank you ! -- Michele Alzetta From jeff@ccvcorp.com Mon Jan 14 18:26:20 2002 From: jeff@ccvcorp.com (Jeff Shannon) Date: Mon, 14 Jan 2002 10:26:20 -0800 Subject: [Tutor] Idle (and sys.path) References: Message-ID: <3C4322CB.F9759874@ccvcorp.com> > "Paul Hartley" wrote: > > I have just started to use Idle and have prited out the manual. Looking = > at using the debugger it says type in the module called dvtest.py save = > it as a file and then import it. > > Now I did that but saved the file dvtest.py somewhere more convenient = > for my source code, not in the python directories, now when I type = > import dvtest.py it cannot find the module. It will not let me type in = > import c:\source\python etc. so how do I get python (or idle) to look = > elsewhere for the module? (I have looked at the documentation for import = > and it talks about sys.path, so maybe I could add directories to = > sys.path in Idle? You can indeed do this. A simpler way is to have Python do this automatically for you. Create a file, in your c:\python21 directory (or wherever you have python installed), with the name python.pth (the name itself isn't important, just that it ends in .pth). In this file, list (one per line) any directories that you want Python to search for imported modules. So in your case, if the contents of this file are: ------------------- c:\source\python ------------------- then any attempt to import a file will look for that file in c:\source\python as well as the standard directories. Jeff Shannon Technician/Programmer Credit International From idiot1@netzero.net Mon Jan 14 19:05:40 2002 From: idiot1@netzero.net (kirk Bailey) Date: Mon, 14 Jan 2002 14:05:40 -0500 Subject: [Tutor] woodchuck test Message-ID: <3C432C04.C38ED248@netzero.net> def woodchuck(wood): index=0 while 1: try: print wood index=index+1 return index -- -Respectfully, -Kirk D Bailey Consulting Loose Cannon end www.howlermonkey.net highprimate@howlermonkey.net www.sacredelectron.org idiot1@netzero.net www.tinylist.org grumpy@tinylist.org ---------------------------------------------------- Sign Up for NetZero Platinum Today Only $9.95 per month! http://my.netzero.net/s/signup?r=platinum&refcd=PT97 From dyoo@hkn.eecs.berkeley.edu Mon Jan 14 21:50:13 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 14 Jan 2002 13:50:13 -0800 (PST) Subject: [Tutor] very elementary help ... [recursion! / a plug for Scheme] In-Reply-To: Message-ID: On Mon, 14 Jan 2002 mikalzet@libero.it wrote: > On Sun, 13 Jan 2002, Danny Yoo wrote: > > > ### > > In evaluating printBackward([node1, node2, node3]): > > head = node1, tail = node2 > > We need to evaluate printBackward([node2, node3]). > > > > In evaluating printBackward([node2, node3]): > > head = node2, tail = node3 > > We need to evaluate printBackward([node3]). > > > > In evaluating printBackward([node3]): > > head = node3, tail = None > > We need to evaluate printBackward(None) > > > > In evaluating printBackward(None): > > We hit the base case, so we return without doing anything. > > > > Print head, which is node3. Return. > > > > Print head, which is node2. Return. > > > > Print head, which is node1. Return. > > ### > > > > I'm using indentation here to emphasize the fact that printBackward() is > > calling other helper functions, and can continue on only after the helper > > is done. The strange part is that printBackward() is using itself to help > > itself. *grin* > > ... mumble ... "...and can continue on only after the helper is done ..." > > EUREKA !! OK, very simple actually once one starts thinking the right way: > my printBackward() function is called various times; my error was in > thinking of it as ONE flow of execution (I have never programmed but I > suppose the way I was thinking of it would be like a Basic "goto previous > line"); whereas each call to printBackward() is independent and prints head [lower level details described below; unnecessary digression ahead! *grin*] Your intuition is good. In fact, at the lower machine level, it is very much like a GOTO, with some extra bits. A main difference between calling a procedure and doing a straight GOTO is that the caller saves its work away in a stack so that the helper doesn't stomp all over it. That's how the system maintains independence between the caller and called functions. Callers also need to provide a way for the called "helper" function to return control back to the caller --- that positional information is also saved on the stack. One consequence of this implementation of recursion is that we have a hard limit on how deeply a function can recurse --- at some point, the call stack gets too deep, and we fall through the floor! ### >>> def factorial(x): ... if (x == 0): return 1 ... return x * factorial(x-1) ... >>> print len(str(factorial(998L))) 2562 >>> print len(str(factorial(999L))) [... lots and lots of errors] File "", line 3, in factorial File "", line 3, in factorial File "", line 3, in factorial File "", line 3, in factorial File "", line 3, in factorial File "", line 3, in factorial File "", line 3, in factorial File "", line 3, in factorial File "", line 3, in factorial RuntimeError: maximum recursion depth exceeded ### In traditional programming languages, recursion isn't used as much as it should be, so most language implementations don't support recursion adequately. The main Python implementation, unfortunately, suffers from this limitation too. *sigh* There are other language implementations that handle recursion in a way that removes this limitation. Stackless Python: http://www.stackless.com/ is a variant of Python that allows unlimited recursion by avoiding the use of a stack. The Scheme programming language: http://www.swiss.ai.mit.edu/projects/scheme/ also handles unlimited recursion. It's not Python, granted, but it's a very cool language to look at when you have the chance. Learning recursion is easier in Scheme because, well, Scheme provides very little room to do looping without recursion. *grin* If you're interested, take a look at: http://www-mitpress.mit.edu/sicp/ which is a textbook similar to "How to Think Like a Computer Scientist", but uses Scheme as the teaching language. It's an excellent book. From jimmy_130@lycos.com Tue Jan 15 00:56:23 2002 From: jimmy_130@lycos.com (James M Lang) Date: Mon, 14 Jan 2002 19:56:23 -0500 Subject: [Tutor] Need help with Pygame Message-ID: As I understood from the Pygame page, there is a set of modules to use Pygame. Before, I tried to run the "punch the monkey" source yet it said that the Pygame module was not found. Where can I download the module and how do I set it up? From shalehperry@attbi.com Tue Jan 15 01:17:58 2002 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Mon, 14 Jan 2002 17:17:58 -0800 (PST) Subject: [Tutor] a better way to express this Message-ID: So today I must have typed the following about 10 times: if dict.has_key(key): dict[key] = dict[key] + 1 # or maybe foo.data else: dict[key] = 1 # or maybe foo.data Is there no better way to code that? From dyoo@hkn.eecs.berkeley.edu Tue Jan 15 01:38:53 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 14 Jan 2002 17:38:53 -0800 (PST) Subject: [Tutor] a better way to express this In-Reply-To: Message-ID: On Mon, 14 Jan 2002, Sean 'Shaleh' Perry wrote: > So today I must have typed the following about 10 times: > > if dict.has_key(key): > dict[key] = dict[key] + 1 # or maybe foo.data > else: > dict[key] = 1 # or maybe foo.data > > Is there no better way to code that? Actually, there is! ### dict[key] = dict.get(key, 0) + 1 ### The get() method of dictionaries support an optional "default" value than you can specify if the element's not in the dictionary. Hope this helps! From SWidney@ci.las-vegas.nv.us Tue Jan 15 01:48:13 2002 From: SWidney@ci.las-vegas.nv.us (Scott Widney) Date: Mon, 14 Jan 2002 17:48:13 -0800 Subject: [Tutor] RE: [Tutor][a plug for Scheme] Message-ID: > There are other language implementations that handle > recursion in a way that removes this limitation. > Stackless Python: is a variant of Python that allows > unlimited recursion by avoiding the use of a stack. > The Scheme programming language: also handles unlimited > recursion. It's not Python, granted, but it's a very > cool language to look at when you have the chance. > Learning recursion is easier in Scheme because, > well, Scheme provides very little room to do looping > without recursion. *grin* You're coming dangerously close to mentioning the bane of my mental existence at the moment -- continuations (generators and iterators and frames, oh my!). Anyone care to take a crack at explaining them in babytalk? I'm looking for an analogy other than likening them to GOTO on steroids. Scott =^) From dyoo@hkn.eecs.berkeley.edu Tue Jan 15 01:49:16 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 14 Jan 2002 17:49:16 -0800 (PST) Subject: [Tutor] Need help with Pygame In-Reply-To: Message-ID: On Mon, 14 Jan 2002, James M Lang wrote: > As I understood from the Pygame page, there is a set of modules to use > Pygame. Before, I tried to run the "punch the monkey" source yet it > said that the Pygame module was not found. Where can I download the > module and how do I set it up? Hi James, You'll want to download the pygame modules here: http://pygame.org/download.shtml If you're on Windows, go for the "pygame-1.3b.win32-py2.2.exe" or "pygame-1.3.win32-py2.1.exe" files. You might need the win32-dependencies.zip file that's linked on that web page too. Tell us if pygame works well for you; I'm thinking of fiddling around with it too when I get the chance. By the way, the author of pygame, Peter "ShredWheat" Shinners, has recently asked people their experiences in book publishing --- he's thinking of writing a book on pygame, and wants to hear horror stories. *grin* For any of the published authors out there (Alan?), maybe you can share your experiences with him: http://advogato.org/article/406.html From dyoo@hkn.eecs.berkeley.edu Tue Jan 15 01:59:26 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 14 Jan 2002 17:59:26 -0800 (PST) Subject: [Tutor] RE: [Tutor][a plug for Scheme] In-Reply-To: Message-ID: On Mon, 14 Jan 2002, Scott Widney wrote: > > > > There are other language implementations that handle > > recursion in a way that removes this limitation. > > Stackless Python: is a variant of Python that allows > > unlimited recursion by avoiding the use of a stack. > > > The Scheme programming language: also handles unlimited > > recursion. It's not Python, granted, but it's a very > > cool language to look at when you have the chance. > > Learning recursion is easier in Scheme because, > > well, Scheme provides very little room to do looping > > without recursion. *grin* > > You're coming dangerously close to mentioning the bane of my mental > existence at the moment -- continuations (generators and iterators and > frames, oh my!). Anyone care to take a crack at explaining them in babytalk? > I'm looking for an analogy other than likening them to GOTO on steroids. I don't know if this is babytalk, but here are two things I've found: http://www.python.org/workshops/2000-01/proceedings/papers/tismers/spcpaper.htm http://www.ps.uni-sb.de/~duchier/python/continuations.html As soon as I understand it myself, I'll let you know. *grin* From glidedon Mon Jan 14 19:06:42 2002 From: glidedon (glidedon) Date: Mon, 14 Jan 2002 19:06:42 +0000 Subject: [Tutor] OK here goes nothing Message-ID: <00039787fa145dfb_mailit@mail.c-zone.net> Hi folks, this looks like the place for me. I'm new to programming, new to Python and need tutoring :-) ( I also am an old dog trying to learn new tricks ) Anyway here's my first program, feel free to point out what I've done wrong or could do in a more "Pythonic" way. Thanks for the effort ! Don #! /boot/home/config/bin/python # Logbook 8 day recap # this program will calculate hours on duty last 7 days, hours avalible tomorrow ,hours on duty last 8 days # for a truck drivers log book print print " Enter Hours on duty" print # collect user input for first 8 days of record day1 = input('Enter total hours on duty day1 ?') day2 = input('Enter total hours on duty day2 ?') day3 = input('Enter total hours on duty day3 ?') day4 = input('Enter total hours on duty day4 ?') day5 = input('Enter total hours on duty day5 ?') day6 = input('Enter total hours on duty day6 ?') day7 = input('Enter total hours on duty day7 ?') day8 = input('Enter total hours on duty day8 ?') # create list to keep track of changing values historyList = [day1,day2,day3,day4,day5,day6,day7,day8] nextDay = 0 Continue = 0 # create loop for additional days input print Continue = raw_input ('do you wish to continue adding days ? y/n : ' ) while Continue != 'n': print nextDay = input('enter hours on duty next day : ') historyList.append(nextDay) print Continue = raw_input ('do you wish to continue adding days? y/n : ' ) if Continue == 'n': print print " RECAP" print "---------------------------------------------------------------------- ---------" print # output running totals when user is done inputing data print "total hours on duty last 7 Days: " , historyList [-1 ] + historyList[- 2]+ historyList[-3]+ historyList[-4]\ + historyList[-5]+ historyList[-6]+ historyList[-7] # create a variable containing the last 7 days concurrently last7Days = historyList [-1 ] + historyList[-2]+ historyList[-3]+ historyList[-4]\ + historyList[-5]+ historyList[-6]+ historyList[-7] print print "total hours avalible tomorrow: " , 70 - last7Days print print "total hours on duty last 8 Days: ", last7Days + historyList [-8] print # output number of days entered print "You have entered ", len (historyList), " Days" print # output list of hours from input print historyList [0:100] print print " Have a Safe Trip :-) " print print print From wesc@deirdre.org Tue Jan 15 02:33:14 2002 From: wesc@deirdre.org (Wesley Chun) Date: Mon, 14 Jan 2002 18:33:14 -0800 (PST) Subject: [Tutor] ANN: SF/SV Python Users Group (BayPIGgies): new meeting! Message-ID: we are bringing BayPIGgies back after a long hiatus since we lost both our meeting place and our domain name. since then, we've got- ten *one* out of the 2 back!! deirdre's original announcement below. if you're interested in the Py course, please sign up ASAP with Mickal at 408-566-4534 because they'll cancel it if there aren't enough students by end of this week!! the textbook website is down at the bottom in my .sig, and if you want to see the course syllabus, homework, handouts, schedule, etc.: http://instruction.ucsc-extension.edu/wesc/013e44 thanks, and hope to see some of you this Wednesday @ Stanfurd!!! -wesley > From: Deirdre Saoirse Moen > Date: Mon, 14 Jan 2002 17:44:43 -0800 > > I know some of you have been waiting anxiously for the return of > BayPIGgies, the Bay Area Python Interest Group. And, with the help of > Danny Yoo and Wesley Chun, we're going to be meeting again. > > A few changes: we have a new home at Stanford University. > > The web pages, due to an oops on my part, have migrated to: > http://deirdre.org/baypiggies/ where the details about the meeting > location and time will be. Note that, after this month, we'll be > meeting on the SECOND Wednesday of the month. [i.e., Feb 13th] > > The mailman mailing list is not yet fully operational due to a > configuration problem, but hopefully that'll be fixed soon. I'd spend > more time on it today, but I have a Python book I'm writing..... > > And, I'd like to take the time to encourage you to either take (or > talk someone else into taking) Wesley Chun's Python class at UC Santa > Cruz Extension in Sunnyvale. Here's the URL for you to peek at: > > http://melvin.ucsc-extension.edu/~wesc/013e44cd.htm > -- > _Deirdre * http://deirdre.net "I live in comfort knowing that my > early works were not printed on acid-free paper." -- Lawrence Block - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall PTR, 2001 http://starship.python.net/crew/wesc/cpp/ wesley.j.chun :: wesc@deirdre.org cyberweb.consulting :: cyberweb@rocketmail.com http://www.roadkill.com/~wesc/cyberweb/ From karthikg@aztec.soft.net Tue Jan 15 04:11:45 2002 From: karthikg@aztec.soft.net (Karthik Gurumurthy) Date: Tue, 15 Jan 2002 09:41:45 +0530 Subject: [Tutor] Descriptors api doubt In-Reply-To: <00039787fa145dfb_mailit@mail.c-zone.net> Message-ID: quoting from , http://www.amk.ca/python/2.2/index.html#SECTION000320000000000000000 >> For example, when you write obj.x, the steps that Python actually performs are: descriptor = obj.__class__.x descriptor.__get__(obj) >> This is what i did: class test(object): def __init__(self): self.name = "python" >>> t = test() >>> desc = t.__class__.name Traceback (most recent call last): File "", line 1, in ? ob = t.__class__.name AttributeError: type object 'test' has no attribute 'name' >>> if python does that internally, then why am in not able to access the descriptor corresponding to "name". is it named something different? The article says the descriptors live inside clas objects. Does that mean they are static members ? or is something totally different? thanks, karthik. From virketis@fas.harvard.edu Tue Jan 15 04:35:04 2002 From: virketis@fas.harvard.edu (Pijus Virketis) Date: Mon, 14 Jan 2002 23:35:04 -0500 Subject: [Tutor] OK here goes nothing References: <00039787fa145dfb_mailit@mail.c-zone.net> Message-ID: <01b101c19d7e$02d44370$dbadf78c@virketis2> Hi, Don! Well, I am sure you will get a hearty welcome from the gurus on our list ... Let me just jump right to some suggestions about the code. > # collect user input for first 8 days of record > > day1 = input('Enter total hours on duty day1 ?') > day2 = input('Enter total hours on duty day2 ?') > day3 = input('Enter total hours on duty day3 ?') > day4 = input('Enter total hours on duty day4 ?') > day5 = input('Enter total hours on duty day5 ?') > day6 = input('Enter total hours on duty day6 ?') > day7 = input('Enter total hours on duty day7 ?') > day8 = input('Enter total hours on duty day8 ?') > > # create list to keep track of changing values > > historyList = [day1,day2,day3,day4,day5,day6,day7,day8] > nextDay = 0 > Continue = 0 Clearly, asking for inputs like this is a bit tedious. You had a great idea with the historyList, so let's use it like so: historyList = [] #store information about each day here for i in range(8): #count from 0 up to (but not including!) 8 querry_string = "Enter total hours on duty on day%d" %(i+1) # generate the querry strings with the right days input = raw_input(querry_string) historyList.append(input) #add the input we just got to the list and start over > > # create loop for additional days input > > print > Continue = raw_input ('do you wish to continue adding days ? y/n : ' ) > while Continue != 'n': > print Hm, I am not quite sure what this print statement does ... Do you just want to drop down one more line? In that case, ask for raw_input like this: Continue = raw_input ('do you wish to continue adding days ? y/n :\n ' ) # the \n at the end adds a new line! > nextDay = input('enter hours on duty next day : ') > historyList.append(nextDay) > print > Continue = raw_input ('do you wish to continue adding days? y/n : ' ) > if Continue == 'n': > print > > print " RECAP" > print "---------------------------------------------------------------------- > ---------" > print > > # output running totals when user is done inputing data > > print "total hours on duty last 7 Days: " , historyList [-1 ] + historyList[- > 2]+ historyList[-3]+ historyList[-4]\ > + historyList[-5]+ historyList[-6]+ historyList[-7] Again, this is better handled by a little loop: for i in historyList: totalhours = totalhours + i print totalhours > > # create a variable containing the last 7 days concurrently > > last7Days = historyList [-1 ] + historyList[-2]+ historyList[-3]+ > historyList[-4]\ > + historyList[-5]+ historyList[-6]+ historyList[-7] Well, I guess we already have the totalhours variable. That's what you need, right? > > > print > print "total hours avalible tomorrow: " , 70 - last7Days > print > print "total hours on duty last 8 Days: ", last7Days + historyList [-8] > print Whenever you need a new line, add \n rather than using a separate print statement: print "\n total hours available tomorrow: " > > # output number of days entered > > print "You have entered ", len (historyList), " Days" > print > > # output list of hours from input > > print historyList [0:100] If you want to do it like this, just say: print historyList[:] # this gets you the whole list > print > print " Have a Safe Trip :-) " > print > print > print > Cheers, Pijus From toodles@yifan.net Tue Jan 15 04:50:45 2002 From: toodles@yifan.net (Andy W) Date: Tue, 15 Jan 2002 12:50:45 +0800 Subject: [Tutor] OK here goes nothing References: <00039787fa145dfb_mailit@mail.c-zone.net> Message-ID: <001c01c19d80$34efccb0$da00a8c0@Sun> > Hi folks, this looks like the place for me. Hi Don, welcome to the list! > > I'm new to programming, new to Python and need tutoring :-) ( I also am an > old dog trying to learn new tricks ) > > Anyway here's my first program, feel free to point out what I've done wrong > or could do in a more "Pythonic" way. Sure thing. I'm no expert, but I'll do my best to answer. Just keep going through the code until you bump into my comment(s). > > Thanks for the effort ! > > Don > > #! /boot/home/config/bin/python > > # Logbook 8 day recap > > # this program will calculate hours on duty last 7 days, hours avalible > tomorrow ,hours on duty last 8 days > # for a truck drivers log book > > print > print " Enter Hours on duty" > print > > # collect user input for first 8 days of record > > day1 = input('Enter total hours on duty day1 ?') > day2 = input('Enter total hours on duty day2 ?') > day3 = input('Enter total hours on duty day3 ?') > day4 = input('Enter total hours on duty day4 ?') > day5 = input('Enter total hours on duty day5 ?') > day6 = input('Enter total hours on duty day6 ?') > day7 = input('Enter total hours on duty day7 ?') > day8 = input('Enter total hours on duty day8 ?') I'm assuming that this code won't be used by any malicious user anyway, but do you know the dangers of using input? If used with Evil Intent, input can be used to damage a system, as it will evaluate the input data. > > # create list to keep track of changing values > > historyList = [day1,day2,day3,day4,day5,day6,day7,day8] > nextDay = 0 > Continue = 0 A common *style* technique for names is using Capitalisation for "classes". That's completely up to you, though. > > # create loop for additional days input > > print > Continue = raw_input ('do you wish to continue adding days ? y/n : ' ) > while Continue != 'n': I'm not sure if you know about the "x in y" statement, nor am I even sure you want to know about it, but I'll go over it anyway :-) Say you wanted to also allow for the input of "no", "No" and "N", you can do the following: ### while Continue is not in ["n","no","No","N"] ### However, I'd be more inclined to go for the optimistic approach. ie. check for the input of "y" ;) Say if the user input something other than "y" or "n" (or the variations if you choose to acknowledge them), then with the current code it will be interpreted as "yes", and the loop will continue. You could either check that the input is acceptable, or you could check for "y", and anything else would mean "no". Maybe that's just one of my quirks. > print > nextDay = input('enter hours on duty next day : ') > historyList.append(nextDay) > print > Continue = raw_input ('do you wish to continue adding days? y/n : ' ) > if Continue == 'n': > print > > print " RECAP" > print "---------------------------------------------------------------------- > ---------" > print > > # output running totals when user is done inputing data > > print "total hours on duty last 7 Days: " , historyList [-1 ] + historyList[- > 2]+ historyList[-3]+ historyList[-4]\ > + historyList[-5]+ historyList[-6]+ historyList[-7] > > # create a variable containing the last 7 days concurrently > > last7Days = historyList [-1 ] + historyList[-2]+ historyList[-3]+ > historyList[-4]\ > + historyList[-5]+ historyList[-6]+ historyList[-7] They're both the same, yes? So you can make it more efficient by evaluating the total once, and then printing it. Also, there's a quicker way to add them. (or 2 quicker ways) ### Method One import operator reduce(operator.add,historyList[-7:]) ### ### Method Two reduce(lambda a,b:a+b,historyList[-7:]) Have you used the reduce function before? It applies the function (the first parameter) to each two elements cumulatively. > > > print > print "total hours avalible tomorrow: " , 70 - last7Days > print > print "total hours on duty last 8 Days: ", last7Days + historyList [-8] > print > > # output number of days entered > > print "You have entered ", len (historyList), " Days" > print > > # output list of hours from input > > print historyList [0:100] When slicing a list, it automatically starts at 0 if you leave it blank. ie. You can say "historyList[:100]". > print > print " Have a Safe Trip :-) " > print > print > print > That's all I can think of. HTH, Andy. > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From dyoo@hkn.eecs.berkeley.edu Tue Jan 15 05:11:42 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 14 Jan 2002 21:11:42 -0800 (PST) Subject: [Tutor] OK here goes nothing [list manipulation] In-Reply-To: <01b101c19d7e$02d44370$dbadf78c@virketis2> Message-ID: Hi Don, welcome aboard! > > day1 = input('Enter total hours on duty day1 ?') > > day2 = input('Enter total hours on duty day2 ?') > > day3 = input('Enter total hours on duty day3 ?') [some code cut...] > Clearly, asking for inputs like this is a bit tedious. You had a great > idea with the historyList, so let's use it like so: > > historyList = [] > for i in range(8): > querry_string = "Enter total hours on duty on day%d" %(i+1) > input = raw_input(querry_string) > historyList.append(input) Pijus shows that Python lists are expandable --- we can append() elements to an empty list, and Python will automagically expand the size of them for us. There's some reference material on Python lists here: http://www.python.org/doc/lib/typesseq-mutable.html if we want to see a complete list of what lists can do. Another good source of information about lists is in the Python tutorial: http://www.python.org/doc/tut/node5.html#SECTION005140000000000000000 http://www.python.org/doc/tut/node7.html#SECTION007100000000000000000 Lots of good stuff. *grin* Play around with it a bit, and I think you'll like what you see. > print "-----------------------------------------------------" There's an easier way to do this: ### print '-' * 60 ### We can "multiply" strings with an integer, and it'll duplicate that string that many times. This is very convenient for building headers. Here's an example with the interpreter: ### >>> header = '-=' * 20 + '-' >>> header '-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-' ### For a quick overview of this, we can look at: http://www.python.org/doc/tut/node5.html#SECTION005120000000000000000 > print "total hours on duty last 7 Days: " , historyList [-1] > + historyList[-2]+ historyList[-3]+ historyList[-4] > + historyList[-5]+ historyList[-6]+ historyList[-7] > > Again, this is better handled by a little loop: > > for i in historyList: > totalhours = totalhours + i > print totalhours It's possible to write helper functions that work with lists: ### def sum(some_list): total = 0 for item in some_list: total = total + item return total ### so that, later on, when we add up historyList, it looks like a bulk action: ### totalhours = sum(historyList) ### which I think is pretty nice. If we just want to add a subset of this list, we can "slice" a portion of the list off. Here's an example of "slicing" in the Python interpreter: ### >>> weekdays = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday'] >>> weekdays[0:3] ['monday', 'tuesday', 'wednesday'] >>> weekdays[-3:] ['wednesday', 'thursday', 'friday'] ### Combining these two ideas, getting the total hours of duty for the last seven days can be short and sweet: ### print "total hours on duty last 7 Days: ", sum(historyList[-7:]) ### > > # output list of hours from input > > > > print historyList [0:100] > > If you want to do it like this, just say: > > print historyList[:] # this gets you the whole list Also, ### print historyList ### will work if we don't need to slice the list. If you have questions, please feel free to ask. From wesc@deirdre.org Tue Jan 15 04:42:31 2002 From: wesc@deirdre.org (Wesley Chun) Date: Mon, 14 Jan 2002 20:42:31 -0800 (PST) Subject: [Tutor] Descriptors api doubt In-Reply-To: Message-ID: On Tue, 15 Jan 2002, Karthik Gurumurthy wrote: > > quoting from , > http://www.amk.ca/python/2.2/index.html#SECTION000320000000000000000 > > For example, when you write obj.x, the steps that Python actually perform= s > are: > > descriptor =3D obj.__class__.x > descriptor.__get__(obj) > > This is what i did: > > class test(object): > =09def __init__(self): > =09=09self.name =3D "python" > > >>> t =3D test() > >>> desc =3D t.__class__.name > Traceback (most recent call last): > File "", line 1, in ? > ob =3D t.__class__.name > AttributeError: type object 'test' has no attribute 'name' > > if python does that internally, then why am in not able to access the > descriptor > corresponding to "name". is it named something different? > > The article says the descriptors live inside clas objects. > Does that mean they are static members ? or is something totally differen= t? good Python 2.2 question. i could be mistaken, but from what i have read so far, i think that descriptors are only used/ useful for *class* attributes. you were messing with an *instance* attribute. a class attribute is either a static data member or a method. i haven't checked the source to see how they have been imple- mented in the code though. hopefully someone else can chip in there. hope this helps a little! -wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall PTR, =A9 2001 http://starship.python.net/crew/wesc/cpp/ wesley.j.chun :: wesc@deirdre.org cyberweb.consulting : henderson, nv : cyberweb@rocketmail.com http://www.roadkill.com/~wesc/cyberweb/ From wesc@deirdre.org Tue Jan 15 05:04:43 2002 From: wesc@deirdre.org (Wesley Chun) Date: Mon, 14 Jan 2002 21:04:43 -0800 (PST) Subject: [Tutor] OK here goes nothing [list manipulation] In-Reply-To: Message-ID: On Mon, 14 Jan 2002, Danny Yoo wrote: > > > print "-----------------------------------------------------" > > There's an easier way to do this: > > print '-' * 60 everyone has such great ideas. i thought i would just elaborate a little on danny's suggestion, which is an oldie but goodie!! if this print statement is inside a loop, the Python virtual machine (VM) has to execute 60 string concatenations each time, which may (or may not) affect performance. a better way to do it would be to perform this calculation once, and use that instead for every future occurrence: dashes =3D '-' * 60=09=09# do it once : print dashes=09=09=09# use whenever : some_loop: : print dashes=09=09# esp. in loops! hope this helps!! -wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall PTR, =A9 2001 http://starship.python.net/crew/wesc/cpp/ wesley.j.chun :: wesc@deirdre.org cyberweb.consulting : henderson, nv : cyberweb@rocketmail.com http://www.roadkill.com/~wesc/cyberweb/ From idiot1@netzero.net Tue Jan 15 05:52:10 2002 From: idiot1@netzero.net (kirk Bailey) Date: Tue, 15 Jan 2002 00:52:10 -0500 Subject: [Tutor] passwords Message-ID: <3C43C38A.AACF655A@netzero.net> OK, I run FreeBSD. I want to write a form and script to chang the passwords for my email users. This way they can go there, tell it the old pasword, the account name, and a new password, and the computer changes the password. There are programs in there to do this quickly and efficently- but they are interctive. Any thought,s suggestions, etc? -- -Respectfully, -Kirk D Bailey Consulting Loose Cannon end www.howlermonkey.net highprimate@howlermonkey.net www.sacredelectron.org idiot1@netzero.net www.tinylist.org grumpy@tinylist.org ---------------------------------------------------- Sign Up for NetZero Platinum Today Only $9.95 per month! http://my.netzero.net/s/signup?r=platinum&refcd=PT97 From idiot1@netzero.net Tue Jan 15 06:25:33 2002 From: idiot1@netzero.net (kirk Bailey) Date: Tue, 15 Jan 2002 01:25:33 -0500 Subject: [Tutor] tinylist.1.0.1.tar.gz is ready Message-ID: <3C43CB5D.82F3A60C@netzero.net> OK, it's ready, you may download at convience. http://www.tinylist.org/tinylist.1.0.1.tar.gz -- -Respectfully, -Kirk D Bailey Consulting Loose Cannon end www.howlermonkey.net highprimate@howlermonkey.net www.sacredelectron.org idiot1@netzero.net www.tinylist.org grumpy@tinylist.org ---------------------------------------------------- Sign Up for NetZero Platinum Today Only $9.95 per month! http://my.netzero.net/s/signup?r=platinum&refcd=PT97 From slime@vsnl.net Tue Jan 15 10:24:32 2002 From: slime@vsnl.net (Prahlad Vaidyanathan) Date: Tue, 15 Jan 2002 10:24:32 GMT Subject: [Tutor] pickle to save time of access Message-ID: <20020115091039.GA1071@marvin.clone> Hi, I have been trying to implement a script to retrieve news for my home system . I have attached the entire script below for your perusal, but I am primarily interested in this : # Retrieves date from conffile f = open(conffile,'r') f.seek(0) oldtime = pickle.load(f) f.close() # Write new date to (the start of) conffile f = open(conffile,'w') f.seek(0) pickle.dump(time.time(),f) f.close() As you can see, I use a pickled time.time() object to find out the previous time the script was successfully run. I then use the 'oldtime' variable to check the time of the news post. If the post's time (newtime) is _after_ oldtime, I retrieve it, else I ignore it. Now, I was wondering if there is a better was of doing the following : * Completely abandong the 'conffile' for a better way of saving the previous time the script was successfully run. * Add error-checking to ensure that 'conffile' was not written to since the last time the script was run successfully. Thanks. pv. The entire script is here : #!/usr/bin/python -S # TODO # * Handle exceptions better # * check for new groups every month or so # * check if conffile is there/has been modified since last pickle.dump # * try and make rfc822.Message from this - readline() ? import smtplib, nntplib, pickle, time from string import split from sys import exit from rfc822 import parsedate # Edit these variables before proceeding newshost = 'news.vsnl.net.in' smtphost = 'marvin.clone' newsgroups = ['alt.humor.best-of-usenet', 'comp.os.linux.announce', 'comp.os.linux.answers'] to_address = 'Prahlad V ' conffile = '/home/prahlad/.fetchnewsrc' # Variables you needn't edit debug_level = 0 agent_name = 'fetchnews' # Drum roll print agent_name, 'started' # Open nntp connection try: ns = nntplib.NNTP(newshost) except: print 'Unable to connect to', newshost exit(1) ns.set_debuglevel(debug_level) # Open smtp connection (sans exceptions ;) server = smtplib.SMTP(smtphost) # Retrieves date from conffile f = open(conffile,'r') f.seek(0) oldtime = pickle.load(f) f.close() # Start retrieving for group in newsgroups: # Get group info resp, count, first, last, name = ns.group(group) print 'Group', name, 'has', count, 'articles, range', first, 'to', last resp, subs = ns.xhdr('subject', first + '-' + last) # Process each mail for id, sub in subs[-10:]: # Construct mail msg = "" # Headers flag = 0 for line in ns.head(id)[3]: try: head, value = split(line,": ",1) except ValueError: continue fromaddr = "" if head == "From": fromaddr = value if head == "Date": newtime = parsedate(value) if time.mktime(newtime) < oldtime: flag = 1 break value = time.strftime('%a, %d %b %Y %H:%M:%S GMT', newtime) msg = msg + head + ": " + value + "\n" if flag: print "Ignoring : ", id, sub continue # Fallback if fromaddr == "": fromaddr = to_address # Put in the To header msg = msg + "To: " + to_address + "\n" # Put in a custom header for me procmail msg = msg + "X-NewsAgent: " + agent_name + "\n" # The body for line in ns.body(id)[3]: msg = msg + line + "\n" # Send the mail print 'Retrieving:', id, sub server.sendmail(fromaddr,to_address,msg) print 'Retrieved news from', group # Write new date to (the start of) conffile f = open(conffile,'w') f.seek(0) pickle.dump(time.time(),f) f.close() # Clean up ns.quit() server.quit() print agent_name, 'done.' -- Prahlad Vaidyanathan Buck-passing usually turns out to be a boomerang. From slime@vsnl.net Tue Jan 15 10:24:42 2002 From: slime@vsnl.net (Prahlad Vaidyanathan) Date: Tue, 15 Jan 2002 10:24:42 GMT Subject: [Tutor] How to access an rfc822.Message.body ? Message-ID: <20020115101907.GA1231@marvin.clone> Hi, I have been constructing a simple MTA for my home system. It basically queues all outgoing mails, and sends them through a smart-host, when I log on. Now, I was wondering how one can access the body of an rfc822.Message. I read the docs, and even looked into the code of the module, but couldn't find anything. The reason is this : the smtplib.SMTP.sendmail() function accepts a message as a string. Hence, when sending a mail, I have to convert the rfc822.Message object into one string. As of now, this is what I do : # Takes an rfc822.Message, and returns a string def constructmail(mail): from rfc822 import formatdate from config import mta_name del mail['date'] del mail['x-mta'] current_time = formatdate() msg = "Date: " + current_time + "\n" msg = msg + "X-MTA: " + mta_name + "\n" for line in mail.headers: msg = msg + line mail.rewindbody() for line in mail.fp.readlines(): msg = msg + line return msg This works all right, but only if the file referred to by mail.fp is open when the function is called. Hence, when I extract a mail from a queue-folder for sending, the queue-folder file _must_ be open for the above function to work (otherwise readline() can't happen ) Is there any way to access the body of the rfc822.Message if the rfc822.Message.fp file is closed ? pv. -- Prahlad Vaidyanathan A diplomat is a man who can convince his wife she'd look stout in a fur coat. From alan.gauld@bt.com Tue Jan 15 10:49:35 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Tue, 15 Jan 2002 10:49:35 -0000 Subject: [Tutor] very elementary help ... [recursion! / a plug for Sch eme] Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C281@mbtlipnt02.btlabs.bt.co.uk> > The Scheme programming language: > > http://www.swiss.ai.mit.edu/projects/scheme/ > > If you're interested, take a look at: > > http://www-mitpress.mit.edu/sicp/ > > which is a textbook similar to "How to Think Like a Computer > Scientist", but uses Scheme as the teaching language. SICP is very good for computer scientists but a better online intro to scheme for beginners is: http://www.htdp.org/ Which is available as a dead tree book under the title "How To Design Programs". I've read both (I'm half way thru the latter) and HTDP is *much* better for a beginner with less math and a slower pace. Just my thoughts, Alan G. From alan.gauld@bt.com Tue Jan 15 11:14:01 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Tue, 15 Jan 2002 11:14:01 -0000 Subject: [Tutor] Descriptors api doubt Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C282@mbtlipnt02.btlabs.bt.co.uk> > For example, when you write obj.x, the steps that Python > actually performs are: > > descriptor = obj.__class__.x > descriptor.__get__(obj) And so it does heres an example, with my comments: >>> class C: ... name = '' ## defie a class member ... def __init__(self,n): self.name = n ## assign to it making an instance specific version ... >>> class D: ... def __init__(self,n): self.name = n ## D only has an instance version no class member ... >>> c = C('foo') >>> d = D('bar') >>> c.__class__.name '' ## The class version is unchanged >>> c.name 'foo' ## there's the instance version >>> d.__class__.name Traceback (most recent call last): File "", line 1, in ? AttributeError: class D has no attribute 'name' ## like it says D has no class member >>> d.name 'bar' ## but it does have an instance one. > This is what i did: > > class test(object): > def __init__(self): > self.name = "python" So the nself.name doesn't come into effect till after you create an instance. The class object has no name attribute. > >>> t = test() > >>> desc = t.__class__.name > Traceback (most recent call last): > File "", line 1, in ? > ob = t.__class__.name > AttributeError: type object 'test' has no attribute 'name' Just like I said... > if python does that internally, then why am in not able > to access the descriptor corresponding to "name". You can as I shoiwed but thats how Python accesses *class* variables not *instance* variables - they are not the same. When you define a class any attributes outside the methods are class members and shared by all instances. When an instance assigns to a class member name python creates a new instance specific member which is accessible to that instance only. class X: foo = 0 def setFoo(self,x): self.foo = x a = X() b = X() # two instances print a.foo, b.foo ### => 0 0 X.foo = 7 # change shared value print a.foo, b.foo ### => 7 7 a.setFoo(5) # create new copy in 'a' only print a.foo, b.foo ### => 5 7 ie b still using shared one X.foo = 42 # change shared one print a.foo, b.foo ### => 5 42 change only seen by b HTH, Alan G. From slime@vsnl.net Tue Jan 15 14:09:14 2002 From: slime@vsnl.net (Prahlad Vaidyanathan) Date: Tue, 15 Jan 2002 14:09:14 GMT Subject: [Tutor] Python implementation of Unix tools Message-ID: <20020115105358.GA2120@marvin.clone> Hi, [Note: This mail contains a mention of perl, but please do not misconstrue it as flame-bait ] I noticed that there was a very nice project called 'Perl Power Tools', http://www.perl.com/language/ppt/ which sought to implement a lot of standard unix tools (like cat, ping, whois, etc) in pure perl. I was wondering if there is a similar project under Python. The reason I ask is that, I often find myself on *nix systems lacking in some basic tool, which I have taken for granted, and can't do without. Hence, instead of having to download the package off the net (not always possible) and go through 'make', I could use a little python tool which does the job (or, at least most of it). I could use the perl implementations, but I would love it if it were in python. Any pointers ? pv. -- Prahlad Vaidyanathan Dave Mack: "Your stupidity, Allen, is simply not up to par." Allen Gwinn: "Yours is." From ewe2@can.org.au Tue Jan 15 14:30:10 2002 From: ewe2@can.org.au (Sean Dwyer) Date: Wed, 16 Jan 2002 01:30:10 +1100 Subject: [Tutor] Python implementation of Unix tools In-Reply-To: <20020115105358.GA2120@marvin.clone> References: <20020115105358.GA2120@marvin.clone> Message-ID: <20020115143010.GA4450@can.org.au> On Tue, Jan 15, 2002 at 02:09:14PM +0000, Prahlad Vaidyanathan wrote: > Hi, > I noticed that there was a very nice project called 'Perl Power Tools', > which sought to implement a lot of standard unix tools (like cat, ping, > whois, etc) in pure perl. > > I was wondering if there is a similar project under Python. [snips] I don't know of any, and a search didn't turn anything up, but that's a great idea :) Note to Rob: now _there's_ a Useless Challenge :) -- Sean Dwyer Web: http://www.geocities.com/ewe2_au/ From scarblac@pino.selwerd.nl Tue Jan 15 14:40:06 2002 From: scarblac@pino.selwerd.nl (Remco Gerlich) Date: Tue, 15 Jan 2002 15:40:06 +0100 Subject: [Tutor] Python implementation of Unix tools In-Reply-To: <20020115105358.GA2120@marvin.clone>; from slime@vsnl.net on Tue, Jan 15, 2002 at 02:09:14PM +0000 References: <20020115105358.GA2120@marvin.clone> Message-ID: <20020115154006.A10998@pino.selwerd.nl> On 0, Prahlad Vaidyanathan wrote: > I was wondering if there is a similar project under Python. The reason I > ask is that, I often find myself on *nix systems lacking in some basic > tool, which I have taken for granted, and can't do without. Hence, > instead of having to download the package off the net (not always > possible) and go through 'make', I could use a little python tool which > does the job (or, at least most of it). > > I could use the perl implementations, but I would love it if it were in > python. Any pointers ? I don't see the use of this at all. If there is a Perl implementation, why is a Python implementation so useful? Far too much open source software is duplicated, several mediocre implementations in several different languages, it's a waste. -- Remco Gerlich From pythontutor@venix.com Tue Jan 15 16:01:01 2002 From: pythontutor@venix.com (Lloyd Kvam) Date: Tue, 15 Jan 2002 11:01:01 -0500 Subject: [Tutor] a better way to express this References: Message-ID: <3C44523D.8030608@venix.com> dict.setdefault(k,defaultval) - requires 2.0 or newer http://starship.python.net/crew/mwh/hacks/setdefault.html setdefault This will initialize the key to the default value when the key is not found in the dictionary, else it returns the value for the key. I think it is slightly more general than Danny's solution. A more descriptive name would be: get_butSetIfMissing(key, defaultvalue) Danny Yoo wrote: > On Mon, 14 Jan 2002, Sean 'Shaleh' Perry wrote: > > >>So today I must have typed the following about 10 times: >> >>if dict.has_key(key): >> dict[key] = dict[key] + 1 # or maybe foo.data >>else: >> dict[key] = 1 # or maybe foo.data >> >>Is there no better way to code that? >> > > Actually, there is! > > ### > dict[key] = dict.get(key, 0) + 1 > ### > > The get() method of dictionaries support an optional "default" value than > you can specify if the element's not in the dictionary. > > > Hope this helps! > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From James.Alexander.McCarney@Cognicase.com Tue Jan 15 17:18:09 2002 From: James.Alexander.McCarney@Cognicase.com (McCarney, James Alexander) Date: Tue, 15 Jan 2002 12:18:09 -0500 Subject: [Tutor] [Tutor]: Totally laughable basic questions Message-ID: <23FD7B1A77E8D211BCB900001D108C02018B290C@camelot> This message is in MIME format. Since your mail reader does not understand this format, some or all of this message may not be legible. ------_=_NextPart_001_01C19DE8.9AA8E7FE Content-Type: text/plain; charset="iso-8859-1" I am a programming neophyte. Yes in my day-to-day life I use tools (usually text editing, manipulation, etc.), and these tools often involve 'programming' of a sort; but now I want to 'look under the hood.' I have heard of, and seen, the wonders of XML; and I am even aware [ gasp! ;-) ] of basic OOP programming principles; but I am often perplexed about how to tie everything together. Of course, I want to do it with Python, because I love Eric Idle, John Cleese, and the gang: Self-defense against a banana, wow! Now my hero is Mr. Bean, but I digress. ;-) What is more embarrassing (for me at least) is knowing when (AND WHY!) to use a dictionary, a tuple, a string object, etc. And when (AND WHY!) to slice, dice, concatenate, or otherwise fr*g with the contents of these groups. Maybe Python-Tutor is not the place for these type of questions, and if so, I apologise. If some kind soul out in Pythonland is aware of completely pre-basic tutors that can help me out with various elementary programming concepts I would be most grateful. Cheers. James Alexander McCarney, Technical Writer M3i Systems Inc., 1111 Saint-Charles Avenue West 11th Floor, East Tower, Longueuil, Quebec, J4K 5G4 Canada Telephone: (450) 928-3386 x2262 Fax: (450) 442-5076 http://www.m3isystems.com ------_=_NextPart_001_01C19DE8.9AA8E7FE Content-Type: text/html; charset="iso-8859-1"
I am a programming neophyte.
 
Yes in my day-to-day life I use tools (usually text editing, manipulation, etc.), and these tools often involve 'programming' of a sort;
but now I want to 'look under the hood.'
 
I have heard of, and seen, the wonders of XML; and I am even aware [ gasp! ;-) ] of basic OOP programming principles;
but I am often perplexed about how to tie everything together.
 
Of course, I want to do it with Python, because I love Eric Idle,
John Cleese, and the gang: Self-defense against a banana, wow!
Now my hero is Mr. Bean, but I digress.  ;-)
 
What is more embarrassing (for me at least) is knowing when (AND WHY!) to use a dictionary, a tuple, a string object, etc.
And when (AND WHY!) to slice, dice, concatenate, or otherwise fr*g with the contents of these groups.
 
Maybe Python-Tutor is not the place for these type of questions, and if so, I apologise. If some kind soul out in Pythonland is aware of
completely pre-basic tutors that can help me out with various elementary programming concepts I would be most grateful.
 
Cheers.

James Alexander McCarney, Technical Writer
M3i Systems Inc., 1111 Saint-Charles Avenue West
11th Floor, East Tower, Longueuil, Quebec, J4K 5G4
Canada

Telephone: (450) 928-3386 x2262
Fax: (450) 442-5076

http://www.m3isystems.com

 
------_=_NextPart_001_01C19DE8.9AA8E7FE-- From jeff@ccvcorp.com Tue Jan 15 17:39:13 2002 From: jeff@ccvcorp.com (Jeff Shannon) Date: Tue, 15 Jan 2002 09:39:13 -0800 Subject: [Tutor] woodchuck test References: Message-ID: <3C446940.9531C46A@ccvcorp.com> > kirk Bailey wrote: > > > def woodchuck(wood): > index=0 > while 1: > try: > print wood > index=index+1 > return index > Heheheh... I like it! But you forgot to put an except (or finally) after your try .... def woodchuck(wood): index = 0 while 1: try: chuck(wood) index += 1 finally: return index :) Jeff Shannon Technician/Programmer Credit International From marcolinux@linuxbr.com.br Tue Jan 15 17:36:42 2002 From: marcolinux@linuxbr.com.br (Marco A. Sousa) Date: Tue, 15 Jan 2002 15:36:42 -0200 Subject: [Tutor] Removing itens from a list Message-ID: <20020115153641.A2129@marcolab.proconet> Hi. This is my first message to this great list. Wish I find out about you before :) Sorry for my english, we speak portuguese here. My question is: In the following list,how do I remove every item with "orange" on it? l = ['I like Orange juice','orange','OranGes are good','I like apple'] I think I should use re module, but dont now how to use it. Do you know any site that explain the use of re module or regex with python ? Thanks in advance, and keep up the good work. You guys are *really* making a difference. -- Buy a copy of a baby naming book and you'll never be at a loss for variable names. - How To Write Unmaintainable Code From mando@mando.org Tue Jan 15 16:37:12 2002 From: mando@mando.org (Mando Escamilla) Date: 15 Jan 2002 11:37:12 -0500 Subject: [Tutor] Removing itens from a list In-Reply-To: <20020115153641.A2129@marcolab.proconet> References: <20020115153641.A2129@marcolab.proconet> Message-ID: <1011112632.244.1.camel@mlinux> > My question is: > > In the following list,how do I remove every item with "orange" on it? > l = ['I like Orange juice','orange','OranGes are good','I like apple'] > > > I think I should use re module, but dont now how to use it. > Do you know any site that explain the use of re module or regex with python ? Sure. http://py-howto.sourceforge.net/regex/regex.html -- Mando From tjenkins@devis.com Tue Jan 15 17:50:08 2002 From: tjenkins@devis.com (Tom Jenkins) Date: 15 Jan 2002 12:50:08 -0500 Subject: [Tutor] a better way to express this In-Reply-To: <3C44523D.8030608@venix.com> References: <3C44523D.8030608@venix.com> Message-ID: <1011117024.1432.6.camel@asimov> Howdy, On Tue, 2002-01-15 at 11:01, Lloyd Kvam wrote: > dict.setdefault(k,defaultval) > - > requires 2.0 or newer > > http://starship.python.net/crew/mwh/hacks/setdefault.html > setdefault > > This will initialize the key to the default value when the key is not found in the > dictionary, else it returns the value for the key. I think it is slightly more > general than Danny's solution. A more descriptive name would be: > get_butSetIfMissing(key, defaultvalue) Actually Danny's implementation is correct. Yes you are right that the setdefault will set the value if it is not set, however in the code snippet the goal is to increment the value for the given key. the implementation using setdefault would only work like this: dict.setdefault(key,0) dict[key] = dict[key] + 1 Danny's dict[key] = dict.get(key,0) + 1 looks better to me > > Danny Yoo wrote: > > > On Mon, 14 Jan 2002, Sean 'Shaleh' Perry wrote: > > > > > >>So today I must have typed the following about 10 times: > >> > >>if dict.has_key(key): > >> dict[key] = dict[key] + 1 # or maybe foo.data > >>else: > >> dict[key] = 1 # or maybe foo.data > >> > >>Is there no better way to code that? > >> > > > > Actually, there is! > > > > ### > > dict[key] = dict.get(key, 0) + 1 > > ### > > > > The get() method of dictionaries support an optional "default" value than > > you can specify if the element's not in the dictionary. > > > > > > Hope this helps! > > > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > -- > Lloyd Kvam > Venix Corp. > 1 Court Street, Suite 378 > Lebanon, NH 03766-1358 > > voice: > 603-443-6155 > fax: > 801-459-9582 > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Tom Jenkins Development InfoStructure http://www.devis.com From tjenkins@devis.com Tue Jan 15 17:55:29 2002 From: tjenkins@devis.com (Tom Jenkins) Date: 15 Jan 2002 12:55:29 -0500 Subject: [Tutor] Removing itens from a list In-Reply-To: <20020115153641.A2129@marcolab.proconet> References: <20020115153641.A2129@marcolab.proconet> Message-ID: <1011117329.1432.8.camel@asimov> Hello and welcome, On Tue, 2002-01-15 at 12:36, Marco A. Sousa wrote: > Hi. This is my first message to this great list. Wish I find out about > you before :) Sorry for my english, we speak portuguese here. > > > My question is: > > In the following list,how do I remove every item with "orange" on it? > l = ['I like Orange juice','orange','OranGes are good','I like apple'] > > > I think I should use re module, but dont now how to use it. > Do you know any site that explain the use of re module or regex with python ? you could use a regular expression however i would use a list comprehension (assuming python 2.x) results = [x for x in l if x.lower().find('orange') == -1] what is going on here is - we loop over 'l' putting the item in 'x' - call lower() on x which lowercases the string - call find('orange') on the lowercased string. if the return value of that call is -1 then 'orange' does not appear in the string - check our return value from find() against -1, if they are equal then append the value of 'x' into our new list > > Thanks in advance, and keep up the good work. You guys are *really* making > a difference. > > -- > Buy a copy of a baby naming book and you'll never be at a loss for > variable names. > - How To Write Unmaintainable Code > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Tom Jenkins Development InfoStructure http://www.devis.com From toodles@yifan.net Tue Jan 15 18:00:04 2002 From: toodles@yifan.net (Andy W) Date: Wed, 16 Jan 2002 02:00:04 +0800 Subject: [Tutor] Removing itens from a list References: <20020115153641.A2129@marcolab.proconet> Message-ID: <003701c19dee$7776b490$da00a8c0@Sun> > Hi. This is my first message to this great list. Wish I find out about > you before :) Sorry for my english, we speak portuguese here. Hi Marco! Welcome to the list. > > > My question is: > > In the following list,how do I remove every item with "orange" on it? > l = ['I like Orange juice','orange','OranGes are good','I like apple'] > > > I think I should use re module, but dont now how to use it. > Do you know any site that explain the use of re module or regex with python ? Using Regular Expressions is not necessary. Try the following: # l = ['I like Orange juice','orange','OranGes are good','I like apple'] for item in l[:]: #Make a copy of the list, and iterate through it. if item.lower().count("orange"): #Get the string in lowercase, and count the number of times "orange" appears. l.remove(item) #If the count > 0, remove the item. # But here's a HOWTO for Regular Expressions anyway. http://py-howto.sourceforge.net/regex/regex.html HTH, Andy > > Thanks in advance, and keep up the good work. You guys are *really* making > a difference. > > -- > Buy a copy of a baby naming book and you'll never be at a loss for > variable names. > - How To Write Unmaintainable Code > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld@bt.com Tue Jan 15 18:05:16 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Tue, 15 Jan 2002 18:05:16 -0000 Subject: [Tutor] Python implementation of Unix tools Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C288@mbtlipnt02.btlabs.bt.co.uk> > On Tue, Jan 15, 2002 at 02:09:14PM +0000, Prahlad Vaidyanathan wrote: > > I noticed that there was a very nice project called 'Perl > Power Tools', > > I was wondering if there is a similar project under Python. There is but I've forgotten the name. It actually is slightly different in that it aims to build the standard unix(posix?) tools in python. There is a nice paper somewhere explaining why they chose python over perl/tcl (large project support mainly). Why are they doing this when cygwin does a similar job? Well, python is portable to a much wider platform range... I think it's on source-forge somewhere. Alan G From idiot1@netzero.net Tue Jan 15 18:57:38 2002 From: idiot1@netzero.net (kirk Bailey) Date: Tue, 15 Jan 2002 13:57:38 -0500 Subject: [Tutor] [Tutor]: Totally laughable basic questions References: <23FD7B1A77E8D211BCB900001D108C02018B290C@camelot> Message-ID: <3C447BA2.DF0B33E9@netzero.net> No, this is the place for these and even more basic questions. WELCOME! > "McCarney, James Alexander" wrote: > > I am a programming neophyte. GOGO GAGA ME TO. > > Yes in my day-to-day life I use tools (usually text editing, > manipulation, etc.), and these tools often involve 'programming' of > a sort; but now I want to 'look under the hood.' Ah, hacking lives. > > I have heard of, and seen, the wonders of XML; and I am even aware [ > gasp! ;-) ] of basic OOP programming principles; > but I am often perplexed about how to tie everything together. > Extended Markup Language. An extension of HTML. Personally, I like to use html with a light seasoning of CSS, a few select javascript notions, and a tasteful sprinkling of Server Side Includes. My preferred stile is lean and clean if the task permits it, and minimize the crud whenever posible. As a result, my preferred pages load FAST, whereas many 'professional' sites take up to A MINUTE (shudder) on a 56k modem. > Of course, I want to do it with Python, because I love Eric Idle, > John Cleese, and the gang: Self-defense against a banana, wow! > Now my hero is Mr. Bean, but I digress. ;-) > Ah, exellent taste. > What is more embarrassing (for me at least) is knowing when (AND > WHY!) to use a dictionary, a tuple, a string object, etc. > And when (AND WHY!) to slice, dice, concatenate, or otherwise fr*g > with the contents of these groups. > > Maybe Python-Tutor is not the place for these type of questions, and > if so, I apologise. If some kind soul out in Pythonland is aware of > completely pre-basic tutors that can help me out with various > elementary programming concepts I would be most grateful. > No, this is the place. A LIST is rather like a 1 dimensional array. You can change the contents of a list, even append new cells. A DICTIONARY is rather like 2 lists in one, where there is a KEY and a CONTENT. Plug in the key, put pops the content associated with the key. In an array, you would use an index number. for instance: FOO(0)=huh?, FOO(1)=no, foo(2)=yes, foo=[huh?,no,yes] in a dictionary, I could do this as: foo[ERROR:huh?,notfound:no,found:yes] earning me >>> foo['notfound'] no >>> This is VERY useful when the data is associated with a word, and us REALLY handy for databases with fieldnames, and tends to sneak into the cgi form circus all over the place. It caqme in REAL handy in writing some email software recently that had to pay attention to the content of the headers in a incoming letter. Headers may not always be in the same sequence, but when you use a dictionary, we don't care. Plug in 'From:' and get back the email address, for instance. Gang, I hesitate to teach anyone anything about Python, I'm only 6 weeks removed from drooling on my python rattle myself. Pardon any inaccuacies or errors. > Cheers. > > James Alexander McCarney, Technical Writer > M3i Systems Inc., 1111 Saint-Charles Avenue West > 11th Floor, East Tower, Longueuil, Quebec, J4K 5G4 > Canada > > Telephone: (450) 928-3386 x2262 > Fax: (450) 442-5076 > > http://www.m3isystems.com > > -- -Respectfully, -Kirk D Bailey Consulting Loose Cannon end www.howlermonkey.net highprimate@howlermonkey.net www.sacredelectron.org idiot1@netzero.net www.tinylist.org grumpy@tinylist.org ---------------------------------------------------- Sign Up for NetZero Platinum Today Only $9.95 per month! http://my.netzero.net/s/signup?r=platinum&refcd=PT97 From vcardon@siue.edu Tue Jan 15 19:01:38 2002 From: vcardon@siue.edu (Victor R. Cardona) Date: Tue, 15 Jan 2002 13:01:38 -0600 Subject: [Tutor] passwords In-Reply-To: <3C43C38A.AACF655A@netzero.net>; from idiot1@netzero.net on Tue, Jan 15, 2002 at 12:52:10AM -0500 References: <3C43C38A.AACF655A@netzero.net> Message-ID: <20020115130138.A19301@client156-52.ll.siue.edu> --y0ulUmNC+osPPQO6 Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Tue, Jan 15, 2002 at 12:52:10AM -0500, kirk Bailey wrote: > OK, I run FreeBSD. I want to write a form and script to chang the > passwords for my email users. This way they can go there, tell it the > old pasword, the account name, and a new password, and the computer > changes the password. There are programs in there to do this quickly > and efficently- but they are interctive. Any thought,s suggestions, > etc? Look at the pw command in FreeBSD. It should offer the functionality you need. -v --=20 Victor R. Cardona Powered by SuSE Linux 7.1 (i386) Professional GPG key ID E81B3A1C Key fingerprint =3D 0147 A234 99C3 F4C5 BC64 F501 654F DB49 E81B 3A1C --y0ulUmNC+osPPQO6 Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iD8DBQE8RHySZU/bSegbOhwRAtLiAJ4vq4jKa6bndnIBuw3m8bhdRjPvvACdGQFg F27eVqlAms695nSEHKiY2Bc= =IC4Q -----END PGP SIGNATURE----- --y0ulUmNC+osPPQO6-- From virketis@fas.harvard.edu Tue Jan 15 19:41:09 2002 From: virketis@fas.harvard.edu (Pijus Virketis) Date: Tue, 15 Jan 2002 14:41:09 -0500 Subject: [Tutor] [Tutor]: Totally laughable basic questions References: <23FD7B1A77E8D211BCB900001D108C02018B290C@camelot> <3C447BA2.DF0B33E9@netzero.net> Message-ID: <028201c19dfc$94d1ee70$dbadf78c@virketis2> > A LIST is rather like a 1 dimensional array. You can change the > contents of a list, even append new cells. > > A DICTIONARY is rather like 2 lists in one, where there is a KEY and a > CONTENT. One very important difference between a list and a dictionary is that a dictionary is not ordered! In other words, it stores the content, but not the structure of the content. Because of that, a dictionary is a "faster" data structure, but a list is sometimes more useful. Of course, if a bit of extra work, you can pretty much use a dictionary in most places you would use a list, by iterating over the key list (which is a list, and hence can be iterated over :)). Cheers, Pijus From JMaia@lexgen.com Tue Jan 15 19:45:40 2002 From: JMaia@lexgen.com (Joao Prado Maia) Date: Tue, 15 Jan 2002 13:45:40 -0600 Subject: [Tutor] Performance Issues with Threaded Python Network Server Message-ID: <80A38867B1DBD511A8C9009027764C8C72AB20@lexchange.lexgen.com> Hi, Before even starting with the description of my problem, let me explain my situation. I'm trying to create a custom Python based NNTP server to serve as a gateway of sorts to some web message boards. This way people can connect to the News server and get messages / reply and such. Please be aware that this is my first real-world python project, so please be gentil if you see something stupid in my code ;) Anyway, I read 'Programming Python' a little bit on the Network programming chapter and decided to use threads (aka SocketServer.ThreadingTCPServer) on my NNTP server. Everything works great but I have been experiencing some heavy CPU usage on the server. A little bit more of information - the heavy CPU load is triggered when the an user tries to download all 1500 messages / articles of one message board. The way NNTP works and the way Outlook Express (the newsreader on this case) works is that it will download all the headers for the articles at once, and then request the actual body of the articles one by one. What this means is that the server will write to the 'wfile' file descriptor to send the response (the headers and bodies of the articles) to the newsreader. The problem here is that whenever this happens, the CPU usage of the NNTP server goes to about 35% and continues increasing slowly while the newsreader is receiving all the message headers and bodies. My guess right now is that I'm doing something bad on the routines that spit the information to the newsreader somehow and because of this the server is consuming a lot of CPU. Since I'm not an expert in the performance tweaks or even about possible bottlenecks, I would love if someone could take a look and maybe get some insight into what could be wrong. The NNTP server gets its information from a MySQL database (and no, MySQL is not the bottleneck as far as I know, since 'top' shows the NNTP server consuming 35% of CPU, not MySQL), formats the output by using string replacement (aka "%s %s <%s@%s>" % (v,x,z,y)) and writes to the 'wfile' file descriptor. The source code for the NNTP server can be found below directly from CVS: http://cvs.phpbrasil.com/chora/co.php/papercut/papercut.py?r=1.18 The source code for the MySQL backend interface that does most of the formatting of the information coming from the database can also be found here: http://cvs.phpbrasil.com/chora/co.php/papercut/backends/phorum_mysql.py?r=1. 3 Any insights would be very much appreciated. Joao -- Joao Prado Maia Software QA Bioinformatics Dept. Lexicon Genetics, Inc. *************************************************************************** The contents of this communication are intended only for the addressee and may contain confidential and/or privileged material. If you are not the intended recipient, please do not read, copy, use or disclose this communication and notify the sender. Opinions, conclusions and other information in this communication that do not relate to the official business of my company shall be understood as neither given nor endorsed by it. *************************************************************************** From kimtitu@yahoo.com Tue Jan 15 19:55:11 2002 From: kimtitu@yahoo.com (Titu Kim) Date: Tue, 15 Jan 2002 11:55:11 -0800 (PST) Subject: [Tutor] Piping gd output to cgi script Message-ID: <20020115195511.20553.qmail@web14708.mail.yahoo.com> Hi, I am trying to find a method or approach to redirect the image created by a C program using gd library using a python cgi script. My goal is to display a page with content type of image. My python cgi script will do a call to my precompile C program. I don't want to write the image to a file. I wish to grab the output of the C program and show that image in a browser window. Can someone give me some suggestion? Is my approach possible? Thanks Regards Kim Titu __________________________________________________ Do You Yahoo!? Send FREE video emails in Yahoo! Mail! http://promo.yahoo.com/videomail/ From dyoo@hkn.eecs.berkeley.edu Tue Jan 15 22:04:36 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 15 Jan 2002 14:04:36 -0800 (PST) Subject: [Tutor] Re: [Tutor]: Totally laughable basic questions [introduction to hashing] In-Reply-To: <028201c19dfc$94d1ee70$dbadf78c@virketis2> Message-ID: On Tue, 15 Jan 2002, Pijus Virketis wrote: > > A LIST is rather like a 1 dimensional array. You can change the > > contents of a list, even append new cells. > > > > A DICTIONARY is rather like 2 lists in one, where there is a KEY and a > > CONTENT. > > One very important difference between a list and a dictionary is that > a dictionary is not ordered! In other words, it stores the content, > but not the structure of the content. Because of that, a dictionary is > a "faster" data structure, but a list is sometimes more useful. [warning: this is a long message, and tries to explain some of the ideas behind dictionaries. Get a cup of coffee first. *grin*] Lists can be "fast" too. Let's say we had a list like this: ### >>> amino_acids = [ ('ala', 'alanine'), ... ('cys', 'cysteine'), ... ('asp', 'aspartic acid'), ... ('glu', 'glutamic acid'), ... ('phe', 'phenylalanine') ] ### It's very easy, with this list structure, to get the 5th element of the list: ### >>> amino_acids[4] ('phe', 'phenylalanine') ### If we know the position of an element of a list, grabbing at that element is very fast. This is important to realize: as long as we have a position into our list, we can grab at that list element instantly. It's a whole other question, though, if we don't already know the position. Let's say that we're looking for the entry associated with 'glu': ### >>> def findEntry(query_name, name_value_pairs): ... for name, value in name_value_pairs: ... if name == query_name: ... return value ... return None ... >>> findEntry('glu', amino_acids) 'glutamic acid' ### As you might guess, this is not so fast. We're basically scanning through each element in our list to search for the entry. The big problem here is that we don't know the numerical position of the element, but we still want to look it up. This is a very important problem! If we have a dictionary of words and definitions, we want to make looking up a definition really fast. If only there were a way to somehow something like "glu" into a position in our list, then we might be able to quickly look up things, if we arrange our list properly. And there is a way! ### >>> hash('glu') 127508733 ### hash() is a function that takes any Python object, and calculates some random looking number. It's not random though; it really does depend on the content of the object: ### >>> l = [(hash(x), x) for x in ['ala', 'cys', 'asp', 'glu', 'phe'] ] >>> l.sort() >>> l [(-1586925553, 'ala'), (-1585925437, 'asp'), (127508733, 'glu'), (413875008, 'cys'), (631676366, 'phe')] ### (Let's take the definition of hash() as a given for this message; we can worry about how it works later.) Now we can imagine a really long list: ### BIGLIST = [('ala', 'alanine'), None, None, ...., ('asp', 'aspartic acid'), None, None, ...., ('glu', 'glutamic acid'), None, None, ...., ('cys', 'cysteine'), None, None, ...., ('phe', 'phenylalanine'), ] ### I'm using four dots here to indicate the hugeness of this list. If we were insane enough to actually construct a list of this size, with entries in the correct positions, then we could instantly look things up, with something like: ### def sillyLookupAminoAcid(key): return BIGLIST[hash(key) + 1586925553] ### But again, we run into another problem: most of us are not insane enough to actually build a list this long! There are only 5 useful elements in BIGLIST, so we're really wasting a heck of a lot of memory here. One approach we can use to reduce the waste is to shrink down the range of the numbers with the 'remainder' or 'modulo' function: ### >>> [ (x % 11, y) for (x, y) in l] [(7, 'ala'), (3, 'asp'), (0, 'glu'), (8, 'cys'), (2, 'phe')] ### Wow, that's a big improvement! Using the modulo function, we've just forced all the numbers to be between 0 and 11, by taking the remainders. And we can build a list for this, no sweat. ### hashed_acids = [('glu', 'glutamic acid'), None, ('phe', 'phenylalanine'), ('asp', 'aspartic acid'), None, None, None, ('ala', 'alanine'), ('cys', 'cysteine')] def lookupAminoAcid(key): return hashed_acids[ hash(key) % 11 ] ### Does this actually work? ### >>> lookupAminoAcid('ala') ('ala', 'alanine') >>> lookupAminoAcid('asp') ('asp', 'aspartic acid') ### Wow. This actually worked. *grin* And it's fast, which is what we're looking for: a fast way of looking up definitions if we have a key. But isn't this all black magic? Wouldn't you rather not worry about all this sort of stuff? That's what dictionaries are for. ### >>> acid_dict = { 'ala' : 'alanine', ... 'cys' : 'cysteine', ... 'asp' : 'aspartic acid', ... 'glu' : 'glutamic acid', ... 'phe' : 'phenylalanine' } >>> acid_dict['asp'] 'aspartic acid' ### Dictionaries do pretty much everything that we did above, automatically, without the mind-numbing boredom of listening to a Computer Science lecture. Lesson: use dictionaries --- they are very good. *grin* Hope this helps! From arcege@speakeasy.net Tue Jan 15 22:19:28 2002 From: arcege@speakeasy.net (Michael P. Reilly) Date: Tue, 15 Jan 2002 17:19:28 -0500 Subject: [Tutor] Removing itens from a list In-Reply-To: <1011117329.1432.8.camel@asimov>; from tjenkins@devis.com on Tue, Jan 15, 2002 at 12:55:29PM -0500 References: <20020115153641.A2129@marcolab.proconet> <1011117329.1432.8.camel@asimov> Message-ID: <20020115171928.A1236@speakeasy.net> On Tue, Jan 15, 2002 at 12:55:29PM -0500, Tom Jenkins wrote: > Hello and welcome, > > On Tue, 2002-01-15 at 12:36, Marco A. Sousa wrote: > > Hi. This is my first message to this great list. Wish I find out about > > you before :) Sorry for my english, we speak portuguese here. > > > > > > My question is: > > > > In the following list,how do I remove every item with "orange" on it? > > l = ['I like Orange juice','orange','OranGes are good','I like apple'] > > > > > > I think I should use re module, but dont now how to use it. > > Do you know any site that explain the use of re module or regex with python ? > > you could use a regular expression however i would use a list > comprehension (assuming python 2.x) > > results = [x for x in l if x.lower().find('orange') == -1] > > what is going on here is > - we loop over 'l' putting the item in 'x' > - call lower() on x which lowercases the string > - call find('orange') on the lowercased string. if the return value of > that call is -1 then 'orange' does not appear in the string > - check our return value from find() against -1, if they are equal then > append the value of 'x' into our new list > And more universially (i.e. works on all versions): has_orange = lambda s: string.find(string.lower(s), 'orange') != -1 results = filter(has_orange, l) Filter will call the given function with each item in the list, if the function returns true, the item is added to the resulting list. Using regular expressions can be far more expensive than using the string functions. -Arcege From mikalzet@libero.it Tue Jan 15 23:18:18 2002 From: mikalzet@libero.it (mikalzet@libero.it) Date: Wed, 16 Jan 2002 00:18:18 +0100 (CET) Subject: [Tutor] facing a new project In-Reply-To: <00039787fa145dfb_mailit@mail.c-zone.net> Message-ID: On Mon, 14 Jan 2002, glidedon wrote: > I'm new to programming, new to Python and need tutoring :-) ( I also am an > old dog trying to learn new tricks ) Sounds like we've got a lot in common. At least; I'm a babe to programming, but I am an old dog ... probably a bit past the age were most people take programming up. > # this program will calculate hours on duty last 7 days, hours avalible > tomorrow ,hours on duty last 8 days > # for a truck drivers log book Well, if I ever become a good python programmer, do you know what is the program I would like to write ? Something which doesn't exist in the GPL world - a good program for creating, managing, checking and printing working schedules for departments with really complex scheduling ... like mine. I haven't even found any really satisfying commercial programs to this purpose. The only thing close is phpSched to be found on Sourceforge, the one and only author doesn't want to develop further on the same lines, seems like he's trying to redo it in perl ... but I haven't seen any progress on the new perl site either. So what should this program do ? I am one of a group of 14 - 17 ER doctors; shifts cover 24 hours a day, but there are various types of shifts - for example shift type 'A' covers 24 hours 365 days a year (one doctor between 22.00 and 8.00 and the day hours covered by two doctors e.g. one shift 8-14, another 14-21, one 9-16, another 16-22 ... times may vary on holidays and the days immediately preceding holidays); shift type 'B' covers 8 to 20.00 (actually 8-14 + 14-20) every day except holidays; shift type 'C' covers 365 nights a year in a geographically detached location ( 20 to 8 ); shift type 'D' covers 365 days a year in this same location (8-14, 14-20). For the moment we've got rid of shift type 'E' ( 365 days from 9 to 17 ) and shift type 'F' ( one night a week) but they may come back ... Just to keep things simple, all ER doctors are equal, but some are more equal than others ... one can only do 'B' type shifts; another only 'C' and 'D'; others will do anything but 'D' and so forth (for various reasons, can't go into them now). In theory we should work 38 hour weeks (ha, ha), a couple however have reduced time contracts (with different times each, of course), and so will not tolerate extra hours. Furthermore, some will not do shifts on certain days and times (for reasons which go from academic involvement to political involvement; it also happens that people do have personal lives as well). So you say, so what. One big spreadsheet and you've done it. Right. We have that. The excel sheet we use even does some basic checks. So why write a new python program to print a big spreadsheet ? Because notwithstanding double checking done by two people, every month we get situations like Tom finds he's supposed to be on duty contemporaneously in two different places or Bob finds he's supposed to end a 12 hour shift ( 6 hour shifts are often attributed two by two) and immediately start another 12 hour shift elsewhere, whereas Tim gets mad because he finds out he's doing six night shifts in one month whereas everybody else is doing four or five, while mike points out he can't keep on doing 78 hour weeks every damn week etc. etc. etc. etc. Besides, the colleague who writes the shifts (not me, luckily) spends hours and hours of his free time every month to do this. The ideal program therefore should: allow input of special conditions and desiderata, different types of days and different types of shifts; GENERATE one or more possible schedule sheets complying with these desiderata, or if it is not possible offer a range of solutions, indicating for each of these which conditions and desiderata are violated; allow manual correction of the generated schedules; do a series of checks of these to avoid requiring people to do impossible things, and finally print a neat, legible schedule. Note: schedules of individual people are not required to have any fixed order - no 'Tom does all the B mornings this week and James next week' stuff, unless explicitly requested. The program owuld also keep track of hours worked etc. etc. A program like this would be extremely useful to thousands of people who work in hospitals all over the world. To strive in this direction I suppose I should concentrate on Python; Tkinter (will have to have a GUI); a database (I don't suppose dictionaries and lists would be sufficient) present on linux and windows (I use linux but the program would have to run on windows) - postgresql ?; whatever method python makes available for printing. The thing that seems most difficult is the 'generating' schedules bit ... If I ever wished to seriously face a new project of this sort, what is the best way to go about it ? First make a gross design of the whole thing ( database schema, classes etc. ) and then start tackling it, or start with small bits of code like the truck drivers log book and then just try to extend it bit by bit ? Not that I'm yet really convinced I mean to do this ... -- Michele Alzetta From arcege@speakeasy.net Wed Jan 16 00:23:28 2002 From: arcege@speakeasy.net (Michael P. Reilly) Date: Tue, 15 Jan 2002 19:23:28 -0500 Subject: [Tutor] Piping gd output to cgi script In-Reply-To: <20020115195511.20553.qmail@web14708.mail.yahoo.com>; from kimtitu@yahoo.com on Tue, Jan 15, 2002 at 11:55:11AM -0800 References: <20020115195511.20553.qmail@web14708.mail.yahoo.com> Message-ID: <20020115192328.A1549@speakeasy.net> On Tue, Jan 15, 2002 at 11:55:11AM -0800, Titu Kim wrote: > Hi, > I am trying to find a method or approach to > redirect the image created by a C program using gd > library using a python cgi script. My goal is to > display a page with content type of image. My python > cgi script will do a call to my precompile C program. > I don't want to write the image to a file. I wish to > grab the output of the C program and show that image > in a browser window. Can someone give me some > suggestion? Is my approach possible? Thanks There is a "gd" module that you might want to look at. But for this, let's assume that you have a os.popen() file object that you want to use. import sys, os gd_input = os.popen(...) # send out the bare minimum HTTP header sys.stdout.write('Content-Type: image/png\n\n') # copy the data to stdout block = gd_input.read(8192) while block: sys.stdout.write(block) block = gd_input.read(8192) Similarly, if you the gd output can be written to stdout, and you don't need to do the extra. import sys, os # send out the bare minimum HTTP header sys.stdout.write('Content-Type: image/png\n\n') # let the output go directly to stdout os.system(...) One reason why you would _want_ to have the data written to a file is to get the length of the file and to pass that along to the web browser in a Content-Length header. If you decide to use the Python "gd" module in the future, the concept is the same, but you can write directly to stdout (instead of a file). -Arcege From jimmy_130@lycos.com Wed Jan 16 01:03:29 2002 From: jimmy_130@lycos.com (James M Lang) Date: Tue, 15 Jan 2002 20:03:29 -0500 Subject: [Tutor] How powerful is Python? Message-ID: Exactly how powerful is Python? Does it come close to C or other such languages? Is it very fast? And one last thing, why do I keep getting what seems to be every Python tutor e-mail even if it has nothing to do with me? It's cluttering my e-mail account.:/ From shalehperry@attbi.com Wed Jan 16 01:34:43 2002 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Tue, 15 Jan 2002 17:34:43 -0800 (PST) Subject: [Tutor] a better way to express this In-Reply-To: <1011117024.1432.6.camel@asimov> Message-ID: > Actually Danny's implementation is correct. Yes you are right that the > setdefault will set the value if it is not set, however in the code > snippet the goal is to increment the value for the given key. the > implementation using setdefault would only work like this: > > dict.setdefault(key,0) > dict[key] = dict[key] + 1 > > Danny's > dict[key] = dict.get(key,0) + 1 > looks better to me > I am also forced to use 1.5.x still. But I agree, this looks and feels better as well. Went through and implemented it today, made things much happier. From dsh8290@rit.edu Wed Jan 16 01:45:10 2002 From: dsh8290@rit.edu (dman) Date: Tue, 15 Jan 2002 20:45:10 -0500 Subject: [Tutor] How powerful is Python? In-Reply-To: References: Message-ID: <20020116014510.GA4460@localhost> On Tue, Jan 15, 2002 at 08:03:29PM -0500, James M Lang wrote: | Exactly how powerful is Python? Very. | Does it come close to C or other such languages? It depends on what you want to do. Certainly C has the ability to do more -- it is closer to the metal and can really twiddle bits (and cause a segfault if you don't do it right). However C is closer to the metal. This means that operations like file and string processing are harder for the programmer to do, and do correctly, than in python. My opinion : use C if you need to do low-level bit twiddling (kernel, device driver, etc) or you have _really_ tight performance constraints. Otherwise use python, its high-level approach will make your life much easier for every day tasks and for larger projects. When it comes to a sizeable project a mixture of the two is good -- use python for everything and then rewrite the bottleneck(s) in C if need be. | Is it very fast? Sure. That's not a good question though. The better question is "Is this script/program fast *enough* for me?". That can only be answered after you write the thing and run it. If it is too slow, profile it. | And one last thing, why do I keep getting what seems to be every | Python tutor e-mail even if it has nothing to do with me? It's | cluttering my e-mail account.:/ You signed up to receive list mail. Use a filter to drop it in its own folder instead of your inbox. -D -- If your company is not involved in something called "ISO 9000" you probably have no idea what it is. If your company _is_ involved in ISO 9000 then you definitely have no idea what it is. (Scott Adams - The Dilbert principle) From shalehperry@attbi.com Wed Jan 16 01:45:00 2002 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Tue, 15 Jan 2002 17:45:00 -0800 (PST) Subject: [Tutor] Removing itens from a list In-Reply-To: <20020115153641.A2129@marcolab.proconet> Message-ID: >>> no_oranges = lambda s: re.search(r'orange', s, re.IGNORECASE) == None >>> filter(no_oranges, l) ['I like apple'] And since everyone gave you an example without a regular expression, I went ahead and made one. This is similar to the has_oranges mail earlier. From dyoo@hkn.eecs.berkeley.edu Wed Jan 16 01:48:05 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 15 Jan 2002 17:48:05 -0800 (PST) Subject: [Tutor] How powerful is Python? In-Reply-To: <20020116014510.GA4460@localhost> Message-ID: On Tue, 15 Jan 2002, dman wrote: > On Tue, Jan 15, 2002 at 08:03:29PM -0500, James M Lang wrote: > > | And one last thing, why do I keep getting what seems to be every > | Python tutor e-mail even if it has nothing to do with me? It's > | cluttering my e-mail account.:/ > > You signed up to receive list mail. Use a filter to drop it in its > own folder instead of your inbox. Also, you can set up your Tutor options so that you don't get general messages from the list. If you visit: http://mail.python.org/mailman/listinfo/tutor and go down to the bottom "Edit Options" form, you can set this option. This will still allow you to send messages to Tutor, but you won't hear the "background noise" from the list. If tutors are careful to use Reply-to-all, you should still receive personal emails from people who want to answer your questions. Personally, though, I like hearing background noise. You'll never know if you're missing something useful! Plus hearing --- excuse me, seeing! --- other people's questions and comments can be really helpful while learning a language. Another option is to turn on "digest" mode in your options, so that instead of getting ten messages a day, you'll get one whole digest. This may be less cluttering for you. Good luck! From toodles@yifan.net Wed Jan 16 01:58:53 2002 From: toodles@yifan.net (Andy W) Date: Wed, 16 Jan 2002 09:58:53 +0800 Subject: [Tutor] How powerful is Python? References: Message-ID: <002801c19e31$5c0608d0$da00a8c0@Sun> > Exactly how powerful is Python? Does it come close to C or other such languages? Is it very fast? And one last thing, why do I keep getting what seems to be every Python tutor e-mail even if it has nothing to do with me? It's cluttering my e-mail account.:/ I'll leave the first few questions to someone more learned, though they might just say what I'd say anyway (interpreted language, very powerful, ... ). But if you don't want the emails, you can unsubscribe from the list: http://mail.python.org/mailman/listinfo/tutor Or you can always change your preferences to receive messages in digest mode, so you can still read but your email account isn't cluttered quite as much. Regards, Andy > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From dyoo@hkn.eecs.berkeley.edu Wed Jan 16 02:00:35 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 15 Jan 2002 18:00:35 -0800 (PST) Subject: [Tutor] facing a new project In-Reply-To: Message-ID: On Wed, 16 Jan 2002 mikalzet@libero.it wrote: > On Mon, 14 Jan 2002, glidedon wrote: > > > I'm new to programming, new to Python and need tutoring :-) > > ( I also am an old dog trying to learn new tricks ) > > Sounds like we've got a lot in common. At least; I'm a babe to > programming, but I am an old dog ... probably a bit past the age were > most people take programming up. Down with ageism! I'm serious. It's wonderful to have people of different ages here. Where else can we do something like this? *grin* > If I ever wished to seriously face a new project of this sort, what is > the best way to go about it ? First make a gross design of the whole > thing ( database schema, classes etc. ) and then start tackling it, or > start with small bits of code like the truck drivers log book and then > just try to extend it bit by bit ? Not that I'm yet really convinced I > mean to do this ... A rough design and working code sounds like a good approach. According to Richard Gabriel, it's more important to get something out that sorta works and then gradually fix that, rather than try to get everything perfect at once. I believe he termed the phrase "Worse Is Better": http://www.dreamsongs.com/WorseIsBetter.html So I wouldn't obsess too much about design, since your program's requirements sound pretty fluid. From toodles@yifan.net Wed Jan 16 02:09:07 2002 From: toodles@yifan.net (Andy W) Date: Wed, 16 Jan 2002 10:09:07 +0800 Subject: [Tutor] How powerful is Python? References: Message-ID: <003501c19e32$c9bdb110$da00a8c0@Sun> > and go down to the bottom "Edit Options" form, you can set this option. > This will still allow you to send messages to Tutor, but you won't hear > the "background noise" from the list. If tutors are careful to use > Reply-to-all, you should still receive personal emails from people who > want to answer your questions. Whoops, I'll stop removing the extra name occasionally. I didn't know anyone didn't like the "background noise" as Danny puts it ;-) > > Personally, though, I like hearing background noise. You'll never know if > you're missing something useful! Plus hearing --- excuse me, seeing! --- > other people's questions and comments can be really helpful while learning > a language. Yup, I agree with this. It helped me no end: I lurked a lot for about half a year to a year, and used to ask the odd question (sometimes they were pretty odd ;-)). Now I answer a whole lot more questions than I ask (albeit sometimes badly). Regards, Andy From virketis@fas.harvard.edu Wed Jan 16 02:21:09 2002 From: virketis@fas.harvard.edu (Pijus Virketis) Date: Tue, 15 Jan 2002 21:21:09 -0500 Subject: [Tutor] How powerful is Python? References: <003501c19e32$c9bdb110$da00a8c0@Sun> Message-ID: <02f001c19e34$75b85ff0$dbadf78c@virketis2> > Yup, I agree with this. It helped me no end: I lurked a lot for about half a > year to a year, and used to ask the odd question (sometimes they were pretty > odd ;-)). Now I answer a whole lot more questions than I ask (albeit > sometimes badly). I agree completely. Not that I have yet answered more questions than I have asked ... :) But you should make an effort to answer other people's questions, even if you might not give the definitive version, because nothing helps one understand a topic better than trying to explain it to someone else! Then you really have to think about it in a general and at the same time clear manner. So, the "background noise" questions are an opportunity to practice and find things out for yourself, as well as help someone else out. My two cents ... Cheers, Pijus From dsh8290@rit.edu Wed Jan 16 02:36:16 2002 From: dsh8290@rit.edu (dman) Date: Tue, 15 Jan 2002 21:36:16 -0500 Subject: [Tutor] How powerful is Python? In-Reply-To: <003501c19e32$c9bdb110$da00a8c0@Sun> References: <003501c19e32$c9bdb110$da00a8c0@Sun> Message-ID: <20020116023616.GA5083@localhost> On Wed, Jan 16, 2002 at 10:09:07AM +0800, Andy W wrote: | > and go down to the bottom "Edit Options" form, you can set this option. | > This will still allow you to send messages to Tutor, but you won't hear | > the "background noise" from the list. If tutors are careful to use | > Reply-to-all, you should still receive personal emails from people who | > want to answer your questions. Mmm, it's not good to rely on people assuming you want a duplicate copy of your mail. I use List-Reply when I post to the list; if you don't have your address in the Mail-Followup-To: header you won't get a duplicate copy. After all, if you're subscribed to the list and you didn't ask for double, why should you get double? The moral : either receive all list mail, or set Mail-Followup-To: appropriately. -D -- Only two things are infinite, the universe and human stupidity, and I'm not sure about the former. Albert Einstein From glidedon Tue Jan 15 18:41:04 2002 From: glidedon (glidedon) Date: Tue, 15 Jan 2002 18:41:04 +0000 Subject: [Tutor] OK here goes nothing In-Reply-To: <01b101c19d7e$02d44370$dbadf78c@virketis2> References: <00039787fa145dfb_mailit@mail.c-zone.net> <01b101c19d7e$02d44370$dbadf78c@virketis2> Message-ID: <0003979bbc48b1f3_mailit@mail.c-zone.net> Hi Pijus, Thanks for the generous welcome, and the effort to decifer my code ! With my rudimentary skills, it sure helps to better understand some of these concepts when I can plug them into some program I already understand :-) I will modify and add to my code to reflect your suggestions. Thanks again for your time ! Don From glidedon Tue Jan 15 18:42:51 2002 From: glidedon (glidedon) Date: Tue, 15 Jan 2002 18:42:51 +0000 Subject: [Tutor] OK here goes nothing In-Reply-To: <001c01c19d80$34efccb0$da00a8c0@Sun> References: <00039787fa145dfb_mailit@mail.c-zone.net> <001c01c19d80$34efccb0$da00a8c0@Sun> Message-ID: <0003979bc2a5a4d9_mailit@mail.c-zone.net> Hi Andy, Thanks for the suggestions, I really appreciate your time. I am vaguely aware of the security issue you mentioned and will check into it further. Is my historyList the Classes you are referring to? Should it be HistoryList? I guess I should pay more attention to style convention while I'm trying to build good habits. I am just getting aware of the x in y thingy thanks for the excellent introduction. Thanks again! Don From virketis@fas.harvard.edu Wed Jan 16 03:01:02 2002 From: virketis@fas.harvard.edu (Pijus Virketis) Date: Tue, 15 Jan 2002 22:01:02 -0500 Subject: [Tutor] OK here goes nothing References: <00039787fa145dfb_mailit@mail.c-zone.net> <001c01c19d80$34efccb0$da00a8c0@Sun> <0003979bc2a5a4d9_mailit@mail.c-zone.net> Message-ID: <030b01c19e3a$0864cc80$dbadf78c@virketis2> > Is my historyList the Classes you are referring to? Should it be HistoryList? > I guess I should pay more attention to style convention while I'm trying to > build good habits. I think what Andy was telling you about is that it is a convention of OOP to capitalise the words used in class names, e.g. "class HistoryList". Why that is, someone wiser in the ways of OO will have to explain. :) So, you may wish to name your variables something else, such as history_list (my preffered style). But truth be said, whatever makes your code easiest to read for you is the best thing ... Of course, if you expect someone else to maintain the code you write, then it might be useful to stick to more "traditional" style. Cheers, Pijus From virketis@fas.harvard.edu Wed Jan 16 03:09:49 2002 From: virketis@fas.harvard.edu (Pijus Virketis) Date: Tue, 15 Jan 2002 22:09:49 -0500 Subject: [Tutor] "Python Web Programming" by Steve Holden Message-ID: <033001c19e3b$425aa3a0$dbadf78c@virketis2> This is a multi-part message in MIME format. ------=_NextPart_000_032D_01C19E11.59618340 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Has anyone bought or looked at this book yet? Amazon just sent me one of = those annoying direct sales emails of theirs, but this one actually = appears to be relevant for a change. :) Perhaps you have read something = else from the author? The book seems to cover CGI/sockets/database API. = If it's not all that, what other books in this genre would you rather = recommend? Cheers,=20 Pijus ------=_NextPart_000_032D_01C19E11.59618340 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
Has anyone bought or looked at = this book yet?=20 Amazon just sent me one of those annoying direct sales emails of = theirs,=20 but this one actually appears to be relevant for a change. :) = Perhaps you=20 have read something else from the author? The book seems to cover=20 CGI/sockets/database API. If it's not all that, what other books in this = genre=20 would you rather recommend?
 
Cheers,
 
Pijus
------=_NextPart_000_032D_01C19E11.59618340-- From dyoo@hkn.eecs.berkeley.edu Wed Jan 16 04:55:10 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 15 Jan 2002 20:55:10 -0800 (PST) Subject: [Tutor] "Python Web Programming" by Steve Holden In-Reply-To: <033001c19e3b$425aa3a0$dbadf78c@virketis2> Message-ID: On Tue, 15 Jan 2002, Pijus Virketis wrote: > Has anyone bought or looked at this book yet? Amazon just sent me one > of those annoying direct sales emails of theirs, but this one actually > appears to be relevant for a change. :) Perhaps you have read > something else from the author? The book seems to cover > CGI/sockets/database API. I haven't read this book yet, sorry. > If it's not all that, what other books in this genre would you rather > recommend? I'd recommend Philip and Alex's Guide to Web Publishing: http://www.arsdigita.com/books/panda/ It's not too particular to any technology, so it might not be immediately useful. On the other hand, after reading a few pages, I felt... inspired to do something creative and useful. I think that's a sign of a good book. *grin* His book covers a lot of design issues, including reasons why databases are critical for a serious web site. The whole book is online on that site, so you can read it at your leisure. Hope this helps! From p.hartley@spitech.com Wed Jan 16 05:09:45 2002 From: p.hartley@spitech.com (Paul Hartley) Date: Wed, 16 Jan 2002 13:09:45 +0800 Subject: [Tutor] Storing source files Message-ID: <006101c19e4c$334be700$ebe710ac@pc7345> This is a multi-part message in MIME format. ------=_NextPart_000_005A_01C19E8F.1170C680 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable I would be interested to hear how experienced programmers organise their = source files and libraries in python. I don't know of one book that = deals with this question - they all assume files are stored in some root = directory. A related issue is how would you organise your modules and classes - all = in one library directory or would you use some directory structure. Given you have developed a whole pile of classes or modules, how are = these documented so you can find the one you need when you need it? No = one likes documentation and it always gets out of date - I realise I am = searching for the holy grail with this one!! Paul ------=_NextPart_000_005A_01C19E8F.1170C680 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
I would be interested to hear how = experienced=20 programmers organise their source files and libraries in python. I don't = know of=20 one book that deals with this question - they all assume files are = stored in=20 some root directory.
 
A related issue is how would you = organise your=20 modules and classes - all in one library directory or would you use some = directory structure.
 
Given you have developed a whole pile = of classes or=20 modules, how are these documented so you can find the one you need when = you need=20 it? No one likes documentation and it always gets out of date - I = realise I am=20 searching for the holy grail with this one!!
 
Paul
 
 
------=_NextPart_000_005A_01C19E8F.1170C680-- From slime@vsnl.net Wed Jan 16 06:28:17 2002 From: slime@vsnl.net (Prahlad Vaidyanathan) Date: Wed, 16 Jan 2002 06:28:17 GMT Subject: [Tutor] Python implementation of Unix tools In-Reply-To: <20020115154006.A10998@pino.selwerd.nl> References: <20020115105358.GA2120@marvin.clone> <20020115154006.A10998@pino.selwerd.nl> Message-ID: <20020116023455.GA2191@marvin.clone> --LQksG6bCIzRHxTLp Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable Hi, On Tue, 15 Jan 2002 Remco Gerlich spewed into the ether: [-- snip --] > I don't see the use of this at all. If there is a Perl implementation, why > is a Python implementation so useful? >=20 > Far too much open source software is duplicated, several mediocre > implementations in several different languages, it's a waste. I agree. But mine is a very selfish reason - I would have to learn perl, with all it's nuances, in order to expand on those existing tools. I am much more familiar with python's syntax, so reading up the library reference and adding functionality shouldn't be all _that_ much a PITA. That said, the 'Perl Power tools' page mentions that it is (was ?) primarily a project to show 'what else perl can do'. Hence, it's mainly just an ego-booster for people out there who wish to show-off their skills ;-) pv. --=20 Prahlad Vaidyanathan Disks travel in packs. --LQksG6bCIzRHxTLp Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.4 (GNU/Linux) Comment: For info see http://www.gnupg.org iD8DBQE8RObPIKhjOSElu4YRAkFZAJ9Lu5jTvlqVtUPmB/z571W/N9C7nACePHH7 lDaBdy6LZ058pi9VGnWHsDg= =H0qo -----END PGP SIGNATURE----- --LQksG6bCIzRHxTLp-- From urnerk@qwest.net Wed Jan 16 06:48:48 2002 From: urnerk@qwest.net (Kirby Urner) Date: Tue, 15 Jan 2002 22:48:48 -0800 Subject: [Tutor] Storing source files In-Reply-To: <006101c19e4c$334be700$ebe710ac@pc7345> Message-ID: <4.2.0.58.20020115224622.00d06b20@pop3.norton.antivirus> At 01:09 PM 1/16/2002 +0800, Paul Hartley wrote: >I would be interested to hear how experienced programmers organise their >source files and libraries in python. I don't know of one book that deals >with this question - they all assume files are stored in some root directory. > Actually, as of recent Pythons, there's some emphasis on using /Lib/site-packages for 3rd party and user-defined code. >A related issue is how would you organise your modules and classes - all >in one library directory or would you use some directory structure. > >Given you have developed a whole pile of classes or modules, how are these >documented so you can find the one you need when you need it? No one likes >documentation and it always gets out of date - I realise I am searching >for the holy grail with this one!! > >Paul The package structure has been useful -- grouping modules together in a subdirectory and treating these as a unit via __init__.py is an important organizational strategy. Kirby From slime@vsnl.net Wed Jan 16 09:39:56 2002 From: slime@vsnl.net (Prahlad Vaidyanathan) Date: Wed, 16 Jan 2002 09:39:56 GMT Subject: [Tutor] Python implementation of Unix tools In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66C288@mbtlipnt02.btlabs.bt.co.uk> References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C288@mbtlipnt02.btlabs.bt.co.uk> Message-ID: <20020116073819.GA12938@marvin.clone> Hi, On Tue, 15 Jan 2002 alan.gauld@bt.com spewed into the ether: > There is but I've forgotten the name. Please point me to a URL if and when you find it. Poked around for a while but nothing turned up. pv. -- Prahlad Vaidyanathan Man is an animal that makes bargains: no other animal does this-- no dog exchanges bones with another. -- Adam Smith From alan.gauld@bt.com Wed Jan 16 11:31:40 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Wed, 16 Jan 2002 11:31:40 -0000 Subject: [Tutor] Removing itens from a list Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C28C@mbtlipnt02.btlabs.bt.co.uk> > I think I should use re module, but dont now how to use it. > Do you know any site that explain the use of re module or > regex with python ? Go to the informIT.com and register(if you haven't already) Search for my name and you should find an article on the use of regular expressions generally, illustrated in python(naturally) If you buy my book(!) you get an expanded version of the same article with a case study showing it in practice. Alan Gauld. Author of the 'Learning to Program' web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld@bt.com Wed Jan 16 11:53:47 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Wed, 16 Jan 2002 11:53:47 -0000 Subject: [Tutor] How powerful is Python? Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C28D@mbtlipnt02.btlabs.bt.co.uk> > Exactly how powerful is Python? Very powerful. In fact for running python programs there's nothing I know of that's more powerful. Of course if you want to compile C++ programs it's not so good, in fact it's pretty poor. And if you want to do desktop publishing using python will be a chore. In other words it depends what you want to do. For general purppose programming in the real world Python is excellent. > Does it come close to C It exceeds C by quite a way. > other such languages? There are other languages which are as powerful, there are a few which are more powerful. > Is it very fast? Assuming you mean "Do the finished programs run fast?" rather than "Is it fast to build programs?"... [ These two approaches to "Is it fast" tend to be mutually exclusive.] No, assembler is the fastest and python's a long way behind that. But fast is not normally a measure of a programming language's "power". Power is usually measured in terms of how much work does the programmer need to do to achieve a given amount of computing work. [Note: there are other definitions, but this is the one that seems most appropriate to Python!] > why do I keep getting what seems to be every Python tutor > e-mail even if it has nothing to do with me? Probably because you subscribed to the tutor mailing list. > It's cluttering my e-mail account.:/ Try switching your list options to digest mode. That way you only get a few mails per day - each containing up to 16 messages within it. Alan G. From alan.gauld@bt.com Wed Jan 16 12:02:33 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Wed, 16 Jan 2002 12:02:33 -0000 Subject: [Tutor] facing a new project Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C28E@mbtlipnt02.btlabs.bt.co.uk> > A rough design and working code sounds like a good approach. > According to Richard Gabriel, it's more important to get > something out that sorta works and then gradually fix that This guy obviously never worked as a maintenance programmer. Seriously, I spend a lot of my time fixing systems where not enough thought went into design - sometimes none at all! Its still true that 80% of the cost of a program comes after the first release - bug fixes and enhancements. Lack of a design makes both much more difficult. BUT I would say its worth doing some prototyping to get the ideas of how it should work clear in your mind, then throw it all away and re-do it properly. The cost of recoding is usually recovered several times over downstream. The only exception to this rule is programs with known short lifespans. If you know you will only be using it once or for a few months then just hack it together whatever way works. But for this specific case you need to seriously consider how to data drive the scheduling algorithms, the people profiles etc. A bit of up front design will help. Alan g. From lonetwin@yahoo.com Wed Jan 16 12:31:01 2002 From: lonetwin@yahoo.com (lonetwin) Date: Wed, 16 Jan 2002 18:01:01 +0530 Subject: [Tutor] Help with tkinter application. Message-ID: <0201161801010D.17191@mercury.worli> Hi all, read on .. I work on linux, sometimes on X...My spelling sucks ...and I just *have* to get the right spelling as I'm editing, I just can't wait till I finish to run a spell checker on the thingy. So, I keep opening a xtrem window with a desktop shortcut (Ctrl-W), then type-in "ispell -a", then type in the word ...this works, eez good ... .... but hey I'm a lazy guy !! an' I haven't tinkered with tkinter much, so I decide to write TKSpell, a frontend to "ispell -a" and bind it to a desktop shortcut (BTW---even when I use X, I mostly use the keyboard, I LOVE WindowMaker that lets me do that). I thought it'd be easy....this is how far I got.....looks pretty ugly, needs touching/cleaning up, needs suggestions, that's why it's here, over to you code ... ====================================================================== #!/usr/bin/python import os from Tkinter import * class Spell: def __init__(self, word): if not word: return fin, fout = os.popen2('ispell -a') version = fout.readline() or "Ispell version unknown" fin.write(word) fin.close() self.result = self.intepret(fout.read()) def intepret(self, output): if output[0] == '*': return ('OK',) if output[0] == '+': return ('Root', output[2:].strip()) if output[0] == '-': return ('Compound', output[2:].strip()) if output[0] == '&': return ('Miss', output[2:].strip()) if output[0] == '?': return ('Guess', output[2:].strip()) if output[0] == '#': return ('Not Found',) def getResult(self): return self.result class Tkspell(Frame): def __init__(self, master=None): Frame.__init__(self, master) self.grid(ipadx=4, ipady=4) self.createWidgets() def createWidgets(self): self.entry = Entry(self) self.entry.grid(column=0, row=0, padx=8) self.entry.focus() self.Ok = Button(self, text="Check", activeforeground="blue", command=self.check) self.Ok.bind("", self.check) self.Ok.grid(column=1, row=0) def check(self, event): self.result = Spell(self.entry.get()).getResult() if self.result[0] in ['OK', 'Root', 'Compound', 'Not Found']: label = Label(self, text=' '.join([ x for x in self.result])) label.grid(column=0, row=1, columnspan=2) self.entry.selection_range(0, END) return 0 elif self.result[0] in ['Miss', 'Guess']: suggestions = self.result[1].split(":")[1].split(',') label = Label(self, text="Suggestions") label.grid(column=0, row=1, columnspan=2) ResultList = Listbox(self, height=len(suggestions)) for x in suggestions: ResultList.insert(END, x) ResultList.grid(column=0, row=2, columnspan=2, pady=4, sticky=EW) # print self.result if __name__ == '__main__': S = Tkspell() S.master.title("Tkspell") S.mainloop() ============================================== Please help ....if you've got the time to that is.... Peace Steve -- ---------------------------------------------- I get up each morning, gather my wits. Pick up the paper, read the obits. If I'm not there I know I'm not dead. So I eat a good breakfast and go back to bed. Oh, how do I know my youth is all spent? My get-up-and-go has got-up-and-went. But in spite of it all, I'm able to grin, And think of the places my get-up has been. -- Pete Seeger ---------------------------------------------- From alan.gauld@bt.com Wed Jan 16 12:58:53 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Wed, 16 Jan 2002 12:58:53 -0000 Subject: [Tutor] OK here goes nothing Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C292@mbtlipnt02.btlabs.bt.co.uk> > > Is my historyList the Classes you are referring to? No, you had a variable name with an upper cae first letter. He was simply saying that to other programmers that usually implies the name refers to a Class rather than a "normal" type object. > I think what Andy was telling you about is that it is a > convention of OOP to capitalise the words used in > class names, e.g. "class HistoryList". Why that > is, someone wiser in the ways of OO will have to > explain. :) Purely so that you can distinguish between objects which are classes and those which are instances of classes. Thus: class Foo: pass foo = Foo() Now when we refer to foo we know its the instance and Foo is the class. This becomes important when we get into murky territory like metaclass programming where we regularly pass classes around as objects def getInstance(c): if type(c) == type.Class: ## untested, maybe slightly wrong print "you passed a class, here's an instance" return c() ## note we here create an instance else: print "You already gave me an instance..." return c ## we here return the original Now we can call this with our previous definitions: f = getInstance(Foo) # pass a class f = getInstance(foo) # pass an instance In both cases f now refers to an instance of Foo. Without the naming convention its hard to see the difference. Alan g. From alan.gauld@bt.com Wed Jan 16 13:09:11 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Wed, 16 Jan 2002 13:09:11 -0000 Subject: [Tutor] Help with tkinter application. Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C293@mbtlipnt02.btlabs.bt.co.uk> Looks OK but... > class Spell: > def __init__(self, word): > if not word: return > fin, fout =3D os.popen2('ispell -a') > version =3D fout.readline() or "Ispell version unknown" If fout.readline doesn't return anything then I suspect you have bigger problems than not knowing the Ispell version! Maybe some more error handling would be a good idea there. Also maybe its just me but it seems kind of back to front to *read* from fout and *write* to fin.... Alan g. From arcege@speakeasy.net Wed Jan 16 14:55:53 2002 From: arcege@speakeasy.net (Michael P. Reilly) Date: Wed, 16 Jan 2002 09:55:53 -0500 Subject: [Tutor] Storing source files In-Reply-To: <006101c19e4c$334be700$ebe710ac@pc7345>; from p.hartley@spitech.com on Wed, Jan 16, 2002 at 01:09:45PM +0800 References: <006101c19e4c$334be700$ebe710ac@pc7345> Message-ID: <20020116095553.C1549@speakeasy.net> On Wed, Jan 16, 2002 at 01:09:45PM +0800, Paul Hartley wrote: > I would be interested to hear how experienced programmers organise > their source files and libraries in python. I don't know of one book > that deals with this question - they all assume files are stored in > some root directory. For me, and most of the companies I've worked for, source files get stored in a "version control system." Probably the most used system for such is CVS; there are a couple books on it these days, but only a couple. As for how to arrange your files into directories, that is more of an art: what organization works for that specific project. (Actually, my career was advising companies just how to do that before I got ill.) There are a few text books, but "software configuration management" is not taught in colleges. In fact the best you can hope for is is that you know someone who has an idea of what do to for long-term projects. For the most part, unless you have a large, long-lasting project, there is little need to put one application's source files into more than one directory. But I would not suggest you store the source files of all your applications in one directory, each application should get its own place. > A related issue is how would you organise your modules and classes - > all in one library directory or would you use some directory > structure. I put my own modules either in: 1. in PYTHONPATH, when they deal with just my own personal operations; 2. in site-packages, when they may be something pretty generic (I have a UNIX system, and write code for operations with other accounts for maintenance which uses things here); 3. in the application directory when they are only used by the application. > Given you have developed a whole pile of classes or modules, how are > these documented so you can find the one you need when you need it? No > one likes documentation and it always gets out of date - I realise I > am searching for the holy grail with this one!! Personally, I don't create dozens and dozens of tiny small modules that do little things, so my libraries don't get hugely cluttered. But most of them have documentation in the beginning that is fairly easy to glean when opened in a viewer. Also what is important is giving good names to the modules. When you look for it, you want to find it easily from just the name. Is there something in particular you want to know? -Arcege From James.Alexander.McCarney@Cognicase.com Wed Jan 16 17:23:26 2002 From: James.Alexander.McCarney@Cognicase.com (McCarney, James Alexander) Date: Wed, 16 Jan 2002 12:23:26 -0500 Subject: [Tutor] Planning to write Python scripts and programs (migrating a Basic macro) Message-ID: <23FD7B1A77E8D211BCB900001D108C02018B2913@camelot> Hi Tutorfolk! Thanks for your information of the other day. I am progressing through the various tools out there, such as Learning Python book, and the various brilliant tutorials. I have a perfect candidate (maybe?) for my first real-life Py project, and I would appreciate your comments (if you would be so kind). I have a Word (Basic) macro that I run against images in docs that I create to resize them. I wonder if I could either rewrite it totally in Py or have Py open the document file, execute the macro, save the file, and quit. The platform I run under is Windows 2000, the Microsoft Word version is 2000, and I have upgraded to Python 2.2. Possibly the quick/dirty way is to have Py open the doc run the Basic macro and close? To begin to attempt the Py (pseudo)code: def OpenDoc(doc_filename): import Some Module # don't know ??? # utter Python confusion ??? ??? I will try to work on this. This mail is sort of my brain-cramp output now But if someone could point me in the direction to start on my Confucian 1000-mile journey... I would be grateful. The Basic code is this (shield your eyes or snip it out now, cos it's not Py!!!) Sub ReduceTo50() ' ' ReduceTo50 Macro ' Macro created 09/12/01 by James Alexander McCarney ' Dim lngX As Long On Error Resume Next 'Important or the code may puke For lngX = 1 To ActiveDocument.InlineShapes.Count ActiveDocument.InlineShapes(lngX).Select If (ActiveDocument.InlineShapes(lngX).Type = wdInlineShapeLinkedPicture Or ActiveDocument.InlineShapes(lngX).Type = wdInlineShapePicture) Then Selection.InlineShapes(1).ScaleHeight = 40 'Set the height to whatever you want 50, 40, 30 (for smaller pix) Selection.InlineShapes(1).ScaleWidth = 40 'Set the height to whatever you want 50, 40, 30 (for smaller pix) End If Next lngX End Sub James Alexander McCarney (450) 928-3386 x2262 Cognicase - M3i Systems, 1111 Saint-Charles Avenue West 11th Floor, East Tower, Longueuil, Quebec, J4K 5G4 Canada http://www.m3isystems.com mailto:James.Alexander.McCarney@Cognicase.com From alan.gauld@bt.com Wed Jan 16 17:26:41 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Wed, 16 Jan 2002 17:26:41 -0000 Subject: [Tutor] Storing source files Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C29D@mbtlipnt02.btlabs.bt.co.uk> > For me, and most of the companies I've worked for, source > files get stored in a "version control system." Absolutely. Even on my home PC I use CVS or RCS to control source code changes. Its saved me many times from ill conceived changes to what was working code ;-) > Probably the most used system for such is CVS; Of the free tools that's true but Microsoft houses tend to use either Merant PVCS or Microsoft SourceSafe. Really big shops with lots of money may use Rational ClearCase or Continuus or several othersuch tools. One very good large scale tool which is cheap is Razor. > As for how to arrange your files into directories, > that is more of an art: what organization works for > that specific project. There are, as Michael says, several ways to do this but the one aspect that you asked about that he didn't mention is shared code - which with python can be quite a lot of it! For that we usually create a global Library directory structure organised into 3 areas - tools/production/untested The first is for little utility type modules that have been used on several projects and informally tested but not necessarily gone through formal QA The second is code gleaned from production projects which has been subject to rigorous tessts and changes to which could have serious ramifications to other projects. The third is somebody's good idea. It worked for them but hasn't really been tested much at all. Code from here may eventually wind up in the first bin after enough people use it.... We do this foreach of C++, Perl, VB and Java code - we don't have many python users... Hope that helps, Alan g. Author of the 'Learning to Program' web site http://www.freenetpages.co.uk/hp/alan.gauld From dyoo@hkn.eecs.berkeley.edu Wed Jan 16 18:27:48 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 16 Jan 2002 10:27:48 -0800 (PST) Subject: [Tutor] facing a new project (fwd) Message-ID: ---------- Forwarded message ---------- Date: Wed, 16 Jan 2002 03:58:15 -0500 From: kirk Bailey To: Danny Yoo Subject: Re: [Tutor] facing a new project Danny Yoo wrote: > > On Wed, 16 Jan 2002 mikalzet@libero.it wrote: > > > On Mon, 14 Jan 2002, glidedon wrote: > > > > > I'm new to programming, new to Python and need tutoring :-) > > > ( I also am an old dog trying to learn new tricks ) > > > > Sounds like we've got a lot in common. At least; I'm a babe to > > programming, but I am an old dog ... probably a bit past the age were > > most people take programming up. > > Down with ageism! > > I'm serious. It's wonderful to have people of different ages here. > Where else can we do something like this? *grin* > I concurr. although 48, I am like a 19 year old going tocollege for compsci for the first time. yayrah, Tutor! Wahoo, Python! > > If I ever wished to seriously face a new project of this sort, what is > > the best way to go about it ? close your eyes, and jump in screaming wildly like I did. > > First make a gross design of the whole > > thing ( database schema, classes etc. ) and then start tackling it, or > > start with small bits of code like the truck drivers log book and then > > just try to extend it bit by bit ? Not that I'm yet really convinced I > > mean to do this ... > > A rough design and working code sounds like a good approach. According to > Richard Gabriel, it's more important to get something out that sorta works > and then gradually fix that, rather than try to get everything perfect at > once. I believe he termed the phrase "Worse Is Better": > > http://www.dreamsongs.com/WorseIsBetter.html > > So I wouldn't obsess too much about design, since your program's > requirements sound pretty fluid. > Design? What's that? Well, it's not that bad, I had a rough flowchart in my head... sort of... > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- -Respectfully, -Kirk D Bailey Consulting Loose Cannon end www.howlermonkey.net highprimate@howlermonkey.net www.sacredelectron.org idiot1@netzero.net www.tinylist.org grumpy@tinylist.org ---------------------------------------------------- Sign Up for NetZero Platinum Today Only $9.95 per month! http://my.netzero.net/s/signup?r=platinum&refcd=PT97 From idiot1@netzero.net Wed Jan 16 19:11:02 2002 From: idiot1@netzero.net (kirk Bailey) Date: Wed, 16 Jan 2002 14:11:02 -0500 Subject: [Tutor] strange error on a list Message-ID: <3C45D046.ED580D76@netzero.net> Gang, this one still puzzles me. Every list is fine- but this one. Here is the alias in the /etc/aliases file: # evil-humor:"|/www/www.howlermonkey.net/cgi-bin/TLpost.py evil-humor" # GMbrianpenn:"|/www/www.howlermonkey.net/cgi-bin/TLpost.py GMbrianpenn" # (for what it's worth, the list above it (evil-humor) works just fine.) Here is the error in the Mail log(beware word wrap!); Jan 16 13:56:40 ns sendmail[6359]: g0GIrj206358: to="|/www/www.howlermonkey.net/cgi-bin/TLpost.py GMbrianpenn", ctladdr= (1/0), delay=00:02:54, xdelay=00:02:52, mailer=prog, pri=30489, dsn=5.3.0, stat=unknown mailer error 1 here is the email that returned: ---------------------------------------------------------------------------------------------- Subject: Returned mail: see transcript for details Date: Wed, 16 Jan 2002 13:56:40 -0500 (EST) From: Mail Delivery Subsystem To: The original message was received at Wed, 16 Jan 2002 13:53:46 -0500 (EST) from mail9.wlv.netzero.net [209.247.163.66] ----- The following addresses had permanent fatal errors ----- "|/www/www.howlermonkey.net/cgi-bin/TLpost.py GMbrianpenn" (reason: 1) (expanded from: ) ----- Transcript of session follows ----- 554 5.3.0 "|/www/www.howlermonkey.net/cgi-bin/TLpost.py GMbrianpenn"... unknown mailer error 1 (Unknown mailer error???) Reporting-MTA: dns; ns.howlermonkey.net Received-From-MTA: DNS; mail9.wlv.netzero.net Arrival-Date: Wed, 16 Jan 2002 13:53:46 -0500 (EST) Final-Recipient: RFC822; GMbrianpenn@howlermonkey.net X-Actual-Recipient: X-Unix; |/www/www.howlermonkey.net/cgi-bin/TLpost.py GMbrianpenn Action: failed Status: 5.0.0 Diagnostic-Code: X-Unix; 1 Last-Attempt-Date: Wed, 16 Jan 2002 13:56:40 -0500 (EST) Subject: test GMbrianpenn Date: Wed, 16 Jan 2002 13:53:32 -0500 From: Kirk Bailey Organization: Silas Dent Memorial Cabal of ERIS Esoteric and hot Dog Boiling Society(fnord)! To: GMbrianpenn@howlermonkey.net test -- -Respectfully, -Kirk D Bailey Consulting Loose Cannon end www.howlermonkey.net highprimate@howlermonkey.net www.sacredelectron.org idiot1@netzero.net www.tinylist.org grumpy@tinylist.org ---------------------------------------------------- Sign Up for NetZero Platinum Today Only $9.95 per month! http://my.netzero.net/s/signup?r=platinum&refcd=PT97 ----------------------------------------------------------------------------------------------- Now I have played with this undo perdition und damnation, und it ist ein sheistderhaven! It is driving me machugana, bonkers, to distraction, etc. ERIS is playing with me, and she forgot to use a lubricant, and I don't like it. Please advise. -- -Respectfully, -Kirk D Bailey Consulting Loose Cannon end www.howlermonkey.net highprimate@howlermonkey.net www.sacredelectron.org idiot1@netzero.net www.tinylist.org grumpy@tinylist.org ---------------------------------------------------- Sign Up for NetZero Platinum Today Only $9.95 per month! http://my.netzero.net/s/signup?r=platinum&refcd=PT97 From idiot1@netzero.net Wed Jan 16 19:29:41 2002 From: idiot1@netzero.net (kirk Bailey) Date: Wed, 16 Jan 2002 14:29:41 -0500 Subject: [Tutor] Ethics in programming Message-ID: <3C45D4A5.ED9310E@netzero.net> Gang, I still amd thinking about how to handle large lists. and how to impede spam. I can use a method of a second alias to sent out the large list, and the original list is simply the address for that alias. TL become in effect a message processor, and the second alias handles the huge outbound list transmission. This is the method used by majordomo. However, that second alias is totally open to spam input. This uses the sendmail function :include: which when aliases are compiled by sendmail, includes the reference to the subscriber file in it's definition. such looks rather like: fubar::include:/pathtofile/subscriberfilename If you ever built a sendmail or a majordomo list, you know the species. It is WIDE OPEN to spam input. This is why I considered a guardian program, but that slows things down again! This is not a normal consideration, but if someone wants to offer an Ezine with 50,000 readers, it get's rather important. Another correspondant wrote to me showing me how to directly talk to sendmail and issue it commands and information, and this looks intresting; I have to go read that manual MORE and mess with Critter's mind some more andsee what happens. IF I implode, you know I flipped the wrong switch. -- -Respectfully, -Kirk D Bailey Consulting Loose Cannon end www.howlermonkey.net highprimate@howlermonkey.net www.sacredelectron.org idiot1@netzero.net www.tinylist.org grumpy@tinylist.org ---------------------------------------------------- Sign Up for NetZero Platinum Today Only $9.95 per month! http://my.netzero.net/s/signup?r=platinum&refcd=PT97 From flash1210@hotmail.com Wed Jan 16 20:25:59 2002 From: flash1210@hotmail.com (Frank Holmes) Date: Wed, 16 Jan 2002 12:25:59 -0800 Subject: [Tutor] writing & reading files Message-ID: Still working with this little phonebook program. When it runs, if 'phoneyold' doesn't exist it creates it and writes data to file. Problem is, if I close the program, open it again and again add entries it overwrites the file and none of the previous entries exist. I have tried replacing the 'w' in f=open('phoneyold','w') with 'a' to append to the file (problem is it is a dictionary) but although when I check the data file the entry is there, I cannot retrieve it. I have also tried 'w+' to append, but again all previous data is dumped when I add. Again I am stumped. How can I add data, close the file, re open it , add again and not dump previous data? import pickle def add_name(): print 'Enter Name:' dname=raw_input() print 'Facility:' fname=raw_input() print 'phone1:' hnum=raw_input() if hnum == " " : #in no huntline entered, hunt =NONE hnum='none' print'phone2:' ph=raw_input() print 'Pager:' pg=raw_input() print 'cell:' cop=raw_input() print 'Comments:' com=raw_input() l=(dname, fname, hnum, ph, pg, cop, com) d1[dname]=l f=open('phoneyold','w') pickle.dump(d1,f) f.close() def get_name(): print "enter name to search" name=raw_input() f=open('phoneyold','r') p_d1=pickle.load(f) if name in p_d1.keys(): g= p_d1[name] print 'Name:', g[0] print print 'place:', g[1] print print 'phone1:', g[2] print print 'Phone2:',g[3] print print 'Pager:', g[4] print print 'cell:', g[5] print print 'Comments:',g[6] f.close() d1={} while 1: print print "Hello, welcome to Docsearch." print print "Please enter selection:" print "Type '1' to search" print print "Type '2' to add name to database or 'quit' to exit" _________________________________________________________________ Send and receive Hotmail on your mobile device: http://mobile.msn.com From spray14@hotmail.com Wed Jan 16 20:44:14 2002 From: spray14@hotmail.com (james kellam) Date: Wed, 16 Jan 2002 15:44:14 -0500 Subject: [Tutor] dynamic printing Message-ID: Hi, Is there a module that allows one to print to a PRINTER instead of the screen? I can save it to a file and then go back with windows and hit File>Print.. I was hoping that I could make the program spit its' results out to the printer directly. thanks, james _________________________________________________________________ Send and receive Hotmail on your mobile device: http://mobile.msn.com From ylee12@uiuc.edu Wed Jan 16 21:20:03 2002 From: ylee12@uiuc.edu (Young-Jin Lee) Date: Wed, 16 Jan 2002 15:20:03 -0600 Subject: [Tutor] [Q] ConfigParser Message-ID: <014a01c19ed3$90111050$95757e82@visit2> Hi, I'm a newbie playing with Python. I have a problem using ConfigParser module. I created a config file in the working directory and tried to read it, but the following scripts gave me nothing. import ConfigParser cfg = ConfigParser.ConfigParser() cfg.read( 'test.cfg' ) # It returned None. Why can't ConfigParser module read the config file in the same directory? TIA. YJ From dyoo@hkn.eecs.berkeley.edu Wed Jan 16 21:38:25 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 16 Jan 2002 13:38:25 -0800 (PST) Subject: [Tutor] dynamic printing In-Reply-To: Message-ID: On Wed, 16 Jan 2002, james kellam wrote: > Is there a module that allows one to print to a PRINTER instead of the > screen? I can save it to a file and then go back with windows and hit > File>Print.. I was hoping that I could make the program spit its' > results out to the printer directly. Hi James, Yes, it's possible. You may want to look at the "Python and Win32 Programming" book: http://www.oreilly.com/catalog/pythonwin32 Chapter 10 of that book talks about Windows printing in a lot of detail. The author of that book mentions an example: http://www.faqts.com/knowledge_base/view.phtml/aid/4463 that shows how to do printing. I couldn't find a more substantial example, but at least it's a step in some direction. *grin* There's another entry in the FAQTS faq page: http://www.faqts.com/knowledge_base/view.phtml/aid/1504/fid/237 and the author recommends that, to be cross platform, you should probably just do save-to-file. There are Python modules that allow you to generate PDF files, and that's a good format that's easily printable. Here are links to a few modules that might help you: Piddle: http://piddle.sourceforge.net/ ReportLab: http://reportlab.com/download.html Good luck to you. From dyoo@hkn.eecs.berkeley.edu Wed Jan 16 21:48:23 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 16 Jan 2002 13:48:23 -0800 (PST) Subject: [Tutor] [Q] ConfigParser In-Reply-To: <014a01c19ed3$90111050$95757e82@visit2> Message-ID: On Wed, 16 Jan 2002, Young-Jin Lee wrote: > I have a problem using ConfigParser module. I created a config file in > the working directory and tried to read it, but the following scripts > gave me nothing. > > import ConfigParser > cfg = ConfigParser.ConfigParser() > cfg.read( 'test.cfg' ) # It returned None. > > Why can't ConfigParser module read the config file in the same > directory? ConfigParser's read() method is supposed to return None --- it's a "side-effect" function that doesn't have a useful return value. After calling read(), try using the get() method, and you should see useful values. Here's a small example that might help: ### from ConfigParser import ConfigParser, NoSectionError from StringIO import StringIO sample_input = StringIO(""" [General] name=Young Jin email=ylee12 """) config = ConfigParser() config.readfp(sample_input) print config.get("General", "name") print config.get("General", "email") try: print config.get("general", "email") except NoSectionError: print "Notice that ConfigParser is case-sensitive." ### Let's run this program and see what happens: ### [dyoo@tesuque dyoo]$ python configparser.py Young Jin ylee12 Notice that ConfigParser is case-sensitive. ### Hope this helps! From arcege@speakeasy.net Wed Jan 16 22:12:21 2002 From: arcege@speakeasy.net (Michael P. Reilly) Date: Wed, 16 Jan 2002 17:12:21 -0500 Subject: [Tutor] writing & reading files In-Reply-To: ; from flash1210@hotmail.com on Wed, Jan 16, 2002 at 12:25:59PM -0800 References: Message-ID: <20020116171221.D1549@speakeasy.net> On Wed, Jan 16, 2002 at 12:25:59PM -0800, Frank Holmes wrote: > > Still working with this little phonebook program. When it runs, if > 'phoneyold' doesn't exist it creates it and writes data to file. Problem is, > if I close the program, open it again and again add entries it overwrites > the file and none of the previous entries exist. I have tried replacing the > 'w' in f=open('phoneyold','w') with 'a' to append to the file (problem is it > is a dictionary) but although when I check the data file the entry is there, > I cannot retrieve it. I have also tried 'w+' to append, but again all > previous data is dumped when I add. Again I am stumped. How can I add data, > close the file, re open it , add again and not dump previous data? You have the right idea. But you are trying to update an object to a file, not just append new data. The open-file modes are only for where the data is placed, not how the data is. Try this: def add_name(): # we get the pickled dictionary from the file to update in the function # 'r+' means read-write, pointer at beginning of file, do not overwrite f = open('phoneyold', 'r+') # we'll overwrite the global 'd1' variable since it does not seem to # be used in get_name() anyway, we could make it global tho d1 = pickle.load(f) dname = raw_input('Enter Name:\n') # the prompt can be here too fname = raw_input('Facility:\n') hnum = raw_input('Phone1:\n') if hnum == "": hnum = "none" ph = raw_input('Phone2:\n') pg = raw_input('Pager:\n') cop= raw_input('Cell:\n') com= raw_input('Comments:\n') # adds to the existing dictionary from the file d1[dname] = (dname, fname, hnum, ph, pg, cop, com) f.seek(0) # rewind to the beginning of the file to write # pickle the dictionary back to the file, overwritten the old data pickle.dump(d1, f) f.close() The problem here seems to be trying to keep the file and the global d1 object in sync. About the only way to do that would be to create a new dictionary-like class so when the dictonary is updated, the data is written to the file. Luckily, there is already something that does that. Look into the shelve module, it creates a new dictionary like object which reads and writes pickled Python objects to a file. With the shelve module, the d1 object could be used in both the add_name() and get_name() modules, without having to reopen the file each time. -Arcege > import pickle > > def add_name(): > print 'Enter Name:' > dname=raw_input() > print 'Facility:' > fname=raw_input() > print 'phone1:' > hnum=raw_input() > if hnum == " " : #in no huntline entered, hunt =NONE > hnum='none' > print'phone2:' > ph=raw_input() > print 'Pager:' > pg=raw_input() > print 'cell:' > cop=raw_input() > print 'Comments:' > com=raw_input() > l=(dname, fname, hnum, ph, pg, cop, com) > d1[dname]=l > f=open('phoneyold','w') > pickle.dump(d1,f) > f.close() > > > > def get_name(): > print "enter name to search" > name=raw_input() > f=open('phoneyold','r') > p_d1=pickle.load(f) > if name in p_d1.keys(): > g= p_d1[name] > print 'Name:', g[0] > print > print 'place:', g[1] > print > print 'phone1:', g[2] > print > print 'Phone2:',g[3] > print > print 'Pager:', g[4] > print > print 'cell:', g[5] > print > print 'Comments:',g[6] > f.close() > > > d1={} > while 1: > print > print "Hello, welcome to Docsearch." > print > print "Please enter selection:" > print "Type '1' to search" > print > print "Type '2' to add name to database or 'quit' to exit" From hall@phyast.nhn.ou.edu Wed Jan 16 21:46:25 2002 From: hall@phyast.nhn.ou.edu (Isaac Hall) Date: Wed, 16 Jan 2002 15:46:25 -0600 Subject: [Tutor] Dictionary questions Message-ID: <02011615553000.09964@ouhep1> Hi everyone, I usually read this mailing list multiple times every day, but I havent been able to do so for the last week or so, due to a rather heavy workload. anyway, in the work Im doing, it turns out I need to take a number that gets spit out of something, and using the information from several functions that could have created that number determine a) what function was used, and b) what its parameters were, knowing that they came from a particular set of numbers (some of them in a dictonary). so anyway, with that setup, here is my question: supposing I can determine all of this, is there a way to get the key back out of a dictonary simply by asking for the content. if not: is there a better structure to use which will make correlation between key and content (in this case, there will only be one to one mapping) by which I can get one by knowing the other and vice versa if anyone can help, I would surely appreciate it Thanks, Ike From urnerk@qwest.net Wed Jan 16 22:55:37 2002 From: urnerk@qwest.net (Kirby Urner) Date: Wed, 16 Jan 2002 14:55:37 -0800 Subject: [Tutor] Dictionary questions In-Reply-To: <02011615553000.09964@ouhep1> Message-ID: <4.2.0.58.20020116145421.015cac00@pop3.norton.antivirus> If it's really 1-to-1, you might want two dictionaries, one with a:b pairs where a is in set1, b in set2, the other with b:a pairs. That'd give you 2-way lookup. Kirby From scarblac@pino.selwerd.nl Wed Jan 16 23:04:05 2002 From: scarblac@pino.selwerd.nl (Remco Gerlich) Date: Thu, 17 Jan 2002 00:04:05 +0100 Subject: [Tutor] Dictionary questions In-Reply-To: <02011615553000.09964@ouhep1>; from hall@phyast.nhn.ou.edu on Wed, Jan 16, 2002 at 03:46:25PM -0600 References: <02011615553000.09964@ouhep1> Message-ID: <20020117000405.A24701@pino.selwerd.nl> On 0, Isaac Hall wrote: (snip explanation of something I can't quite understand but not relevant to the question) > supposing I can determine all of this, is there a way to get the key back out > of a dictonary simply by asking for the content. Sort of: take all the keys, and for each key, check if its value is the value we're looking for. Fast for small dictionaries, slow for huge dictionaries. It doesn't "feel" fast (and it's O(len(dict))), but in most cases it should do fine. for key in dict.keys(): if dict[key] == valuewerelookingfor: return key > if not: > is there a better structure to use which will make correlation between key > and content (in this case, there will only be one to one mapping) by which > I can get one by knowing the other and vice versa Easiest would be to simply use two dictionaries: one with key->value pairs and one with value->key pairs. This is possible only because of the one-to-one mapping, of course. You could put the two into a class, so that you never forget to update both, something like class DoubleDict: def __init__(self): self.key_to_val = {} self.val_to_key = {} def set(self, key, value): self.key_to_val[key] = value self.val_to_key[value] = key def get_value(self, key): return self.key_to_val[key] def get_key(self, value): return self.val_to_key[value] Use with dict = DoubleDict() dict.set("Key", "Value") print dict.get_key("Value") It's just a quick framework of course, but you get the idea. -- Remco Gerlich From jimmy_130@lycos.com Wed Jan 16 22:50:11 2002 From: jimmy_130@lycos.com (James M Lang) Date: Wed, 16 Jan 2002 17:50:11 -0500 Subject: [Tutor] Why does pygame still not work? Message-ID: I tried running the monkey source and got this: Traceback (most recent call last): File "C:\Python22\monkey", line 14, in ? if not pygame.font: print 'Warning, fonts disabled' AttributeError: 'module' object has no attribute 'font' WHY? From rufmetal@rogers.com Thu Jan 17 03:27:12 2002 From: rufmetal@rogers.com (Chris Keelan) Date: Wed, 16 Jan 2002 22:27:12 -0500 Subject: [Tutor] test -ignore Message-ID: <20020117032712.ED07320BA9@rufmetal> From rufmetal@rogers.com Thu Jan 17 03:35:16 2002 From: rufmetal@rogers.com (Chris Keelan) Date: Wed, 16 Jan 2002 22:35:16 -0500 Subject: [Tutor] test -ignore Message-ID: <20020117033517.455D720BA9@rufmetal> Dang Rogers changed their e-mail settings! - C From rufmetal@rogers.com Thu Jan 17 03:50:02 2002 From: rufmetal@rogers.com (Chris Keelan) Date: Wed, 16 Jan 2002 22:50:02 -0500 Subject: [Tutor] test -ignore Message-ID: <3C4649EA.70701@rogers.com> Dang Rogers. They went and changed their e-mail settings! From wilson@visi.com Thu Jan 17 04:38:01 2002 From: wilson@visi.com (Tim Wilson) Date: Wed, 16 Jan 2002 22:38:01 -0600 (CST) Subject: [Tutor] recursive factoring Message-ID: Hi everyone, I've been trying to write a little function that will generate a list of all the prime factors of a given integer. This seems like the sort of problem that maps very well to a recursive algorithm. Take the prime factors of 24 for example: 24 / \ 2 12 / \ 2 6 / \ 2 3 The prime factors are 2, 2, 2, and 3. If that isn't recursion waiting to happen, I don't know what is. :-) Unfortunately, I can't get my function to work. I just don't grok recursion. Here's what I've tried (one version of it anyway): import math def isPrime(n): if n in [1, 2]: return 1 for i in [2] + range(3, math.sqrt(n)+1, 2): if n % i == 0: return 0 return 1 def factor(n, factors=[]): if isPrime(n): factors.append(n) return factors else: for i in range(2, math.sqrt(n)+1): if n % i == 0: factor(n/i, factors) This is quite broken (it returns 'None'), but I hope you can see where I was headed. Any suggestions? -Tim -- Tim Wilson | Visit Sibley online: | Check out: Henry Sibley HS | http://www.isd197.org | http://www.zope.com W. St. Paul, MN | | http://slashdot.org wilson@visi.com | | http://linux.com From urnerk@qwest.net Thu Jan 17 05:09:55 2002 From: urnerk@qwest.net (Kirby Urner) Date: Wed, 16 Jan 2002 21:09:55 -0800 Subject: [Tutor] recursive factoring In-Reply-To: Message-ID: <4.2.0.58.20020116210225.00cd4e90@pop3.norton.antivirus> > >Any suggestions? > >-Tim This change to your factor function seems to work: def factor(n): if isPrime(n): return [n] for i in range(2, math.sqrt(n)+1): if isPrime(i) and n%i==0: return [i] + factor(n/i) Kirby From idiot1@netzero.net Thu Jan 17 05:09:22 2002 From: idiot1@netzero.net (kirk Bailey) Date: Thu, 17 Jan 2002 00:09:22 -0500 Subject: [Tutor] PRINTING A GIF IMAGE Message-ID: <3C465C82.2F885873@netzero.net> I wanted to display the pythonpowered.gif image in a script, and inclluded a print line with an html image tag. The thing BARKED LIKE A DOG and TRIED TO EXECUTE THE IMAGE. The html was pristine, completely right. W.T.F.????? I took it out. But why? -- -Respectfully, -Kirk D Bailey Consulting Loose Cannon end www.howlermonkey.net highprimate@howlermonkey.net www.sacredelectron.org idiot1@netzero.net www.tinylist.org grumpy@tinylist.org ---------------------------------------------------- Sign Up for NetZero Platinum Today Only $9.95 per month! http://my.netzero.net/s/signup?r=platinum&refcd=PT97 From urnerk@qwest.net Thu Jan 17 05:31:21 2002 From: urnerk@qwest.net (Kirby Urner) Date: Wed, 16 Jan 2002 21:31:21 -0800 Subject: [Tutor] recursive factoring In-Reply-To: Message-ID: <4.2.0.58.20020116212648.01998f00@pop3.norton.antivirus> Here's another approach which doesn't keep scanning the same numbers over and over for primes. Instead, a sieve is run against n right off the bat, and then isprime just uses this as a lookup list: class Primes: def __init__(self,n): self.primes = sieve(n) def __call__(self,val): if val in self.primes: return 1 else: return 0 def factor(n): isprime = Primes(n) def getnext(n): if isprime(n): return [n] for i in range(2, math.sqrt(n)+1): if isprime(i) and n%i==0: return [i] + getnext(n/i) return getnext(n) But of course this means you need a sieve function as well. Here's one: def sieve(n): """ In-place sieving of odd numbers, adapted from code by Mike Fletcher """ candidates = range(3, n+1, 2) # start with odds for p in candidates: if p: # skip zeros if p*p>n: break # done for q in xrange(p*p, n+1, 2*p): # sieving candidates[(q-3)/2] = 0 return [2] + filter(None, candidates) # [2] + remaining nonzeros Kirby From urnerk@qwest.net Thu Jan 17 05:36:41 2002 From: urnerk@qwest.net (Kirby Urner) Date: Wed, 16 Jan 2002 21:36:41 -0800 Subject: [Tutor] recursive factoring In-Reply-To: <4.2.0.58.20020116210225.00cd4e90@pop3.norton.antivirus> References: Message-ID: <4.2.0.58.20020116213354.019bc350@pop3.norton.antivirus> At 09:09 PM 1/16/2002 -0800, Kirby Urner wrote: >>Any suggestions? >> >>-Tim > >This change to your factor function seems to work: > > def factor(n): > if isPrime(n): > return [n] > for i in range(2, math.sqrt(n)+1): > if isPrime(i) and n%i==0: > return [i] + factor(n/i) > >Kirby > OK, one more thing -- isn't the version below more efficent than the one above? I don't know for sure. Seems it would be. def factor(n): if isPrime(n): return [n] for i in range(2, math.sqrt(n)+1): if isPrime(i) and n%i==0: break return [i] + factor(n/i) Kirby From idiot1@netzero.net Thu Jan 17 06:19:10 2002 From: idiot1@netzero.net (kirk Bailey) Date: Thu, 17 Jan 2002 01:19:10 -0500 Subject: [Tutor] sORRY Message-ID: <3C466CDE.D21B1605@netzero.net> someone on the GMbrianpenn list closed an account and did not tell us od come and do the wtright thing and unsubscribe. We jus tdiscovered the error fed back from sendmail when it cannot connect to the account, the error comnig back blows the acript at that point- and remaining members do nto get the message, but the submiting member DOES get a error message. Removing old members one at a time, I discovered which ones were doing it, and they are not disrupting it any more. I need to set up a Try:/Except ERROR: block with a small program and a tiny dummy message, and see what the errors look like, and prepare to handle them. This shall surely show up again. Anyone familiar with the python aspects of this? BTW, GMbrianpenn is working fine. there is no problem with the list, or the software- except that a dead account can raise havoc. -- -Respectfully, -Kirk D Bailey Consulting Loose Cannon end www.howlermonkey.net highprimate@howlermonkey.net www.sacredelectron.org idiot1@netzero.net www.tinylist.org grumpy@tinylist.org ---------------------------------------------------- Sign Up for NetZero Platinum Today Only $9.95 per month! http://my.netzero.net/s/signup?r=platinum&refcd=PT97 From kimtitu@yahoo.com Thu Jan 17 06:26:30 2002 From: kimtitu@yahoo.com (Titu Kim) Date: Wed, 16 Jan 2002 22:26:30 -0800 (PST) Subject: [Tutor] How to ignore some decimal values? Message-ID: <20020117062630.50579.qmail@web14708.mail.yahoo.com> Hi there, Do someone has any idea on keeping the floor value of a fixed decimal point n? For instance: a=12.3451 b=0.5699 c=0.0 How can i make a,b, and c become float values as a=12.34 b=0.56 c=0.00 if my n=2. If n=3 a=12.345 b=0.569 c=0.000 Thanks for any suggestion? Regards, Kim Titu __________________________________________________ Do You Yahoo!? Send FREE video emails in Yahoo! Mail! http://promo.yahoo.com/videomail/ From dyoo@hkn.eecs.berkeley.edu Thu Jan 17 06:56:23 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 16 Jan 2002 22:56:23 -0800 (PST) Subject: [Tutor] PRINTING A GIF IMAGE In-Reply-To: <3C465C82.2F885873@netzero.net> Message-ID: On Thu, 17 Jan 2002, kirk Bailey wrote: > I wanted to display the pythonpowered.gif image in a script, and > inclluded a print line with an html image tag. The thing BARKED LIKE A > DOG and TRIED TO EXECUTE THE IMAGE. The html was pristine, completely > right. We need more information; since it's surprising to you, it's probably also a complete mystery to us. *grin* Successful bug hunting involves looking at the clues, and keeping our eyes open. We need do say exactly why we think there's a bug, what we expected to see, and what happened instead. Most importantly, we have to fight the impulse to make prejudgements on our own code. Here are a few questions that might help us understand the context of the bug: Can you show us the string you printed? What exactly tried to execute the image: Python, or the web browser, or...? At what part of your program were we in before doing this? Was this for CGI, or a standalone program? What happens when we vary the content of the image tag? From lonetwin@yahoo.com Thu Jan 17 10:25:53 2002 From: lonetwin@yahoo.com (lonetwin) Date: Thu, 17 Jan 2002 15:55:53 +0530 Subject: [Tutor] Help with tkinter application. In-Reply-To: <0201161801010D.17191@mercury.worli> References: <0201161801010D.17191@mercury.worli> Message-ID: <02011715555300.20468@mercury.worli> Hi All, OK, so I didn't ask my question properly, my fault....I was hoping someone would cut-paste the code and try it out. Anyways, I still could use some help. Hey Alan, thanx for your reply : ======================================== > Looks OK but... > > > class Spell: > > def __init__(self, word): > > if not word: return > > fin, fout = os.popen2('ispell -a') > > version = fout.readline() or "Ispell version unknown" > > > If fout.readline doesn't return anything then I suspect > you have bigger problems than not knowing the Ispell version! > Maybe some more error handling would be a good idea there. Re: Right-O, will do that ....(after I get it working alrite ;)) > Also maybe its just me but it seems kind of back to > front to *read* from fout and *write* to fin.... Re: fin is input to the command, and fout is it's output, that made more sense to me than associating the names with read() and write(). I can't think too hard, it hurts :) ============================================ OK, Now here are the problems, I'd like to TkSpell to o Display a window like so: ___________________ [_________________[x] | ________ | |[|_______] [CHECK] | +===================+ This it does, The entry box gets focus o Now, when I type in a word and press [check], it should display a label saying either i) OK/ROOT/Compound if the spelling was correct and export the word in the clipboard or ii) MISS/GUESS if the spelling was incorrect and a listbox of suggestions Fact is ....it does these things too..... o Problem is, if I type in another word and press [check], the Label box and Listbox do not get redrawn. Also, after I choose a word from the suggeted-correct spellings, I would like to export that word to the clipbord. Any suggestions ??? Peace Steve Here's the code again: ======================================================== #!/usr/bin/python import os from Tkinter import * class Spell: def __init__(self, word): if not word: return fin, fout = os.popen2('ispell -a') version = fout.readline() or "Ispell version unknown" fin.write(word) fin.close() self.result = self.intepret(fout.read()) def intepret(self, output): if output[0] == '*': return ('OK',) if output[0] == '+': return ('Root', output[2:].strip()) if output[0] == '-': return ('Compound', output[2:].strip()) if output[0] == '&': return ('Miss', output[2:].strip()) if output[0] == '?': return ('Guess', output[2:].strip()) if output[0] == '#': return ('Not Found',) def getResult(self): return self.result class Tkspell(Frame): def __init__(self, master=None): Frame.__init__(self, master) self.grid(ipadx=4, ipady=4) self.createWidgets() def createWidgets(self): self.entry = Entry(self) self.entry.grid(column=0, row=0, padx=8) self.entry.focus() self.Ok = Button(self, text="Check", activeforeground="blue", command=self.check) self.Ok.bind("", self.check) self.Ok.grid(column=1, row=0) def check(self, event): self.result = Spell(self.entry.get()).getResult() if self.result[0] in ['OK', 'Root', 'Compound', 'Not Found']: label = Label(self, text=' '.join([ x for x in self.result])) label.grid(column=0, row=1, columnspan=2) self.entry.selection_range(0, END) return 0 elif self.result[0] in ['Miss', 'Guess']: suggestions = self.result[1].split(":")[1].split(',') label = Label(self, text="Suggestions") label.grid(column=0, row=1, columnspan=2) ResultList = Listbox(self, height=len(suggestions)) for x in suggestions: ResultList.insert(END, x) ResultList.grid(column=0, row=2, columnspan=2, pady=4, sticky=EW) # print self.result if __name__ == '__main__': S = Tkspell() S.master.title("Tkspell") S.mainloop() ======================================================= -- ---------------------------------------------- I get up each morning, gather my wits. Pick up the paper, read the obits. If I'm not there I know I'm not dead. So I eat a good breakfast and go back to bed. Oh, how do I know my youth is all spent? My get-up-and-go has got-up-and-went. But in spite of it all, I'm able to grin, And think of the places my get-up has been. -- Pete Seeger ---------------------------------------------- From lonetwin@yahoo.com Thu Jan 17 11:55:52 2002 From: lonetwin@yahoo.com (lonetwin) Date: Thu, 17 Jan 2002 17:25:52 +0530 Subject: [Tutor] Help with tkinter application. Message-ID: <02011717255200.21675@mercury.worli> Hi Once Again, :) I made a few changes, now the label gets redrawn, also, besides being exported to the clipboard, the entry box gets focus after a (correctly spelled) word is checked. The only problem now is redrawing the listbox or making it go away after entering a second word to check. the code : ================================================== #!/usr/bin/python import os from Tkinter import * class Spell: def __init__(self, word): if not word: return fin, fout = os.popen2('ispell -a') version = fout.readline() or "Ispell version unknown" fin.write(word) fin.close() self.result = self.interpret(fout.read()) def interpret(self, output): if output[0] == '*': return ('OK',) if output[0] == '+': return ('Root', output[2:].strip()) if output[0] == '-': return ('Compound', output[2:].strip()) if output[0] == '&': return ('Miss', output[2:].strip()) if output[0] == '?': return ('Guess', output[2:].strip()) if output[0] == '#': return ('Not Found',) def getResult(self): return self.result class Tkspell(Frame): def __init__(self, master=None): Frame.__init__(self, master) self.grid(ipadx=4, ipady=4) self.createWidgets() def createWidgets(self): self.entry = Entry(self) self.entry.grid(column=0, row=0, padx=8) self.entry.focus() self.Ok = Button(self, text="Check", activeforeground="blue", command=self.check) self.Ok.bind("", self.check) self.Ok.grid(column=1, row=0) ####################### # Change here, made label instance var. instead of local to check() # but I don't make it visible now self.label = Label(self) def check(self, event): self.result = Spell(self.entry.get()).getResult() ####################### # Change here vvvvvvvvv self.label['text']= self.result[0] if self.result[0] in ['OK', 'Root', 'Compound', 'Not Found']: ##### And here vvvvvvvvv self.label.grid(column=0, row=1, columnspan=2) self.entry.selection_range(0, END) ##### And here vvvvvvvvv self.entry.focus() return 0 elif self.result[0] in ['Miss', 'Guess']: suggestions = self.result[1].split(":")[1].split(',') ##### And here vvvvvvvvv self.label.grid(column=0, row=1, columnspan=2) ResultList = Listbox(self, height=len(suggestions)) for x in suggestions: ResultList.insert(END, x) ResultList.grid(column=0, row=2, columnspan=2, pady=4, sticky=EW) print self.result if __name__ == '__main__': S = Tkspell() S.master.title("Tkspell") S.mainloop() ------------------------------------------------------- Peace Steve PS: anyone with me ??....if not plz lemme know, I'll quitely go away :) -- ---------------------------------------------- I get up each morning, gather my wits. Pick up the paper, read the obits. If I'm not there I know I'm not dead. So I eat a good breakfast and go back to bed. Oh, how do I know my youth is all spent? My get-up-and-go has got-up-and-went. But in spite of it all, I'm able to grin, And think of the places my get-up has been. -- Pete Seeger ------------------------------------------ From arcege@speakeasy.net Thu Jan 17 13:36:18 2002 From: arcege@speakeasy.net (Michael P. Reilly) Date: Thu, 17 Jan 2002 08:36:18 -0500 Subject: [Tutor] Help with tkinter application. In-Reply-To: <02011717255200.21675@mercury.worli>; from lonetwin@yahoo.com on Thu, Jan 17, 2002 at 05:25:52PM +0530 References: <02011717255200.21675@mercury.worli> Message-ID: <20020117083618.F1549@speakeasy.net> On Thu, Jan 17, 2002 at 05:25:52PM +0530, lonetwin wrote: > Hi Once Again, :) > I made a few changes, now the label gets redrawn, also, besides being > exported to the clipboard, the entry box gets focus after a (correctly > spelled) word is checked. > The only problem now is redrawing the listbox or making it go away after > entering a second word to check. You can try the 'forget()' method. But it will mean keeping track of the listbox as well. I'd suggest the following changes. > the code : > ================================================== > #!/usr/bin/python > import os > from Tkinter import * > > class Spell: > def __init__(self, word): > if not word: return > fin, fout = os.popen2('ispell -a') > version = fout.readline() or "Ispell version unknown" > fin.write(word) > fin.close() > self.result = self.interpret(fout.read()) > > def interpret(self, output): > if output[0] == '*': > return ('OK',) > if output[0] == '+': > return ('Root', output[2:].strip()) > if output[0] == '-': > return ('Compound', output[2:].strip()) > if output[0] == '&': > return ('Miss', output[2:].strip()) > if output[0] == '?': > return ('Guess', output[2:].strip()) > if output[0] == '#': > return ('Not Found',) > > def getResult(self): > return self.result > > class Tkspell(Frame): > def __init__(self, master=None): > Frame.__init__(self, master) > self.grid(ipadx=4, ipady=4) > self.createWidgets() > > def createWidgets(self): > self.entry = Entry(self) > self.entry.grid(column=0, row=0, padx=8) > self.entry.focus() > > self.Ok = Button(self, text="Check", activeforeground="blue", > command=self.check) > self.Ok.bind("", self.check) > self.Ok.grid(column=1, row=0) > ####################### > # Change here, made label instance var. instead of local to check() > # but I don't make it visible now > self.label = Label(self) self.resultlist = None > > def check(self, event): > self.result = Spell(self.entry.get()).getResult() > ####################### > # Change here vvvvvvvvv > self.label['text']= self.result[0] > if self.result[0] in ['OK', 'Root', 'Compound', 'Not Found']: > ##### And here vvvvvvvvv > self.label.grid(column=0, row=1, columnspan=2) > self.entry.selection_range(0, END) > ##### And here vvvvvvvvv > self.entry.focus() # we know there should be nothing in the listbox if self.resultlist: self.resultlist.delete(1, END) self.resultlist.forget() > return 0 > elif self.result[0] in ['Miss', 'Guess']: > suggestions = self.result[1].split(":")[1].split(',') > ##### And here vvvvvvvvv > self.label.grid(column=0, row=1, columnspan=2) > ResultList = Listbox(self, height=len(suggestions)) if self.resultlist: ResultList = resultlist # should be empty else: ResultList = Listbox(self, heigh=len(suggestions)) self.resultlist = ResultList > for x in suggestions: > ResultList.insert(END, x) > ResultList.grid(column=0, row=2, columnspan=2, pady=4, sticky=EW) > > print self.result > > > if __name__ == '__main__': > S = Tkspell() > S.master.title("Tkspell") > S.mainloop() > > ------------------------------------------------------- > > Peace > Steve > > PS: anyone with me ??....if not plz lemme know, I'll quitely go away :) Some people just need their ten gallons of coffee to answer. :) -Arcege From mikalzet@libero.it Thu Jan 17 14:55:57 2002 From: mikalzet@libero.it (mikalzet@libero.it) Date: Thu, 17 Jan 2002 15:55:57 +0100 (CET) Subject: [Tutor] recursive factoring In-Reply-To: Message-ID: On Wed, 16 Jan 2002, Tim Wilson wrote: > Hi everyone, > > I've been trying to write a little function that will generate a list of > all the prime factors of a given integer. This seems like the sort of > problem that maps very well to a recursive algorithm. Take the prime > factors of 24 for example: > > 24 > / \ > 2 12 > / \ > 2 6 > / \ > 2 3 > > The prime factors are 2, 2, 2, and 3. If that isn't recursion waiting to > happen, I don't know what is. :-) Well, I have taken a look at all the recursive solutions proposed. My impression is that a non-recursive solution would be simpler and more efficient. What do you people think of: def primeNumber(n): if n==1: return 1 a = [] b = 2 while b <= n: while n % b == 0: a.append(b) n = n/b b = b + 1 return a I've tried it and it seems to work well. -- Michele Alzetta From dsh8290@rit.edu Thu Jan 17 15:47:53 2002 From: dsh8290@rit.edu (dman) Date: Thu, 17 Jan 2002 10:47:53 -0500 Subject: [Tutor] How to ignore some decimal values? In-Reply-To: <20020117062630.50579.qmail@web14708.mail.yahoo.com> References: <20020117062630.50579.qmail@web14708.mail.yahoo.com> Message-ID: <20020117154753.GA19168@localhost> On Wed, Jan 16, 2002 at 10:26:30PM -0800, Titu Kim wrote: | Hi there, | Do someone has any idea on keeping the floor value | of a fixed decimal point n? For instance: | a=12.3451 | b=0.5699 | c=0.0 | | How can i make a,b, and c become float values as | a=12.34 | b=0.56 | c=0.00 | if my n=2. If n=3 | a=12.345 | b=0.569 | c=0.000 | | Thanks for any suggestion? Ignoring the fact that binary floating point can't represent all decimal numbers : def truncate( f , n ) : shift = 10**n return int( f*shift ) / shift 'f' is the float you want to truncate, 'n' is an integer for the number of decimals you want to keep What it does is shift the decimal over so that all the digits you want are on the left side. Then convert to an int (drop all fractional part), then shift the decimal point back where it belongs. -D -- The remote desktop feature of Windows XP is really nice (and *novel*!). As a Microsoft consultant can *remotely* disable the personal firewall and control the system. We'll ignore the fact that this tampering with the firewall is not logged, and more importantly, that the firewall isn't restored when the clowns from Redmond are done with their job. -- bugtraq From dsh8290@rit.edu Thu Jan 17 15:54:51 2002 From: dsh8290@rit.edu (dman) Date: Thu, 17 Jan 2002 10:54:51 -0500 Subject: [Tutor] sORRY In-Reply-To: <3C466CDE.D21B1605@netzero.net> References: <3C466CDE.D21B1605@netzero.net> Message-ID: <20020117155451.GB19168@localhost> On Thu, Jan 17, 2002 at 01:19:10AM -0500, kirk Bailey wrote: | someone on the GMbrianpenn list closed an account and did not tell us | od come and do the wtright thing and unsubscribe. We jus tdiscovered | the error fed back from sendmail when it cannot connect to the | account, the error comnig back blows the acript at that point- and | remaining members do nto get the message, but the submiting member | DOES get a error message. Removing old members one at a time, I | discovered which ones were doing it, and they are not disrupting it | any more. | | I need to set up a Try:/Except ERROR: block with a small program and a | tiny dummy message, and see what the errors look like, and prepare to | handle them. This shall surely show up again. Are you doing the SMTP transfer yourself, or are you piping to your MTA and letting it deal with it? In the former case, read RFC2821 and the source of some MTA and see how to handle errors. (this is why it is better to simply pipe to your MTA and let it deal with it) In the latter case, you need a way to set the envelope sender ("MAIL FROM:") to a magic address on your machine that is handled by a bot. If a message arrives at that address, your bot removes the address from the subscription list. However, don't do that immediately, only do it if multiple bounces occur (it may be a one-shot problem with the user's setup and you don't want to drop them in that case). For example debian-user sets "bounce-debian-user=dsh8290=rit.edu@lists.debian.org" as the sender address for mail it delivers to me. If the mail is undeliverable, that's where the bounce message goes. (unless the system sending the bounce is a badly broken (MS) system which sends the bounce to the From: address). Then you need to configure your MTA to accept pattern addresses and deliver them to the bot. -D -- I can do all things through Christ who strengthens me. Philippians 4:13 From mando@mando.org Thu Jan 17 14:41:37 2002 From: mando@mando.org (Mando Escamilla) Date: 17 Jan 2002 09:41:37 -0500 Subject: [Tutor] How to ignore some decimal values? In-Reply-To: <20020117154753.GA19168@localhost> References: <20020117062630.50579.qmail@web14708.mail.yahoo.com> <20020117154753.GA19168@localhost> Message-ID: <1011278499.4856.5.camel@mlinux> On Thu, 2002-01-17 at 10:47, dman wrote: > On Wed, Jan 16, 2002 at 10:26:30PM -0800, Titu Kim wrote: > | Hi there, > | Do someone has any idea on keeping the floor value > | of a fixed decimal point n? For instance: > | a=12.3451 > | b=0.5699 > | c=0.0 > | > | How can i make a,b, and c become float values as > | a=12.34 > | b=0.56 > | c=0.00 > | if my n=2. If n=3 > | a=12.345 > | b=0.569 > | c=0.000 > | > | Thanks for any suggestion? > > Ignoring the fact that binary floating point can't represent all > decimal numbers : > > def truncate( f , n ) : > shift = 10**n > return int( f*shift ) / shift > > 'f' is the float you want to truncate, > 'n' is an integer for the number of decimals you want to keep > > What it does is shift the decimal over so that all the digits you want > are on the left side. Then convert to an int (drop all fractional > part), then shift the decimal point back where it belongs. You could also use fpformat, which seems to do the same thing :-). >>> import fpformat >>> a = 5.44444 >>> i = 1 >>> print fpformat.fix(a, i); 5.4 >>> -- Mando From dsh8290@rit.edu Thu Jan 17 16:05:20 2002 From: dsh8290@rit.edu (dman) Date: Thu, 17 Jan 2002 11:05:20 -0500 Subject: [Tutor] Ethics in programming In-Reply-To: <3C45D4A5.ED9310E@netzero.net> References: <3C45D4A5.ED9310E@netzero.net> Message-ID: <20020117160520.GC19168@localhost> On Wed, Jan 16, 2002 at 02:29:41PM -0500, kirk Bailey wrote: | Gang, I still amd thinking about how to handle large lists. and how to | impede spam. Check this out. I just set up spamassassin on my system. It is really cool. I have exim pipe all incoming messages through spamassassin, and spamassassin gives it back with some headers added. In my filter I then drop all messages tagged as spam into a junk folder so I can double check it (in case it gives a false positive). | I can use a method of a second alias to sent out the large list, and | the original list is simply the address for that alias. TL become in | effect a message processor, and the second alias handles the huge | outbound list transmission. This is the method used by majordomo. | However, that second alias is totally open to spam input. How about getting rid of the open alias? In TinyList you will pipe the message to spamassassin, then read the tagged message from its stdout. Then you check the X-Spam-Flag: header. If that header exists, then spamassassin thinks the message is spam. In that case you drop it somewhere for the list admin to verify that it is spam (this is so false positives can be corrected by the admin). If the message isn't spam, you continue by piping it to your MTA with the list of recipient addresses. | This uses the sendmail function :include: which when aliases are | compiled by sendmail, includes the reference to the subscriber file in | it's definition. Why not have TinyList itself manage the subscriber list, instead of sendmail. No aliases are needed then, you just stick all the addresses on the sendmail command line. Something like : # 'message' is a string-representation of the entire spam checked message f = file( "subscriberlist" , "r" ) slist = f.readlines() f.close() slist = map( string.strip , slist ) # strip out the newlines for subscriber in slist : bounce_addr = "bounce-=%s@" % \ subscriber.replace( "@" , "=" ) # you get the idea pipe = os.popen( "sendmail" , "-f %s" % bounce_addr , subscriber ) # check for errors returned from the pipe! pipe.write( message ) pipe.close() I think you get the idea here. In this setup each subscriber gets their own copy of the message (no long recipient lines) and bounces are sent back to you for processing by your bot (which you have yet to write). -D -- Contrary to popular belief, Unix is user friendly. It just happens to be selective about who it makes friends with. -- Dave Parnas From urnerk@qwest.net Thu Jan 17 16:26:07 2002 From: urnerk@qwest.net (Kirby Urner) Date: Thu, 17 Jan 2002 08:26:07 -0800 Subject: [Tutor] recursive factoring In-Reply-To: References: Message-ID: <4.2.0.58.20020117080013.00cd8200@pop3.norton.antivirus> > >What do you people think of: > >def primeNumber(n): > if n==1: return 1 > a = [] > b = 2 > while b <= n: > while n % b == 0: > a.append(b) > n = n/b > b = b + 1 > return a > > >I've tried it and it seems to work well. Looks good! You're taking advantage of the fact that the *smallest* factor of n will be a *prime* factor. No need to separately test if it's prime. This could also be written recursively: def factor(n): if n==1: return [] b = 2 while b <= n: while not n%b: return [b] + factor(n/b) b += 1 return a which is actually a few lines shorter (and I stopped it from saying 1 is a prime factor of anything, as technically 1 is not a prime -- other programs had that problem too). Sieving primes to sqrt(n) ahead of time and test-dividing by those primes only, is likely faster, especially if it's like a 7-digit prime number to start with, as this program counts up to it 1-by-1. I should do some profiling to get actual time comparisons. This one is probably faster up to a point, then the sieve would overtake it. Yours is definitely winner in terms of sheer simplicity. Good job. Note: All trial by division methods, including sieve-based, fail for the really big numbers (e.g. 100-digit). They run out of memory and/or time. Kirby From alan.gauld@bt.com Thu Jan 17 16:25:59 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Thu, 17 Jan 2002 16:25:59 -0000 Subject: [Tutor] writing & reading files Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C2A7@mbtlipnt02.btlabs.bt.co.uk> Frank, First comment: Save a lo of typing and lines by putting the prompt inside the raw_input() call: > def add_name(): > print 'Enter Name:' > dname=raw_input() dname = raw_input('Enter name:\n') > l=(dname, fname, hnum, ph, pg, cop, com) > d1[dname]=l Where is d1 defined? If you read it in from the pickle file somewhere else then we're OK, otherwise what? where? > f=open('phoneyold','w') > pickle.dump(d1,f) > f.close() > d1={} Ah here it is. But how is it loaded? I think you need to assign p_d1 to it in your get_name function? Otherwise the old names are never in d1 and so never get written out... Alan g From urnerk@qwest.net Thu Jan 17 16:29:50 2002 From: urnerk@qwest.net (Kirby Urner) Date: Thu, 17 Jan 2002 08:29:50 -0800 Subject: [Tutor] How to ignore some decimal values? In-Reply-To: <1011278499.4856.5.camel@mlinux> References: <20020117154753.GA19168@localhost> <20020117062630.50579.qmail@web14708.mail.yahoo.com> <20020117154753.GA19168@localhost> Message-ID: <4.2.0.58.20020117082742.019c1750@pop3.norton.antivirus> > >You could also use fpformat, which seems to do the same thing :-). > > >>> import fpformat > >>> a = 5.44444 > >>> i = 1 > >>> print fpformat.fix(a, i); >5.4 > >>> > >-- >Mando Actually fpformat.fix, like equivalent % format expression, rounds up, does't truncate. e.g. >>> print fpformat.fix(5.08,1) 5.1 But the question was how to simply drop a digit (truncate), not round it up, i.e. you'd get 5.0 not 5.1 Kirby From alan.gauld@bt.com Thu Jan 17 16:27:57 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Thu, 17 Jan 2002 16:27:57 -0000 Subject: [Tutor] dynamic printing Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C2A8@mbtlipnt02.btlabs.bt.co.uk> > Is there a module that allows one to print to a PRINTER > instead of the screen? I can save it to a file and then go > back with windows > and hit File>Print.. The equivalent to this is to use os.system("print foo.txt") where foo,txt is your file. For pretty formating I usually create an HTML file and get netscape to print it... Alan g From alan.gauld@bt.com Thu Jan 17 16:34:40 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Thu, 17 Jan 2002 16:34:40 -0000 Subject: [Tutor] recursive factoring Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C2A9@mbtlipnt02.btlabs.bt.co.uk> > def isPrime(n): > > def factor(n, factors=[]): > if isPrime(n): > factors.append(n) > return factors > else: > for i in range(2, math.sqrt(n)+1): > if n % i == 0: > factor(n/i, factors) And if n%i != 0 what happens? And in either case what do we return? Nothing... Alan G From mikalzet@libero.it Thu Jan 17 17:38:20 2002 From: mikalzet@libero.it (mikalzet@libero.it) Date: Thu, 17 Jan 2002 18:38:20 +0100 (CET) Subject: [Tutor] recursive factoring In-Reply-To: <4.2.0.58.20020117080013.00cd8200@pop3.norton.antivirus> Message-ID: On Thu, 17 Jan 2002, Kirby Urner wrote: > This could also be written recursively: > > def factor(n): > if n==1: return [] > b = 2 > while b <= n: > while not n%b: > return [b] + factor(n/b) > b += 1 > return a > I should do some profiling to get actual time > comparisons. This one is probably faster up to > a point, then the sieve would overtake it. It would be interesting to find out. I recently faced a similar problem with the fibonacci() function taken from "Learning how to think like a Computer Scientist with Python". The first fibonacci() function the text suggests is def fibonacci(n): if n == 0 or n == 1: return 1 else: return fibonacci(n-1) + (fibonacci(n-2) this function calculates fibonacci(30) in a preceptible time, and fibonacci(40) takes pretty long on my system. Later in the text a different method is suggested: previous = {0:1L, 1:1L} def fibonacci(n): if previous.has_key(n): return previous(n) else: newValue = fibonacci(n-1) + fibonacci(n-2) previous[n] = newValue return newValue Now fibonacci(40) is practically instantaneous. This is much faster; however calculation of fibonacci much greater than 500 is impossible first go. To calculate fibonacci(100000) you have to first build the dictionary in approximately 500-large steps, i.e. after calcualting fibonacci(500) it becomes possible to calcualte fibonacci(1000), it now becomes possible to calculate fibonacci(1500) and so on. So I wrote a non-recursive function like this: def fibonacci(n): a = 1L b = 1L if n < 2: return 1 else: z=2 while z <= n: c = a + b a, b = b, c z = z + n return c This function seems at least as fast as the previous one, but there is a big difference: fibonacci(100000) is possible first go (it takes looong seconds and the result is a number of over 20000 digits if I well remember). This makes me think that perhaps for this sort of chore recursion is not as efficient as direct calculation methods. I wander: are there any guidelines as to when recursion is more / less efficient than other methods ? (One could avoid struggling to invent one type of solution in situations where other types of solution are known to be more efficient). -- Michele Alzetta From jeff@ccvcorp.com Thu Jan 17 17:51:58 2002 From: jeff@ccvcorp.com (Jeff Shannon) Date: Thu, 17 Jan 2002 09:51:58 -0800 Subject: [Tutor] recursive factoring References: Message-ID: <3C470F3E.552AC4C5@ccvcorp.com> > alan.gauld@bt.com wrote: > > > def isPrime(n): > > > > def factor(n, factors=[]): > > if isPrime(n): > > factors.append(n) > > return factors > > else: > > for i in range(2, math.sqrt(n)+1): > > if n % i == 0: > > factor(n/i, factors) > > And if n%i != 0 what happens? > And in either case what do we return? Nothing... > > Alan G Yes, but we *are* appending to an outside (global?) list. If n%i !=0 then we want to ignore the results (it's not a factor); if n%i == 0 then we *have* a factor and use a recursive call to determine that factor's prime factors. So this function is, essentially, run only for side effects. Probably not the clearest way of doing things, though. :) Yet another example of why relying on side effects is poor practice, I guess.... Of course, if the original call is not made with a prime number, and relies upon that default empty list, then you'll never get anything back from it. That 'return factors' statement is only executed if n is prime, and the return values of the recursively called factor() are never used anyhow.... so you're sort-of right, after all. It should work, though, if that return statement is eliminated and factor() is called with an outside list, like so: f = [] factor(42, f) Jeff Shannon Technician/Programmer Credit International From urnerk@qwest.net Thu Jan 17 18:43:50 2002 From: urnerk@qwest.net (Kirby Urner) Date: Thu, 17 Jan 2002 10:43:50 -0800 Subject: [Tutor] recursive factoring In-Reply-To: References: Message-ID: <4.2.0.58.20020117093018.019c7100@pop3.norton.antivirus> As I expected, a sieve-based method is somewhat faster than chewing off smallest factors while counting up from 1. And once the factors get big enough the sieve- based method remains practical (to some further point), while the counting-by-1 approach dies, simply because it has to go "all the way" before figuring out it's dealing with a prime. To profile, I use the function below, which takes the function to test, and its argument, as its own arguments: import time def profile(f,arg): a = time.time() print f(arg) b = time.time() return b-a >>> profile(factor,20034321) [3, 79, 84533] 0.060000061988830566 is sieve-based. Then I try Michele's (original version): >>> profile(primeNumber,20034321) [3, 79, 84533] 0.1099998950958252 Somewhat slower. However, the sieve-based version isn't so pretty to look at. Likely this could be simplified. It's not recursive: import math from primes import sieve def factor(n): plist = sieve(math.sqrt(n)) pfacts = [] ldiv=1 while 1: if ldiv: if n==1: break else: ldiv=0 for i in plist: if n%i==0: ldiv=1 n = n/i pfacts.append(i) if not ldiv: pfacts.append(n) break return pfacts The basic idea is it lists primes up to the sqrt of n, and if none of those divide, no divisor is found, and n itself is considered prime. But in most cases, you get into a loop and break out from the top when n==1. But on top of all that, you still need the sieve. I included an efficient one a few posts back, and that's what I'm importing from primes.py. E.g. when I ask for the factors of 211, the sieve returns primes only up to sqrt(211) i.e. [2, 3, 5, 7, 11, 13]. Since all those fail to divide 211 evenly, we return out the bottom, appending 211 itself as a prime factor. The sieve itself has another sqrt in it, i.e. since we only need primes up to 13, it's only going to test divide by 2 and 3. Actually, it begins with odds 3 5 7 9 11 13 with 2 already known to be prime. After eliminating the 9 (the first 3 is kept), we're done. This is all quite efficient. Let's try a much bigger number: >>> profile(factor,2133431113212) [2, 3, 7, 17, 2, 3, 3, 165999931L] 4.2300000190734863 The sieve-based function runs in under 5 seconds (depends on processor of course), whereas the non sieve-based function isPrimenumber gets stuck counting to that last prime factor by 1, which takes a long time. Just try against that last factor (165999931) to see why one might want to sieve: >>> profile(primeNumber,165999931) # ouch [165999931] 205.37000000476837 >>> profile(factor,165999931) # sometimes 0.0 [165999931] 0.059999942779541016 There's a method called Miller-Rabin which generates very large numbers very likely to be prime. These are so far not practical to crack (factor), which is why we have a "trap door" function -- something we can do, but not undo. The RSA algorithm takes two of these huge probable primes and multiplies them together for a public key. Even though the key is public, no known techniques let us factor such a number in reasonable time. If a public key could be factored, the code could be broken (people used to think 512-bit public keys were safe, but a team cracked a challenge public key of that size, so now everyone says to go 1024 bits at least -- note that every bit *doubles* the keyspace, so doubling the key size is way more than doubling the difficulty of factoring). Raising to powers modulo N is a cyclic thing -- you keep rotating through the same numbers. Knowing the factors of N and the power the message had been raised to (which is also public) would tell you how to raise the ciphertext to a countering power that'd rotate it back through to the message itself, one power after message^0 = 1 on the dial. Not knowing the factors, the dial is just too big around to try every power-position. Here's a 50-digit probable prime: >>> from primes import bigppr >>> bigppr(50) Working... Percent chance of being prime: 100.0 Elapsed time: 0.399939657051 seconds 757795979917279974119994023697095922339387199771439L That's out of range for my sieve-based program, to check for factors (most likely 1, and the above are the only two). Kirby From dsh8290@rit.edu Thu Jan 17 19:08:08 2002 From: dsh8290@rit.edu (dman) Date: Thu, 17 Jan 2002 14:08:08 -0500 Subject: [Tutor] How to ignore some decimal values? In-Reply-To: <1011278499.4856.5.camel@mlinux> References: <20020117062630.50579.qmail@web14708.mail.yahoo.com> <20020117154753.GA19168@localhost> <1011278499.4856.5.camel@mlinux> Message-ID: <20020117190808.GA21674@localhost> On Thu, Jan 17, 2002 at 09:41:37AM -0500, Mando Escamilla wrote: | You could also use fpformat, which seems to do the same thing :-). | | >>> import fpformat | >>> a = 5.44444 | >>> i = 1 | >>> print fpformat.fix(a, i); | 5.4 | >>> I wasn't aware of this module, but it isn't quite the same : >>> type( fpformat.fix( 5.4444 , 1 ) ) In that case you get back a string, not a float. -D -- THe lot is cast into the lap, but its every decision is from the Lord. Proverbs 16:33 From dsh8290@rit.edu Thu Jan 17 19:11:06 2002 From: dsh8290@rit.edu (dman) Date: Thu, 17 Jan 2002 14:11:06 -0500 Subject: [Tutor] dynamic printing In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66C2A8@mbtlipnt02.btlabs.bt.co.uk> References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C2A8@mbtlipnt02.btlabs.bt.co.uk> Message-ID: <20020117191106.GB21674@localhost> | Is there a module that allows one to print to a PRINTER | instead of the screen? I can save it to a file and then go | back with windows and hit File>Print.. If you're using a Unix system, you could go straight to the printer with printer = open( "/dev/lp0" , "a" ) printer.write( "some text that will spit out of the printer" ) printer.close() better than doing that is to use the print spooler on the system import os printer = os.popen( "lp" ) printer.write( "some text to send to the printer" ) printer.write( " in the proper format and when it is ready!!" ) printer.close() On Windows, uhh, who knows. Devices aren't accessed as files there. -D -- Religion that God our Father accepts as pure and faultless is this: to look after orphans and widows in their distress and to keep oneself from being polluted by the world. James 1:27 From idiot1@netzero.net Thu Jan 17 19:51:01 2002 From: idiot1@netzero.net (kirk Bailey) Date: Thu, 17 Jan 2002 14:51:01 -0500 Subject: [Tutor] Ethics in programming References: <3C45D4A5.ED9310E@netzero.net> <20020117160520.GC19168@localhost> Message-ID: <3C472B25.D682518@netzero.net> Dman, I have 2 concenrs; preventing my users from being spammed, and preventing my tools I produce from being used TO spam. This is why I am sitting on a guardian program to handle transmission to large lists. dman wrote: > > On Wed, Jan 16, 2002 at 02:29:41PM -0500, kirk Bailey wrote: > | Gang, I still amd thinking about how to handle large lists. and how to > | impede spam. > > Check this out. I just set up spamassassin on my system. It is > really cool. I have exim pipe all incoming messages through > spamassassin, and spamassassin gives it back with some headers added. > In my filter I then drop all messages tagged as spam into a junk > folder so I can double check it (in case it gives a false positive). > > | I can use a method of a second alias to sent out the large list, and > | the original list is simply the address for that alias. TL become in > | effect a message processor, and the second alias handles the huge > | outbound list transmission. This is the method used by majordomo. > | However, that second alias is totally open to spam input. > > How about getting rid of the open alias? > > In TinyList you will pipe the message to spamassassin, then read the > tagged message from its stdout. Then you check the X-Spam-Flag: > header. If that header exists, then spamassassin thinks the message > is spam. In that case you drop it somewhere for the list admin to > verify that it is spam (this is so false positives can be corrected by > the admin). If the message isn't spam, you continue by piping it to > your MTA with the list of recipient addresses. > > | This uses the sendmail function :include: which when aliases are > | compiled by sendmail, includes the reference to the subscriber file in > | it's definition. > > Why not have TinyList itself manage the subscriber list, instead of > sendmail. No aliases are needed then, you just stick all the > addresses on the sendmail command line. Something like : > Actually, as of now, it does. It uses the smtplib functions to talk to sendmail and send one envlope per recipient. this is GOOD, there is no unsecured alias sitting there waiting to be found like there is with majordomo. Also, someone could use TLwebmanager to manage SENDMAIL lists. Would never reccomend it, as sendmail lists are not secure at all. But they could. Such a subscriber list is a simple flat text file, samo as used by TL. Just write a .info file for it and it shows up on the menu! You DID know that majordomo uses a unguarded unfiltered outbound alias for EVERY list used, and that most people never deviate from the example in the manuals of (listname)-outbound::include:/pathtofile/subscriberfilename right? Yep. EVERY majordomo user is hosting a major spamshark feeding ground waiting for the right person to come along and exploit it. The technique to discover prime read meat is simple: Subscribe to a list there, any list. Send a test message to 'listname'-outgoing@thatplace.foo; see if you get it. This is a postmaster psycology test to see if they used a random name or went with the forms used in the manuals as examples- which it then tells you not to do. Well, people are creatures of habit. Many still went and built majordomo lists with the -outgoing part as per example. if would be spam artist gets that letter, that site's lists are his to spam; just email listname-ouotgoing and all them folk are going to get a letter. NO WAY TO STOP IT. By chance, do you host any lists? Try that on TL, abject failure. TL is SECURE. I am loathe to abandon that. > # 'message' is a string-representation of the entire spam checked message > > f = file( "subscriberlist" , "r" ) > slist = f.readlines() > f.close() > slist = map( string.strip , slist ) # strip out the newlines > for subscriber in slist : > bounce_addr = "bounce-=%s@" % \ > subscriber.replace( "@" , "=" ) # you get the idea > pipe = os.popen( "sendmail" , "-f %s" % bounce_addr , subscriber ) > # check for errors returned from the pipe! > pipe.write( message ) > pipe.close() > > I think you get the idea here. In this setup each subscriber gets > their own copy of the message (no long recipient lines) and bounces > are sent back to you for processing by your bot (which you have yet to > write). > > -D > > -- > > Contrary to popular belief, Unix is user friendly. > It just happens to be selective about who it makes friends with. > -- Dave Parnas > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- -Respectfully, -Kirk D Bailey Consulting Loose Cannon end www.howlermonkey.net highprimate@howlermonkey.net www.sacredelectron.org idiot1@netzero.net www.tinylist.org grumpy@tinylist.org ---------------------------------------------------- Sign Up for NetZero Platinum Today Only $9.95 per month! http://my.netzero.net/s/signup?r=platinum&refcd=PT97 From idiot1@netzero.net Thu Jan 17 19:55:03 2002 From: idiot1@netzero.net (kirk Bailey) Date: Thu, 17 Jan 2002 14:55:03 -0500 Subject: [Tutor] SMTP Message-ID: <3C472C17.BA23FB8A@netzero.net> OK, someone wrote me a letter a while back talking about sending commands directly to sendmail, and gave a breif example. alas, it is buried/misplaced/accidentally deleted. If someone here is will ing to either repost it to the list, or arite afresh, it would be handy. I do not recall all of it, but from the command line it was $sendmail (missing data arguements) << EOF Is there a sendmail meister in the house? The manual is not disclosing such eldritch sorcery. -- -Respectfully, -Kirk D Bailey Consulting Loose Cannon end www.howlermonkey.net highprimate@howlermonkey.net www.sacredelectron.org idiot1@netzero.net www.tinylist.org grumpy@tinylist.org ---------------------------------------------------- Sign Up for NetZero Platinum Today Only $9.95 per month! http://my.netzero.net/s/signup?r=platinum&refcd=PT97 From idiot1@netzero.net Thu Jan 17 19:55:27 2002 From: idiot1@netzero.net (kirk Bailey) Date: Thu, 17 Jan 2002 14:55:27 -0500 Subject: [Tutor] sORRY References: <3C466CDE.D21B1605@netzero.net> <20020117155451.GB19168@localhost> Message-ID: <3C472C2F.FD075178@netzero.net> dman wrote: > > On Thu, Jan 17, 2002 at 01:19:10AM -0500, kirk Bailey wrote: > | someone on the GMbrianpenn list closed an account and did not tell us > | od come and do the wtright thing and unsubscribe. We jus tdiscovered > | the error fed back from sendmail when it cannot connect to the > | account, the error comnig back blows the acript at that point- and > | remaining members do nto get the message, but the submiting member > | DOES get a error message. Removing old members one at a time, I > | discovered which ones were doing it, and they are not disrupting it > | any more. > | > | I need to set up a Try:/Except ERROR: block with a small program and a > | tiny dummy message, and see what the errors look like, and prepare to > | handle them. This shall surely show up again. > > Are you doing the SMTP transfer yourself, or are you piping to your > MTA and letting it deal with it? TLpost has a loop in it that reads a list variable ('members') and sends the prepared message to that member with the smtplib functions. Here is that loop: server = smtplib.SMTP(localhost) for to_addr in members : # for each address in 'listnamemembers', # print "to_addr: ", to_addr # print "from_addr: ", from_addr # print "msg=" + CRLF, msg server.sendmail(from_addr, to_addr, msg) # 400 send envlope and msg! # don't delete the above line! server.quit() # then close the connection. Works fine as long as all the addresses are good ones. Blows out when there is a bad one involved. Probably the solution should be something like: server = smtplib.SMTP(localhost) for to_addr in members : # for each address in 'listnamemembers', Try: # print "to_addr: ", to_addr # print "from_addr: ", from_addr # print "msg=" + CRLF, msg server.sendmail(from_addr, to_addr, msg) # 400 send envlope and msg! Except ERROR:foofoofoo # just skip the bad address for now and continue the loop. # server.quit() # then close the connection. Any discussion or suggestions or really sick jokes? wait, this is not the evil-humor list, skip the last one, save them for over there. > > In the former case, read RFC2821 and the source of some MTA and see > how to handle errors. (this is why it is better to simply pipe to > your MTA and let it deal with it) This can be done 2 ways. One of them is a security problem, and the other one is a security FAILURE. 1. sendmail calls. We limit recipients per envlope to 10 in the sendmail.cf file to limit someone getting an account to do a spam run. TL avoids this by this loop and sending one envlope per recipient, I am unsure that direct calls and handing it the list would be friendly to the limitation. 2. outbound aliases. Sendmail compiles aliases and recognizes a few imbedded commands when doing so. One of these is ':include:'. This is the method used by majordomo and some other MLM's. such an aslias would be: mylist-outgoing::include:/www/www.mydomain.foo/lists/mylist And when something hits this alias, it goes out. FROM ANYONE. Good news is sendmail sends it out one envlope per person. There is NO input filtering, ANY spammeister can play with your list at will. Now not so long ago, > > In the latter case, you need a way to set the envelope sender > ("MAIL FROM:") to a magic address on your machine that is handled by a > bot. If a message arrives at that address, your bot removes the > address from the subscription list. However, don't do that > immediately, only do it if multiple bounces occur (it may be a > one-shot problem with the user's setup and you don't want to drop them > in that case). For example debian-user sets > "bounce-debian-user=dsh8290=rit.edu@lists.debian.org" as the sender > address for mail it delivers to me. If the mail is undeliverable, > that's where the bounce message goes. (unless the system sending the > bounce is a badly broken (MS) system which sends the bounce to the > From: address). Then you need to configure your MTA to accept > pattern addresses and deliver them to the bot. > > -D > > -- > > I can do all things through Christ who strengthens me. > Philippians 4:13 > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- -Respectfully, -Kirk D Bailey Consulting Loose Cannon end www.howlermonkey.net highprimate@howlermonkey.net www.sacredelectron.org idiot1@netzero.net www.tinylist.org grumpy@tinylist.org ---------------------------------------------------- Sign Up for NetZero Platinum Today Only $9.95 per month! http://my.netzero.net/s/signup?r=platinum&refcd=PT97 From dyoo@hkn.eecs.berkeley.edu Thu Jan 17 20:28:19 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 17 Jan 2002 12:28:19 -0800 (PST) Subject: [Tutor] recursive factoring In-Reply-To: Message-ID: On Thu, 17 Jan 2002 mikalzet@libero.it wrote: > def fibonacci(n): > a = 1L > b = 1L > if n < 2: return 1 > else: > z=2 > while z <= n: > c = a + b > a, b = b, c > z = z + n > return c > > > This function seems at least as fast as the previous one, but there is a > big difference: fibonacci(100000) is possible first go (it takes looong > seconds and the result is a number of over 20000 digits if I well > remember). > > This makes me think that perhaps for this sort of chore recursion is > not as efficient as direct calculation methods. [warning: this message is sort of a rah! rah! cheerleader message for Scheme. *grin*] Let's do a comparison for a moment. Here's another recoding of the fibonacci() function in a recursive style: ### def fibonacci(n): def loop(a, b, x): if x == 0: return a return loop(b, a+b, x-1) return loop(1, 1, n) ### Before we continue, let's make sure this works. ### >>> [fibonacci(n) for n in range(10)] [1, 1, 2, 3, 5, 8, 13, 21, 34, 55] ### Ok, that looks right. Anyway, recursion itself doesn't have to be expensive --- unfortunately, it's the current implementation of recursion in Python that's not efficient. What makes recursion look expensive is the call here: return loop(b, a+b, x-1) and the overhead involved in calling a function. But let's take a look at that fragment again: ### def loop(a, b, x): if x == 0: return a return loop(b, a+b, x-1) ### If Python were "smart", it would realize that all it would need to do to get equivalent results is to do something like: ### def loop(a, b, x): while 1: if x == 0: return a (a, b, x) = (b, a+b, x-1) ### In language implementations that really support recursion well, this transformation is done automatically. The transformation is based on the following idea: if the very last thing --- the very "tail" of our function --- is just returning the value of a function, all the system needs to do is set up our parameters up right, and just goto the function start. In CS terms, this is called "tail recursion", and if implemented correctly, this kind of recursion is just as fast as a while loop. Unforutnately, Python's standard implementation doesn't do this optimization. *sigh* At least, not yet. (I think the Java implementors are trying to get it to work in Java now.) However, it does work with Scheme implementations: if we write fibonacci in Scheme: ;;; (define (fibonacci n) (define (loop a b x) (if (= x 0) a (loop b (+ a b) (- x 1)))) (loop 1 1 n)) ;;; and run it: ;;; guile> (fibonacci 100000) 4202692702995154386319005101293915131773915702 6322345033047160871983357314572762266339384772 6701366096253366170285832918664116229882221533 3733574147268614522205177960360216576292096795 5306565025379983144950263305006207190888989846 4361959992647623610831850502374986470385949102 4686621241730682736115723551647724257547502352 4124687460748510533539234387035478700197015862 7451490394358177801241082646446182327292482674 9362282954004235923662667858166740323769532233 5408104342666616797388659593046520172457610944 9556607116705430169089571460488401367949139456 6493844646298912078940644595782507997928878739 3929856101801013438826002838203981392009271635 1212296992483983946353362236959988059362454831 ... [lots and lots of digits] ;;; then this actually runs well, and more importantly, its memory usage is constant, just as if it were a while loop. In reality, recursion in Python is not optimal, just because Python doesn't optimize tail-recursive function calls. In theory, though, recursive functions can be just as efficient as functions with loops. Michael Hudson's "bytecodehacks" package actually does the processing to make tail-recursion work: http://bytecodehacks.sourceforge.net/bch-docs/bch/module-bytecodehacks.tailr.html but, as the name suggests, it's very hacky. *grin* I think it would take some extensive thinking to allow tail-recursion to really work in Python. From dsh8290@rit.edu Thu Jan 17 20:43:49 2002 From: dsh8290@rit.edu (dman) Date: Thu, 17 Jan 2002 15:43:49 -0500 Subject: [Tutor] SMTP In-Reply-To: <3C472C17.BA23FB8A@netzero.net> References: <3C472C17.BA23FB8A@netzero.net> Message-ID: <20020117204349.GA22353@localhost> On Thu, Jan 17, 2002 at 02:55:03PM -0500, kirk Bailey wrote: | OK, someone wrote me a letter a while back talking about sending | commands directly to sendmail, and gave a breif example. alas, it is | buried/misplaced/accidentally deleted. If someone here is will ing to | either repost it to the list, or arite afresh, it would be handy. | | I do not recall all of it, but from the command line it was | | $sendmail (missing data arguements) << EOF | Is there a sendmail meister in the house? The manual is not disclosing | such eldritch sorcery. Hehe. Read "spec.txt" from the exim distribution. Philip wrote some _very_ excellent documentation. $ sendmail << EOF EOF -D -- I can do all things through Christ who strengthens me. Philippians 4:13 From dsh8290@rit.edu Thu Jan 17 20:44:51 2002 From: dsh8290@rit.edu (dman) Date: Thu, 17 Jan 2002 15:44:51 -0500 Subject: [Tutor] Ethics in programming In-Reply-To: <3C472B25.D682518@netzero.net> References: <3C45D4A5.ED9310E@netzero.net> <20020117160520.GC19168@localhost> <3C472B25.D682518@netzero.net> Message-ID: <20020117204451.GB22353@localhost> On Thu, Jan 17, 2002 at 02:51:01PM -0500, kirk Bailey wrote: | Dman, I have 2 concenrs; preventing my users from being spammed, and | preventing my tools I produce from being used TO spam. That's why you're about to insert spamassassin in the middle of your chain of mail handlers, right? | This is why I am sitting on a guardian program to handle | transmission to large lists. What is a "guardian program"? -D -- After you install Microsoft Windows XP, you have the option to create user accounts. If you create user accounts, by default, they will have an account type of administrator with no password. -- bugtraq From dsh8290@rit.edu Thu Jan 17 20:54:16 2002 From: dsh8290@rit.edu (dman) Date: Thu, 17 Jan 2002 15:54:16 -0500 Subject: [Tutor] sORRY In-Reply-To: <3C472C2F.FD075178@netzero.net> References: <3C466CDE.D21B1605@netzero.net> <20020117155451.GB19168@localhost> <3C472C2F.FD075178@netzero.net> Message-ID: <20020117205416.GC22353@localhost> On Thu, Jan 17, 2002 at 02:55:27PM -0500, kirk Bailey wrote: | dman wrote: | > | > On Thu, Jan 17, 2002 at 01:19:10AM -0500, kirk Bailey wrote: | > | someone on the GMbrianpenn list closed an account and did not tell us | > | od come and do the wtright thing and unsubscribe. We jus tdiscovered | > | the error fed back from sendmail when it cannot connect to the | > | account, the error comnig back blows the acript at that point- and | > | remaining members do nto get the message, but the submiting member | > | DOES get a error message. Removing old members one at a time, I | > | discovered which ones were doing it, and they are not disrupting it | > | any more. | > | | > | I need to set up a Try:/Except ERROR: block with a small program and a | > | tiny dummy message, and see what the errors look like, and prepare to | > | handle them. This shall surely show up again. | > | > Are you doing the SMTP transfer yourself, or are you piping to your | > MTA and letting it deal with it? | | TLpost has a loop in it that reads a list variable ('members') and | sends the prepared message to that member with the smtplib functions. | Here is that loop: | | server = smtplib.SMTP(localhost) | for to_addr in members : # for each address in 'listnamemembers', | # print "to_addr: ", to_addr | # print "from_addr: ", from_addr | # print "msg=" + CRLF, msg | server.sendmail(from_addr, to_addr, msg) # 400 send envlope and msg! | | # don't delete the above line! | server.quit() # then close the connection. This is ok, and perhaps makes it easier to handle bad addressess. I still like using a pipe better and leaving SMTP for the masters (such as Philip Hazel :-)). | Probably the solution should be something like: | | server = smtplib.SMTP(localhost) | for to_addr in members : # for each address in 'listnamemembers', | Try: | # print "to_addr: ", to_addr | # print "from_addr: ", from_addr | # print "msg=" + CRLF, msg | server.sendmail(from_addr, to_addr, msg) # 400 send envlope and msg! | Except ERROR:foofoofoo | # just skip the bad address for now and continue the loop. | # | server.quit() # then close the connection. | | Any discussion or suggestions RTFM and see what exceptions can be thrown. Catch them and print them out so you know what there is and can figure out how to deal with it : try : except Exception , err : print err.__class__ print err print dir( err ) | > In the former case, read RFC2821 and the source of some MTA and see | > how to handle errors. (this is why it is better to simply pipe to | > your MTA and let it deal with it) | | This can be done 2 ways. One of them is a security problem, and the | other one is a security FAILURE. | | 1. sendmail calls. We limit recipients per envlope to 10 in the | sendmail.cf file to limit someone getting an account to do a spam | run. TL avoids this by this loop and sending one envlope per | recipient, I am unsure that direct calls and handing it the list would | be friendly to the limitation. What do you mean by "sendmail calls"? Running sendmail from the commandline? The example (psuedo-)code I gave still only puts one recipient per envelope. | 2. outbound aliases. Sendmail compiles aliases and recognizes a few | imbedded commands when doing so. One of these is ':include:'. This is | the method used by majordomo and some other MLM's. such an aslias | would be: Are you using an outbound alias? I told you not to. It seems that you are saying the same thing. Why do you keep describing them? Once we (you) have decided not to use them, forget about them. | And when something hits this alias, it goes out. FROM ANYONE. Good | news is sendmail sends it out one envlope per person. There is NO | input filtering, ANY spammeister can play with your list at will. So use exim. It will be easy then to only allow members to post. And you can stick spamassassin in the middle to flag spam messages (which you can do with as you like then). I think you are not understanding what spamassassin does or why I think you really want to use it. It is a program that takes a mail message on stdin and returns it on stdout. When it returns it it adds a couple of headers that you can look for. These headers tell you whether or not the message is spam. How is this helpful? If the message is tagged as spam, don't continue delivering it! It provides an easy way for you to block spam messages sent to any address. In fact, I assert that TL is not "secure" right now. I can send a message (call is spam) to your list address, and it will be sent to the list's subscribers. This is how I get all my spam. Instead if you filter the message through a spam detector before relaying it, you can drop these spam messages and not worry about someone guessing your alias address. -D -- He who walks with the wise grows wise, but a companion of fools suffers harm. Proverbs 13:20 From dsh8290@rit.edu Thu Jan 17 21:00:08 2002 From: dsh8290@rit.edu (dman) Date: Thu, 17 Jan 2002 16:00:08 -0500 Subject: [Tutor] Ethics in programming In-Reply-To: <3C472B25.D682518@netzero.net> References: <3C45D4A5.ED9310E@netzero.net> <20020117160520.GC19168@localhost> <3C472B25.D682518@netzero.net> Message-ID: <20020117210008.GD22353@localhost> (oops, missed the in-line part of the post) On Thu, Jan 17, 2002 at 02:51:01PM -0500, kirk Bailey wrote: | dman wrote: | > Why not have TinyList itself manage the subscriber list, instead of | > sendmail. No aliases are needed then, you just stick all the | > addresses on the sendmail command line. Something like : | | Actually, as of now, it does. It uses the smtplib functions to talk to | sendmail and send one envlope per recipient. this is GOOD, there is no | unsecured alias sitting there waiting to be found like there is with | majordomo. Oh, I thought you were using an alias since you talk about it in every post. | Also, someone could use TLwebmanager to manage SENDMAIL lists. Would | never reccomend it, as sendmail lists are not secure at all. But they | could. Such a subscriber list is a simple flat text file, samo as used | by TL. Just write a .info file for it and it shows up on the menu! | | You DID know that majordomo uses a unguarded unfiltered outbound alias | for EVERY list used, I know it only because you say it in every post :-). | The technique to discover prime read meat is simple: Subscribe to a | list there, any list. No need. Just find out what the list's address is and send mail to there! | Send a test message to | 'listname'-outgoing@thatplace.foo; see if you get it. This is a | postmaster psycology test to see if they used a random name or went | with the forms used in the manuals as examples- which it then tells | you not to do. Well, people are creatures of habit. Many still went | and built majordomo lists with the -outgoing part as per example. if | would be spam artist gets that letter, that site's lists are his to | spam; just email listname-ouotgoing and all them folk are going to get | a letter. NO WAY TO STOP IT. Yeah, put spamassassin in the middle and drop (not relay) spam. | By chance, do you host any lists? Not yet. | Try that on TL, abject failure. TL is SECURE. I am loathe to abandon | that. Why do you say it is secure? Nothing is secure. Even ssh isn't secure. So far no one has cracked ssh2, but the key word is "so far". Are you identifying all spam messages automatically in TL? If not, then I can send spam to the list's address and it will get sent to all the subscribers. -D -- Whoever gives heed to instruction prospers, and blessed is he who trusts in the Lord. Proverbs 16:20 From dyoo@hkn.eecs.berkeley.edu Thu Jan 17 23:00:11 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 17 Jan 2002 15:00:11 -0800 (PST) Subject: [Tutor] PRINTING A GIF IMAGE In-Reply-To: <3C47232C.F68ABA@netzero.net> Message-ID: On Thu, 17 Jan 2002, kirk Bailey wrote: > > Here are a few questions that might help us understand the context of the > > bug: Can you show us the string you printed? > Alas, it is gone, removed, and not preserved. I only accord that honor > for successes. *laugh* It can be interesting to probe "failures" as well. I personally have goofed up a LOT; in retrospect, I think I've learned more from my "failures" than my successes. > > What exactly tried to execute the image: Python, > > Python, one of my TL scripts, the menu, 'TLwebmgr.py'. Figured I could > pretty things up later- and hesitated, as text only loaded SO much > faster than a page with images. Have you noticed the tendancy to > websites that take UP TO A MINUTE TO LOAD?!?!? AAIIIEEEE! REVOLTING! > > But back to cases. The statement in question was in the order of > > print ''
' ^ The only thing I see weird in this line is the quote I highlighted up there, but that's probably just a typo in the email and not in the program. How about putting it back in and seeing if you can reproduce the bug? I'd be happy to check the bug out if you can tell me how to get the bug to show up. > I tried several variations, kept getting the same errors and deleted > it- and that error went away. Single quoted, double with escaped > doubles where needed, name it. In Python, the single and double quotes have the same meaning; there's no distinction between them. (The Perl language, on the other hand, makes the distinction between the double quotes that interpolate, and the single quotes that don't.) What kind of error did you get? Do you have a copy of the error recorded in the server access log file? > > Was this for CGI, > Yes, the web menu page. > > or a > > standalone program? > NO. > > What happens when we vary the content of the image? > > It tries to execute it. Now that's strange! How do you know it is trying to execute the image? This is not meant to be a flippant question; it's important because it might clue us into the 'why' of what's going on. >From my understanding, HTML is an inert thing --- it's only when a browser like IE or Netscape looks at HTML that things begin to roll. Python has no control over how any web browser might interpret HTML, so the error is really puzzling to me. From ehoute@zeelandnet.nl Thu Jan 17 23:25:04 2002 From: ehoute@zeelandnet.nl (Ewald van Houte) Date: Fri, 18 Jan 2002 0:25:4 +0100 Subject: [Tutor] Re: Re: How to ignore some decimal values? (dman) Message-ID: <20020117232246.3583C56911@mail.zeelandnet.nl> T24gVGh1LCAyMDAyLTAxLTE3IGF0IDEwOjQ3LCBkbWFuIHdyb3RlOgkNCjxzbmlwPg0KPg0KPkln bm9yaW5nIHRoZSBmYWN0IHRoYXQgYmluYXJ5IGZsb2F0aW5nIHBvaW50IGNhbid0IHJlcHJlc2Vu dCBhbGwNCj5kZWNpbWFsIG51bWJlcnMgOg0KPg0KPmRlZiB0cnVuY2F0ZSggZiAsIG4gKSA6DQo+ ICAgIHNoaWZ0ID0gMTAqKm4NCj4gICAgcmV0dXJuIGludCggZipzaGlmdCApIC8gc2hpZnQNCj4N CjxzbmlwPg0KVGhpcyBkb2Vzbid0IGdpdmUgY29ycmVjdCByZXN1bHQ6DQpQeXRob24gMi4yICgj MjgsIERlYyAyMSAyMDAxLCAxMjoyMToyMikgW01TQyAzMiBiaXQgKEludGVsKV0gb24gd2luMzIN Cj4+PiBwcmludCB0cnVuY2F0ZSg0LjIyLDEpDQo0CQkjc2hvdWxkIGJlIDQuMg0KPj4+IHByaW50 IHRydW5jYXRlKDEyLjU1NCwyKQ0KMTINCg0KZGl2aXNpb24gaXMgaW50L2ludCBzbyByZXN1bHQg aXMgaW50ICh3aXRoIGNsYXNzaWMgZGV2aXNpb24pLCBidXQgYSBmbG9hdCBpcyBuZWVkZWQuIFNt YWxsIG1vZGlmaWNhdGlvbjoNCmRlZiB0cnVuY2F0ZShmLG4pOg0KCXNoaWZ0PTEwKipuDQoJcmV0 dXJuIGludChmKnNoaWZ0KS9mbG9hdChzaGlmdCkNCgkNCj4+PiBwcmludCB0cnVuY2F0ZSg0LjIy LDEpDQo0LjINCj4+PiBwcmludCB0cnVuY2F0ZSgxMi41NTQsMikNCjEyLjU1CQ0KCQ0KSFRILA0K RXdhbGQJDQoNCgkJCQ0KDQoJDQoNCgkNCg0KCQ0KCQ0KDQo= From paul@biostarinc.com Fri Jan 18 00:03:17 2002 From: paul@biostarinc.com (Paulson Ambookan) Date: Thu, 17 Jan 2002 16:03:17 -0800 Subject: [Tutor] Need a Python tutor in New York! Message-ID: <004001c19fb3$8e582bf0$6803a8c0@shannon> This is a multi-part message in MIME format. ------=_NextPart_000_003D_01C19F70.7A0C1410 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Any asistence available. Please forward names or resumes to our office at paul@biostarinc.com Paul Ambookan 116 West 23rd street New York, NY 10011 (Tel) 646-375-2397 (Fax) 646-375-2353 ------=_NextPart_000_003D_01C19F70.7A0C1410 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
Any asistence available.
Please forward names or resumes to our = office at paul@biostarinc.com
 
Paul Ambookan
116 West 23rd = street
New York,=20 NY 10011
(Tel) 646-375-2397
(Fax) = 646-375-2353
------=_NextPart_000_003D_01C19F70.7A0C1410-- From Aleriel Thu Jan 17 23:10:56 2002 From: Aleriel (Anna Tiounina) Date: Thu, 17 Jan 2002 18:10:56 -0500 Subject: [Tutor] PRINTING A GIF IMAGE In-Reply-To: References: Message-ID: <503224583.20020117181056@hedgemaze.org> On Thu, 17 Jan 2002, kirk Bailey wrote: > print ''
' ^^ I'm just guessing, but.. could it be that the ./ above makes the image be executed? I don't see why it'd be so, but on *nix systems ./ usually means execution. -- Regards, Anna aatiouni@uwaterloo.ca From dsh8290@rit.edu Fri Jan 18 00:52:12 2002 From: dsh8290@rit.edu (dman) Date: Thu, 17 Jan 2002 19:52:12 -0500 Subject: [Tutor] Re: Re: How to ignore some decimal values? (dman) In-Reply-To: <20020117232246.3583C56911@mail.zeelandnet.nl> References: <20020117232246.3583C56911@mail.zeelandnet.nl> Message-ID: <20020118005212.GA24578@localhost> On Fri, Jan 18, 2002 at 12:25:04AM +0100, Ewald van Houte wrote: | On Thu, 2002-01-17 at 10:47, dman wrote: | | > | >Ignoring the fact that binary floating point can't represent all | >decimal numbers : | > | >def truncate( f , n ) : | > shift = 10**n | > return int( f*shift ) / shift | > | | This doesn't give correct result: | Python 2.2 (#28, Dec 21 2001, 12:21:22) [MSC 32 bit (Intel)] on win32 | >>> print truncate(4.22,1) | 4 #should be 4.2 | >>> print truncate(12.554,2) | 12 | | division is int/int so result is int (with classic devision), but a | float is needed. Small modification: How about "from __future__ import division" ? ;-). >>> from __future__ import division >>> def truncate( f , n ) : >>> ... shift = 10**n >>> ... return int( f*shift ) / shift >>> ... >>> truncate( 4.22 , 1 ) 4.2000000000000002 (btw, you're right -- I didn't test it before) (also you can see the limitations of binary fp above, print uses str() which rounds for you, the interactive interpreter uses repr() which shows all (or at least more) positions) -D -- One man gives freely, yet gains even more; another withholds unduly, but comes to poverty. Proverbs 11:24 From dyoo@hkn.eecs.berkeley.edu Fri Jan 18 02:45:35 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 17 Jan 2002 18:45:35 -0800 (PST) Subject: [Tutor] Need a Python tutor in New York! In-Reply-To: <004001c19fb3$8e582bf0$6803a8c0@shannon> Message-ID: On Thu, 17 Jan 2002, Paulson Ambookan wrote: > Any asistence available. > Please forward names or resumes to our office at paul@biostarinc.com Dear Paulson, If you're trying to learn Python programming, please feel free to ask your questions on the Tutor mailing list. If you can't find a tutor in New York, please consider Tutor as an alternative. From dyoo@hkn.eecs.berkeley.edu Fri Jan 18 02:55:42 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 17 Jan 2002 18:55:42 -0800 (PST) Subject: [Tutor] How to ignore some decimal values? In-Reply-To: <20020117062630.50579.qmail@web14708.mail.yahoo.com> Message-ID: On Wed, 16 Jan 2002, Titu Kim wrote: > Do someone has any idea on keeping the floor value > of a fixed decimal point n? For instance: > a=12.3451 > b=0.5699 > c=0.0 > > How can i make a,b, and c become float values as > a=12.34 > b=0.56 > c=0.00 > if my n=2. If n=3 > a=12.345 > b=0.569 > c=0.000 By the way, there's a module called "FixedPoint" written by Tim Peters. You can find it here: ftp://python.org/pub/python/contrib-09-Dec-1999/DataStructures/FixedPoint.py.Z If you're doing math that involves keeping decimal places, FixedPoint may be useful for you. For example: ### >>> import FixedPoint >>> a = FixedPoint.FixedPoint("12.3451", 2) >>> a FixedPoint('12.35', 2) >>> b = .75 >>> a * b FixedPoint('9.26', 2) ### Good luck to you. From dyoo@hkn.eecs.berkeley.edu Fri Jan 18 03:06:51 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 17 Jan 2002 19:06:51 -0800 (PST) Subject: [Tutor] Why does pygame still not work? In-Reply-To: Message-ID: On Wed, 16 Jan 2002, James M Lang wrote: > I tried running the monkey source and got this: > > Traceback (most recent call last): > File "C:\Python22\monkey", line 14, in ? > if not pygame.font: print 'Warning, fonts disabled' > AttributeError: 'module' object has no attribute 'font' Yikes! Hmmm... According to the tutorial at: http://pygame.org/docs/tut/ChimpLineByLine.html the Monkey game assumes that 'pygame.font' is set to None if Pygame can't initialize its Font module. But according to the error message, this isn't happening. I'm surprised because you're on a Windows system, so I would have assumed that the prepackaged Pygame should have no problems. You may want to talk with the Pygame folks here: http://pygame.org/info.shtml#maillist They may be better able to help you figure out what's going on here. Sorry about not being able to help more on this. From slime@vsnl.net Fri Jan 18 03:11:19 2002 From: slime@vsnl.net (Prahlad Vaidyanathan) Date: Fri, 18 Jan 2002 03:11:19 GMT Subject: [Tutor] Re: recursive factoring In-Reply-To: References: Message-ID: <20020117173450.GB3446@marvin.clone> Hi, On Wed, 16 Jan 2002 Tim Wilson spewed into the ether: > Hi everyone, > > I've been trying to write a little function that will generate a list of > all the prime factors of a given integer. This seems like the sort of > problem that maps very well to a recursive algorithm. Take the prime > factors of 24 for example: [-- snip --] This works for me : def primefactors(num): """Returns list of prime factors for 'num' """ result = [] if num == 0 : return [] if num % 2 == 0: result.append (2) while num % 2 == 0 : num = num / 2 factor = 3 while num != 1: if num % factor == 0 : result.append(factor) while num % factor == 0 : num = num / factor else : factor = factor + 2 return result pv. -- Prahlad Vaidyanathan Never argue with a woman when she's tired -- or rested. From urnerk@qwest.net Fri Jan 18 03:21:03 2002 From: urnerk@qwest.net (Kirby Urner) Date: Thu, 17 Jan 2002 19:21:03 -0800 Subject: [Tutor] Why does pygame still not work? In-Reply-To: References: Message-ID: <4.2.0.58.20020117191950.01993f00@pop3.norton.antivirus> > >You may want to talk with the Pygame folks here: > > http://pygame.org/info.shtml#maillist > >They may be better able to help you figure out what's >going on here. Sorry about not being able to help >more on this. It's amazing the level you look into so many problems. I've rarely encountered such a dedicated tutor on any list. The Python community owes you a big debt of gratitude. Kirby From glidedon Thu Jan 17 19:34:28 2002 From: glidedon (glidedon) Date: Thu, 17 Jan 2002 19:34:28 +0000 Subject: [Tutor] Truckers log Recap Message-ID: <000397c4b6ea321b_mailit@mail.c-zone.net> Hello kind people, While trying to implement all your great suggestions, I ran in to a problem. Please excuse my ignorance :-) When I replaced this : # collect user input for first 8 days of record day1 = input('Enter total hours on duty day1 ?') day2 = input('Enter total hours on duty day2 ?') day3 = input('Enter total hours on duty day3 ?') day4 = input('Enter total hours on duty day4 ?') day5 = input('Enter total hours on duty day5 ?') day6 = input('Enter total hours on duty day6 ?') day7 = input('Enter total hours on duty day7 ?') day8 = input('Enter total hours on duty day8 ?') with this : for i in range( 8 ): querry_string = " Enter total hours on duty on day%d " % ( i +1 ) input = raw_input(querry_string) history_list.append( input ) I think the values are stored as strings and not numbers and thus breaks the rest of the program. Am I right in this thinking?...and strings are imutable so I can't change them back to numbers later in the program.. Right ? Thanks in advance Don From dyoo@hkn.eecs.berkeley.edu Fri Jan 18 03:25:25 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 17 Jan 2002 19:25:25 -0800 (PST) Subject: [Tutor] Planning to write Python scripts and programs (migrating a Basic macro) In-Reply-To: <23FD7B1A77E8D211BCB900001D108C02018B2913@camelot> Message-ID: On Wed, 16 Jan 2002, McCarney, James Alexander wrote: > I have a Word (Basic) macro that I run against images in docs that I > create to resize them. I wonder if I could either rewrite it totally > in Py or have Py open the document file, execute the macro, save the > file, and quit. Hi James, Yes, it's possible to do this. You may want to look at the book "Python and Win32 Programming", by Mark Hammond: http://www.oreilly.com/catalog/pythonwin32/ I don't have the book with me, but I think the book does cover examples of making Word dance around with Python. If you're a Windows user, and you want to use Python to fiddle around with Windows itself, the book is a must buy. > The Basic code is this (shield your eyes or snip it out now, cos it's > not Py!!!) Don't worry about it; I think we can handle it. *grin* > Sub ReduceTo50() > ' > ' ReduceTo50 Macro > ' Macro created 09/12/01 by James Alexander McCarney > ' > Dim lngX As Long > On Error Resume Next 'Important or the code may puke > > For lngX = 1 To ActiveDocument.InlineShapes.Count > ActiveDocument.InlineShapes(lngX).Select > If (ActiveDocument.InlineShapes(lngX).Type = wdInlineShapeLinkedPicture > Or ActiveDocument.InlineShapes(lngX).Type = wdInlineShapePicture) Then > Selection.InlineShapes(1).ScaleHeight = 40 'Set the height to > whatever you want 50, 40, 30 (for smaller pix) > Selection.InlineShapes(1).ScaleWidth = 40 'Set the height to > whatever you want 50, 40, 30 (for smaller pix) > > End If > > Next lngX > > End Sub Hey, that didn't look too bad at all. Wow, BASIC has changed. *grin* I think this function should translate pretty well to Python, but I don't know well enought the kind of objects we can fool around with. Oh well, I'll try guessing. Here's a very buggy translation --- I'm positive that it won't work --- but it might help you get started: ### def ReduceTo50(): """ ReduceTo50 Macro Macro created 09/12/01 by James Alexander McCarney """ for i in range(1, ActiveDocument.InlineShapes.Count): try: shape = ActiveDocument.InlineShapes(i) shape.Select() if shape.Type in (wdInlineShapeLinedPicture, wdInlineShapePicture): selection.InlineShapes(1).ScaleHeight = 40 selection.InLineShapes(1).ScaleWidth = 40 except Exception, e: ## Do we want to pass errors silently? Maybe ## we should say something to the user to warn them. ## For now, let's just pass it. pass ### Since it looks like you're doing a lot of Windows specific stuff, you'll definitely want to get in contact with the python-win32 mailing list, so that you can also ask for their expertise too. You can find them here: http://mail.python.org/mailman/listinfo/python-win32 Best of wishes to you. Tell us your progress on this; it sounds really interesting! From glidedon Thu Jan 17 19:48:57 2002 From: glidedon (glidedon) Date: Thu, 17 Jan 2002 19:48:57 +0000 Subject: [Tutor] Why does pygame still not work? In-Reply-To: <4.2.0.58.20020117191950.01993f00@pop3.norton.antivirus> References: <4.2.0.58.20020117191950.01993f00@pop3.norton.antivirus> Message-ID: <000397c4eab355a4_mailit@mail.c-zone.net> > >It's amazing the level you look into so many problems. >I've rarely encountered such a dedicated tutor on any >list. The Python community owes you a big debt of >gratitude. > >Kirby Ditto Don From dyoo@hkn.eecs.berkeley.edu Fri Jan 18 03:40:00 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 17 Jan 2002 19:40:00 -0800 (PST) Subject: [Tutor] Truckers log Recap [type conversion] In-Reply-To: <000397c4b6ea321b_mailit@mail.c-zone.net> Message-ID: On Thu, 17 Jan 2002, glidedon wrote: > While trying to implement all your great suggestions, I ran in to a > problem. > > Please excuse my ignorance :-) Hey, no problem. Let's take a look at the program. > # collect user input for first 8 days of record > > day1 = input('Enter total hours on duty day1 ?') > day2 = input('Enter total hours on duty day2 ?') > day3 = input('Enter total hours on duty day3 ?') > day4 = input('Enter total hours on duty day4 ?') > day5 = input('Enter total hours on duty day5 ?') > day6 = input('Enter total hours on duty day6 ?') > day7 = input('Enter total hours on duty day7 ?') > day8 = input('Enter total hours on duty day8 ?') > > with this : > > for i in range( 8 ): > querry_string = " Enter total hours on duty on day%d " % ( i +1 ) > input = raw_input(querry_string) > history_list.append( input ) > > I think the values are stored as strings and not numbers and thus > breaks the rest of the program. Yes, raw_input() always returns strings. Unlike other languages, Python won't automatically turn strings into numbers, since strings can be 'added' together, and we get string concatenation. ### >>> answer = "42" >>> answer + answer '4242' ### We probably want to convert the strings into numerical values. We have a few basic functions we can use to convert between types. The ones I've used a lot are the int(), float(), and str() functions: ### >>> int(answer) 42 >>> float(answer) 42.0 >>> str(answer) '42' >>> float(str(float(int(answer)))) 42.0 ### Of course, calling str() on a string value is a little redundant, but it's nice to know that we can str() pretty much anything. One thing you might run into with these type conversion functions is this: ### >>> int("42.3") Traceback (most recent call last): File "", line 1, in ? ValueError: invalid literal for int(): 42.3 ### int() apparently is designed to be sorta picky about things; it can turn a float into an int, and can turn a string into an int, but if we try to get it to turn a string-that-looks-like-a-float into an int, it just fumbles. But: ### >>> int(float("42.3")) 42 ### will work. > Am I right in this thinking?...and strings are imutable so I can't > change them back to numbers later in the program.. Right ? We can't modify the string value itself, but we can substitute the string in our list with the number: ### for i in range(len(history_list)): history_list[i] = float(history_list[i]) ### And that will "convert" every value in our history_list to a float. Strings are immutable, but that doesn't stop us from just tossing them out of the ship. *grin* Often, people do the type conversion as they're inserting into a list, just so that they don't forget to do it later. We can do the same thing: ### for i in range( 8 ): querry_string = " Enter total hours on duty on day%d " % ( i +1 ) input = raw_input(querry_string) history_list.append( float(input) ) ### Hope this helps! From JJ8404@aol.com Fri Jan 18 03:35:38 2002 From: JJ8404@aol.com (JJ8404@aol.com) Date: Thu, 17 Jan 2002 22:35:38 EST Subject: [Tutor] Help! from JJ8404@aol.com Message-ID: <60.19a6d92e.2978f20a@aol.com> Will anyone who knows python and will like to teach a newbie please email me. I have read a large amount of scripts and can do basic programming. I just need someone to help me along. I have no problem with authority and will do what i am told. If needed i will send you my 2 best programs so you can get an idea where i am. So please if anyone out there fits this description then help a fellow programmer out. i am sure you were a newbies once and know what it feels like. So help me out. Thanx. From dyoo@hkn.eecs.berkeley.edu Fri Jan 18 03:51:32 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 17 Jan 2002 19:51:32 -0800 (PST) Subject: [Tutor] facing a new project In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66C28E@mbtlipnt02.btlabs.bt.co.uk> Message-ID: On Wed, 16 Jan 2002 alan.gauld@bt.com wrote: > > A rough design and working code sounds like a good approach. > > According to Richard Gabriel, it's more important to get > > something out that sorta works and then gradually fix that > > This guy obviously never worked as a maintenance programmer. *laugh* My apologies. I painted him in black and white, but he's much more complicated than that. He's written more than "Worse is Better": Worse is Better: http://www.dreamsongs.com/WorseIsBetter.html Worse is Better is Worse: http://www.dreamsongs.com/NewFiles/worse-is-worse.pdf Is Worse Really Better? http://www.dreamsongs.com/NewFiles/IsWorseReallyBetter.pdf And other essays here: http://www.dreamsongs.com/SiteMap.html From glidedon Thu Jan 17 20:15:46 2002 From: glidedon (glidedon) Date: Thu, 17 Jan 2002 20:15:46 +0000 Subject: [Tutor] Truckers log Recap [type conversion] In-Reply-To: References: Message-ID: <000397c54aa244b1_mailit@mail.c-zone.net> Hi Danny, >And that will "convert" every value in our history_list to a float. >Strings are immutable, but that doesn't stop us from just tossing them out >of the ship. *grin* I like that :-) I just spent several hours trying to figure that out, you just solved it, 10 minutes after I posted to the list. Carefull, you may end up writing my whole program :-) Thanks again Don From idiot1@netzero.net Fri Jan 18 05:41:50 2002 From: idiot1@netzero.net (kirk Bailey) Date: Fri, 18 Jan 2002 00:41:50 -0500 Subject: [Tutor] PRINTING A GIF IMAGE References: Message-ID: <3C47B59E.4995A8ED@netzero.net> Danny Yoo wrote: > > On Thu, 17 Jan 2002, kirk Bailey wrote: > > > > Here are a few questions that might help us understand the context of the > > > bug: Can you show us the string you printed? > > Alas, it is gone, removed, and not preserved. I only accord that honor > > for successes. > > *laugh* > > It can be interesting to probe "failures" as well. I personally have > goofed up a LOT; in retrospect, I think I've learned more from my > "failures" than my successes. > > > > What exactly tried to execute the image: Python, > > > > Python, one of my TL scripts, the menu, 'TLwebmgr.py'. Figured I could > > pretty things up later- and hesitated, as text only loaded SO much > > faster than a page with images. Have you noticed the tendancy to > > websites that take UP TO A MINUTE TO LOAD?!?!? AAIIIEEEE! REVOLTING! > > > > But back to cases. The statement in question was in the order of > > > > print ''
' > ^ > > The only thing I see weird in this line is the quote I highlighted up > there, but that's probably just a typo in the email and not in the > program. > > How about putting it back in and seeing if you can reproduce the bug? > I'd be happy to check the bug out if you can tell me how to get the bug to > show up. sure thing. It will be in the Menu page by morning, so take a look as is convient. > > > I tried several variations, kept getting the same errors and deleted > > it- and that error went away. Single quoted, double with escaped > > doubles where needed, name it. > > In Python, the single and double quotes have the same meaning; there's no > distinction between them. > > (The Perl language, on the other hand, makes the distinction between the > double quotes that interpolate, and the single quotes that don't.) > > What kind of error did you get? Do you have a copy of the error recorded > in the server access log file? > > > > Was this for CGI, > > Yes, the web menu page. > > > or a > > > standalone program? > > NO. > > > > What happens when we vary the content of the image? > > > > It tries to execute it. > > Now that's strange! How do you know it is trying to execute the image? It said so in the web error log. 'ERROR trying to execute pythonpowered.gif' as near as I recall. Resets log on a 24 hour basis, is gone now. > This is not meant to be a flippant question; it's important because it > might clue us into the 'why' of what's going on. I know this is not a silly question, you manage to clearly indicate when the silly bit is set andwhen it is not, and I am grateful for that. > > >From my understanding, HTML is an inert thing --- it's only when a browser > like IE or Netscape looks at HTML that things begin to roll. Ah, but then we introduce a ssi enabled web server, and things start to get intresting. > Python has > no control over how any web browser might interpret HTML, so the error is > really puzzling to me. > It's at the server end, the errors were in the logs. > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- -Respectfully, -Kirk D Bailey Consulting Loose Cannon end www.howlermonkey.net highprimate@howlermonkey.net www.sacredelectron.org idiot1@netzero.net www.tinylist.org grumpy@tinylist.org ---------------------------------------------------- Sign Up for NetZero Platinum Today Only $9.95 per month! http://my.netzero.net/s/signup?r=platinum&refcd=PT97 From idiot1@netzero.net Fri Jan 18 06:15:35 2002 From: idiot1@netzero.net (kirk Bailey) Date: Fri, 18 Jan 2002 01:15:35 -0500 Subject: [Tutor] Strange magic... Message-ID: <3C47BD87.8A98360B@netzero.net> THIS MESSAGE CONTAINS LINES OF POLITICALLY INCORRECT LENGTH. ok, here is the print statement:(Ware word wrap!) print 'click to visit the python language website!' and here is the error report:(DITTO!) [Fri Jan 18 01:03:19 2002] [error] [client 63.208.204.126] file permissions deny server execution: /www/www.tinylist.org/cgi-bin/pythonpowered.gif SO, I took out the "./" part in the img tag. Got this error: [Fri Jan 18 01:07:50 2002] [error] [client 63.208.204.126] file permissions deny server execution: /www/www.tinylist.org/cgi-bin/pythonpowered.gif OK, so let's loko at the permissions... ns# ls -l *.gif -rw-r--r-- 1 root wheel 1077 Jan 18 00:58 pythonpowered.gif ns# world readable. Fine by me. Not executable, which is the error, but WHO THE HELL WANTS TO EXECUTE IT? Well, let's get wierd and turn the X bit on. ns# chmod +x *.gif ns# ls -l *.gif -rwxr-xr-x 1 root wheel 1077 Jan 18 00:58 pythonpowered.gif ns# Still no show on the web page, error log says: [Fri Jan 18 01:12:00 2002] [error] (8)Exec format error: exec of /www/www.tinylist.org/cgi-bin/pythonpowered.gif failed [Fri Jan 18 01:12:00 2002] [error] [client 63.208.204.126] Premature end of script headers: /www/www.tinylist.org/cgi-bin/pythonpowered.gif Hey, this really bites, ya know? They say the most exciting moments in science ar when someone says, 'Now THAT's odd...' This must be one liver quivvering moment, let me tell ya, `cause I'm befuddled. . -- -Respectfully, -Kirk D Bailey Consulting Loose Cannon end www.howlermonkey.net highprimate@howlermonkey.net www.sacredelectron.org idiot1@netzero.net www.tinylist.org grumpy@tinylist.org ---------------------------------------------------- Sign Up for NetZero Platinum Today Only $9.95 per month! http://my.netzero.net/s/signup?r=platinum&refcd=PT97 From idiot1@netzero.net Fri Jan 18 06:29:33 2002 From: idiot1@netzero.net (kirk Bailey) Date: Fri, 18 Jan 2002 01:29:33 -0500 Subject: [Tutor] PUBLIC HEALTH WARNING! Message-ID: <3C47C0CD.B9FDAE88@netzero.net> There is now a coalition to ban the dangerous substance duhydrogen monoxide. This oderless colorless substance is responsable for thousands of deaths annually, millions in property damage, and vast acerage of soil damage. You can learn more about this terrible probeem at http://www.gumbopages.com/fridge/dmho.html -- -Respectfully, -Kirk D Bailey Consulting Loose Cannon end www.howlermonkey.net highprimate@howlermonkey.net www.sacredelectron.org idiot1@netzero.net www.tinylist.org grumpy@tinylist.org ---------------------------------------------------- Sign Up for NetZero Platinum Today Only $9.95 per month! http://my.netzero.net/s/signup?r=platinum&refcd=PT97 From idiot1@netzero.net Fri Jan 18 08:03:32 2002 From: idiot1@netzero.net (kirk Bailey) Date: Fri, 18 Jan 2002 03:03:32 -0500 Subject: [Tutor] error trap Message-ID: <3C47D6D4.CC13E0EA@netzero.net> ok, built a pretty blunt weapon to handle errors. IN TLpost.py; for to_addr in members : # for each address in 'listnamemembers', # print "to_addr: ", to_addr # print "from_addr: ", from_addr # print "msg=" + CRLF, msg try: server.sendmail(from_addr, to_addr, msg) # 400 send envlope and msg! except: print "Bad address='"+to_addr+"'" # don't delete the above line! server.quit() # then close the connection. Testing with a known bad address in the list, it comes up with an error print, and finishes the job. Now, I could set this up as a send operation to the postmaster, or delete the address from the file automatically, whatever. I tend to favor human intervention when there is a problem, rather than trust to a server to do important things such as erase member data. Comments? -- -Respectfully, -Kirk D Bailey Consulting Loose Cannon end www.howlermonkey.net highprimate@howlermonkey.net www.sacredelectron.org idiot1@netzero.net www.tinylist.org grumpy@tinylist.org ---------------------------------------------------- Sign Up for NetZero Platinum Today Only $9.95 per month! http://my.netzero.net/s/signup?r=platinum&refcd=PT97 From dyoo@hkn.eecs.berkeley.edu Fri Jan 18 08:03:24 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 18 Jan 2002 00:03:24 -0800 (PST) Subject: [Tutor] Strange magic... In-Reply-To: <3C47BD87.8A98360B@netzero.net> Message-ID: On Fri, 18 Jan 2002, kirk Bailey wrote: > THIS MESSAGE CONTAINS LINES OF POLITICALLY INCORRECT LENGTH. > ok, here is the print statement:(Ware word wrap!) > print ' src="./pythonpowered.gif" width="110" height="44" border="0" > alt="click to visit the python language website!">' > > > and here is the error report:(DITTO!) > [Fri Jan 18 01:03:19 2002] [error] [client 63.208.204.126] file > permissions deny server execution: > /www/www.tinylist.org/cgi-bin/pythonpowered.gif Ok, now that's more like it! I think I have a reasonable hypothesis! Here's my guess: if a file is within the /cgi-bin/ directory, perhaps a file request for a file in the cgi-bin directory causes Apache to try executing the file. I don't think this has anything to do with Python, as the error message you're showing me, ### > [Fri Jan 18 01:12:00 2002] [error] (8)Exec format error: exec of > /www/www.tinylist.org/cgi-bin/pythonpowered.gif failed > [Fri Jan 18 01:12:00 2002] [error] [client 63.208.204.126] Premature > end of script headers: /www/www.tinylist.org/cgi-bin/pythonpowered.gif ### implies that Apache itself is trying to execute 'pythonpowered.gif'. According to the Apache documentation at: http://httpd.apache.org/docs/mod/mod_alias.html any requests to files in a "ScriptAliased" directory like "/cgi-bin" triggers CGI handling. Despite the fact that 'pythonpowered.gif' has the extension of 'gif', Apache has no way of knowing the context of this! It'll just execute it. (And in fact, one can take advantage of this strangeness by writing a Python script that has a "gif" extension, but actually generates dynamic gif images.) But I'd better stop guessing. *grin* Let's test this hypothesis out. How about moving your pythonpowered.gif file somewhere else like 'icons/', outside your cgi directory? From dyoo@hkn.eecs.berkeley.edu Fri Jan 18 08:08:28 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 18 Jan 2002 00:08:28 -0800 (PST) Subject: [Tutor] error trap In-Reply-To: <3C47D6D4.CC13E0EA@netzero.net> Message-ID: On Fri, 18 Jan 2002, kirk Bailey wrote: > ok, built a pretty blunt weapon to handle errors. > > IN TLpost.py; > for to_addr in members : # for each address in > 'listnamemembers', > # print "to_addr: ", to_addr > # print "from_addr: ", from_addr > # print "msg=" + CRLF, msg > try: > server.sendmail(from_addr, to_addr, msg) # 400 > send envlope and msg! > except: > print "Bad address='"+to_addr+"'" It might be good to also print out the error message that the system itself gives. Every exception that gets thrown brings with it a useful error message for debugging purposes. So: ### try: server.sendmail(from_addr, to_addr, msg) except Exception, e: print "Bad address='"+to_addr+"'" print "exception message:", e ### is more informative, if a bit uglier. Still, it'll help if anything weird happens. > Testing with a known bad address in the list, it comes up with an > error print, and finishes the job. The reason why we still want to print out the exception is as a worst-case thing: what if there were some other way to make server.sendmail() die other than a bad 'to_addr'? There probably isn't a way, but let's make certain that, in the case that we've overlooked something, we'll still get useful information from the error. From idiot1@netzero.net Fri Jan 18 08:17:11 2002 From: idiot1@netzero.net (kirk Bailey) Date: Fri, 18 Jan 2002 03:17:11 -0500 Subject: [Tutor] Strange magic... References: Message-ID: <3C47DA07.B79515F2@netzero.net> Indeed, this is the case. A copy resides in the web directory, and I simply added "../" to the img src declaration, and it displayed. On another front, I now have a try/exception clause in the SMTP loop so if a address is bad and raises an error, it can finish the email delivery run. Much thanks to Mr Brian Penn for noticing the problem on his list. As soon as I am fully awake 2moro, I will copy over and configure the upgraded programs to the other site (my email service); the tinylist.org site is already updated. Goodnight. ZZZZzzzz.... Danny Yoo wrote: > > On Fri, 18 Jan 2002, kirk Bailey wrote: > > > THIS MESSAGE CONTAINS LINES OF POLITICALLY INCORRECT LENGTH. > > ok, here is the print statement:(Ware word wrap!) > > print ' > src="./pythonpowered.gif" width="110" height="44" border="0" > > alt="click to visit the python language website!">' > > > > > > and here is the error report:(DITTO!) > > [Fri Jan 18 01:03:19 2002] [error] [client 63.208.204.126] file > > permissions deny server execution: > > /www/www.tinylist.org/cgi-bin/pythonpowered.gif > > Ok, now that's more like it! I think I have a reasonable hypothesis! > Here's my guess: if a file is within the /cgi-bin/ directory, perhaps a > file request for a file in the cgi-bin directory causes Apache to try > executing the file. > > I don't think this has anything to do with Python, as the error message > you're showing me, > > ### > > [Fri Jan 18 01:12:00 2002] [error] (8)Exec format error: exec of > > /www/www.tinylist.org/cgi-bin/pythonpowered.gif failed > > [Fri Jan 18 01:12:00 2002] [error] [client 63.208.204.126] Premature > > end of script headers: /www/www.tinylist.org/cgi-bin/pythonpowered.gif > ### > > implies that Apache itself is trying to execute 'pythonpowered.gif'. > > According to the Apache documentation at: > > http://httpd.apache.org/docs/mod/mod_alias.html > > any requests to files in a "ScriptAliased" directory like "/cgi-bin" > triggers CGI handling. Despite the fact that 'pythonpowered.gif' has the > extension of 'gif', Apache has no way of knowing the context of this! > It'll just execute it. > > (And in fact, one can take advantage of this strangeness by writing a > Python script that has a "gif" extension, but actually generates dynamic > gif images.) > > But I'd better stop guessing. *grin* Let's test this hypothesis out. > How about moving your pythonpowered.gif file somewhere else like 'icons/', > outside your cgi directory? -- -Respectfully, -Kirk D Bailey Consulting Loose Cannon end www.howlermonkey.net highprimate@howlermonkey.net www.sacredelectron.org idiot1@netzero.net www.tinylist.org grumpy@tinylist.org ---------------------------------------------------- Sign Up for NetZero Platinum Today Only $9.95 per month! http://my.netzero.net/s/signup?r=platinum&refcd=PT97 From lonetwin Fri Jan 18 08:24:01 2002 From: lonetwin (lonetwin) Date: Fri, 18 Jan 2002 13:54:01 +0530 (IST) Subject: [Tutor] Help with tkinter application. Message-ID: Hey Arcege, Thanx for the reply, although it didn't quite work as you suggested, I got the general idea. Thanx to you TKSpell is ready. Have a look below ....you may even want to run it :) !!! Also Eve, thanx for trying it out, the error you mentioned: =============================================== python tkinter_spell.py File "tkinter_spell.py", line 51 label = Label(self, text=' '.join([ x for x in self.result])) ^ SyntaxError: invalid syntax =============================================== most probably is because you are running python version 1.5, which does not understand list comprehensions which are just a short cut way of doing a particular thing to elements of a list. Eg: >>> l = [ "A", "B", "C" ] >>> p = [ x.lower() for x in l ] >>> p ['a', 'b', 'c'] makes sense ?? if it doesn't, ask. Anyways, here's TKSpell, for anybody who care :) Peace Steve ======================================================== #!/usr/bin/python # Written by lonetwin import os from Tkinter import * Ispell = "/usr/bin/ispell" class Spell: global Ispell def __init__(self, word): if not word: return fin, fout = os.popen2('%s -a' % Ispell) version = fout.readline() if version == '': print "ispell not found at %s" % Ispell os.sys.exit(1) fin.write(word) fin.close() self.result = self.intepret(fout.read()) def intepret(self, output): if output[0] == '*': return ('OK',) if output[0] == '+': return ('Root', output[2:].strip()) if output[0] == '-': return ('Compound', output[2:].strip()) if output[0] == '&': return ('Miss', output[2:].strip()) if output[0] == '?': return ('Guess', output[2:].strip()) if output[0] == '#': return ('Not Found',) def getResult(self): return self.result class Tkspell(Frame): def __init__(self, master=None): Frame.__init__(self, master) self.grid(ipadx=4, ipady=4) self.createWidgets() def createWidgets(self): self.entry = Entry(self) self.entry.grid(column=0, row=0, padx=8) self.entry.focus() self.Ok = Button(self, text="Check", activeforeground="blue", command=self.check) self.Ok.bind("", self.check) self.Ok.grid(column=1, row=0) self.label = Label(self) self.ResultList = Listbox(self, selectmode=SINGLE) def check(self, event): self.result = Spell(self.entry.get()).getResult() self.label['text']= self.result[0] self.ResultList.delete(0, END) if self.result[0] in ['OK', 'Root', 'Compound', 'Not Found']: self.label.grid(column=0, row=1, columnspan=2) self.entry.selection_range(0, END) self.entry.focus() self.ResultList.grid_forget() return 0 elif self.result[0] in ['Miss', 'Guess']: suggestions = self.result[1].split(":")[1].split(',') self.label.grid(column=0, row=1, columnspan=2) self.ResultList['height']=len(suggestions) for x in suggestions: self.ResultList.insert(END, x) self.ResultList.selection_set(0) self.ResultList.grid(column=0, row=2, columnspan=2, pady=4, sticky=EW) self.entry.focus() # print self.result if __name__ == '__main__': S = Tkspell() S.master.title("Tkspell") S.mainloop() ========================================================================== -- Nusbaum's Rule: The more pretentious the corporate name, the smaller the organization. (For instance, the Murphy Center for the Codification of Human and Organizational Law, contrasted to IBM, GM, and AT&T.) ---------------------------------------------- From idiot1@netzero.net Fri Jan 18 08:25:38 2002 From: idiot1@netzero.net (kirk Bailey) Date: Fri, 18 Jan 2002 03:25:38 -0500 Subject: [Tutor] error trap References: Message-ID: <3C47DC02.D956776B@netzero.net> Danny Yoo wrote: > > On Fri, 18 Jan 2002, kirk Bailey wrote: > > > ok, built a pretty blunt weapon to handle errors. > > > > IN TLpost.py; > > for to_addr in members : # for each address in > > 'listnamemembers', > > # print "to_addr: ", to_addr > > # print "from_addr: ", from_addr > > # print "msg=" + CRLF, msg > > try: > > server.sendmail(from_addr, to_addr, msg) # 400 send envlope and msg! > > except: > > print "Bad address='"+to_addr+"'" > > It might be good to also print out the error message that the system > itself gives. Every exception that gets thrown brings with it a useful > error message for debugging purposes. So: > > ### > try: > server.sendmail(from_addr, to_addr, msg) > except Exception, e: ^^^^^^^^^ ^ ??? more data please? > print "Bad address='"+to_addr+"'" > print "exception message:", e <-- this must be ther actual error reported? > ### > > is more informative, if a bit uglier. Still, it'll help if anything weird > happens. Should I install a wierdness magnet? Maybe a prayer wheel to obtain blessings? To perdition with cosmetics, just help me understand it! (we can pretty up the listing later...) > > Testing with a known bad address in the list, it comes up with an > > error print, and finishes the job. > > The reason why we still want to print out the exception is as a worst-case > thing: what if there were some other way to make server.sendmail() die > other than a bad 'to_addr'? There probably isn't a way, but let's make > certain that, in the case that we've overlooked something, we'll still get > useful information from the error. Sounds like a plan to me, just tell me a little more bout this statement I threw carrots at. (bad pun I know.) -- -Respectfully, -Kirk D Bailey Consulting Loose Cannon end www.howlermonkey.net highprimate@howlermonkey.net www.sacredelectron.org idiot1@netzero.net www.tinylist.org grumpy@tinylist.org ---------------------------------------------------- Sign Up for NetZero Platinum Today Only $9.95 per month! http://my.netzero.net/s/signup?r=platinum&refcd=PT97 From kauphlyn@speakeasy.org Fri Jan 18 09:23:06 2002 From: kauphlyn@speakeasy.org (Daniel Coughlin) Date: Fri, 18 Jan 2002 01:23:06 -0800 (PST) Subject: [Tutor] Why does pygame still not work? In-Reply-To: <4.2.0.58.20020117191950.01993f00@pop3.norton.antivirus> Message-ID: On Thu, 17 Jan 2002, Kirby Urner wrote: > > > > >You may want to talk with the Pygame folks here: > > > > http://pygame.org/info.shtml#maillist > > > >They may be better able to help you figure out what's > >going on here. Sorry about not being able to help > >more on this. > > It's amazing the level you look into so many problems. > I've rarely encountered such a dedicated tutor on any > list. The Python community owes you a big debt of > gratitude. > > Kirby I absolutely concur. Mr Yoo's generosity to this list and community far surpasses any amount of praise I can articulate. At the same time I thank everybody on this list - tutor and tutee - for participating in and generating one of the most fantastic resources available. Python truly rocks. And so do you. From kauphlyn@speakeasy.org Fri Jan 18 10:34:46 2002 From: kauphlyn@speakeasy.org (Daniel Coughlin) Date: Fri, 18 Jan 2002 02:34:46 -0800 (PST) Subject: [Tutor] error trap In-Reply-To: <3C47DC02.D956776B@netzero.net> Message-ID: On Fri, 18 Jan 2002, kirk Bailey wrote: > > > Danny Yoo wrote: > > > > On Fri, 18 Jan 2002, kirk Bailey wrote: > > > > > ok, built a pretty blunt weapon to handle errors. > > > > > > IN TLpost.py; > > > for to_addr in members : # for each address in > > > 'listnamemembers', > > > # print "to_addr: ", to_addr > > > # print "from_addr: ", from_addr > > > # print "msg=" + CRLF, msg > > > try: > > > server.sendmail(from_addr, to_addr, msg) # 400 send envlope and msg! > > > except: > > > print "Bad address='"+to_addr+"'" > > > > It might be good to also print out the error message that the system > > itself gives. Every exception that gets thrown brings with it a useful > > error message for debugging purposes. So: > > > > ### > > try: > > server.sendmail(from_addr, to_addr, msg) > > except Exception, e: > ^^^^^^^^^ ^ ??? more data please? > > print "Bad address='"+to_addr+"'" > > print "exception message:", e <-- this must be ther actual error reported? > > > ### > > > > is more informative, if a bit uglier. Still, it'll help if anything weird > > happens. > > Should I install a wierdness magnet? Maybe a prayer wheel to obtain > blessings? > > To perdition with cosmetics, just help me understand it! > (we can pretty up the listing later...) > > > > Testing with a known bad address in the list, it comes up with an > > > error print, and finishes the job. > > > > The reason why we still want to print out the exception is as a worst-case > > thing: what if there were some other way to make server.sendmail() die > > other than a bad 'to_addr'? There probably isn't a way, but let's make > > certain that, in the case that we've overlooked something, we'll still get > > useful information from the error. > > Sounds like a plan to me, just tell me a little more bout this > statement I threw carrots at. > (bad pun I know.) The statement you threw carrots at: 1. Exception is the base class for all exceptions. All Exceptions are built from this class. 2. The variable e will be an instance of the Exception class. Adding this variable is optional to except statement. 3. Depending on the exception, you may get more information about it by reviewing e.args. 4. You can refine you exception by saying >>> except SpecificException, s such as IndexError or TypeError or you can define your own by extending the Exception class. 5. And last! you can play in the interpreter like this: >>> try: >>> l = [1] >>> l[2] >>>except Exception, e: >>> print e list out of range >>> l = [1] >>> l[2] >>> Traceback (most recent call last): ... IndexError: list out of range Note that IndexError is a specific type of exception, derived from the Exception class. and if this were one of the problems you might encounter in you code you coulde write >>> except IndexError, i: whatever in this way you can specify what way you want to handle specific exceptions. hope this helps! Daniel From lha2@columbia.edu Fri Jan 18 11:50:12 2002 From: lha2@columbia.edu (Lloyd Hugh Allen) Date: Fri, 18 Jan 2002 06:50:12 -0500 Subject: [Tutor] fib (was recursive factoring) References: Message-ID: <3C480BF4.AF5463ED@mail.verizon.net> Of course, an even faster way to compute fibs would be to use import math r = (1 + math.sqrt(5))/2 s = (1 - math.sqrt(5))/2 def fib(n): return long((r**n - s**n)/math.sqrt(5)) if only Python had infinite precision. This method should break about where floats run out of digits. Might be able to squeeze out a few more by using ((1 + math.sqrt(5))**n) / (2**n) instead of r**n or even more if there's an infinite precision math module out there. Maybe by using continued fractions, unless that would be slower than using a list-growing technique to "recursively" compute fibs in the first place. Lots of info on above relationship @ http://www.mcs.surrey.ac.uk/Personal/R.Knott/Fibonacci/fib.html Sometimes (granted, not above, since it breaks--although I'm curious where) recognizing a general formula is the best way to recurse. For instance, I would definitely prefer def sum1(first,last): return ((first + last)*(last - first + 1))/2 to some algorithm that first creates a list of the numbers from first to last and then adds them up. (last - first + 1) is the number of numbers in the list. If I remembered it right, the formula is due to Gauss (and if I remembered the formula wrong, it's my own creation). We usually think of it as the average of the first and last number, times the number of elements in the list; however, if you first take the average, you'll lose a .5 when dividing an odd sum. (I haven't 2.2ed yet, and wouldn't want a groady float getting in there anyway). If you want to use this with really big numbers, neither of which are yet long, it would probably be good to change (first + last) to (first + long(last)) (which somehow amuses me anyway). Danny Yoo wrote: > > On Thu, 17 Jan 2002 mikalzet@libero.it wrote: > > > def fibonacci(n): > > a = 1L > > b = 1L > > if n < 2: return 1 > > else: > > z=2 > > while z <= n: > > c = a + b > > a, b = b, c > > z = z + n > > return c > > From pythontutor@venix.com Fri Jan 18 13:18:49 2002 From: pythontutor@venix.com (Lloyd Kvam) Date: Fri, 18 Jan 2002 08:18:49 -0500 Subject: [Tutor] Planning to write Python scripts and programs (migrating a Basic macro) References: Message-ID: <3C4820B9.3040101@venix.com> I second Danny's book recommendation. Here is a snippet of code that we have been using for creating a report in Word. There's more, but it starts depending on other classes that we've written, so it is harder to use anywhere. As you can see from the comment, the book includes enough sample code to get you productive very quickly. (With WordReport, we started with the sample code and made modifications to fit our needs.) import win32com.client class WordReport: """ Wrapper around Word 8 documents to make them easy to build. Has variables for the Applications, Document and Selection; most methods add things at the end of the document. Taken from 'Python Programming on Win32' """ def __init__(self, templatefile=None): self.wordApp = win32com.client.Dispatch('Word.Application') if templatefile == None: self.wordDoc = self.wordApp.Documents.Add() else: self.wordDoc = self.wordApp.Documents.Add(Template=templatefile) #set up the selection self.wordDoc.Range(0,0).Select() self.wordSel = self.wordApp.Selection def show(self): # convenience when debugging self.wordApp.ActiveWindow.View.Type = 3 # wdPageView self.wordApp.Visible = 1 def getStyleList(self): # returns a dictionary of the styles in a document self.styles = [] stylecount = self.wordDoc.Styles.Count for i in range(1, stylecount + 1): styleObject = self.wordDoc.Styles(i) self.styles.append(styleObject.NameLocal) def saveAs(self, filename): self.wordDoc.SaveAs(filename) def printout(self): self.wordDoc.PrintOut() def selectEnd(self): # ensures insertion point is at the end of the document self.wordSel.Collapse(0) # 0 is the constant wdCollapseEnd; don't want to depend # on makepy support. def selectBegin(self): # ensures insertion point is at the start of selection self.wordSel.Collapse() # default of Collapse() is start def addText(self, text, bookmark=None): if bookmark: self.wordDoc.Bookmarks(bookmark).Select() self.wordApp.Selection.TypeText(text) else: self.wordSel.InsertAfter(text) self.selectEnd() def addStyledPara(self, text, stylename): if text[-1] <> '\n': text = text + '\n' self.wordSel.InsertAfter(text) self.wordSel.Style = stylename self.selectEnd() Danny Yoo wrote: > On Wed, 16 Jan 2002, McCarney, James Alexander wrote: > > >>I have a Word (Basic) macro that I run against images in docs that I >>create to resize them. I wonder if I could either rewrite it totally >>in Py or have Py open the document file, execute the macro, save the >>file, and quit. >> > > Hi James, > > Yes, it's possible to do this. You may want to look at the book "Python > and Win32 Programming", by Mark Hammond: > > http://www.oreilly.com/catalog/pythonwin32/ > > I don't have the book with me, but I think the book does cover examples of > making Word dance around with Python. If you're a Windows user, and you > want to use Python to fiddle around with Windows itself, the book is a > must buy. > > > >>The Basic code is this (shield your eyes or snip it out now, cos it's >>not Py!!!) >> > > Don't worry about it; I think we can handle it. *grin* > > > >>Sub ReduceTo50() >>' >>' ReduceTo50 Macro >>' Macro created 09/12/01 by James Alexander McCarney >>' >>Dim lngX As Long >>On Error Resume Next 'Important or the code may puke >> >>For lngX = 1 To ActiveDocument.InlineShapes.Count >> ActiveDocument.InlineShapes(lngX).Select >> If (ActiveDocument.InlineShapes(lngX).Type = wdInlineShapeLinkedPicture >>Or ActiveDocument.InlineShapes(lngX).Type = wdInlineShapePicture) Then >> Selection.InlineShapes(1).ScaleHeight = 40 'Set the height to >>whatever you want 50, 40, 30 (for smaller pix) >> Selection.InlineShapes(1).ScaleWidth = 40 'Set the height to >>whatever you want 50, 40, 30 (for smaller pix) >> >> End If >> >>Next lngX >> >>End Sub >> > > Hey, that didn't look too bad at all. Wow, BASIC has changed. *grin* > > > I think this function should translate pretty well to Python, but I don't > know well enought the kind of objects we can fool around with. Oh well, > I'll try guessing. Here's a very buggy translation --- I'm positive that > it won't work --- but it might help you get started: > > ### > def ReduceTo50(): > """ > ReduceTo50 Macro > Macro created 09/12/01 by James Alexander McCarney > """ > for i in range(1, ActiveDocument.InlineShapes.Count): > try: > shape = ActiveDocument.InlineShapes(i) > shape.Select() > if shape.Type in (wdInlineShapeLinedPicture, > wdInlineShapePicture): > selection.InlineShapes(1).ScaleHeight = 40 > selection.InLineShapes(1).ScaleWidth = 40 > except Exception, e: > ## Do we want to pass errors silently? Maybe > ## we should say something to the user to warn them. > ## For now, let's just pass it. > pass > ### > > Since it looks like you're doing a lot of Windows specific stuff, you'll > definitely want to get in contact with the python-win32 mailing list, so > that you can also ask for their expertise too. You can find them here: > > http://mail.python.org/mailman/listinfo/python-win32 > > > Best of wishes to you. Tell us your progress on this; it sounds really > interesting! > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From mikalzet@libero.it Fri Jan 18 13:20:52 2002 From: mikalzet@libero.it (mikalzet@libero.it) Date: Fri, 18 Jan 2002 14:20:52 +0100 (CET) Subject: [Tutor] fib (was recursive factoring) In-Reply-To: <3C480BF4.AF5463ED@mail.verizon.net> Message-ID: On Fri, 18 Jan 2002, Lloyd Hugh Allen wrote: > Of course, an even faster way to compute fibs would be to use > > import math > r = (1 + math.sqrt(5))/2 > s = (1 - math.sqrt(5))/2 > def fib(n): > return long((r**n - s**n)/math.sqrt(5)) > > if only Python had infinite precision. This method should break about > where floats run out of digits. Which proves one thing: to make a good program to solve a problem it is necessary first to have a good knowledge of how to solve the problem normally ... I didn't have any idea of how to solve fibs mathematically. (Nor do I have any idea of what they may be useful for :-) ) I also didn't realize when we started speaking about factoring that we were actually entering such dangerous ground (encryption and so forth). You mean to say that if tomorrow a mathematician dreams up a quick and easy factoring solution for huge numbers ... all the gpg and ssl etc. becomes a pack of useless byte-exchanging software ? What is the limit for floats in python anyway ? I've seen that long integers are very long indeed ... are floats as long or not ? -- Michele Alzetta From alan.gauld@bt.com Fri Jan 18 13:57:21 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Fri, 18 Jan 2002 13:57:21 -0000 Subject: [Tutor] PRINTING A GIF IMAGE Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C2B6@mbtlipnt02.btlabs.bt.co.uk> > I'm just guessing, but.. could it be that the ./ above makes the image > be executed? I don't see why it'd be so, but on *nix systems ./ > usually means execution. Nope, '.' means execute thus: $ . /foo executes /foo in a Bourne type shell environment. ./ is a path relative to the current directory(.). Alan g From arcege@speakeasy.net Fri Jan 18 14:03:40 2002 From: arcege@speakeasy.net (Michael P. Reilly) Date: Fri, 18 Jan 2002 09:03:40 -0500 Subject: [Tutor] Help with tkinter application. In-Reply-To: ; from lonetwin@yahoo.com on Fri, Jan 18, 2002 at 01:54:01PM +0530 References: Message-ID: <20020118090340.A900@speakeasy.net> On Fri, Jan 18, 2002 at 01:54:01PM +0530, lonetwin wrote: > Hey Arcege, > Thanx for the reply, although it didn't quite work as you suggested, I got > the general idea. Thanx to you TKSpell is ready. Have a look below ....you > may even want to run it :) !!! > Also Eve, thanx for trying it out, the error you mentioned: > > =============================================== > python tkinter_spell.py > File "tkinter_spell.py", line 51 > label = Label(self, text=' '.join([ x for x in self.result])) > ^ > SyntaxError: invalid syntax > =============================================== > most probably is because you are running python version 1.5, which does > not understand list comprehensions which are just a short cut way of doing a > particular thing to elements of a list. > > Eg: > >>> l = [ "A", "B", "C" ] > >>> p = [ x.lower() for x in l ] > >>> p > ['a', 'b', 'c'] > > makes sense ?? if it doesn't, ask. List comprehensions are about the same as filter and map, just in a different format. I find the format to be less intuitive and syntactically more confusing with 'for' and 'if' statements. Also, string methods were added in 2.0, so ' '.join(...) would not work either. >>> l = [ "A", "B", "C" ] >>> p = map(string.lower, l) >>> p ['a', 'b', 'c'] And more importantly, both list comprehensions and the functional mechanisms work with sequences, not just lists. The list comprehension above is the same as 'list(self.result)' and 'map(None, self.result)'. But also, the join method works with any sequence. You could have just written: ' '.join( self.result ) As an aside, the "os.sys.exit()" function call should just be "sys.exit()". The program runs well tho. Good job. -Arcege From James.Alexander.McCarney@Cognicase.com Fri Jan 18 15:01:07 2002 From: James.Alexander.McCarney@Cognicase.com (McCarney, James Alexander) Date: Fri, 18 Jan 2002 10:01:07 -0500 Subject: [Tutor] Planning to write Python scripts and programs (migrat ing a Basic macro) Message-ID: <23FD7B1A77E8D211BCB900001D108C02018B2924@camelot> Hi Danny, Lloyd, and Python tutors universal and triumphant...<8-) Thank you for your tips! At first I thought I had committed a hacker sin by posting another language to the pristine Py group. Whew. Anyhow, I continue to be amazed both by the generosity of people on the list and by the amazing breadth and depth of the Python language. Since right now I am busier than a one-legged man at an *ss-kicking contest, I have to work on this at the end of the day. But what is cool is that I have some very interesting stuff to do and things to which I look forward as dusk approaches. To end this saccharine post, some Py code. <8-) >>> s="Thank you, Py-guys!" >>> print s >>> import sys; sys.exit() James Alexander McCarney, technical writer (450) 928-3386 x2262 Cognicase - M3i Systems, 1111 Saint-Charles Avenue West 11th Floor, East Tower, Longueuil, Quebec, J4K 5G4 Canada http://www.m3isystems.com mailto:James.Alexander.McCarney@Cognicase.com From qhup@yahoo.com Fri Jan 18 15:09:57 2002 From: qhup@yahoo.com (Justin khup) Date: Fri, 18 Jan 2002 07:09:57 -0800 (PST) Subject: [Tutor] installing python on Sun OS 5.6 Message-ID: <20020118150957.36450.qmail@web10802.mail.yahoo.com> --0-51834861-1011366597=:34666 Content-Type: text/plain; charset=us-ascii Hi there, Can anyone help me on how to install python on Sun OS 5.6. I badly need to install python but am new to unix OS .I would be extra glad if you could provide me with every step.Thanks in advance. qhup --------------------------------- Do You Yahoo!? Send FREE video emails in Yahoo! Mail. --0-51834861-1011366597=:34666 Content-Type: text/html; charset=us-ascii

Hi there,

  Can anyone help me on how to install python on Sun OS 5.6. I badly need to install python but am new to unix OS .I would be extra glad if you could provide me with every step.Thanks in advance.

qhup



Do You Yahoo!?
Send FREE video emails in Yahoo! Mail. --0-51834861-1011366597=:34666-- From Eugene.Leitl@lrz.uni-muenchen.de Fri Jan 18 15:26:42 2002 From: Eugene.Leitl@lrz.uni-muenchen.de (Eugene Leitl) Date: Fri, 18 Jan 2002 16:26:42 +0100 (MET) Subject: [Tutor] installing python on Sun OS 5.6 In-Reply-To: <20020118150957.36450.qmail@web10802.mail.yahoo.com> Message-ID: Usually, you just untar the tarball, cd into the directory, then enter $ ./configure $ make $ make test $ su $ make install Tell me if you have problems. There might be Solaris packages available, which would be preferable (installable with pkgadd). There's sunfreeware something, which has binary packages. On Fri, 18 Jan 2002, Justin khup wrote: > > Hi there, > > Can anyone help me on how to install python on Sun OS 5.6. I badly > need to install python but am new to unix OS .I would be extra glad if > you could provide me with every step.Thanks in advance. > > qhup > > > > --------------------------------- > Do You Yahoo!? > Send FREE video emails in Yahoo! Mail. -- Eugen* Leitl leitl ______________________________________________________________ ICBMTO: N48 04'14.8'' E11 36'41.2'' http://www.leitl.org 57F9CFD3: ED90 0433 EB74 E4A9 537F CFF5 86E7 629B 57F9 CFD3 From alan.gauld@bt.com Fri Jan 18 15:48:50 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Fri, 18 Jan 2002 15:48:50 -0000 Subject: [Tutor] Help! from JJ8404@aol.com Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C2B9@mbtlipnt02.btlabs.bt.co.uk> > Will anyone who knows python and will like to teach a newbie > please email me. Why settle for any *one* when you can have the full list help you out? Thats what we are here for. Ask your questions, post your code samples (and any error messages you get!) and whoever has time and sees it will do their best to answer. Welcome to the Python tutor list :-) Alan g. Author of the 'Learning to Program' web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld@bt.com Fri Jan 18 16:48:50 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Fri, 18 Jan 2002 16:48:50 -0000 Subject: [Tutor] Strange magic... Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C2BB@mbtlipnt02.btlabs.bt.co.uk> > and here is the error report:(DITTO!) > [Fri Jan 18 01:03:19 2002] [error] [client 63.208.204.126] file > permissions deny server execution: > /www/www.tinylist.org/cgi-bin/pythonpowered.gif Its trying to execute it because its in the cgi-bin directory. Move your images into an images directory instead. Any file in the cgi-bin will be "executed" by the server regardless of type. > world readable. Fine by me. Not executable, which is the error, but > WHO THE HELL WANTS TO EXECUTE IT? The server by virtue of it being in cgi-bin Alan G From idiot1@netzero.net Fri Jan 18 16:55:20 2002 From: idiot1@netzero.net (kirk Bailey) Date: Fri, 18 Jan 2002 11:55:20 -0500 Subject: [Tutor] Mail-SpamAssassin Message-ID: <3C485378.75960C84@netzero.net> After reviewing the spamassassin program and docs, I have come to several conclusions: 1. I need to read it WAY more. WAY WAY more. 2. I am not going to install a call to it on TL, although I will install a line to detect the added header -and trash any letter containing it. 3. I am going to install is systemwide for my entire server for all email at all times. As it will be in there working, TL will not need specific calls to it, merely the ability to detect the added header line. -- -Respectfully, -Kirk D Bailey Consulting Loose Cannon end www.howlermonkey.net highprimate@howlermonkey.net www.sacredelectron.org idiot1@netzero.net www.tinylist.org grumpy@tinylist.org ---------------------------------------------------- Sign Up for NetZero Platinum Today Only $9.95 per month! http://my.netzero.net/s/signup?r=platinum&refcd=PT97 From urnerk@qwest.net Fri Jan 18 17:47:32 2002 From: urnerk@qwest.net (Kirby Urner) Date: Fri, 18 Jan 2002 09:47:32 -0800 Subject: [Tutor] fib (was recursive factoring) In-Reply-To: References: <3C480BF4.AF5463ED@mail.verizon.net> Message-ID: <4.2.0.58.20020118093438.01b11a80@pop3.norton.antivirus> > >You mean to say that if tomorrow a mathematician dreams >up a quick and easy factoring solution for huge numbers ... >all the gpg and ssl etc. becomes a pack of useless >byte-exchanging software ? Yes. Anything RSA-based that is. I think ssl qualifies. You can bet many talented math heads have cracked their nut on this problem. Fame and glory awaits the solver. In the meantime, lots of good math has stemmed from the research, as a side-effect. >What is the limit for floats in python anyway ? I've seen that long >integers are very long indeed ... are floats as long or not ? Floats occupy a fixed number of bits, some of which belong to a mantissa, some to the exponent, and then there's the sign. No way to use floats to get good number- theoretic results involving long strings of digits. There are some Python modules that do something like infinite precision floats. Harder to use than long integers but possible. Here's another fib program that computes the nth fib: def fib(n): a,b = 0,1 while n: a,b = b,a+b n -= 1 return a >>> [fib(i) for i in range(10)] [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] In Python 2.2, you don't have to start out with a,b long -- it goes to long automatically, when a,b start getting big. The 10,000th fib is well within the capabilities of this program. No method with ordinary floats'll do it. Kirby From idiot1@netzero.net Fri Jan 18 18:08:31 2002 From: idiot1@netzero.net (kirk Bailey) Date: Fri, 18 Jan 2002 13:08:31 -0500 Subject: [Tutor] error trap References: Message-ID: <3C48649F.C652ED3E@netzero.net> OK, I am trying to handle it with a default except statement, and capture the error feedback, but I get nothing but complaints when I try THIS: for to_addr in members : # for each address in 'listnamemembers', # print "to_addr: ", to_addr # print "from_addr: ", from_addr # print "msg=" + CRLF, msg try: server.sendmail(from_addr, to_addr, msg) # 400 send envlope and msg! except e: print "POSSIBLE Bad address='"+to_addr+"' ?" print "exception message:", e So I removed the 'e' in the line 'except e:' and the second print statement in the exception block. This handles bad emails, so preserves function and continues delivery. Still, I would love to see that error feedback if possible- maybe have it email me with it. Daniel Coughlin wrote: > > On Fri, 18 Jan 2002, kirk Bailey wrote: > > > > > > > Danny Yoo wrote: > > > > > > On Fri, 18 Jan 2002, kirk Bailey wrote: > > > > > > > ok, built a pretty blunt weapon to handle errors. > > > > > > > > IN TLpost.py; > > > > for to_addr in members : # for each address in > > > > 'listnamemembers', > > > > # print "to_addr: ", to_addr > > > > # print "from_addr: ", from_addr > > > > # print "msg=" + CRLF, msg > > > > try: > > > > server.sendmail(from_addr, to_addr, msg) # 400 send envlope and msg! > > > > except: > > > > print "Bad address='"+to_addr+"'" > > > > > > It might be good to also print out the error message that the system > > > itself gives. Every exception that gets thrown brings with it a useful > > > error message for debugging purposes. So: > > > > > > ### > > > try: > > > server.sendmail(from_addr, to_addr, msg) > > > except Exception, e: > > ^^^^^^^^^ ^ ??? more data please? > > > print "Bad address='"+to_addr+"'" > > > print "exception message:", e <-- this must be ther actual error reported? > > > > > ### > > > > > > is more informative, if a bit uglier. Still, it'll help if anything weird > > > happens. > > > > Should I install a wierdness magnet? Maybe a prayer wheel to obtain > > blessings? > > > > To perdition with cosmetics, just help me understand it! > > (we can pretty up the listing later...) > > > > > > Testing with a known bad address in the list, it comes up with an > > > > error print, and finishes the job. > > > > > > The reason why we still want to print out the exception is as a worst-case > > > thing: what if there were some other way to make server.sendmail() die > > > other than a bad 'to_addr'? There probably isn't a way, but let's make > > > certain that, in the case that we've overlooked something, we'll still get > > > useful information from the error. > > > > Sounds like a plan to me, just tell me a little more bout this > > statement I threw carrots at. > > (bad pun I know.) > > The statement you threw carrots at: > > 1. Exception is the base class for all exceptions. All Exceptions are built from > this class. > > 2. The variable e will be an instance of the Exception class. Adding this > variable is optional to except statement. > > 3. Depending on the exception, you may get more information about it by > reviewing > e.args. > > 4. You can refine you exception by saying > >>> except SpecificException, s > such as IndexError or TypeError or you can define your own by extending the > Exception class. > > 5. And last! you can play in the interpreter like this: > >>> try: > >>> l = [1] > >>> l[2] > >>>except Exception, e: > >>> print e > list out of range > >>> l = [1] > >>> l[2] > >>> > Traceback (most recent call last): > ... > IndexError: list out of range > > Note that IndexError is a specific type of exception, derived from the Exception > class. > > and if this were one of the problems you might encounter in you code > you coulde write > >>> except IndexError, i: > whatever > > in this way you can specify what way you want to handle specific exceptions. > > hope this helps! > > Daniel > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- -Respectfully, -Kirk D Bailey Consulting Loose Cannon end www.howlermonkey.net highprimate@howlermonkey.net www.sacredelectron.org idiot1@netzero.net www.tinylist.org grumpy@tinylist.org ---------------------------------------------------- Sign Up for NetZero Platinum Today Only $9.95 per month! http://my.netzero.net/s/signup?r=platinum&refcd=PT97 From kauphlyn@speakeasy.org Fri Jan 18 18:43:57 2002 From: kauphlyn@speakeasy.org (Daniel Coughlin) Date: Fri, 18 Jan 2002 10:43:57 -0800 (PST) Subject: [Tutor] error trap In-Reply-To: <3C48649F.C652ED3E@netzero.net> Message-ID: On Fri, 18 Jan 2002, kirk Bailey wrote: > OK, I am trying to handle it with a default except statement, and > capture the error feedback, but I get nothing but complaints when I > try THIS: > > for to_addr in members : # for each address in > 'listnamemembers', > # print "to_addr: ", to_addr > # print "from_addr: ", from_addr > # print "msg=" + CRLF, msg > try: > server.sendmail(from_addr, to_addr, msg) # 400 > send envlope and msg! > except e: This line should be except Exception, e: or whatever specific exception you want: except NameError, n: then you can email yourself the value of n. Hope this helps! Daniel From toodles@yifan.net Fri Jan 18 18:49:58 2002 From: toodles@yifan.net (Andy W) Date: Sat, 19 Jan 2002 02:49:58 +0800 Subject: [Tutor] error trap References: <3C48649F.C652ED3E@netzero.net> Message-ID: <001301c1a050$ef07faf0$da00a8c0@Sun> Hiya > OK, I am trying to handle it with a default except statement, and > capture the error feedback, but I get nothing but complaints when I > try THIS: It should be "except Exception, e:", not "except e:". Try that out. Andy > > for to_addr in members : # for each address in > 'listnamemembers', > # print "to_addr: ", to_addr > # print "from_addr: ", from_addr > # print "msg=" + CRLF, msg > try: > server.sendmail(from_addr, to_addr, msg) # 400 > send envlope and msg! > except e: > print "POSSIBLE Bad address='"+to_addr+"' ?" > print "exception message:", e > > So I removed the 'e' in the line 'except e:' and the second print > statement in the exception block. > This handles bad emails, so preserves function and continues delivery. > Still, I would love to see that error feedback if possible- maybe have > it email me with it. > > Daniel Coughlin wrote: > > > > On Fri, 18 Jan 2002, kirk Bailey wrote: > > > > > > > > > > > Danny Yoo wrote: > > > > > > > > On Fri, 18 Jan 2002, kirk Bailey wrote: > > > > > > > > > ok, built a pretty blunt weapon to handle errors. > > > > > > > > > > IN TLpost.py; > > > > > for to_addr in members : # for each address in > > > > > 'listnamemembers', > > > > > # print "to_addr: ", to_addr > > > > > # print "from_addr: ", from_addr > > > > > # print "msg=" + CRLF, msg > > > > > try: > > > > > server.sendmail(from_addr, to_addr, msg) # 400 send envlope and msg! > > > > > except: > > > > > print "Bad address='"+to_addr+"'" > > > > > > > > It might be good to also print out the error message that the system > > > > itself gives. Every exception that gets thrown brings with it a useful > > > > error message for debugging purposes. So: > > > > > > > > ### > > > > try: > > > > server.sendmail(from_addr, to_addr, msg) > > > > except Exception, e: > > > ^^^^^^^^^ ^ ??? more data please? > > > > print "Bad address='"+to_addr+"'" > > > > print "exception message:", e <-- this must be ther actual error reported? > > > > > > > ### > > > > > > > > is more informative, if a bit uglier. Still, it'll help if anything weird > > > > happens. > > > > > > Should I install a wierdness magnet? Maybe a prayer wheel to obtain > > > blessings? > > > > > > To perdition with cosmetics, just help me understand it! > > > (we can pretty up the listing later...) > > > > > > > > Testing with a known bad address in the list, it comes up with an > > > > > error print, and finishes the job. > > > > > > > > The reason why we still want to print out the exception is as a worst-case > > > > thing: what if there were some other way to make server.sendmail() die > > > > other than a bad 'to_addr'? There probably isn't a way, but let's make > > > > certain that, in the case that we've overlooked something, we'll still get > > > > useful information from the error. > > > > > > Sounds like a plan to me, just tell me a little more bout this > > > statement I threw carrots at. > > > (bad pun I know.) > > > > The statement you threw carrots at: > > > > 1. Exception is the base class for all exceptions. All Exceptions are built from > > this class. > > > > 2. The variable e will be an instance of the Exception class. Adding this > > variable is optional to except statement. > > > > 3. Depending on the exception, you may get more information about it by > > reviewing > > e.args. > > > > 4. You can refine you exception by saying > > >>> except SpecificException, s > > such as IndexError or TypeError or you can define your own by extending the > > Exception class. > > > > 5. And last! you can play in the interpreter like this: > > >>> try: > > >>> l = [1] > > >>> l[2] > > >>>except Exception, e: > > >>> print e > > list out of range > > >>> l = [1] > > >>> l[2] > > >>> > > Traceback (most recent call last): > > ... > > IndexError: list out of range > > > > Note that IndexError is a specific type of exception, derived from the Exception > > class. > > > > and if this were one of the problems you might encounter in you code > > you coulde write > > >>> except IndexError, i: > > whatever > > > > in this way you can specify what way you want to handle specific exceptions. > > > > hope this helps! > > > > Daniel > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > -- > > > -Respectfully, > -Kirk D Bailey > Consulting Loose Cannon > > end > > > > www.howlermonkey.net highprimate@howlermonkey.net > www.sacredelectron.org idiot1@netzero.net > www.tinylist.org grumpy@tinylist.org > ---------------------------------------------------- > Sign Up for NetZero Platinum Today > Only $9.95 per month! > http://my.netzero.net/s/signup?r=platinum&refcd=PT97 > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From dyoo@hkn.eecs.berkeley.edu Fri Jan 18 18:47:11 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 18 Jan 2002 10:47:11 -0800 (PST) Subject: [Tutor] How to update file? In-Reply-To: Message-ID: On Fri, 18 Jan 2002 MRCASH111@aol.com wrote: > not sure why i am recieving these tech questions because i am new to > Linux and Python. the addresses must be crossed up. > > rick hylton Hi Rick, Tutor is set up so that everyone, by default, hears everything that's posted to the list. It's based on the idea that other people might ask good questions that help clear things up. If you see anything that goes over your head, just ignore it. *grin* And if the volume of the messages is getting large, you can change your mailing list options by visiting: http://mail.python.org/mailman/listinfo/tutor and set the delivery method to a "digest" mode that tries to bundle up messages. If you have more questions, please feel free to ask. From rob@jam.rr.com Fri Jan 18 18:57:25 2002 From: rob@jam.rr.com (Rob Andrews) Date: Fri, 18 Jan 2002 12:57:25 -0600 Subject: [Tutor] checking in Message-ID: <3C487015.1050209@jam.rr.com> I figured I'd let people know I'm not dead. I went to some efforts to arrange some burnout-prevention time off, but just when it all started to come together I became extremely ill for a few months here. (Go figure.) I'm starting to come back around, and plan to get the long-promised Useless Python update together soon. Extra thanks to everyone who noticed I was gone and wished me well. Uselessly, Rob http://www.lowerstandard.com/python -- In the U.S.: Every 13 minutes a name is added to the organ transplant waiting list. Every 91 minutes a life ends because the needed organ didn't come. Signing a donor card takes less than 1 minute. http://www.organdonor.gov From idiot1@netzero.net Fri Jan 18 19:03:10 2002 From: idiot1@netzero.net (kirk Bailey) Date: Fri, 18 Jan 2002 14:03:10 -0500 Subject: [Tutor] TL images Message-ID: <3C48716E.788E4D27@netzero.net> upgraded TL to now display the logo for python. Menu page also uses this as a link to the python.org site. -- -Respectfully, -Kirk D Bailey Consulting Loose Cannon end www.howlermonkey.net highprimate@howlermonkey.net www.sacredelectron.org idiot1@netzero.net www.tinylist.org grumpy@tinylist.org ---------------------------------------------------- Sign Up for NetZero Platinum Today Only $9.95 per month! http://my.netzero.net/s/signup?r=platinum&refcd=PT97 From toodles@yifan.net Fri Jan 18 19:15:06 2002 From: toodles@yifan.net (Andy W) Date: Sat, 19 Jan 2002 03:15:06 +0800 Subject: [Tutor] checking in References: <3C487015.1050209@jam.rr.com> Message-ID: <000d01c1a054$71e16b20$da00a8c0@Sun> Welcome back, Rob. Good to know that you're well again. Also good to know that we can start sending in Useless code again! ;-) Andrew W > I figured I'd let people know I'm not dead. I went to some efforts to > arrange some burnout-prevention time off, but just when it all started > to come together I became extremely ill for a few months here. (Go figure.) > > I'm starting to come back around, and plan to get the long-promised > Useless Python update together soon. Extra thanks to everyone who > noticed I was gone and wished me well. > > Uselessly, > Rob > http://www.lowerstandard.com/python > -- > In the U.S.: > Every 13 minutes a name is added to the organ transplant waiting list. > Every 91 minutes a life ends because the needed organ didn't come. > Signing a donor card takes less than 1 minute. http://www.organdonor.gov > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From rob@jam.rr.com Fri Jan 18 19:32:44 2002 From: rob@jam.rr.com (Rob Andrews) Date: Fri, 18 Jan 2002 13:32:44 -0600 Subject: [Tutor] checking in References: <3C487015.1050209@jam.rr.com> <000d01c1a054$71e16b20$da00a8c0@Sun> Message-ID: <3C48785C.5060107@jam.rr.com> Andy W wrote: > Welcome back, Rob. Good to know that you're well again. > Also good to know that we can start sending in Useless code again! ;-) > > Andrew W > Most kind of you. And by all means feel free to sent it on in. There has been a trickle of submission and error correction during my downtime. I just kept sending people messages: "sorry about the delay. on vacation. a couple of weeks, I promise" Now at least I'm up and moving about. For a while there every time I thought I was well enough to move around I'd find myself back in bed within hours. It's still fighting with me, but I'm at least able to spend time at the PC for long enough to do more than compose an email. Useless will rise again! 3;-> -- In the U.S.: Every 13 minutes a name is added to the organ transplant waiting list. Every 91 minutes a life ends because the needed organ didn't come. Signing a donor card takes less than 1 minute. http://www.organdonor.gov From idiot1@netzero.net Fri Jan 18 19:46:27 2002 From: idiot1@netzero.net (kirk Bailey) Date: Fri, 18 Jan 2002 14:46:27 -0500 Subject: [Tutor] error trap References: Message-ID: <3C487B93.8FA70B13@netzero.net> Dan, nice idea, but what if an error comes up I did not anticipate? I want it to send me ANY/ALL errors, so Iwant to write an exception with a blanket definition. This only works for exceptions I manage to anticipate. What about the rest? Daniel Coughlin wrote: > > On Fri, 18 Jan 2002, kirk Bailey wrote: > > > OK, I am trying to handle it with a default except statement, and > > capture the error feedback, but I get nothing but complaints when I > > try THIS: > > > > for to_addr in members : # for each address in > > 'listnamemembers', > > # print "to_addr: ", to_addr > > # print "from_addr: ", from_addr > > # print "msg=" + CRLF, msg > > try: > > server.sendmail(from_addr, to_addr, msg) # 400 > > send envlope and msg! > > except e: > > This line should be > > except Exception, e: > > or whatever specific exception you want: > > except NameError, n: > > then you can email yourself the value of n. > > Hope this helps! > > Daniel -- -Respectfully, -Kirk D Bailey Consulting Loose Cannon end www.howlermonkey.net highprimate@howlermonkey.net www.sacredelectron.org idiot1@netzero.net www.tinylist.org grumpy@tinylist.org ---------------------------------------------------- Sign Up for NetZero Platinum Today Only $9.95 per month! http://my.netzero.net/s/signup?r=platinum&refcd=PT97 From dyoo@hkn.eecs.berkeley.edu Fri Jan 18 19:55:00 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 18 Jan 2002 11:55:00 -0800 (PST) Subject: [Tutor] error trap In-Reply-To: <3C487B93.8FA70B13@netzero.net> Message-ID: On Fri, 18 Jan 2002, kirk Bailey wrote: > Dan, nice idea, but what if an error comes up I did not anticipate? I > want it to send me ANY/ALL errors, so Iwant to write an exception with > a blanket definition. This only works for exceptions I manage to > anticipate. What about the rest? The 'Exception' class is the root of all ev... err, that is, it's the ancestor of every Exception --- it accounts for everything. See: http://www.python.org/doc/lib/module-exceptions.html for more information on this. From fpeavy@pop.net Fri Jan 18 20:26:12 2002 From: fpeavy@pop.net (Frank Peavy) Date: Fri, 18 Jan 2002 12:26:12 -0800 Subject: [Tutor] Zope and loading Python on a Hosted Website Message-ID: <5.1.0.14.0.20020118122202.025f1660@mail45566.popserver.pop.net> Hello All, I have two related questions. 1) Has anyone tried using ZOPE for content management? Pros and Cons? 2) I thought I saw somewhere where there was a Python"runtime" that you could FTP to a hosted site, to provide the ability to run your Python scripts without the hosting service loading Python. Was I mistaken? If I'm not, has anyone tried it? Thanks. From dyoo@hkn.eecs.berkeley.edu Fri Jan 18 21:37:13 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 18 Jan 2002 13:37:13 -0800 (PST) Subject: [Tutor] error trap In-Reply-To: <3C487F46.A399A3F0@netzero.net> Message-ID: On Fri, 18 Jan 2002, kirk Bailey wrote: > intresting. If I read this right, if I say > > Exception enception e: > > it will accept ANY exception??? and e will capture the string fed to > the thing and be printable later? Yes, if we do a try/except block with: ### try: ... except Exception, e: .... ### barring catastrophic failure, this should allow you to catch everything. Now that you know about this, it's important to say that is usually not such a good idea to have a catch-all unless the situation requires it. Having something like: ### try: ... except IndexError, e: ... ### is useful, because it's saying "we do expect that it's possible IndexError will occur, and in that case, we can handle this particular situation with grace." But: ### try: ... except Exception, e: ... ### is often a sign of: "I don't want my system to just die on me, even if it should. I just want it to keep chugging along, despite all circumstances." From pythontutor@venix.com Fri Jan 18 22:23:36 2002 From: pythontutor@venix.com (Lloyd Kvam) Date: Fri, 18 Jan 2002 17:23:36 -0500 Subject: [Tutor] Zope and loading Python on a Hosted Website References: <5.1.0.14.0.20020118122202.025f1660@mail45566.popserver.pop.net> Message-ID: <3C48A068.90300@venix.com> I have not yet used the new template abilities. They promise to make ZOPE a must use. The ZOPE documentation has tended to be long on examples and How-To, but short on theory. This as made it tough for me to try some ideas. However, there are now at least three ZOPE books out (I have bought two), and I think that ZOPE will now be reasonably well explained. If you need a program/data driven web site, I think ZOPE IS the way to go. (Warning. I have only played with ZOPE. low volumes of data and web usage.) point 2: You can run Python from non-standard locations so long as you know how to set the permissions, etc. A Python "runtime" would simply be the Python Interpreter plus modules, libraries, etc. If you are looking to hook your scripts to your website, you will need the help and cooperation of the ISP who is doing the hosting. Frank Peavy wrote: > Hello All, > I have two related questions. > > 1) Has anyone tried using ZOPE for content management? Pros and Cons? > > 2) I thought I saw somewhere where there was a Python"runtime" that you > could FTP to a hosted > site, to provide the ability to run your Python scripts without the > hosting service loading Python. > Was I mistaken? If I'm not, has anyone tried it? > Thanks. > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From arcege@speakeasy.net Fri Jan 18 23:43:44 2002 From: arcege@speakeasy.net (Michael P. Reilly) Date: Fri, 18 Jan 2002 18:43:44 -0500 Subject: [Tutor] error trap In-Reply-To: ; from dyoo@hkn.eecs.berkeley.edu on Fri, Jan 18, 2002 at 01:37:13PM -0800 References: <3C487F46.A399A3F0@netzero.net> Message-ID: <20020118184344.C900@speakeasy.net> On Fri, Jan 18, 2002 at 01:37:13PM -0800, Danny Yoo wrote: > On Fri, 18 Jan 2002, kirk Bailey wrote: > > > intresting. If I read this right, if I say > > > > Exception enception e: > > > > it will accept ANY exception??? and e will capture the string fed to > > the thing and be printable later? > > Yes, if we do a try/except block with: > > ### > try: > ... > except Exception, e: > .... > ### > > barring catastrophic failure, this should allow you to catch everything. Or barring an old-style string exception, or a class being used as an exception but is not a subclass of the class Exception. The following will work with everything from string exceptions to multiple threads. try: ... except: (exc, val, tb) = sys.exc_info() e = val This is kind of an aside, since we hope everyone is making their exceptions as subclasses of the Exception (to the rule?). Additionally, the value returned with the exception (e) could be anything, not just a string. For example, if you were to make a parser, you might want to carry with the exception the line in the file, position within the string and the line number currently being parsed. As another example, look at EnvironmentError which returns the error number and string. -Arcege From tbrauch@tbrauch.com Sat Jan 19 00:33:24 2002 From: tbrauch@tbrauch.com (tbrauch@tbrauch.com) Date: Fri, 18 Jan 2002 19:33:24 -0500 Subject: [Tutor] =?iso-8859-1?Q?Reading=20and=20Writing=20=28No=20Arithmetic=3F=29?= Message-ID: <3C47902000000DCD@mail.san.yahoo.com> I am trying to write a quick little program to help me with a menial task= ... Isn't that the whole purpose of programming? I have a small html, let's call it info.html (because that is its name) file that consists of someth= ing like: Some Inspirational Quote Here I also have a data file called info.data chock full o' inspirational quot= es, one per line (they also might have some additional HTML such as links). What I am trying to do is find the best why to pull a line at random and= insert it into the info.html file. What works with only a few lines in the data file is: [Untested code below, I think it is right] import random f =3D open('info.data', 'r') i =3D open('info.html', 'w') quotes =3D f.readlines() newQuote =3D quotes[random.randrange(0,quotes.len())] i.write(''+newQuote+'') f.close() i.close() But, how could I get a random line if there are thousand of lines in the data file without bogging down the computer? - Tim From grimm.tooth@verizon.net Fri Jan 18 23:37:02 2002 From: grimm.tooth@verizon.net (Jeff Grimmett) Date: Fri, 18 Jan 2002 18:37:02 -0500 Subject: [Tutor] Doc string extractors? Message-ID: I've looked at pydoc, happydoc, and gendoc/pythondoc, and thus far I am coming up goose eggs on useful (or even working!) extractors for python doc strings. To make matters more frustrating, the chapter on Documenting Python seems to be written by Nostradamus on a Jolt Cola binge (OK, it's not that bad but it doesn't seem to address the issue in a straightforward manner, or maybe I'm just thick). (actually, I know part of the problem is that I'm using the 'regular' version of Python in a Cygwin BASH shell, but some things should just work, darn it). Does anyone have any alternative suggestions? I am looking to take my doc strings and plunk them into a nice HTML document, that's all. P.S. -- while pydoc is documented in the current 2.2 docs as being available since V2.1 or so, in reality it is not, really, available until V2.2. Should I log a bug report @ sourceforge? -- what is the ettiquette on this? From e.kotyk@shaw.ca Fri Jan 18 13:54:26 2002 From: e.kotyk@shaw.ca (Eve Kotyk) Date: Fri, 18 Jan 2002 13:54:26 +0000 Subject: [Tutor] Need help with dict.calculation Message-ID: <3C482912.382FAC24@shaw.ca> In the script below I would like to add up the totals for each item into one final total. So far I haven't come up with anything. Help. def food_add(): print "Enter all foods you have eaten today." items = raw_input("Add Food Item: ") portion = input("Enter number of portions: ") cal_portion = input("Enter calories per portion: ") more = raw_input("Do you wish to continue? y/n: ") while more != 'n': food_add() break total_calories[items] = portion * cal_portion total = 0 for i in total_calories.values(): total = total + i print "Total calories: ",total My output is: Total calories: 120 Total calories: 254 The total calories for each item entered with the last entry first, rather than just a Total calories: 374 -- ekotyk http://members.shaw.ca/e.kotyk/virtualstudio.htm From paulsid@shaw.ca Sat Jan 19 03:01:41 2002 From: paulsid@shaw.ca (Paul Sidorsky) Date: Fri, 18 Jan 2002 20:01:41 -0700 Subject: [Tutor] Re: [Tutor]Reading and Writing (No Arithmetic?) References: <3C47902000000DCD@mail.san.yahoo.com> Message-ID: <3C48E195.A446BC7C@shaw.ca> tbrauch@tbrauch.com wrote: > newQuote = quotes[random.randrange(0,quotes.len())] This can be shortened to: newQuote = random.choice(quotes) > But, how could I get a random line if there are thousand of lines in the > data file without bogging down the computer? I think there are a couple of libraries around for that kind of thing. However, if you want to do it yourself (which is usually more fun :-)), there are two options that shouldn't be too hard to implement. One is to move to a fixed-length quote string. Then when you want to choose, get the file size (s), divide it by the fixed length (l), then pick a number (n) from 0 to (s/l)-1, seek n*l bytes into the file, and read your quote. The bad news is you waste space and also lose some ease of maintainability of the quotes file. Another idea is to build an index of some kind. A simple one would have the number of quotes first, followed by the offsets of each of the quotes. Then you can read in the number of quotes, pick your random number, find its offset in the index, seek to it, and read to the newline. This keeps the maintainability and doesn't use as much extra space, but of course any time you change the quotes file you have to remember to rebuild the index. Hope that helps. Admittedly these are very C-like approaches; there might be something nicer that Python can do that I've missed. I haven't worked with binary files in Python much. -- ====================================================================== Paul Sidorsky Calgary, Canada paulsid@shaw.ca http://members.shaw.ca/paulsid/ From vlindberg@verio.net Sat Jan 19 01:06:10 2002 From: vlindberg@verio.net (VanL) Date: Fri, 18 Jan 2002 18:06:10 -0700 Subject: [Tutor] 'File' utility for python? Message-ID: <3C48C682.10104@verio.net> Hello, Does anyone know of a python utility that can do the same thing as the unix utility 'file'? I need to figure out if something is non-destructively editable (i.e., text) before I run a search-and replace on it. Thnx, Van From dyoo@hkn.eecs.berkeley.edu Sat Jan 19 03:26:35 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 18 Jan 2002 19:26:35 -0800 (PST) Subject: [Tutor] Re: [Tutor]Reading and Writing (No Arithmetic?) [linecache?] In-Reply-To: <3C48E195.A446BC7C@shaw.ca> Message-ID: On Fri, 18 Jan 2002, Paul Sidorsky wrote: > > But, how could I get a random line if there are thousand of lines in the > > data file without bogging down the computer? > > I think there are a couple of libraries around for that kind of thing. If you want to use something precooked, the 'linecache' module should give you random access to a test file: http://www.python.org/doc/current/lib/module-linecache.html To get a random line from a file still requires that we count how many lines are in a file, but that can be a quick linear scan. > Another idea is to build an index of some kind. A simple one would > have the number of quotes first, followed by the offsets of each of > the quotes. Then you can read in the number of quotes, pick your > random number, find its offset in the index, seek to it, and read to > the newline. This keeps the maintainability and doesn't use as much > extra space, but of course any time you change the quotes file you > have to remember to rebuild the index. I think this is how 'linecache' works, but I'd have to check the code to make sure about it... wait, nope, it actually tries to suck the whole file. Ugh, then 'linecache' is actually not quite so useful then! Hmmm... I thought this sounded like an interesting thing to write, so I've cooked up a 'RandomFile' class that gives random access to a file: ### class RandomFile: """Allows random access in a file-like object. Requires that we be able to seek() through it.""" def __init__(self, fp): """Initializer. 'fp' should be a file pointer that supports seek().""" self.fp = fp self._cache = [] self.updatecache() def getline(self, n): """Returns line #n.""" pos = self._cache[n] self.fp.seek(pos) return self.fp.readline() def countlines(self): """Returns the number of lines in our file.""" return len(self._cache) def updatecache(self): """Scans through the file to find where every line starts.""" self._cache = [0] self.fp.seek(0) n = 0 while 1: ch = self.fp.read(1) if not ch: break if ch == '\n': self._cache.append(n+1) n = n + 1 ### Here's a totally random example of it in action: ### >>> import RandomFile >>> f = RandomFile.RandomFile(open("RandomFile.py")) >>> f.getline(0) 'class RandomFile:\n' >>> f.getline(0) 'class RandomFile:\n' >>> f.getline(20) ' return len(self._cache)\n' >>> f.getline(19) ' """Returns the number of lines in our file."""\n' >>> f.getline(18) ' def countlines(self):\n' ### This class isn't battle tested --- I just cooked it, so it might still need some simmering. (If we put more effort into it, we can make it this RandomFile look like a Python list by overriding a __getitem__(). Hmmm...) But I hope this may be useful for you. Good luck! From dsh8290@rit.edu Sat Jan 19 03:54:15 2002 From: dsh8290@rit.edu (dman) Date: Fri, 18 Jan 2002 22:54:15 -0500 Subject: [Tutor] =?us-ascii?Q?=3D=3Fiso-8859-1?= =?us-ascii?Q?=3FQ=3FReading=3D20and=3D20Writing=3D20=3D28No=3D20Arithme?= =?us-ascii?Q?t?= ic=3F=29?= In-Reply-To: <3C47902000000DCD@mail.san.yahoo.com> References: <3C47902000000DCD@mail.san.yahoo.com> Message-ID: <20020119035415.GA4499@localhost> On Fri, Jan 18, 2002 at 07:33:24PM -0500, tbrauch@tbrauch.com wrote: | I am trying to write a quick little program to help me with a menial task... | Isn't that the whole purpose of programming? I have a small html, let's | call it info.html (because that is its name) file that consists of something | like: | | Some Inspirational Quote Here | | I also have a data file called info.data chock full o' inspirational quotes, | one per line (they also might have some additional HTML such as links). | What I am trying to do is find the best why to pull a line at random and | insert it into the info.html file. What works with only a few lines in | the data file is: Here's what I did for my sigs : ~~~~~~~~~~~~~~~~~~~~~~ #!/usr/bin/env python # docstring """ When executed it chooses a quote randomly and prints it on stdout. It is quite useful for sig generation. """ quote_list = [ """ But As for me and my household, we will serve the Lord. Joshua 24:15 """, """ Thy Word is a lamp unto my feet and a light unto my path. Psalms 119:105 """, """ Python is executable pseudocode. Perl is executable line noise. """, ] import random # the signature; "%s" will be replaced by the qoute sig = """\ %s\ """ print ( sig % random.choice( quote_list ) ) ~~~~~~~~~~~~~~~~~~~~~~ Pretty simple (about 3 lines, really) and no file IO to deal with. The data is just some string literals in a list. -D -- If your life is a hard drive, Christ can be your backup. From dsh8290@rit.edu Sat Jan 19 03:56:32 2002 From: dsh8290@rit.edu (dman) Date: Fri, 18 Jan 2002 22:56:32 -0500 Subject: [Tutor] 'File' utility for python? In-Reply-To: <3C48C682.10104@verio.net> References: <3C48C682.10104@verio.net> Message-ID: <20020119035632.GB4499@localhost> On Fri, Jan 18, 2002 at 06:06:10PM -0700, VanL wrote: | Hello, | | Does anyone know of a python utility that can do the same thing as the | unix utility 'file'? No, but I think there is a library that could probably be wrapped, or 'file' can be run in a pipe and the output looked at. | I need to figure out if something is non-destructively editable (i.e., | text) before I run a search-and replace on it. Do a search for anything that is not in the US-ASCII printable range. That will likely suffice. if re.search( "[^[:alnum:][:space:][:punct:]]" , ) : print "not plain ascii" else : = .replace( , ) -D -- Even youths grow tired and weary, and young men stumble and fall; but those who hope in the Lord will renew their strength. They will soar on wings like eagles; they will run and not grow weary, they will walk and not be faint. Isaiah 40:31 From chrislubrecht@home.com Sat Jan 19 04:03:39 2002 From: chrislubrecht@home.com (ccl) Date: Fri, 18 Jan 2002 23:03:39 -0500 Subject: [Tutor] socket programming Message-ID: <5.1.0.14.0.20020118224907.00a8a180@pop3.norton.antivirus> I must be missing something, or am just not getting something. If I do... while 1: a = socketthing.recv(1024) socketthing.send("Spam! =>"+a) It sends back whatever is typed... If I do... While 1: a = socketthing.recv(1024) if a == "Dead Parrot": sockettthing.send("It's Dead") else: socketthing.send("Silly") I get nothing on sending "It's dead"..but then I hit enter again and I get "Silly" I've double checked the rest. if I change in the echo part, it works ok..which tells me I'm doing the sockets right...what am I doing wrong with the rest? Thanks! Chris From chrislubrecht@home.com Sat Jan 19 04:45:30 2002 From: chrislubrecht@home.com (ccl) Date: Fri, 18 Jan 2002 23:45:30 -0500 Subject: [Tutor] Dumb question Message-ID: <5.1.0.14.0.20020118234413.00a90ec0@pop3.norton.antivirus> I'm not a programmer, so this is a kinda dumb question. What exactly is a class? Why would use one? How do you define one? I've done alot of reading on Python and this whole concept escapes me. Thanks Chris From tbost@ifarm.com Sat Jan 19 05:28:06 2002 From: tbost@ifarm.com (Tracy Bost) Date: Fri, 18 Jan 2002 23:28:06 -0600 Subject: [Tutor] Blackadder IDE References: <5.1.0.14.0.20020118234413.00a90ec0@pop3.norton.antivirus> Message-ID: <001401c1a0aa$13042dd0$980e2118@computer> Has anyone used Blackadder IDE for python ? Is so, please let me know your experiences with it.. Good ? bad? I'm thinking of purchasing. Thanks ----- Original Message ----- From: "ccl" To: Sent: Friday, January 18, 2002 10:45 PM Subject: [Tutor] Dumb question > > I'm not a programmer, so this is a kinda dumb question. What exactly is a > class? Why would use one? How do you define one? I've done alot of reading > on Python and this whole concept escapes me. > > Thanks > > Chris > > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From urnerk@qwest.net Sat Jan 19 05:48:21 2002 From: urnerk@qwest.net (Kirby Urner) Date: Fri, 18 Jan 2002 21:48:21 -0800 Subject: [Tutor] Dumb question In-Reply-To: <5.1.0.14.0.20020118234413.00a90ec0@pop3.norton.antivirus> Message-ID: <4.2.0.58.20020118214240.00ce2cf0@pop3.norton.antivirus> At 11:45 PM 1/18/2002 -0500, ccl wrote: >I'm not a programmer, so this is a kinda dumb question. What exactly is a >class? Why would use one? How do you define one? I've done alot of reading >on Python and this whole concept escapes me. > >Thanks > >Chris A class is a blueprint. An instance is the thing you make from the blueprint. One class, many instances. A subclass is a blueprint that inherits all the features of its parent(s), but then contains modifications. The programmer can just focus on what's different, knowing the full-featured parent is in the background. You can also compose classes (not just subclass 'em). Write a blueprint in which instances of other classes are used internally, by instances of the class you're designing. Like, a house blueprint uses instances of wall, floor, and plumbing classes. Classes typically contain properties and methods. When you create an instance of a class, it'll be ready to have its properties set, and to have its behaviors triggered. The toilet object flushes and refills, has states: ready, filling, flushing, broken. Kirby From grimmtoothtoo@yahoo.com Sat Jan 19 06:06:28 2002 From: grimmtoothtoo@yahoo.com (Grimmtooth) Date: Sat, 19 Jan 2002 01:06:28 -0500 Subject: [Tutor] Dumb question In-Reply-To: <5.1.0.14.0.20020118234413.00a90ec0@pop3.norton.antivirus> Message-ID: > I'm not a programmer, so this is a kinda dumb question. What exactly is a > class? Why would use one? How do you define one? I've done alot > of reading > on Python and this whole concept escapes me. Welcome to my world :-) After beating my head against the wall for what seems like years (OK, it HAS been years, but whaddya expect for a self-taught geek?) I'm starting to grok classes and thier uses. My latest project is almost entirely classes. Think of a class as kind of a function that can be used as a template. Instead of executing a function, you assign an object to a class. That object can then be manipulated, can do things, and so on without disturbing the original. You can create multiple copies of a class, alter them, and the original will still be pristine. For example: class Address: def __init__(self, name, street, zip=None): self.Name = name self.Street = street self.Zip = zip def PrintAddr(self): print "%s\n%s %s\n\n" % (name, street, zip) (this class is probably broken but...) Now, AddressBook = [] while 1: n, s, z = QueryForAddress() # assume an input routine here if n: AddressBook.append(Address(n,s,z)) else: break for i in AddressBook: i.PrintAddr() In the above fictitious example, the Address class contains three attributes and two methods. Method #1 is the __init__, an internal method, which sets up the address. method #2 prints the contents of the address object. The program itself queries you for names and addresses. As you provide them, the Address 'template' is filled in with the info and it is stacked into an address book. Later on, we then assign 'i' to each address in the book and invoke the PrintAddr method to generate a printed address book. This is a highly simplified example, but hopefully it helps. Hang in there, it'll come to you :-) _________________________________________________________ Do You Yahoo!? Get your free @yahoo.com address at http://mail.yahoo.com From boud@valdyas.org Sat Jan 19 07:45:18 2002 From: boud@valdyas.org (Boudewijn Rempt) Date: Sat, 19 Jan 2002 08:45:18 +0100 (CET) Subject: [Tutor] Blackadder IDE In-Reply-To: <001401c1a0aa$13042dd0$980e2118@computer> Message-ID: On Fri, 18 Jan 2002, Tracy Bost wrote: > Has anyone used Blackadder IDE for python ? Is so, please > let me know your experiences with it.. Good ? bad? > I'm thinking of purchasing. > Well, it's not finished -- and the author has been very busy on porting the PyQt bindings to Qt 3 and the Sharp Zaurus, so he hasn't had time to finish it. But it should become quite good -- if you look at Informit and search for my name, it should turn up a review of the most current beta. You might also want to read the relevant chapters from the on-line version of my book on PyQt programming (and then buy the paper version -- should be out now :-). http://www.opendocs.com Boudewijn Rempt | http://www.valdyas.org From flash1210@hotmail.com Sat Jan 19 09:17:15 2002 From: flash1210@hotmail.com (Frank Holmes) Date: Sat, 19 Jan 2002 01:17:15 -0800 Subject: [Tutor] Help, for I have lost the PATH Message-ID: I cannot seem to get the path right so that python can find modules I have written. It will run Tkinter OK, but not my test modules. I am running Windows ME, have python 2.0 installed in C:\Python20 and keep my python programs and stuff in c:\stuff I have set the path in my autoexec as follows: PATH C:\python20;%PATH% SET PYTHONPATH=.;C:\Python20\lib;c:\Python20\lib\tkinter;c:\stuff SET PATH=C:\WINDOWS;C:\WINDOWS\COMMAND;C:\WINDOWS;C:\WINDOWS\COMMAND SET windir=C:\WINDOWS SET winbootdir=C:\WINDOWS SET COMSPEC=C:\WINDOWS\COMMAND.COM SET PROMPT=$p$g SET TEMP=C:\WINDOWS\TEMP SET TMP=C:\WINDOWS\TEMP I have also tried: SET PATH=C:\WINDOWS;C:\WINDOWS\COMMAND;C:\WINDOWS;C:\WINDOWS\COMMAND;C:\python20;%PATH% SET PYTHONPATH=.;C:\Python20\lib;c:\Python20\lib\tkinter;c:\stuff SET windir=C:\WINDOWS SET winbootdir=C:\WINDOWS SET COMSPEC=C:\WINDOWS\COMMAND.COM SET PROMPT=$p$g SET TEMP=C:\WINDOWS\TEMP SET TMP=C:\WINDOWS\TEMP My programs run, I can import a button from Tkinter but I cannot import modules from 'stuff' I know this is more a dos question than python, but would appreciate any help. Thanx _________________________________________________________________ MSN Photos is the easiest way to share and print your photos: http://photos.msn.com/support/worldwide.aspx From toodles@yifan.net Sat Jan 19 10:43:53 2002 From: toodles@yifan.net (Andy W) Date: Sat, 19 Jan 2002 18:43:53 +0800 Subject: [Tutor] Need help with dict.calculation References: <3C482912.382FAC24@shaw.ca> Message-ID: <001901c1a0d6$31c51690$da00a8c0@Sun> Hi Eve, I won't make changes that are _too_ drastic, but I suggest you divide tasks into separate functions. At the moment it's recursive, and I don't think that's very useful here. (It could work, but I just don't think it's necessary). The first function will gather the data, the second will do the looping/control. This is all untested, but it should give you some ideas. > In the script below I would like to add up the totals for each item into > one final total. So far I haven't come up with anything. Help. # def gather_data(): items = raw_input("Add food item: ") portion = input("Enter number of portions: ") cal_portion = input("Enter calories per portion: ") return items,portion,cal_portion def get_total_calories(): print "Enter all foods you have eaten today." more="" while more!="n": items,portion,cal_portion = gather_data() total_calories[items]=portion * cal_portion more = raw_input("Do you want to continue? y/n: ") for i in total_calories.values(): total = total + i print "Total calories: ",total # As a side note, you don't even need to put it in a dictionary, you can just have a running total in an integer variable. I said I wouldn't make drastic changes though :o) Andy > > def food_add(): > print "Enter all foods you have eaten today." > > items = raw_input("Add Food Item: ") > portion = input("Enter number of portions: ") > cal_portion = input("Enter calories per portion: ") > > more = raw_input("Do you wish to continue? y/n: ") > while more != 'n': > food_add() > break > total_calories[items] = portion * cal_portion > total = 0 > for i in total_calories.values(): > total = total + i > print "Total calories: ",total > > My output is: > > Total calories: 120 > Total calories: 254 > > The total calories for each item entered with the last entry first, > rather than just a Total calories: 374 > -- > > ekotyk > > http://members.shaw.ca/e.kotyk/virtualstudio.htm > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From bwinton@tor.dhs.org Sat Jan 19 13:28:12 2002 From: bwinton@tor.dhs.org (Blake Winton) Date: Sat, 19 Jan 2002 08:28:12 -0500 Subject: [Tutor] Re: [Tutor]Reading and Writing (No Arithmetic?) [linecache?] In-Reply-To: References: <3C48E195.A446BC7C@shaw.ca> Message-ID: <20020119082812.A21565@tor.dhs.org> * Danny Yoo [020118 22:32]: > On Fri, 18 Jan 2002, Paul Sidorsky wrote: > To get a random line from a file still requires that we count how many > lines are in a file, but that can be a quick linear scan. Alternately, couldn't we just go to a random byte in the file, scan backwards for the first newline, then forwards for the next newline, and that would give us a random line? I guess it would tend to weight longer lines heavier, but I don't think that's a terrible restriction, given that it should be stupid-fast, and tke up very little memory. Perhaps I'll whip up some code to do this later... Later, Blake. -- 9:40pm up 52 days, 21:07, 2 users, load average: 0.02, 0.09, 0.07 From arcege@speakeasy.net Sat Jan 19 16:47:09 2002 From: arcege@speakeasy.net (Michael P. Reilly) Date: Sat, 19 Jan 2002 11:47:09 -0500 Subject: [Tutor] Re: [Tutor]Reading and Writing (No Arithmetic?) [linecache?] In-Reply-To: <20020119082812.A21565@tor.dhs.org>; from bwinton@tor.dhs.org on Sat, Jan 19, 2002 at 08:28:12AM -0500 References: <3C48E195.A446BC7C@shaw.ca> <20020119082812.A21565@tor.dhs.org> Message-ID: <20020119114709.D900@speakeasy.net> --7JfCtLOvnd9MIVvH Content-Type: text/plain; charset=us-ascii Content-Disposition: inline On Sat, Jan 19, 2002 at 08:28:12AM -0500, Blake Winton wrote: > * Danny Yoo [020118 22:32]: > > On Fri, 18 Jan 2002, Paul Sidorsky wrote: > > To get a random line from a file still requires that we count how many > > lines are in a file, but that can be a quick linear scan. > > Alternately, couldn't we just go to a random byte in the file, scan > backwards for the first newline, then forwards for the next newline, > and that would give us a random line? > > I guess it would tend to weight longer lines heavier, but I don't > think that's a terrible restriction, given that it should be > stupid-fast, and tke up very little memory. Better to take a full block, not just a byte. It makes it easier to find the newline without seeking too much. This may be a little long winded bit of code, but it seems to work well. All you need to do is get a function to give a random number. Except for long lines, you would read in one or two block (default is 1k). The function would scan from the location in the file backwards for the first newline and forwards for the first newline, getting more blocks if needed. from random import random from randline import getstring_precent print getstring_precent(random() * 100) The assumption made with my code is that it won't be used more than once or twice, so building a cache would be wasteful. -Arcege PS: Yikes... this took some effort with my ailment.. but I'm glad I can still do it. :) --7JfCtLOvnd9MIVvH Content-Type: text/plain; charset=us-ascii Content-Disposition: inline; filename="randline.py" #!/usr/bin/python """Get a line from a given file at the specified position. One function is by a float percentage (0-100), the other function is by byte position in the file. The default block size is 1k. getstring_percent(filename, percentage, [blocksize=1k]) returns line at that percentage, including the newline getstring_locaton(filename, byte_location, [blocksize=1k]) returns line at that location (i.e. seek value), including the newline """ import os, string def getstring_percent(fname, percent, blocksize = 1024): """Get the line at the position in the file given by a certain percentage. The percentage could be a floating point number. For example, 100% would be the last line, 99% might get the third to last line, so 99.5% would retrieve the second to last line.""" size = os.path.getsize(fname) # get the byte location at the percentage given byte_location = int(size * (percent / 100.0)) - 1 return getstring_location(fname, byte_location, blocksize) def getstring_location(fname, byte_location, blocksize = 1024): """Get the line at the position in the file given by the byte location.""" blockno, charpos = divmod(byte_location, blocksize) size = os.path.getsize(fname) if byte_location >= size: raise IndexError("out-of-range") f = open(fname, 'r') f.seek(blockno * blocksize) # advance to the block we want block = f.read(blocksize) # the next two while loops are very similar, but unfortunately, there # are too many differences to make it into one nice function blocklist = [block] begin, curblock, curpos = -1, blockno, charpos # we will find the start of the line (previous newline); if we cannot # we'll get more blocks until we can find it, or the beginning of the # file while begin == -1: begin = string.rfind(block, '\n', 0, curpos) if begin == -1: curblock = curblock - 1 f.seek(curblock * blocksize) # rewind back one block block = f.read(blocksize) if not block: break blocklist.insert(0, block) curpos = len(block) # this may not be blocksize # at this point, begin == -1 means that we start at the beginning of file block = blocklist[-1] end, curblock, curpos = -1, blockno, charpos # starting at the first block read, we'll go forward and find the # next newline; we'll get more blocks until we reach the end of the # file or find the next newline while end == -1: end = string.find(block, '\n', curpos) if end == -1: curblock = curblock + 1 f.seek(curblock * blocksize) block = f.read(blocksize) if not block: break blocklist.append(0, block) curpos = len(block) # prune the available data and get only what we want if len(blocklist) == 1: # special case if begin != -1 and end != -1: blocklist[0] = blocklist[0][begin+1:end+1] elif begin == -1: blocklist[0] = blocklist[0][:end+1] elif end == -1: blocklist[0] = blocklist[0][begin+1:] else: pass # this means the the whole file is the string else: if begin != -1: # replace the first block with only the portion it needs blocklist[0] = blocklist[0][begin+1:] # we'll do the same with the last block if end != -1: blocklist[-1] = blocklist[-1][:end+1] block = string.join( blocklist, '' ) # join all the blocks return block def _test(value, fname): try: print value, `getstring_location(fname, value)` except IndexError, err: print value, 'is', err try: print value, `getstring_percent(fname, value)` except IndexError, err: print '%g%% is' % value, err if __name__ == '__main__': import sys try: fname = sys.argv[1] except: fname = sys.argv[0] # use the script itself try: value = string.atof(sys.argv[2]) except: value = 100 _test(value, fname) --7JfCtLOvnd9MIVvH-- From printers@sendme.cz Sat Jan 19 21:58:45 2002 From: printers@sendme.cz (A) Date: Sat, 19 Jan 2002 22:58:45 +0100 Subject: [Tutor] How to compare to time strings? Message-ID: <3C49FA25.30437.2479933@localhost> Hello, I have two time strings like Mon, 31 Dec 2001 15 and Sat, 19 Jan 2002 21 How can I compare them and find out that Mon, 31 Dec 2001 15 is before Sat, 19 Jan 2002 21 ? I can not use strptime function , to convert it first,because I use windows and there is not that function. Thanks for help Ladislav From marklists@mceahern.com Sat Jan 19 22:10:03 2002 From: marklists@mceahern.com (Mark McEahern) Date: Sat, 19 Jan 2002 14:10:03 -0800 Subject: [Tutor] RE: How to compare to time strings? In-Reply-To: <3C49FA25.30437.2479933@localhost> Message-ID: Short answer: Use mx.DateTime from egenix: http://www.egenix.com/files/python/eGenix-mx-Extensions.html#mxBASE Here's sample code, once you've installed that: $ python >>> s1 = "Mon, 31 Dec 2001 15" >>> import mx.DateTime >>> d1 = mx.DateTime.DateFrom(s1) >>> print d1 2001-12-31 00:00:00.00 >>> s2 = "Sat, 19 Jan 2002 21" >>> d2 = mx.DateTime.DateFrom(s2) >>> print (d2 > d1) 1 // mark From dyoo@hkn.eecs.berkeley.edu Sat Jan 19 22:42:30 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 19 Jan 2002 14:42:30 -0800 (PST) Subject: [Tutor] Why does pygame still not work? In-Reply-To: Message-ID: On Thu, 17 Jan 2002, Danny Yoo wrote: > Yikes! Hmmm... According to the tutorial at: > > http://pygame.org/docs/tut/ChimpLineByLine.html > > the Monkey game assumes that 'pygame.font' is set to None if Pygame can't > initialize its Font module. But according to the error message, this > isn't happening. I'm surprised because you're on a Windows system, so I > would have assumed that the prepackaged Pygame should have no problems. Ok, I took a closer look at the chimp source from the pygame distribution itself. It looks like they check for font support like this: ### try: import pygame.font except ImportError: print 'Warning, fonts disabled' pygame.font = None try: import pygame.mixer except ImportError: print 'Warning, sound disabled' pygame.mixer = None ### That is, they try doing it "by permission". If denied, that's when they set 'pygame.font = None'. It's strange that they don't mention this in the tutorial online! You should definitely talk with the pygame folks and ask about this. Anyway, try putting that somewhere near the beginning of your chimp example. This should take care of the AttributeError's you've been seeing. From kjphotog@juno.com Sun Jan 20 00:43:31 2002 From: kjphotog@juno.com (kjphotog@juno.com) Date: Sat, 19 Jan 2002 16:43:31 -0800 Subject: [Tutor] Help Message-ID: <20020119.170940.-210897.0.kjphotog@juno.com> Can't seem to figure out how-to access a POP3 account. I can get a connected message, but can go no further to retrieve messages. Any suggestions? I'm using Python 2.1 Keith ________________________________________________________________ GET INTERNET ACCESS FROM JUNO! Juno offers FREE or PREMIUM Internet access for less! Join Juno today! For your FREE software, visit: http://dl.www.juno.com/get/web/. From dyoo@hkn.eecs.berkeley.edu Sun Jan 20 06:27:33 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 19 Jan 2002 22:27:33 -0800 (PST) Subject: [Tutor] my first pygame experiment Message-ID: Hi everyone, I'm finally starting to play around with pygame, and I really think it looks great! I thought it might be fun to show my first silly pygame program: ### """A simple hypnotic pulsing screen. Uses Python 2.2 generators. Danny Yoo (dyoo@hkn.eecs.berkeley.edu) """ from __future__ import generators import pygame from pygame.locals import * from random import randrange import sys def strobeIter(n, step=1, start=0): """Returns a "strobing" iterator. This iterator bounces between the values [0, n]. Think KIT's red strobing light.""" x = start direction = 1 delta = step*direction while 1: yield x x = clamp(x+delta, 0, n) if x in (0, n): direction = direction * -1 delta = step * direction def clamp(x, low, high): """Clamps down x within the range: [low, high].""" return max(low, min(x, high)) def handleQuit(): for event in pygame.event.get(): if event.type is QUIT: sys.exit(0) elif event.type is KEYDOWN and event.key is K_ESCAPE: sys.exit(0) if __name__ == '__main__': (r, g, b) = (strobeIter(255, randrange(1, 10)), strobeIter(255, randrange(1, 10)), strobeIter(255, randrange(1, 10))) display = pygame.display.set_mode((300, 300)) while 1: handleQuit() bgcolor = r.next(), g.next(), b.next() display.fill(bgcolor) pygame.display.flip() ### From dyoo@hkn.eecs.berkeley.edu Sun Jan 20 06:41:47 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 19 Jan 2002 22:41:47 -0800 (PST) Subject: [Tutor] Why does pygame still not work? In-Reply-To: Message-ID: On Sat, 19 Jan 2002, James M Lang wrote: > Thanks. I don't even know how to program yet. Gotta start reading > those tutorials. -- Don't worry about it. You got me interested in pygame; I'm playing around with it now. *grin* > > It looks like they check for font support like this: > > > >### > >try: > > import pygame.font > >except ImportError: > > print 'Warning, fonts disabled' > > pygame.font = None > >try: > > import pygame.mixer > >except ImportError: > > print 'Warning, sound disabled' > > pygame.mixer = None > >### I did a followup, and found this: http://archives.seul.org/pygame/users/Jan-2002/msg00020.html The pygame developers just recently fixed pygame so that if any of the optional modules (like font) are missing, they'll be set to None for convenience's sake. However, notice that they made this change very recently, around January 5th. It's likely that the chimp tutorial assumes that we have the newest pygame that's in development, so it'd probably best to keep our eyes open to this until a new pygame release is available. Hope this helps! From Tarasub Sun Jan 20 09:35:02 2002 From: Tarasub (Tarasub) Date: Sun, 20 Jan 2002 10:35:02 +0100 Subject: [Tutor] Help In-Reply-To: <20020119.170940.-210897.0.kjphotog@juno.com> References: <20020119.170940.-210897.0.kjphotog@juno.com> Message-ID: <35219619236.20020120103502@subdimension.com> kjc> Can't seem to figure out how-to access a POP3 account. I can get a kjc> connected message, but can go no further to retrieve messages. kjc> Any suggestions? I'm using Python 2.1 kjc> Keith A very simple example: import poplib pop = poplib.POP3('server', 'port') pop.user('username') pop.pass_('password') num_msg_list = len(pop.list()[1]) # Iterate over all messages. for i in range(num_msg_list): # Loop over all lines of the message, except index 1, which is the response. for j in pop.retr(i+1)[1]: # Print the line. print j More can be found in the manual with poplib. From alan.gauld@bt.com Sun Jan 20 16:55:36 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Sun, 20 Jan 2002 16:55:36 -0000 Subject: [Tutor] error trap Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C2C4@mbtlipnt02.btlabs.bt.co.uk> > > Exception enception e: except Exception, e except => the python keyword Exception => the type of exception, in this case everything descended from class 'Exception' which is all of them e => the Exception instance representing the actual error > Now that you know about this, it's important to say that is > usually not such a good idea to have a catch-all unless > the situation requires it. Personally I nearly always do use a catch all at the top level of my program. That's just to stop end users seeing anything horrible like a python stack trace, during development it's commented out. In Kirk's case the end users won't see it so he doesn't need it. Alan G. From alan.gauld@bt.com Sun Jan 20 17:30:53 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Sun, 20 Jan 2002 17:30:53 -0000 Subject: [Tutor] Reading and Writing (No Arithmetic?) Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C2C5@mbtlipnt02.btlabs.bt.co.uk> > quotes = f.readlines() > newQuote = quotes[random.randrange(0,quotes.len())] > i.write(''+newQuote+'') > > But, how could I get a random line if there are thousand of > lines in the data file without bogging down the computer? Getting the random line won't be the perblem. Reading the file is much more likely to slow things down. Are you intending running this in real-time or is it a batch job producing the html periodically? If a batch job you could handle millions of lines without too much worry. In realtime you might like to have a list of filenames and select one at random then select a line from one of those, thus each file is kept short enough to be easily read. HTH, Alan g From alan.gauld@bt.com Sun Jan 20 17:50:40 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Sun, 20 Jan 2002 17:50:40 -0000 Subject: [Tutor] Dumb question Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C2C6@mbtlipnt02.btlabs.bt.co.uk> > I'm not a programmer, so this is a kinda dumb question. Its not dumb at all. In fact its something experienced programmers often find harder to understand than beginners! > What exactly is a class? When programming it often helps to build a kind of model of the "real world problem". Classes are descriptions of the real world 'objects' that we are modelling. This is similar to the techniquie of drawing a scale diagram to measure somethjing, or building a scale model for windtunnel testing used in other engineering disciplines. Classes are the blueprints for our "scale model" objects. > Why would use one? To try to keep the solution as much like the problem as possible - it helps us focus on the important bits of the problem without getting bogged down in details (which are hidden inside the class!) > How do you define one? class Pen: # define properties of the class here ink = 'black' # also define operations on the objects here # just like normal functions but inside the class def draw(self, x,y): # ignore self for now but we need it... # code to draw here Now we can create an instance of a Pen: p = Pen() Draw with it p.draw(5,9) Describe it print "Ink color is ", p.ink and so forth. We can forget about the details of how to draw(I dodn't show them anyhow!) and just think about using pens. > alot of reading on Python and this whole concept escapes me. I dunno if it included my tutor but i have a topic on Object orientation and examples of its use in both the Event Driven chapter and the GUI chapter plus the Case Study Alan g. Author of the 'Learning to Program' web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld@bt.com Sun Jan 20 18:02:04 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Sun, 20 Jan 2002 18:02:04 -0000 Subject: [Tutor] Help, for I have lost the PATH Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C2C7@mbtlipnt02.btlabs.bt.co.uk> > I cannot seem to get the path right so that python can find > modules I have written. OK, the one we need to worry about is PYTHONPATH (BTW Have you tried setting the path.py(or was it python.pth?) file, someone mentioned this as an alternative tecnique that sounded good.) > keep my python programs and stuff in c:\stuff > > I have set the path in my autoexec as follows: > PATH C:\python20;%PATH% This is odd coz the rest of Path isn't defined except for the default values > SET PYTHONPATH=.;C:\Python20\lib;c:\Python20\lib\tkinter;c:\stuff This looks OK to me. > SET PATH=C:\WINDOWS;C:\WINDOWS\COMMAND;C:\WINDOWS;C:\WINDOWS\COMMAND This is even wierder coz you replace the previous value of PATH with this which includes 2 folders twice! Try: SET PATH=C:\WINDOWS;C:\WINDOWS\COMMAND;C:\PYTHON20;%PATH% and remove the top line. ....< snip other irrelevant stuff>.... But the PYTHONPATH line looks OK. What error do you get exactly? > SET > PATH=C:\WINDOWS;C:\WINDOWS\COMMAND;C:\WINDOWS;C:\WINDOWS\COMMA > ND;C:\python20;%PATH% Closer but still duplicates entries. > SET PYTHONPATH=.;C:\Python20\lib;c:\Python20\lib\tkinter;c:\stuff Still right. Alan g From jgriffin@pclnet.net Sun Jan 20 19:04:05 2002 From: jgriffin@pclnet.net (Joseph Griffin) Date: Sun, 20 Jan 2002 13:04:05 -0600 Subject: [Tutor] Dumb question In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66C2C6@mbtlipnt02.btlabs.bt.co.uk> Message-ID: Alan, The concept of a class fell out of the problem of *managing* programs that were hundred's of thousands of lines long. Managment in this sense is 1)Upgrading only parts of the entire program without wrecking the rest of the application, 2)Debugging, and 3) coordinating the efforts of not one programmer, but scores of programmers. That is what classes do for you. You won't see that until you start working (designing and coding) on a huge project. In short, classes give you code organization. Joseph -----Original Message----- From: tutor-admin@python.org [mailto:tutor-admin@python.org]On Behalf Of alan.gauld@bt.com Sent: Sunday, January 20, 2002 11:51 AM To: chrislubrecht@home.com; tutor@python.org Subject: RE: [Tutor] Dumb question > I'm not a programmer, so this is a kinda dumb question. Its not dumb at all. In fact its something experienced programmers often find harder to understand than beginners! > What exactly is a class? When programming it often helps to build a kind of model of the "real world problem". Classes are descriptions of the real world 'objects' that we are modelling. This is similar to the techniquie of drawing a scale diagram to measure somethjing, or building a scale model for windtunnel testing used in other engineering disciplines. Classes are the blueprints for our "scale model" objects. > Why would use one? To try to keep the solution as much like the problem as possible - it helps us focus on the important bits of the problem without getting bogged down in details (which are hidden inside the class!) > How do you define one? class Pen: # define properties of the class here ink = 'black' # also define operations on the objects here # just like normal functions but inside the class def draw(self, x,y): # ignore self for now but we need it... # code to draw here Now we can create an instance of a Pen: p = Pen() Draw with it p.draw(5,9) Describe it print "Ink color is ", p.ink and so forth. We can forget about the details of how to draw(I dodn't show them anyhow!) and just think about using pens. > alot of reading on Python and this whole concept escapes me. I dunno if it included my tutor but i have a topic on Object orientation and examples of its use in both the Event Driven chapter and the GUI chapter plus the Case Study Alan g. Author of the 'Learning to Program' web site http://www.freenetpages.co.uk/hp/alan.gauld _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From dyoo@hkn.eecs.berkeley.edu Sun Jan 20 19:06:19 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 20 Jan 2002 11:06:19 -0800 (PST) Subject: [Tutor] my first pygame experiment In-Reply-To: <3C4AF78D.A092E00F@netzero.net> Message-ID: On Sun, 20 Jan 2002, kirk Bailey wrote: > Danny, what's with this error I got? > > C:\Python21>python game1.py > File "game1.py", line 22 > yield x > ^ > SyntaxError: invalid syntax Sorry, I should have mentioned it earlier; I'm using a Python 2.2 feature called "generators" in the code. I can fix the code to be more compatible if you'd like. From jvs619@hotmail.com Sun Jan 20 13:57:51 2002 From: jvs619@hotmail.com (johan henao) Date: Sun, 20 Jan 2002 08:57:51 -0500 Subject: [Tutor] hey i need a tutor Message-ID:
well i just want to learn how to program if some one could please help
im lost i cant even download it when i down loaded it my computer could not read da file


Send and receive Hotmail on your mobile device: Click Here
From dsh8290@rit.edu Sun Jan 20 21:03:51 2002 From: dsh8290@rit.edu (dman) Date: Sun, 20 Jan 2002 16:03:51 -0500 Subject: [Tutor] hey i need a tutor In-Reply-To: References: Message-ID: <20020120210351.GA18146@localhost> On Sun, Jan 20, 2002 at 08:57:51AM -0500, johan henao wrote: | well i just want to learn how to program if some one could please help That's what this list is for. | im lost i cant even download it when i down loaded it my computer could | not read da file What is "it"? The windows installer? Some documentation? Please provide more details. Include o the URL of the file you tried to download o details of exactly what you did o details of what happened -D -- A violent man entices his neighbor and leads him down a path that is not good. Proverbs 16:29 From jimmy_130@lycos.com Sun Jan 20 23:21:04 2002 From: jimmy_130@lycos.com (James M Lang) Date: Sun, 20 Jan 2002 18:21:04 -0500 Subject: [Tutor] What would be the best tutorial? Message-ID: I want to learn python quickly and easily. And if it helps any, I'm 14 years old. So what would be the best tutorial for me? From idiot1@netzero.net Mon Jan 21 00:35:26 2002 From: idiot1@netzero.net (kirk Bailey) Date: Sun, 20 Jan 2002 19:35:26 -0500 Subject: [Tutor] lARGE LISTS W/TL Message-ID: <3C4B624E.3C687C2@netzero.net> Well, I installed TL in my email service and turned it on. Anyone clicking on LISTS! in the menu gets the web manager page. It is live and serving list traffic, handling management requests, and (hopefully) earning a living tossing list traffic. THIS is where ai wanted to be by when Listbot went tits-up last subber. Promised software, never arrived. Tried another product, could not handle large lists. Tried majordomo, majorcool is a wino junkie and drives me mad. Tried to learn perl, bounced. Tried to get my perl maven to help, he works AND goes to college, clocktics are REAL short in his life. So TL lives. List service is FINALLY decent, reliable, easy. Let's see how the world at large takes it. I just notified the membership base with the announcement list 'monkeyshines', which is a TinyList list. It even tripped over, recovered from, and handled a bad email- made sure my address was LAST on the lsit, so if it blew out, I would never get mine. It arrived, as also did an email announcement that there was a bad address. I think I shall go have a little coniac... yum, Henessy XO. -- -Respectfully, -Kirk D Bailey Consulting Loose Cannon end www.howlermonkey.net highprimate@howlermonkey.net www.sacredelectron.org idiot1@netzero.net www.tinylist.org grumpy@tinylist.org ---------------------------------------------------- Sign Up for NetZero Platinum Today Only $9.95 per month! http://my.netzero.net/s/signup?r=platinum&refcd=PT97 From jgriffin@pclnet.net Mon Jan 21 01:23:07 2002 From: jgriffin@pclnet.net (Joseph Griffin) Date: Sun, 20 Jan 2002 19:23:07 -0600 Subject: [Tutor] What would be the best tutorial? In-Reply-To: Message-ID: Jimmy, Having learn VC++,VB,VFP, and Fortran - there will be a certain amount of drudgery to wade through in order to learn Python (I am new to it too). Start with the tutorial using the Window's Extentsions by Mark Hammond (I'm assuming you have a Windows Machine). If this is your first language, you will stuggle at first - as will I. There are concepts that you will need to learn that are not specific to Python, but to all computer languages. These are 1) object oriented design, 2) encapsulation, and 3) component coupling - to name a few. For now it will be enough just to get Python up and running on your machine, go through the tutorial, and then play with the code to see if you can make it do what you want. Good Luck. Joseph -----Original Message----- From: tutor-admin@python.org [mailto:tutor-admin@python.org]On Behalf Of James M Lang Sent: Sunday, January 20, 2002 5:21 PM To: tutor@python.org Subject: [Tutor] What would be the best tutorial? I want to learn python quickly and easily. And if it helps any, I'm 14 years old. So what would be the best tutorial for me? _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From Johannes Gijsbers Mon Jan 21 01:44:23 2002 From: Johannes Gijsbers (Johannes Gijsbers) Date: Mon, 21 Jan 2002 02:44:23 +0100 Subject: [Tutor] What would be the best tutorial? In-Reply-To: References: Message-ID: <51277787476.20020121024423@subdimension.com> JG> I want to learn python quickly and easily. And if it helps any, I'm 14 years JG> old. So what would be the best tutorial for me? Jimmy, it depends. Do you know any programming languages yet? If you do, I would just recommend the python tutorial in the documentation by Guido van Rossum, the creator of Python. If you don't, take a look here: http://python.org/doc/Newbies.html Of these, I would recommend Alan Gauld's tutorial: http://www.freenetpages.co.uk/hp/alan.gauld/ Of course, if you have some money to spend(or can get you parents to spend some money for you ;), you should try buying the book bij Alan Gauld: http://www.amazon.com/exec/obidos/ASIN/0201709384/pythonbookstore From glidedon Sun Jan 20 20:55:19 2002 From: glidedon (glidedon) Date: Sun, 20 Jan 2002 20:55:19 +0000 Subject: [Tutor] Truckers Log....Me Again Message-ID: <00039802319dfc1f_mailit@mail.c-zone.net> Hello Folks, I'm stuck again. I am trying to figure out how to do this in a while loop. While X is Yes do this if X is no do this if x is not yes or no print this go back to the beginning of the while loop I hope this makes sense too you :-) Thanks for the help ! Don From dyoo@hkn.eecs.berkeley.edu Mon Jan 21 04:53:58 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 20 Jan 2002 20:53:58 -0800 (PST) Subject: [Tutor] Truckers Log....Me Again In-Reply-To: <00039802319dfc1f_mailit@mail.c-zone.net> Message-ID: On Sun, 20 Jan 2002, glidedon wrote: > I am trying to figure out how to do this in a while loop. > > > While X is Yes > do this > if X is no > do this > if x is not yes or no > print this > go back to the beginning of the while loop It sounds like you want to do something like the following pseudocode ## while 1: read the input x if x == yes: do this elif x == no: do the other thing else: print some warning ### This is often called a "read-eval-print" loop: 1. We read some input from the user. 2. We evaluate or interpret that response. 3. We print out some output. 4. Repeat! and is often used with interactive programs that need to read input from a user. Hope this helps! From erikprice@mac.com Mon Jan 21 05:23:15 2002 From: erikprice@mac.com (Erik Price) Date: Mon, 21 Jan 2002 00:23:15 -0500 Subject: [Tutor] Truckers Log....Me Again In-Reply-To: Message-ID: Hello everyone, This is my first post to the list. I've spent the past couple of months learning PHP as my first programming language (except the obligatory BASIC from years ago, and a smattering of bash/AppleScript -ing) and thought to extend my skillset. It seems that everyone is recommending Python for aspiring self-taught programmers. I have a few questions, and the first of them stems from this example: On Sunday, January 20, 2002, at 11:53 PM, Danny Yoo wrote: > It sounds like you want to do something like the following pseudocode > > ## > while 1: > read the input x > if x == yes: > do this > elif x == no: > do the other thing > else: > print some warning > ### Admittedly, I am new so I don't know anything. But it would seem to me that this "while" loop would never end, since the condition "1" evaluates to "true" infinitely. I would assume that this is for the sake of example, and not to demonstrate an actual program's pseudocode. But on this list I have seen more than one example use this convention. Is Python different from other languages in this respect? Another question I have is about objects. I appreciate the "dumb question" thread from earlier this weekend, since I do not completely grasp the notion of objects myself. I have done a brief tutorial in PHP's classes from a book, but haven't seen a situation where it would be helpful to me so far. (Though this could easily be due to my inexperience in programming.) One of the reasons Python is recommended so heavily is that it is "true object oriented". And in response to 14-yr old Jimmy's request for programming assistance, another python-tutor-lister recommended becoming familiar with the use of objects. Is the use of objects somehow more tightly integrated into Python than in other languages such as PHP and Perl? I had assumed that I could learn Python's syntax and hopefully get started with some small-scale development as a learning exercise, and worry about objects later. But is it a better idea to try to tackle this topic as early on as possible? Thanks in advance for any answers to these questions. I look forward to learning more. Erik From glidedon Sun Jan 20 21:46:53 2002 From: glidedon (glidedon) Date: Sun, 20 Jan 2002 21:46:53 +0000 Subject: [Tutor] Truckers Log....Me Again In-Reply-To: References: Message-ID: <00039802e9fc1769_mailit@mail.c-zone.net> > >It sounds like you want to do something like the following pseudocode > >## >while 1: > read the input x > if x == yes: > do this > elif x == no: > do the other thing > else: > print some warning >### > > >This is often called a "read-eval-print" loop: > > 1. We read some input from the user. > 2. We evaluate or interpret that response. > 3. We print out some output. > 4. Repeat! > >and is often used with interactive programs that need to read input from a >user. > > >Hope this helps! I must be thick headed! When I substitue elif for if, in the code below I get this error: SyntaxError: invalid syntax /boot/home/py>LogRecapv1.3.py File "./LogRecapv1.3.py", line 47 elif : add_days in ( 'n', 'N', 'no', 'NO' ): ^ The program works as is below but it exits after the last line. You can see what I was trying before your sugestion in the lines I commented out at the bottom. Thanks Danny ! # Logbook 8 day recap # this program will calculate hours on duty last 7 days, # hours avalible tomorrow(70 hours minus total last 7 days on duty) ,hours on duty last 8 days # for a truck drivers log book #create list for storing hours on duty record history_list = [ ] last_7_days = 0 print ' \n ' *2 , ' Welcome to Don\'s Recap Calculator ! ', ' \n ' print ' I hope this makes recaping your log easier. ' , ' \n ' # populate history_list with first 8 days of recap and convert to float for i in range( 8 ): querry_string = " Enter total hours on duty on day%d " % ( i +1 ) input = raw_input(querry_string) history_list.append( float( input ) ) # ask for additional days input add_days = raw_input( 'Do you want to add more days to recap ? y/n : ' ) # create loop to check if the answer is y or n, or some variation of # assign value of the last 7 entries in history_list to the variable last_7days # output current recap status # continue loop for more input while add_days in ( 'y','Y', 'yes','YES', 'ok', 'OK', 'yeah', 'YEAH' ) : next_day =raw_input( ' Enter hours on duty next day : ') history_list.append( float (next_day ) ) print ' \n', '='*20,'RECAP', '=' *33,' \n', '=' * 60 import operator last_7_days = reduce( operator.add,history_list[ -7: ] ) print ' Total hours on duty last 7 days : ', last_7_days print ' Total hours available tomorrow : ' , 70 - last_7_days print ' Total hours on duty last 8 days : ' , last_7_days + history_list [ -8 ] print ' You have entered ' , len(history_list), ' Days ', ' \n' print ' ' ,history_list, '\n' , '=' * 60, '\n' add_days = raw_input( 'Do you want to add more days to recap ? y/n : ' ) if add_days in ( 'n', 'N', 'no', 'NO' ): print ' \n', '='*20,'RECAP', '=' *33,' \n', '=' * 60 , ' \n ' import operator last_7_days = reduce( operator.add,history_list[ -7: ] ) print ' Total hours on duty last 7 days : ', last_7_days print ' Total hours available tomorrow : ' , 70 - last_7_days print ' Total hours on duty last 8 days : ' , last_7_days + history_list [ -8 ] print ' You have entered ' , len(history_list), ' Days ', ' \n' print ' ' ,history_list print ' \n', '='*20,'EXIT', '=' *34,' \n', '=' * 60 print ' \n ' *2, 'Thanks for using Don\'s Recap calculator ! ', ' \n '*2, 'Have a safe trip :-) ',' \n' *3 #elif add_days != ( 'y','Y', 'yes','YES', 'ok', 'OK', 'yeah', 'YEAH' ) or( 'n', 'N', 'no', 'NO' ): #print ' Nice try good buddy, enter a y/n , ten-four ? ' else: print ' Nice try good buddy, enter a y/n , ten-four ? ' -- BeTween the BeS is the BeAutiful BeCalm AbitBE6, PIII 500, 192ram, AIW 128 Pro AGP,IBM udma66 9g, WD UDMA33 9g, HP 8200i CDRW, Pioneer 106s DVD Running BeOS 5.03 THE best OS on the Planet! From toodles@yifan.net Mon Jan 21 06:01:34 2002 From: toodles@yifan.net (Andy W) Date: Mon, 21 Jan 2002 14:01:34 +0800 Subject: [Tutor] Truckers Log....Me Again References: Message-ID: <005001c1a241$20385060$da00a8c0@Sun> > Hello everyone, Hi Erik, welcome to the tutor list. > > This is my first post to the list. I've spent the past couple of months > learning PHP as my first programming language (except the obligatory > BASIC from years ago, and a smattering of bash/AppleScript -ing) and > thought to extend my skillset. It seems that everyone is recommending > Python for aspiring self-taught programmers. I have a few questions, > and the first of them stems from this example: > > On Sunday, January 20, 2002, at 11:53 PM, Danny Yoo wrote: > > > It sounds like you want to do something like the following pseudocode > > > > ## > > while 1: > > read the input x > > if x == yes: > > do this > > elif x == no: > > do the other thing > > else: > > print some warning > > ### > > Admittedly, I am new so I don't know anything. But it would seem to me > that this "while" loop would never end, since the condition "1" > evaluates to "true" infinitely. I would assume that this is for the > sake of example, and not to demonstrate an actual program's pseudocode. > But on this list I have seen more than one example use this convention. > Is Python different from other languages in this respect? Sure you know something, you knew how to read that pseudocode and apply logical thinking :-) You're quite right, that pseudocoded loop as it is will not exit, _unless_ in "do this" or "do the other thing", there is a break statement. eg. while 1: print "I am invincible!" break #This statement breaks from the loop. print "Foiled yet again..." And you're right, it was for the sake of example. > > Another question I have is about objects. I appreciate the "dumb > question" thread from earlier this weekend, since I do not completely > grasp the notion of objects myself. I have done a brief tutorial in > PHP's classes from a book, but haven't seen a situation where it would > be helpful to me so far. (Though this could easily be due to my > inexperience in programming.) > > One of the reasons Python is recommended so heavily is that it is "true > object oriented". And in response to 14-yr old Jimmy's request for > programming assistance, another python-tutor-lister recommended becoming > familiar with the use of objects. Is the use of objects somehow more > tightly integrated into Python than in other languages such as PHP and > Perl? I had assumed that I could learn Python's syntax and hopefully > get started with some small-scale development as a learning exercise, > and worry about objects later. But is it a better idea to try to tackle > this topic as early on as possible? I would say it depends on what you want to do later. If you have no goal in regards of some program to develop, but rather you just wish to become more proficient in Python then - I would start off with the basics of Python first, and when you're comfortable and ready, move onto classes and other things. It could well be that you won't need classes if your programs are of a small scale, and undertake small tasks. Being the strange little man I am, I threw myself at C++ as my first language at the age of...14? (I'm 17 now). I grasped the fundamentals eventually, and classes quickly, maybe because I had never known any other type of programming. I haven't ever programmed in Perl or PHP, so I'll leave those questions to someone else. HTH Andy > > Thanks in advance for any answers to these questions. I look forward to > learning more. > > > > Erik > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From bronto@pobox.com Mon Jan 21 06:06:54 2002 From: bronto@pobox.com (Anton Sherwood) Date: Sun, 20 Jan 2002 22:06:54 -0800 Subject: [Tutor] Truckers Log....Me Again References: Message-ID: <3C4BAFFE.E1F271B5@pobox.com> > On Sun, 20 Jan 2002, glidedon wrote: > > I am trying to figure out how to do this in a while loop. [...] Danny Yoo wrote, omitting one line: > while 1: > read the input x > if x == yes: > do this > elif x == no: > do the other thing break #### > else: > print some warning as in C, `break' aborts the nearest enclosing loop, which appears to be what Glidedon appears to have in mind. -- Anton Sherwood -- http://www.ogre.nu/ From pythontutor@infopackaging.com Mon Jan 21 06:06:21 2002 From: pythontutor@infopackaging.com (as) Date: Mon, 21 Jan 2002 01:06:21 -0500 Subject: [Tutor] help making my ftp script more pythony Message-ID: <20020121060621.OXZI10469.femail3.sdc1.sfba.home.com@sony-c1xs> Hi all, I am a long time lurker, first time poster. Here is a little python script to = download the latest virus sigs from CA and run them. It works ok but I know it = is not very pythony. If you were going to write a simple FTP download what = would you of done differently. I feel the only functionality that I am missing = is some user feedback during the file transfer. Which could be done with a = callback function. Thanks for any info. Later, Troy =20 # Download latest CA Inoculan Personal Edition virus sigs and run. import ftplib import win32api import os PathList =3D [] def CallBak(DirString): Path =3D DirString[56:] # print Path PathList.append(Path) return=20 #Connect to host try: ftp =3D ftplib.FTP('ftpav.cai.com') except ftplib.all_errors, e: print e #Login try: ftp.login() # user anonymous, passwd user@hostname except ftplib.all_errors, e: print e #Change working directory try: ftp.cwd('pub/ipe') except ftplib.all_errors, e: print e #Get the directory into PathList try: ftp.dir(CallBak) except ftplib.all_errors, e: print e PathList.sort() # sort the list #Change working directory try: ftp.cwd(PathList[-1]) # choose the last item in the list ie. the most = recient except ftplib.all_errors, e: print e PathList =3D [] # clear the list to use again #Get the directory into PathList try: ftp.dir(CallBak) except ftplib.all_errors, e: print e PathList.sort() FileName =3D PathList[-1] # choose the last item in the list ie. the most = recient TempPath =3D win32api.GetEnvironmentVariable('temp') if os.path.isfile(TempPath+"\\"+FileName): try: os.remove(TempPath+"\\"+FileName) #it's a file, delete it except: #probably failed because it is not a normal file win32api.SetFileAttributes(TempPath+"\\"+FileName, = win32con.FILE_ATTRIBUTE_NORMAL) os.remove(TempPath+"\\"+FileName) #it's a file, delete it print "Downloading " + FileName + " to " + TempPath F =3D open(TempPath+"\\"+FileName, 'w') =20 ftp.retrbinary('RETR '+FileName, F.write, 1024) F.close() print ".....Done....." # win32api.WinExec(TempPath+"\\"+FileName) # run the downloaded file ftp.quit() From slime@vsnl.net Mon Jan 21 06:11:18 2002 From: slime@vsnl.net (Prahlad Vaidyanathan) Date: Mon, 21 Jan 2002 06:11:18 GMT Subject: [Tutor] Re: How to compare to time strings? In-Reply-To: <3C49FA25.30437.2479933@localhost> References: <3C49FA25.30437.2479933@localhost> Message-ID: <20020121053810.GA4766@marvin.clone> Hi, On Sat, 19 Jan 2002 A spewed into the ether: > Hello, > I have two time strings like > Mon, 31 Dec 2001 15 > and > Sat, 19 Jan 2002 21 > > How can I compare them and find out that > Mon, 31 Dec 2001 15 > is before > Sat, 19 Jan 2002 21 > ? > > I can not use > strptime function , to convert it first,because I use windows and > there is not that function. > Thanks for help > Ladislav You could use rfc822.parsedate(). Even if it doesn't work exactly the way you want it to, it should provide a decent starting point. pv. -- Prahlad Vaidyanathan Thank goodness modern convenience is a thing of the remote future. -- Pogo, by Walt Kelly From kalle@gnupung.net Mon Jan 21 06:31:30 2002 From: kalle@gnupung.net (Kalle Svensson) Date: Mon, 21 Jan 2002 07:31:30 +0100 Subject: [Tutor] Truckers Log....Me Again In-Reply-To: References: Message-ID: <20020121063130.GA1560@sandra.lysator.liu.se> [Erik Price] > Hello everyone, > > This is my first post to the list. [...] Welcome! > On Sunday, January 20, 2002, at 11:53 PM, Danny Yoo wrote: > > >It sounds like you want to do something like the following pseudocode > > > >## > >while 1: > > read the input x > > if x == yes: > > do this > > elif x == no: > > do the other thing > > else: > > print some warning > >### > > Admittedly, I am new so I don't know anything. But it would seem to me > that this "while" loop would never end, since the condition "1" > evaluates to "true" infinitely. I would assume that this is for the > sake of example, and not to demonstrate an actual program's pseudocode. > But on this list I have seen more than one example use this convention. > Is Python different from other languages in this respect? No, you're right. There would have to be a "break" somewhere in the real code, or there would be an infinite loop. The break statement is used to exit loops, like: while 1: x = raw_input("Break loop? (y/n)") if x in ("y", "Y"): print "Yes!" break else: print "No!" print "y entered!" > Another question I have is about objects. I appreciate the "dumb > question" thread from earlier this weekend, since I do not completely > grasp the notion of objects myself. I have done a brief tutorial in > PHP's classes from a book, but haven't seen a situation where it would > be helpful to me so far. (Though this could easily be due to my > inexperience in programming.) > > One of the reasons Python is recommended so heavily is that it is "true > object oriented". And in response to 14-yr old Jimmy's request for > programming assistance, another python-tutor-lister recommended becoming > familiar with the use of objects. Is the use of objects somehow more > tightly integrated into Python than in other languages such as PHP and > Perl? I had assumed that I could learn Python's syntax and hopefully > get started with some small-scale development as a learning exercise, > and worry about objects later. But is it a better idea to try to tackle > this topic as early on as possible? Well, regarding the comparision to Perl and PHP, I think many consider the use of objects to be more natural in Python. In fact, everything is an object in Python. Don't let this scare you, though. To answer your real question, I don't think you have to consider object orientation in the beginning. One of the beauties of Python, in my opinion, is that it supports many ways of programming (usually called paradigms). To begin programming in Python, learn the basic datatypes and start playing with loops, functions and such. And then, when you feel curious about classes and other object oriented stuff, you go on tho that part of the language. It's all about wanting to learn something. When you're interested, there's no way to stop you from learning. :) Peace, Kalle -- Kalle Svensson (kalle@gnupung.net) - Laziness, impatience, hubris: Pick two! English: http://www.gnupung.net/ Svenska: http://www.lysator.liu.se/~kalle/ Stuff: ["http://www.%s.org/" % x for x in "gnu debian python emacs".split()] From dyoo@hkn.eecs.berkeley.edu Mon Jan 21 06:29:16 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 20 Jan 2002 22:29:16 -0800 (PST) Subject: [Tutor] Truckers Log....Me Again In-Reply-To: Message-ID: On Mon, 21 Jan 2002, Erik Price wrote: > This is my first post to the list. I've spent the past couple of > months learning PHP as my first programming language (except the > obligatory BASIC from years ago, and a smattering of bash/AppleScript > -ing) and Hi Erik, nice to have you here! > > ## > > while 1: > > read the input x > > if x == yes: > > do this > > elif x == no: > > do the other thing > > else: > > print some warning > > ### > > Admittedly, I am new so I don't know anything. But it would seem to > me that this "while" loop would never end, since the condition "1" > evaluates to "true" infinitely. You're right: as it stands, this while loop says nothing about being able to get out of it. *grin* Let's talk a little more about the details. Conventionally, there's an idiom we can use to be able to get out, or "break" out of this loop. Here's a concrete example of this in the interpreter: ### >>> def readPassword(): ... while 1: ... print "password?" ... p = raw_input() ... if p == 'elbereth': ... break ... print "no good, try again" ... >>> readPassword() password? sega no good, try again password? griffindor no good, try again password? elbereth ### This is a function that won't let us go until we've said some magic word. If we want to get out of a loop, we can use the 'break' statement. In our case, 'break' pulls us out of the "infinite" loop. (Perhaps it's called "break" because tries to put the "breaks" on a runaway train? *grin*) > I would assume that this is for the sake of example, and not to > demonstrate an actual program's pseudocode. But on this list I have > seen more than one example use this convention. Is Python different > from other languages in this respect? Sorta. Python has two main "looping" or "iterative" syntax structures --- the 'while' loop and the 'for' loop. From what I remember, Python's for loop looks very similar to your bash shell's, so you should feel pretty comfortable with it once you see it. ### for name in ['humbert humbert', 'john nash', 'art doyle']: print "hello", name ### is an example of a Python for loop that goes over every element in a list of names. One of Python's main design points is that 'statements' --- things like variable assignment --- can't be plugged into things that expect 'expressions'. For example, something like: while ( (p = raw_input()) != "elbereth" ): isn't allowed in Python. If you come from a Perl/C/C++/Java background, this may be a little shocking to you. One side effect of this restriction is that certain bug-ridden constructs like: ### if x = 42: print "that's a magic number" ### can be flagged by Python as a syntax error, since the programmer probably meant to check for equality using '==', not assignment. I don't know if this quite answers your question, but it does touch on one of the "big" differences that people often run into when they first encounter Python. > Another question I have is about objects. I appreciate the "dumb > question" thread from earlier this weekend, since I do not completely > grasp the notion of objects myself. Ah! Keep the questions coming, and bring us back to earth. *grin* These questions are not dumb, and I personally like chattering about this stuff. > One of the reasons Python is recommended so heavily is that it is > "true object oriented". Python does allow a lot of kinds of programming, including programming that focuses on objects... but you don't have to jump into object oriented stuff until you need to. We can program productively without explicitely using object oriented programming (OOP). > And in response to 14-yr old Jimmy's request for programming > assistance, another python-tutor-lister recommended becoming familiar > with the use of objects. Is the use of objects somehow more tightly > integrated into Python than in other languages such as PHP and Perl? I can't say anything about PHP. Python has support for the creation of classes as a part of the language itself. On the other hand, Perl uses some preexisting concepts in its language to make writing OOP classes fit with the rest of the system. Using objects is about equally convenient in both Python and Perl. Here's a way of getting a file object in Python and printing a line: f = open("somefile") print f.readline() and in Perl, it's about the same: $f = IO::File->new("somefile"); print $f->getline(); > I had assumed that I could learn Python's syntax and hopefully get > started with some small-scale development as a learning exercise, and > worry about objects later. But is it a better idea to try to tackle > this topic as early on as possible? My opinion: go with your plan. You can pick up objects as you go along. A lot of the advantage of having objects is being able to organize programs into managable pieces, but you won't run into the managability problem until much later, and by then, objects should make more sense. You might need to know just enough to do things with files: ### >>> f = open("/home/dyoo/.bash_profile") >>> f.readline() '# ~/.bash_profile: executed by bash(1) for login shells.\n' >>> f.readline() '# see /usr/share/doc/bash/examples/startup-files for examples\n' ### but that's about it. You can write good programs without writing classes. Now, functions are a different matter. Definitely learn functions cold. *grin* Good luck to you. From shalehperry@attbi.com Mon Jan 21 06:36:41 2002 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Sun, 20 Jan 2002 22:36:41 -0800 (PST) Subject: [Tutor] help making my ftp script more pythony In-Reply-To: <20020121060621.OXZI10469.femail3.sdc1.sfba.home.com@sony-c1xs> Message-ID: > > def CallBak(DirString): > Path = DirString[56:] > # print Path > PathList.append(Path) > return > an empty return has no point >#Connect to host > try: > ftp = ftplib.FTP('ftpav.cai.com') > except ftplib.all_errors, e: > print e > you do not actually handle any of these exceptions, you just print. I more typical python app would likely wrap this whole block in a single exception, perhaps withing a loop > > if os.path.isfile(TempPath+"\\"+FileName): > try: > os.remove(TempPath+"\\"+FileName) #it's a file, delete it > except: > #probably failed because it is not a normal file > win32api.SetFileAttributes(TempPath+"\\"+FileName, > win32con.FILE_ATTRIBUTE_NORMAL) > os.remove(TempPath+"\\"+FileName) #it's a file, delete it > use os.path.join(), makes the code a lot clearer. filename = os.path.join(TempPath, Filename) From paulsid@shaw.ca Mon Jan 21 07:35:42 2002 From: paulsid@shaw.ca (Paul Sidorsky) Date: Mon, 21 Jan 2002 00:35:42 -0700 Subject: [Tutor] Objects (was Re: Truckers Log....Me Again) References: Message-ID: <3C4BC4CE.46A8BECD@shaw.ca> Before I start, I don't think I ever introduced myself to the list even though I've been here for a while and posted a few times. So I'll do it now, though I hate to make a very long post even longer: I'm 25 and a 3rd year Computer Science student at the local University, but I've been programming since I was 7 (first in BASIC, then C, then C++) so I'm mostly there to get the piece of paper (though I am nevertheless learning a lot). The data structures course introduced me to Python last year, and I've been hooked ever since. I wish I had discovered it many years ago, before I started C++. It would have bridged the gap nicely. Anyhow I like to help out people with programming when I can, so that's why I'm here. Plus the odd time I might even need to ask a question myself! Erik Price wrote: > Admittedly, I am new so I don't know anything. But it would seem to me > that this "while" loop would never end, since the condition "1" > evaluates to "true" infinitely. I would assume that this is for the > sake of example, and not to demonstrate an actual program's pseudocode. > But on this list I have seen more than one example use this convention. > Is Python different from other languages in this respect? It's pretty natural to mix Python and pseudocode in examples because Python has such a clean syntax. As for the specific example, Python has no "do...while" construct (that is, a loop that evaluates the conditional at the end rather than the beginning) so the usual workaround is this: while 1: # do stuff if loop_condition: break Danny's pseudo-Python didn't show a break but it would have to be included somewhere of course. Similarly, my example, while valid Python, needs to have something inserted where the comment is to make loop_condition true or it will also run on forever. > Another question I have is about objects. I appreciate the "dumb > question" thread from earlier this weekend, since I do not completely > grasp the notion of objects myself. I have done a brief tutorial in > PHP's classes from a book, but haven't seen a situation where it would > be helpful to me so far. (Though this could easily be due to my > inexperience in programming.) Objects have a lot of power and they make life a lot easier. The big problem is that the benefits tend to be more long-term in nature so they can't easily be seen. It doesn't help that a lot of OOP tutorials try to explain them by using fancy words like "encapsulation" which just seem to make people more confused. I'll try to illustrate some of their advantages through a very simple example. (All code is untested.) Without objects: seconds = 0 minutes = 0 hours = 0 def setclock(h=0, m=0, s=0): global hours, minutes, seconds hours = h minutes = m seconds = s def tickclock(): global hours, minutes, seconds seconds += 1 if seconds == 60: seconds = 0 minutes += 1 if minutes == 60: minutes = 0 hours += 1 if hours == 24: hours = 0 def printclock(): print "%02i:%02i:%02i" % (hours, minutes, seconds) if __name__ == "__main__": setclock(12, 0, 0) while 1: printclock() tick() With objects: class Clock: def __init__(self, hours=0, minutes=0, seconds=0): self.hours = hours self.minutes = minutes self.seconds = seconds def tick(self): self.seconds += 1 if self.seconds == 60: self.seconds = 0 self.minutes += 1 if self.minutes == 60: self.minutes = 0 self.hours += 1 if self.hours == 24: self.hours = 0 def __repr__(self): return "%02i:%02i:%02i" % (self.hours, self.minutes, self.seconds) if __name__ == "__main__": myclock = Clock(12, 0, 0) while 1: print myclock myclock.tick() On the surface, the object version looks simpler to write and about the same to use. So all this junk about putting self in front of everything and defining special behaviours (__init__ and __repr__) doesn't seem worth the bother. The two versions are identical in functionality, so what is the point of using an object here when it doesn't seem to be needed? The first big payoff is in reuse. If, down the road, you want to put a clock in another program, with the object version you can do this: import cheapclock anotherclock = cheapclock.Clock(12, 30) #do some stuff anotherclock.tick() print anotherclock You can do something similar with the non-object version, but it's uglier: import cheapclock cheapclock.hours = 12 cheapclock.minutes = 30 ... cheapclock.tick() cheapclock.printclock() Imagine doing that for many more variables and functions. Also, what if you need more than one clock? I'm not even sure you can do it with the non-object version. With the object version it's trivial to make even a thousand clocks: clocklist = [] for i in range(1000): clocklist.append(cheapclock.Clock()) Another huge win with the object version comes in maintenance. If you come back to the first version many months later, it takes a while to get reacquainted. You have to find out where hours, minutes, etc. are declared and used. You may have to relearn the function names. With the second version you can instantly see that minutes, hours, seconds belong to the Clock, and that the clock can tick itself and print itself. (No need to find the name of the print function because you can just print the clock object itself!) Lastly, extension is much easier. Lets say later on you want a clock that has milliseconds. You can't change your cheapclock module above because you have other programs using it the way it is, so these extensions will have to be done in a different module. This is quite simple with the object version: import cheapclock class MilliClock(cheapclock.Clock): def __init__(self, hours=0, minutes=0, seconds=0, ms=0): cheapclock.Clock.__init__(hours, minutes, seconds) self.milliseconds = ms def tick(self): self.milliseconds += 1 if self.milliseconds = 1000: self.milliseconds = 0 cheapclock.Clock.tick(self) def __repr__(self): return cheapclock.Clock.__repr__(self) + ("%03i" % self.milliseconds) With the non-object version, what do you do? Probably you copy the old cheapclock module and hack it to include milliseconds. That'll mean changing a lot of those "global" lists, among other things. Even once you do that, what if there's a bug in the original code that you've also copied? Now you have to change it in two places. Ditto if you want to make an enhancement to the general cheapclock and use it in your millisecond clock as well. With the object version, though, you can make the change in the original cheapclock module and not even touch the millisecond version, yet still get its benefits. It's tough to convey the power of objects in a single message and with such a small example, but I hope this provides some insight into WHY one might use them. > One of the reasons Python is recommended so heavily is that it is "true > object oriented". And in response to 14-yr old Jimmy's request for > programming assistance, another python-tutor-lister recommended becoming > familiar with the use of objects. Is the use of objects somehow more > tightly integrated into Python than in other languages such as PHP and > Perl? I had assumed that I could learn Python's syntax and hopefully > get started with some small-scale development as a learning exercise, > and worry about objects later. But is it a better idea to try to tackle > this topic as early on as possible? I would suggest trying to learn them as soon as you have the fundamentals of the language down (loops, functions, etc.). The problem if you don't is that you start to learn ways to compensate for their absence, and often these habits are VERY bad and make your life much more difficult than it needs to be. I mentioned a few of the problems these habits might cause in my example above, but that's just the tip of the iceberg. The big problem with objects in Python is that it's easy to largely ignore them. While everything in Python is an object, you don't have to know this to use the language. This is in contrast to a language like Java where you must consciously define at least one new class for every program. In Python you can go a long time and do a lot of neat stuff without ever defining your own classes or even using multiple modules of your own. So to learn to use objects in Python does take some discipline. The benefits, though, are well worth it. -- ====================================================================== Paul Sidorsky Calgary, Canada paulsid@shaw.ca http://members.shaw.ca/paulsid/ From karthikg@aztec.soft.net Mon Jan 21 08:33:55 2002 From: karthikg@aztec.soft.net (Karthik Gurumurthy) Date: Mon, 21 Jan 2002 14:03:55 +0530 Subject: [Tutor] a quetion on "There should be one and preferabley one obvious way to do it" In-Reply-To: <3C4BC4CE.46A8BECD@shaw.ca> Message-ID: hi all, this is what i read @ bruce eckel's python site. He says this is against Perl's "there is more than one way to do it" Let me point out that i'm not asking about languages comparisons here ! So am not interested in Perl's way of doing things! For example, map(None,l1,l2) does the same thing as say zip(l1,l2) + there are more ways of doin it dict.has_key(key) is same as if key in dict We have list comprehensions that work like maps So here too we have different ways of getting something done. I guess i have not been able to get a clear picture of this python philosophy. any inputs? thanks, karthik. From glidedon Mon Jan 21 00:29:29 2002 From: glidedon (glidedon) Date: Mon, 21 Jan 2002 00:29:29 +0000 Subject: [Tutor] Truckers Log....Me Again In-Reply-To: References: Message-ID: <000398052f7c63a5_mailit@mail.c-zone.net> Hey, thanks for your help I got it working the way I wanted. The object disscusion was informative too ! This list is awsome :-) Thanks again Don From paulsid@shaw.ca Mon Jan 21 08:50:47 2002 From: paulsid@shaw.ca (Paul Sidorsky) Date: Mon, 21 Jan 2002 01:50:47 -0700 Subject: [Tutor] a quetion on"There should be one and preferabley one obvious way to do it" References: Message-ID: <3C4BD667.6C5FE531@shaw.ca> Karthik Gurumurthy wrote: > So here too we have different ways of getting something done. > I guess i have not been able to get a clear picture of this python > philosophy. > any inputs? The features mentioned were all added to later versions of Python. zip() and list comprehensions were new for 2.0, key in dict is brand new for 2.2. This is far from my area of expertise, but from what I understand they are generally there to clean up some of the uglier parts of the language. List comprehensions replace a lot of map(lambda...) garbage which is very unsightly. I believe zip() is supposed to fill the gap for where list comprehensions aren't quite enough by providing a slightly cleaner call than map(). key in dict is natural to write and is a mistake that just about every newbie makes anyhow. :-) Remember one goal of Python's design is to encourage programmers to create cleaner code. These features seem to do that, in my book at least. Lastly, if you really want to learn more about the thinking behind some of these additions then I suggest reading the PEPs behind some of these enhancements: http://www.python.org/peps/ -- ====================================================================== Paul Sidorsky Calgary, Canada paulsid@shaw.ca http://members.shaw.ca/paulsid/ From scarblac@pino.selwerd.nl Mon Jan 21 09:18:28 2002 From: scarblac@pino.selwerd.nl (Remco Gerlich) Date: Mon, 21 Jan 2002 10:18:28 +0100 Subject: [Tutor] a quetion on "There should be one and preferabley one obvious way to do it" In-Reply-To: ; from karthikg@aztec.soft.net on Mon, Jan 21, 2002 at 02:03:55PM +0530 References: <3C4BC4CE.46A8BECD@shaw.ca> Message-ID: <20020121101828.A30382@pino.selwerd.nl> On 0, Karthik Gurumurthy wrote: > So here too we have different ways of getting something done. > I guess i have not been able to get a clear picture of this python > philosophy. > any inputs? Practicality beats purity. It's a nice guideline, but not a holy law. Other ways to do something can be added if Guido thinks it is worth it. In Perl, it seems it is actually a *goal* to have several ways to do the same thing, in Python it's seen as a negative thing (if there's no other benefit), but not more than that. [ In fact, zip() and map(None,) differ in their effect when two lists with unequal sizes are used - try it ] -- Remco Gerlich From alan.gauld@bt.com Mon Jan 21 09:24:16 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon, 21 Jan 2002 09:24:16 -0000 Subject: [Tutor] Dumb question Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C2C8@mbtlipnt02.btlabs.bt.co.uk> > The concept of a class fell out of the problem of *managing* > programs that were hundred's of thousands of lines long. Nope, sorry. Classes came from simulation. Simula67 was devised to model problems in telecommunications. Smalltalk 73 thru 80 came from experimenting with CS concepts. The early LISP OO variants (Flavors, LOOPS etc) during the 70s and early 80s likewise were focused on experimental projects, not large scale stuff. I could also mention CLU, Dylan etc... It was only in the 1980s with C++ that using classes as an organisational concept to control large projects (with millions not 100Ks of lines of code) came to be. We were building programs with many 100K LOC without OO for a long time. 100K lines only needs 1 or 2 programmers. Not hard to organise or maage, 10 million LOC needs scores of programmers and yes OO helps to organise that but its a beneficial side effect. If classes were primarily about organising large projecs we wouldn't need them in python - very few projects in python (if any!) get close to 100+ programmers > 1)Upgrading only parts of the entire program without wrecking > the rest of the application, Is much harder to achieve than it sounds - read the metaclasses book to understand why... > 2)Debugging, There is much objective evidence that suggests that OO projects are no easier to manage than non OO. What is more important is having a clearly defined architecture and code structure, with all programmers asdhering to those principles. One study indicated that using C++ on a project coud increase the mainteance overhead - especialy when multiple inheritance is used(abused?) > 3) coordinating the efforts of not one > programmer, but scores of programmers. As I said thats a side effect, ot what any of the early OO languages were concerned with. > won't see that until you start working (designing and coding) > on a huge project. The biggest project I've worked on was a 40 million line of code COBOL system written by over 400 programmers working for 3 companies in 4 countries. There were bits that were OO but most wasn't (The UI was written in Smalltalk) The second biggest was 3.5 million lines of C/C++ and was entirely OO(even the C parts using a proprietary OO library) This had over 100 programmers in 3 sites. The organisation of both projects was very similar. The OO aspects had little to do with the success or failure of either project. Interestingly the COBOL system is still running, the C++ one was decommissioned 2 years ago after 8 years of service. I've been programming in objects since 1984 in 9 different OO languages, I think OO is a valuable tool in the programmers toolkit. Its also important to recognise the problems it introduces as well as the benefits it brings. > In short, classes give you code organization. Joseph They do indeed. But what organisation do you use? You model your problem, that's what provides the intellectual leverage to make large bodies of code comprehensible. You can trace requirements(and bugs) from the customers/users language right through to the entities in your code. Alan g. From alan.gauld@bt.com Mon Jan 21 09:30:30 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon, 21 Jan 2002 09:30:30 -0000 Subject: [Tutor] hey i need a tutor Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C2C9@mbtlipnt02.btlabs.bt.co.uk> ------_=_NextPart_001_01C1A25E.44D24120 Content-type: text/plain; charset="ISO-8859-1" > well i just want to learn how to program if some one could please help Sure thats why we're here. im lost i cant even download it when i down loaded it my computer could not read da file What kind of computer is it? What OS are you running? PC/Mac/Sun? Windows(9x/Me/2000/XP) or MacOS(9 or X) or Linux or.... What file did you download and from where? What happens when you try to run it? If you give us those bits of info we can try to figure out whats happening. Alan g ------_=_NextPart_001_01C1A25E.44D24120 Content-type: text/html; charset="ISO-8859-1"
 >  well i just want to learn how to program if some one could please help 
 
Sure thats why we're here. 
im lost i cant even download it when i down loaded it my computer could not read da file 
What kind of computer is it? What OS are you running?
PC/Mac/Sun?
Windows(9x/Me/2000/XP) or MacOS(9 or X) or Linux or....
 
What file did you download and from where?
 
What happens when you try to run it?
 
If you give us those bits of info we can try to figure
out whats happening.
 
Alan g
------_=_NextPart_001_01C1A25E.44D24120-- From glingl@aon.at Mon Jan 21 09:32:57 2002 From: glingl@aon.at (Gregor Lingl) Date: Mon, 21 Jan 2002 10:32:57 +0100 Subject: [Tutor] What would be the best tutorial? References: Message-ID: <005d01c1a25e$9c36ff00$1664a8c0@mega> Dear Jimmy! I recommend to you the material of the LiveWires - Python Course, The LiveWires Python Course is intended to teach the Python programming language to people who have never programmed before. The material was used on computer-camps in 1999, 2000 and 2001 with students of just your age. You'll find it here: http://www.livewires.org.uk/python/index.html Good luck! Gregor ----- Original Message ----- From: "James M Lang" To: Sent: Monday, January 21, 2002 12:21 AM Subject: [Tutor] What would be the best tutorial? > I want to learn python quickly and easily. And if it helps any, I'm 14 years old. So what would be the best tutorial for me? > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld@bt.com Mon Jan 21 09:36:53 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon, 21 Jan 2002 09:36:53 -0000 Subject: [Tutor] Truckers Log....Me Again Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C2CA@mbtlipnt02.btlabs.bt.co.uk> > While X is Yes > do this > if X is no > do this > if x is not yes or no > print this > go back to the beginning of the while loop while 1: # loop forever if X is yes: do this continue # back to while - not essential but makes explicit elif X is no: do the other break # only do it once, then leave the loop else: print this # returns to while HTH Alan G From alan.gauld@bt.com Mon Jan 21 09:41:55 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon, 21 Jan 2002 09:41:55 -0000 Subject: [Tutor] Truckers Log....Me Again Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C2CB@mbtlipnt02.btlabs.bt.co.uk> > that this "while" loop would never end, since the condition "1" > evaluates to "true" infinitely. Correct, Danny forgot to put a break statement in one of the branches. > Another question I have is about objects. I appreciate the "dumb > question" thread from earlier this weekend, since I do not completely > grasp the notion of objects myself. > familiar with the use of objects. Is the use of objects somehow more > tightly integrated into Python than in other languages such > as PHP and Perl? Yes it is but its not toally essential. See Kirks TL project where he hasn't used objects(or at least hasn't created any) but built a production strength mail list handler.... > I had assumed that I could learn Python's syntax and hopefully > get started with some small-scale development as a learning exercise, > and worry about objects later. You an, no worries. You will learn to use objects, possibly subliminally, in Python. Once you are comfortable in using them you can start thinking about creating them. Python is good for both approaches. Alan g. Author of the 'Learning to Program' web site http://www.freenetpages.co.uk/hp/alan.gauld From Tron@submatrix.com Mon Jan 21 09:21:32 2002 From: Tron@submatrix.com (Tron) Date: Mon, 21 Jan 2002 01:21:32 -0800 Subject: [Tutor] Smart Cards References: <3C4BC4CE.46A8BECD@shaw.ca> <20020121101828.A30382@pino.selwerd.nl> Message-ID: <011401c1a25d$0446c690$7001a8c0@praxis> Anyone have any experience with these? -Tron From dyoo@hkn.eecs.berkeley.edu Mon Jan 21 10:07:14 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 21 Jan 2002 02:07:14 -0800 (PST) Subject: [Tutor] Truckers Log....Me Again [functions] In-Reply-To: <00039802e9fc1769_mailit@mail.c-zone.net> Message-ID: [some code cut] > while add_days in ( 'y','Y', 'yes','YES', 'ok', 'OK', 'yeah', 'YEAH' ) : [more code cut] > if add_days in ( 'n', 'N', 'no', 'NO' ): One suggestion: it might be nice to make up a separate function that says if an input is "yes"-ish or "no"-ish. Here's a function that might help: ### def isYes(answer): return answer in ( 'y','Y', 'yes','YES', 'ok', 'OK', 'yeah', 'YEAH' ) ### If we have this definition for isYes(), we can say things like: ### while isYes(add_days): ... ### to see if the user respons favorably to us. It's not really a matter of saving space, since we end up actually typing a little more to write a function definition. Instead, it's more for clarity's sake, so that later on, we can look at isYes() and say "Ah, so that's what it means for the user's input to be a Yes." Ok, that does sound picky. I mean, it's just one line, and its action is so limited! Hmmm... I'd better pick another example. Here's another section that might be amendable to this function approach: > print ' \n', '='*20,'RECAP', '=' *33,' \n', '=' * 60 > last_7_days = reduce( operator.add,history_list[ -7: ] ) > print ' Total hours on duty last 7 days : ', last_7_days > print ' Total hours available tomorrow : ' , 70 - last_7_days > print ' Total hours on duty last 8 days : ' , last_7_days + > history_list [ -8 ] With functions, it's possible to group this set of statements into a some imaginative name like...errr... "printSummary()". I'm sorry, it's late, and I'm too sleepy to think of a good function name... *grin* If we have some function like printSummary(), we'd be able to write the code to read like: ### print ' You have entered ' , len(history_list), ' Days ', ' \n' print ' ' ,history_list, '\n' , '=' * 60, '\n' add_days = raw_input( 'Do you want to add more days to recap ? y/n : ') printSummary() ### It's very nice to be able to print out a whole summary of the timesheet with a single word. In a sense, functions almost act like paragraphs because they group related statements together, and by writing a function, we're almost saying that these set of instructions work in cooperation toward a common goal. Functions also allow us to avoid cut-and-pasting old code, but that's a side benefit. One of the main reasons we write functions is because they allow us to group a disparate collection of actions with a good name. For some strange reason, this ability to group-and-name often helps humans deal with simple ideas as well as the complex. Hope this helps! From dyoo@hkn.eecs.berkeley.edu Mon Jan 21 11:16:28 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 21 Jan 2002 03:16:28 -0800 (PST) Subject: [Tutor] a quetion on "There should be one and preferabley one obvious way to do it" In-Reply-To: Message-ID: On Mon, 21 Jan 2002, Karthik Gurumurthy wrote: > hi all, > > this is what i read @ bruce eckel's python site. He says this is > against Perl's "there is more than one way to do it" Yes, according to the "Zen of Python": http://www.python.org/doc/Humor.html#zen Python tries to maintain the idea that "There should be one-- and preferably only one --obvious way to do it." > For example, > > map(None,l1,l2) > > does the same thing as > say > > zip(l1,l2) Yes, good point! The problem is that people have argued that: map(None, l1, l2) looked totally weird --- what did it mean to map 'None' against those two lists? Let's try it. ### >>> l1, l2 = range(10), list('abcdefghij') >>> map(None, l1, l2) [(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd'), (4, 'e'), (5, 'f'), (6, 'g'), (7, 'h'), (8, 'i'), (9, 'j')] ### It "ruffle shuffles" or "zips" the two lists together! How strange! Yet it's documented: """ map(function, list, ...) Apply function to every item of list and return a list of the results. If additional list arguments are passed, function must take that many arguments and is applied to the items of all lists in parallel; if a list is shorter than another it is assumed to be extended with None items. If function is None, the identity function is assumed; if there are multiple list arguments, map() returns a list consisting of tuples containing the corresponding items from all lists (a kind of transpose operation). The list arguments may be any kind of sequence; the result is always a list. """ It's documented... but yet, this behavior of map() is not "obvious" at a first glance. We talked about this a bit on Tutor back in August: http://mail.python.org/pipermail/tutor/2001-August/008204.html and I'm sure we weren't alone in our confusion. Python Enhancement Proposal (PEP) 201 was born to address the 'map(None, l1, l2)' issue: http://python.sourceforge.net/peps/pep-0201.html so that's why we have a zip() function, to take the load off of map(). > there are more ways of doin it > > dict.has_key(key) > is same as > if key in dict Yes, this uses the new iterator system that's part of Python 2.2. It's true that: dict.has_key(key) and if key in dict have similar effects, but there's another benefit to being able to do this, and it applies specifically for the 'for loop' on dictionaries: ### for key in dict: ### There's actually a performance benefit to doing it this way with iterators, as opposed to: ### for key in dict.keys(): ### This benefit is explained in PEP 234 under the "Dictionary Iterators" section: http://python.sourceforge.net/peps/pep-0234.html but basically, it summarizes to the idea that Python won't have to actually construct a list of a dictionary's keys before traversing them, if it uses iterators. > We have list comprehensions that work like maps But for people to effectively use map(), people need to feel very comfortable passing around functions as objects. For many programmers, being able to hold a function in our hand: ### >>> def square(x): return x * x ... >>> square ### and being able to spontaneously build new functions: ### >>> cube = lambda x: square(square(x)) >>> cube(42) 3111696 ### is weird as heck. *grin* List comprehensions are a bit easier to understand --- they use the syntax in a way that does seem less alien than map(). The implementors explain why they chose to add list comprehensions to the language here: http://python.sourceforge.net/peps/pep-0202.html > So here too we have different ways of getting something done. Yes, Python does allow the programmer to choose different ways to do something. Often, though, the designers have tried to make certain things easier to do, like 'zipping' or constructing lists with list comprehensions, things that people are doing a lot. It's "syntactic sugar": it's meant to make certain things more palatable. I do agree that, at a certain point, the implementors should stop adding syntactic features to Python. (What were they thinking with 'print >>>'?! *sigh*) For the most part, though, I think they've had pretty good taste. By the way, you might be interested in the technetcast.com talk about the "Lightweight Languages Workshop" at MIT: http://technetcast.ddj.com/tnc_catalog.html?item_id=1295 In particular, Shriram Khrishnamurthi's talk, "The Swine Before PERL" does address the idea that adding syntax to make things easier might not be an optimal approach to design a language. It's a lot of fun to listen to an "academic geek", and he does touch on the questions that you're asking. http://technetcast.ddj.com/tnc_play_stream.html?stream_id=644 Anyway, I hope I didn't sound too shrill. *grin* Now I'm going to sleep. Talk to you later! From karthikg@aztec.soft.net Mon Jan 21 12:02:29 2002 From: karthikg@aztec.soft.net (Karthik Gurumurthy) Date: Mon, 21 Jan 2002 17:32:29 +0530 Subject: Thanks for all the answers!: RE: [Tutor] "There should be one and preferabley one " In-Reply-To: <20020121101828.A30382@pino.selwerd.nl> Message-ID: > Practicality beats purity. > It's a nice guideline, but not a holy law. Other ways to do something can be > added if Guido thinks it is worth it. > In Perl, it seems it is actually a *goal* to have several ways to do the > same thing, in Python it's seen as a negative thing (if there's no other > benefit), but not more than that. > [ In fact, zip() and map(None,) differ in their effect when two lists with unequal sizes are used - try it ] >-- >Remco Gerlich thanks. Thanks for pointing out the difference, i found that map retains the items from the bigger list while zip does not. Moreover, i wanted to thank the list for being so helpful. I did'nt want to flood the list with "thank you" messages everytime my queries got answered, though i wanted to! I don't think anyone can find better explanations anywhere else..this list is that good! I'm conducting a 1 hour presentation on python @ our place every week and it's being received well. I figured out that introducing a language in an hour is one hell of a job but managed somehow. It's been great fun and learning for me, for i have never made any presentations on a language before. I had to do a bit of reading on Perl too to contrast it with python. Our guys know Perl. We have 200 odd developers @ our place and I hope to add a handful of guys to the py-community through my humble efforts. This would not have been possible w/o the help of this great list! karthik. _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From csmith@blakeschool.org Mon Jan 21 14:24:19 2002 From: csmith@blakeschool.org (Christopher Smith) Date: Mon, 21 Jan 2002 08:24:19 -0600 Subject: [Tutor] Re: Tutor digest, Vol 1 #1357 - 15 msgs In-Reply-To: References: Message-ID: tutor@python.org writes: >From: "Gregor Lingl" >To: , > >Subject: Re: [Tutor] What would be the best tutorial? I cut my Python teeth on the How to Think book. The (much) revised version is at http://www.ibiblio.org/obp/thinkCSpy/. I was able to complete the book and then move on to several other tutorials that are located on the web (many of which have been mentioned) and often consulted the Python tutorials and documentation and this tutor list. Just a note: there is a beginner's page at the Python home page from where you can access many of the materials that have been mentioned: http://www.python.org/doc/Newbies.html /c From rob@jam.rr.com Mon Jan 21 15:08:14 2002 From: rob@jam.rr.com (Rob Andrews) Date: Mon, 21 Jan 2002 09:08:14 -0600 Subject: [Tutor] Re: Tutor digest, Vol 1 #1357 - 15 msgs References: Message-ID: <3C4C2EDE.9030703@jam.rr.com> Actual *proof* that I yet live, here's my obligatory plug for the Useless Python Tutorial Links page: http://www.lowerstandard.com/python/tutoriallinks.html wink-wink-nudge-nudge, Rob Christopher Smith wrote: tutor@python.org writes: From: "Gregor Lingl" To: , Subject: Re: [Tutor] What would be the best tutorial? I cut my Python teeth on the How to Think book. The (much) revised version is at http://www.ibiblio.org/obp/thinkCSpy/. I was able to complete the book and then move on to several other tutorials that are located on the web (many of which have been mentioned) and often consulted the Python tutorials and documentation and this tutor list. Just a note: there is a beginner's page at the Python home page from where you can access many of the materials that have been mentioned: http://www.python.org/doc/Newbies.html /c _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor -- In the U.S.: Every 13 minutes a name is added to the organ transplant waiting list. Every 91 minutes a life ends because the needed organ didn't come. Signing a donor card takes less than 1 minute. http://www.organdonor.gov From sexyaggie06@Aggies.com Mon Jan 21 17:08:36 2002 From: sexyaggie06@Aggies.com (Joey Dixon) Date: Mon, 21 Jan 2002 17:08:36 +0000 Subject: [Tutor] I need a Tutor Message-ID:


i am just getting started in programing and am in need of a tutor!  A one-on-one person to help me.  If you can e-mail me@ hot_stuff343@hotmail.com



Chat with friends online, try MSN Messenger: Click Here
From mando@mando.org Mon Jan 21 17:45:04 2002 From: mando@mando.org (Mando Escamilla) Date: Mon, 21 Jan 2002 12:45:04 -0500 Subject: [Tutor] socket programming In-Reply-To: <5.1.0.14.0.20020118224907.00a8a180@pop3.norton.antivirus> Message-ID: <002001c1a2a3$5c2a0070$66422444@CC1050110A> Try this: While 1: a = socketthing.recv(1024) if a == "Dead Parrot": sockettthing.send("It's Dead\0") ^^ else: socketthing.send("Silly\0") ^^ Honestly, I've long since forgotten why that works. Maybe someone else here can explain. -- Mando From kjphotog@juno.com Mon Jan 21 16:36:53 2002 From: kjphotog@juno.com (kjphotog@juno.com) Date: Mon, 21 Jan 2002 08:36:53 -0800 Subject: [Tutor] Free Books Message-ID: <20020121.094059.-206357.12.kjphotog@juno.com> This message is in MIME format. Since your mail reader does not understand this format, some or all of this message may not be legible. ----__JNP_000_3d43.3c84.0593 Content-Type: text/plain; charset=us-ascii Content-Transfer-Encoding: 7bit Jimmy, In response to your "What would be the best tutorial? I want to learn python quickly and easily." And it was suggested you buy some Python books. I've discovered books like Learning Python, Win32, Python Bible & others are available FREE @ my public library. Check it out! At L.A. Public libraries you can reserve books on-line & pick them up at a branch near you (www.lapl.org). ----__JNP_000_3d43.3c84.0593 Content-Type: text/html; charset=us-ascii Content-Transfer-Encoding: quoted-printable
Jimmy,
 
In response to your "What would be the best tutorial? I want to = learn=20 python quickly and easily." And it was suggested you buy= some=20 Python books. 
 
I've discovered books like Learning Python, Win32, Python Bible=20 & 
others are available FREE @ my public library. Check = it=20 out! At L.A. Public libraries you can reserve books on-line & pick= them=20 up at a branch near you (www.lapl.org).=
 
----__JNP_000_3d43.3c84.0593-- ________________________________________________________________ GET INTERNET ACCESS FROM JUNO! Juno offers FREE or PREMIUM Internet access for less! Join Juno today! For your FREE software, visit: http://dl.www.juno.com/get/web/. From kjphotog@juno.com Mon Jan 21 17:12:39 2002 From: kjphotog@juno.com (kjphotog@juno.com) Date: Mon, 21 Jan 2002 09:12:39 -0800 Subject: [Tutor] Which Py? Message-ID: <20020121.094059.-206357.14.kjphotog@juno.com> Just as I start figuring out how to use 2.1.1 (I like the easy to read PythonWin window that 2.1.2 doesn't seem to have) & now there's versions 2.1.2 & 2.2. Which version should I use? Keith ________________________________________________________________ GET INTERNET ACCESS FROM JUNO! Juno offers FREE or PREMIUM Internet access for less! Join Juno today! For your FREE software, visit: http://dl.www.juno.com/get/web/. From ylee12@uiuc.edu Mon Jan 21 17:55:19 2002 From: ylee12@uiuc.edu (Young-Jin Lee) Date: Mon, 21 Jan 2002 11:55:19 -0600 Subject: [Tutor] [Q] inheriting a class Message-ID: <004b01c1a2a4$ca3d0f20$95757e82@visit2> Hi, I have a question how to inherit a class. I wanted to add a new method to the existing class and I thought it would be possible with the following code. #### class ball( sphere ): def printProperty(): print 'print property' #### I wanted to use the parent class's __init__ method, but when I tried typed the above codes in the pythons shell, I got "TypeError: __init__() takes exactly 2 arguments (4 given)" error message. I don't know how the parent class's __init__ method is configured because it was given as a DLL. Is there any way to use the parent class's __init__ method? How come I gave 4 arguments? Thanks in advance. YJ From rob@jam.rr.com Mon Jan 21 18:24:27 2002 From: rob@jam.rr.com (Rob Andrews) Date: Mon, 21 Jan 2002 12:24:27 -0600 Subject: [Tutor] Which Py? References: <20020121.094059.-206357.14.kjphotog@juno.com> Message-ID: <3C4C5CDB.1010105@jam.rr.com> kjphotog@juno.com wrote: > Just as I start figuring out how to use 2.1.1 (I like the easy to read > PythonWin window that 2.1.2 doesn't seem to have) & now there's > versions 2.1.2 & 2.2. Which version should I use? > Use any version that brings you pleasure, if you are just learning the language or don't have specific reasons to do things a certain way. In general, I think it's a good idea to use the most current version you can come to terms with. Rob http://www.lowerstandard.com/python From pythontutor@venix.com Mon Jan 21 18:22:11 2002 From: pythontutor@venix.com (Lloyd Kvam) Date: Mon, 21 Jan 2002 13:22:11 -0500 Subject: [Tutor] I need a Tutor References: Message-ID: <3C4C5C53.6090906@venix.com> You have very expert people watching the maillist here including Danny Yoo Alan Gauld They and others will respond to your questions. If you really want someone helping you in person, you should check with your local colleges and/or high schools. You may need to start with getting some help with basic "computer literacy". If you look through the archives http://aspn.activestate.com/ASPN/Mail/Browse/Threaded/python-Tutor ASPN : python-Tutor : Jan 21 2002 8:33AM - Dec 15 2001 5:45PM you can see the kind of support that is provided here. This help along with the web tutorials should get you started programming. Joey Dixon wrote: > > i am just getting started in programing and am in need of a tutor! A > one-on-one person to help me. If you can e-mail me@ > hot_stuff343@hotmail.com > > > ------------------------------------------------------------------------ > Chat with friends online, try MSN Messenger: Click Here > > _______________________________________________ Tutor maillist - > Tutor@python.org http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From pythontutor@venix.com Mon Jan 21 18:22:53 2002 From: pythontutor@venix.com (Lloyd Kvam) Date: Mon, 21 Jan 2002 13:22:53 -0500 Subject: [Tutor] Which Py? References: <20020121.094059.-206357.14.kjphotog@juno.com> Message-ID: <3C4C5C7D.8070306@venix.com> http://www.activestate.com/Products/Download/Get.plex?id=ActivePython ActiveState -- Programming for the People ActiveState provides a Windows oriented Python release that is easy to install and get started. They consider their 2.2 to be an Alpha release and have not yet released 2.1.2. The simplest solution is too simply wait for them to get things packaged up. Otherwise, Mark Hammond just released his win32all packages with a security update http://starship.python.net/crew/mhammond/win32/Downloads.html Win32 Extensions for Python I am installing his 2.2 update along with the regular Python 2.2 release, but have not yet tested it with my existing Python code. (I have been using 2.0). If you do not have too much code at risk from the recent language changes, I would go to 2.2 kjphotog@juno.com wrote: > Just as I start figuring out how to use 2.1.1 (I like the easy to read > PythonWin window that 2.1.2 doesn't seem to have) & now there's > versions 2.1.2 & 2.2. Which version should I use? > > Keith > > ________________________________________________________________ > GET INTERNET ACCESS FROM JUNO! > Juno offers FREE or PREMIUM Internet access for less! > Join Juno today! For your FREE software, visit: > http://dl.www.juno.com/get/web/. > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From troels.petersen@sveg.se.sykes.com Mon Jan 21 19:34:59 2002 From: troels.petersen@sveg.se.sykes.com (Troels Petersen) Date: Mon, 21 Jan 2002 20:34:59 +0100 Subject: [Tutor] Extracting filenames from a List? Message-ID: Hi, I have a list containing filenames. What I would like to do is to extract all files ending in '.jpg' - the case does not matter. Everything ending in '.JpG' should be extracted. What is the best way to do this? A Regular expression or..? It should fast and something that can be understood by a newbie like me (I need to finish the 2 last chapters of 'How to Think Like A Computer Scientist'). Troels From kauphlyn@speakeasy.org Mon Jan 21 20:00:36 2002 From: kauphlyn@speakeasy.org (Daniel Coughlin) Date: Mon, 21 Jan 2002 12:00:36 -0800 (PST) Subject: [Tutor] Extracting filenames from a List? In-Reply-To: Message-ID: Hi Troels! given: l = ['file.exe','another.gif','evenmore.bat','JPEG.jpg'] --- >>import string >>for file in l: >> if string.lower(file[-3:]) == 'jpg': >> l.pop(l.index(file)) 'JPEG.jpg' the file[-3:] is a string slice of the last three characters of the string. the string.lower() converts the characters to lower case. pop() removes and returns the item from the list, if it passes the if test. you could do whatever you want with the list item once you know it passes the test.. if 'extracted' were another list you could write extracted.append(l.pop(l.index(file))) Hope this helps Daniel On Mon, 21 Jan 2002, Troels Petersen wrote: > Hi, > > I have a list containing filenames. > > What I would like to do is to extract all files ending in '.jpg' - the case > does not matter. Everything ending in '.JpG' should be extracted. > > What is the best way to do this? A Regular expression or..? It should fast > and something that can be understood by a newbie like me (I need to finish > the 2 last chapters of 'How to Think Like A Computer Scientist'). > > Troels > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From tjenkins@devis.com Mon Jan 21 20:07:17 2002 From: tjenkins@devis.com (Tom Jenkins) Date: 21 Jan 2002 15:07:17 -0500 Subject: [Tutor] Extracting filenames from a List? In-Reply-To: References: Message-ID: <1011643637.1936.81.camel@asimov> Hello, On Mon, 2002-01-21 at 14:34, Troels Petersen wrote: > Hi, > > I have a list containing filenames. > > What I would like to do is to extract all files ending in '.jpg' - the case > does not matter. Everything ending in '.JpG' should be extracted. > > What is the best way to do this? A Regular expression or..? It should fast > and something that can be understood by a newbie like me (I need to finish > the 2 last chapters of 'How to Think Like A Computer Scientist'). well, how fast is fast? lets take a quicky algorithm and see if it is fast enough for your purpose. (that's what we're looking for btw "fast enough") you have a list of filenames, you want to iterate over the list. for each filename look at the last 4 characters and see if they match '.jpg'. what you don't say is how you want these matching files returned... i'll assume a list. def findJPGs(filenameList): results = [] for x in filenameList: #this gives use the iteration over the list if x[-4:].lower() == '.jpg': # this checks the last 4 characters results.append(x) return results how fast is this? well on my system a list of 1700 filenames takes milliseconds. is that fast enough? if not then you can use list comprehension to see if the code is faster... def findJPGs2(filenameList): return [x for x in filenameList if x[-4:].lower() == '.jpg'] if you look closely, you see that all the code from findJPG is now in the list comprehension. Does this run faster? just barely on my system. do you want to get faster? well, then go ahead and look at the algorithm. see if anything in there can be done better/faster. for me, this is "fast enough" -- Tom Jenkins Development InfoStructure http://www.devis.com From troels.petersen@sveg.se.sykes.com Mon Jan 21 20:23:27 2002 From: troels.petersen@sveg.se.sykes.com (Troels Petersen) Date: Mon, 21 Jan 2002 21:23:27 +0100 Subject: [Tutor] Extracting filenames from a List? Message-ID: >well, how fast is fast? Well - Your quickie is certainly 'fast enough' :) (But won't extract filenames that are not in lowercase - but that is solved in a previous posting)! I just wanted to see the pro's suggestions - and not get into bad habits from beginning. Thank You. /Troels From tjenkins@devis.com Mon Jan 21 20:36:59 2002 From: tjenkins@devis.com (Tom Jenkins) Date: 21 Jan 2002 15:36:59 -0500 Subject: [Tutor] Extracting filenames from a List? In-Reply-To: References: Message-ID: <1011645420.2054.90.camel@asimov> On Mon, 2002-01-21 at 15:23, Troels Petersen wrote: > > >well, how fast is fast? > > Well - Your quickie is certainly 'fast enough' :) (But won't extract > filenames that are not in lowercase - but that is solved in a previous > posting)! > really? hrmm.. In def findJPGs(filenameList): results = [] for x in filenameList: #this gives use the iteration over the list if x[-4:].lower() == '.jpg': # this checks the last 4 characters results.append(x) return results the x[-4:].lower() will lowercase the last 4 characters and compare them to '.jpg'. note that i've switched over to python 2.x and so don't usually import string, instead calling the string methods directly on the string in question. -- Tom Jenkins Development InfoStructure http://www.devis.com From cmccormick@thestate.com Mon Jan 21 18:59:41 2002 From: cmccormick@thestate.com (Chris McCormick) Date: Mon, 21 Jan 2002 13:59:41 -0500 Subject: [Tutor] <> Question re: list.append() Message-ID: <5.1.0.14.0.20020121124537.00a0dec0@mail> --=====================_277196007==_.ALT Content-Type: text/plain; charset="us-ascii"; format=flowed Hello all, Let me first start by saying that I am Chris McCormick, and I'm pretty much a newbie to this list, though I have programmed some in Python before, and am picking it up again after a long hiatus. If there is a better place to send questions like these, please let me know. I am working on a very small game/AI demo, and I want it to have a tile-based map (let me stop here to say that I have scoured the web in vain for Python-related tile-based map code/techniques/tutorials, and if you have anything related, I would _love_ to get my grubby hands on it). I implement my 10 by 10 square map with Python's equivalent of a two dimensional array - a list of lists. Taken out of context, my code looks like this: ### SNIP ---------------------------------------------------------------------------------------------- ## Initialize variables map_cells = [] # Create a blank list to hold the map map_rows = 10 # Number of rows map_cols = 10 # Number of columns for i in range(map_rows): map_tiles_append([]) # Create blank row for appending cells for j in range(map_cols): cell = map.Cell() # Map cell object from my own map module map_cells[i].append(cell) # Add a cell to the row ### SNIP ---------------------------------------------------------------------------------------------- This appears to work fine. But then I found a page about "list comprehension," where I would use something like this(?): map_cells = [ [map.Cell() for j in range(map_cols) ] for i in range(map_rows) ] My first response to this is "That looks disgusting!" I'd probably never remember what I was doing. But more to the point, which method is faster? My O'Reilly Programming Python says in the footnote on P. 48 that L.append(X) is much faster than L+[X]. But the list comprehension is only one line, as opposed to several with the for constructs. Opinions? Thanks in advance for your replies, Chris McCormick PS - If I can get anywhere with this tile-based scrolling map thingy, I plan on documenting it nicely and putting it up on the web. I can't imagine I'm the only one who's doing it.... --=====================_277196007==_.ALT Content-Type: text/html; charset="us-ascii" Hello all,
        Let me first start by saying that I am Chris McCormick, and I'm pretty much a newbie to this list, though I have programmed some in Python before, and am picking it up again after a long hiatus.  If there is a better place to send questions like these, please let me know.

        I am working on a very small game/AI demo, and I want it to have a tile-based map (let me stop here to say that I have scoured the web in vain for Python-related tile-based map code/techniques/tutorials, and if you have anything related, I would _love_ to get my grubby hands on it). 

        I implement my 10 by 10 square map with Python's equivalent of a two dimensional array - a list of lists.  Taken out of context, my code looks like this:


### SNIP ----------------------------------------------------------------------------------------------

## Initialize variables
map_cells = []          # Create a blank list to hold the map
map_rows = 10           # Number of rows
map_cols = 10                   # Number of columns

for i in range(map_rows):
        map_tiles_append([])                    # Create blank row for appending cells
        for j in range(map_cols):
                cell = map.Cell()               # Map cell object from my own map module
                map_cells[i].append(cell)       # Add a cell to the row

### SNIP ----------------------------------------------------------------------------------------------

This appears to work fine.  But then I found a page about "list comprehension," where I would use something like this(?):

map_cells = [ [map.Cell() for j in range(map_cols) ]  for i in range(map_rows) ]

My first response to this is "That looks disgusting!"  I'd probably never remember what I was doing.  But more to the point, which method is faster?  My O'Reilly Programming Python says in the footnote on P. 48 that L.append(X) is much faster than L+[X].  But the list comprehension is only one line, as opposed to several with the for constructs.

Opinions? 

Thanks in advance for your replies,
Chris McCormick

PS - If I can get anywhere with this tile-based scrolling map thingy, I plan on documenting it nicely and putting it up on the web.  I can't imagine I'm the only one who's doing it....

--=====================_277196007==_.ALT-- From scarblac@pino.selwerd.nl Mon Jan 21 23:45:00 2002 From: scarblac@pino.selwerd.nl (Remco Gerlich) Date: Tue, 22 Jan 2002 00:45:00 +0100 Subject: [Tutor] Extracting filenames from a List? In-Reply-To: ; from troels.petersen@sveg.se.sykes.com on Mon, Jan 21, 2002 at 08:34:59PM +0100 References: Message-ID: <20020122004500.A32051@pino.selwerd.nl> On 0, Troels Petersen wrote: > I have a list containing filenames. > > What I would like to do is to extract all files ending in '.jpg' - the case > does not matter. Everything ending in '.JpG' should be extracted. > > What is the best way to do this? A Regular expression or..? It should fast > and something that can be understood by a newbie like me (I need to finish > the 2 last chapters of 'How to Think Like A Computer Scientist'). Here, I like the list comprehension better than filter(), because filter needs a lambda definition: jpgs = [f for f in filelist if f.lower().endswith(".jpg")] vs jpgs = filter(lambda f: f.lower().endswith(".jpg"), filelist) I certainly believe that the functional programming way is much easier to understand than a for loop, in this case. But that may be because of my experience. The following is more basic Python, and also avoids string methods so it should work in old Pythons as well: import string jpgs = [] for f in filelist: if string.lower(f)[-4:] == ".jpg": jpgs.append(f) I don't know why I'm posting this since others already posted solutions, but whatever :) -- Remco Gerlich From alan.gauld@bt.com Tue Jan 22 00:00:00 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Tue, 22 Jan 2002 00:00:00 -0000 Subject: [Tutor] a quetion on"There should be one and preferabley one obvious way to do it" Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C2CD@mbtlipnt02.btlabs.bt.co.uk> > List comprehensions replace a lot of map(lambda...) > garbage which is very unsightly. I disagree. I find the map(lambda... ) form much more readable than the confusion that is comprehensions. Every time I see a comprehension I have to mentally rewrite it in a for loop form. But then I spent a lot of time reading Lisp where every function starts like: (define foo (lambda x ....)) Which is directly equivalet to: foo = lambda x:.... in Python. To me a map looks much cleaner than a comprehension! (But is less flexible I think) Maybe if comprehensions had clause delimiters somehow, like: [x,y: for i in L: (i,i+1)] instead of [x, y for i in L: i, i+1] or something... Alan G (Who is almost certainly in a minority of one on this! :-) From hot_stuff343@hotmail.com Tue Jan 22 00:12:25 2002 From: hot_stuff343@hotmail.com (Joey Dixon) Date: Mon, 21 Jan 2002 18:12:25 -0600 Subject: [Tutor] I need a tutor Message-ID: ------=_NextPart_001_0000_01C1A2A7.2D8BF670 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable i am just getting started in programing and am in need of a tutor! A one= -on-one person to help me. If you can e-mail me@ hot_stuff343@hotmail.co= mGet more from the Web. FREE MSN Explorer download : http://explorer.msn= .com ------=_NextPart_001_0000_01C1A2A7.2D8BF670 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
i am just gett= ing started in programing and am in need of a tutor!  A one-on-one p= erson to help me.  If you can e-mail me@ hot_stuff343@hotmail.com


Get more from the Web. FREE MSN= Explorer download : http://explorer.= msn.com

------=_NextPart_001_0000_01C1A2A7.2D8BF670-- From alan.gauld@bt.com Tue Jan 22 00:12:43 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Tue, 22 Jan 2002 00:12:43 -0000 Subject: [Tutor] [Q] inheriting a class Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C2CE@mbtlipnt02.btlabs.bt.co.uk> > I wanted to add a new method to the existing class and I > thought it would be possible with the following code. > > #### > class ball( sphere ): > def printProperty(): #<--- Close but you need self > print 'print property' > I wanted to use the parent class's __init__ method, > I tried typed > the above codes in the pythons shell, What codes? The above is a class definition with no init. You don't do anything that would call int either... > __init__() takes exactly 2 arguments (4 given)" error message. I'd guess sphere takes self and a radius as arguments thus: s = sphere(5) > method? How come I gave 4 arguments? I have no idea what you tried to do coz you haven't posted the code... Wanna try again ;-? Alan G From alan.gauld@bt.com Tue Jan 22 00:16:08 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Tue, 22 Jan 2002 00:16:08 -0000 Subject: [Tutor] Which Py? Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C2CF@mbtlipnt02.btlabs.bt.co.uk> > > Just as I start figuring out how to use 2.1.1 ... > > now there's versions 2.1.2 & 2.2. > > Which version should I use? > Use any version that brings you pleasure, Agreed. But if learning you might consider using the version that your book/tutorial was written for. One advantage of the Python tutor is that it gets updated for each release! > general, I think it's a good idea to use the most > current version you can come to terms with. I allways use the version behind the currenmt one - let somebody else find the bugs! Alan G. From alan.gauld@bt.com Tue Jan 22 00:21:14 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Tue, 22 Jan 2002 00:21:14 -0000 Subject: [Tutor] I need a Tutor Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C2D0@mbtlipnt02.btlabs.bt.co.uk> Kind words Lloyd, but although an enthusiastic supporter of tutor I'm no expert in Python. ( I might realistically be considered an expert in some other areas, but never in Python) There are far more expert experts on this list. Even the tim bot puts in the occasional appearance! Lets all value the help everyone offers, after all another beginner can offer a clearer explanation to a beginner than a guru at times...and I know that's what you were really saying. :-) Alan G From lha2@columbia.edu Tue Jan 22 00:31:05 2002 From: lha2@columbia.edu (Lloyd Hugh Allen) Date: Mon, 21 Jan 2002 19:31:05 -0500 Subject: [Tutor] I need a tutor References: Message-ID: <3C4CB2C9.4067F318@mail.verizon.net> Perhaps there should be something in the FAQ clarifying the mission of this listserv (and a bot checking for messages with "I need a tutor" in either the subject or body of the message). There seems to be a rash of them lately. Post your specific question, Joey, and it will be answered. If you are looking for particular resources to learn Python, check if you know another programming language, and if you don't. From kjphotog@juno.com Tue Jan 22 00:32:50 2002 From: kjphotog@juno.com (kjphotog@juno.com) Date: Mon, 21 Jan 2002 16:32:50 -0800 Subject: [Tutor] POP3 Help Message-ID: <20020121.163255.-235547.5.kjphotog@juno.com> When I ran tutor Tara's example for retrieving e-mail using this POP3: import poplib pop = poplib.POP3('server', 'port') pop.user('username') pop.pass_('password') num_msg_list = len(pop.list()[1]) # Iterate over all messages. for i in range(num_msg_list): # Loop over all lines of the message, except index 1, which is the response. for j in pop.retr(i+1)[1]: # Print the line. print j But I only got a brief glimpse at my message list before my screen exploded into an unreadable alphabet soup. Had to CtrlAltD to stop IT! How do I decode my messages to read them? Thanks again, Keith ________________________________________________________________ GET INTERNET ACCESS FROM JUNO! Juno offers FREE or PREMIUM Internet access for less! Join Juno today! For your FREE software, visit: http://dl.www.juno.com/get/web/. From jeff@ccvcorp.com Tue Jan 22 01:17:25 2002 From: jeff@ccvcorp.com (Jeff Shannon) Date: Mon, 21 Jan 2002 17:17:25 -0800 Subject: [Tutor] <> Question re: list.append() References: Message-ID: <3C4CBDA4.46D6C161@ccvcorp.com> > "Chris McCormick" wrote: > > I am working on a very small game/AI demo, and I want it to have a > tile-based map (let me stop here to say that I have scoured the web in vain > for Python-related tile-based map code/techniques/tutorials, and if you > have anything related, I would _love_ to get my grubby hands on it). Have you seen PyGame? (www.pygame.org I believe) I haven't looked at it closely, but I wouldn't be surprised if they have something of this sort there, with a lot of bells and whistles built in... > map_cells = [ [map.Cell() for j in range(map_cols) ] for i in > range(map_rows) ] > > My first response to this is "That looks disgusting!" I'd probably never > remember what I was doing. But more to the point, which method is > faster? My O'Reilly Programming Python says in the footnote on P. 48 that > L.append(X) is much faster than L+[X]. But the list comprehension is only > one line, as opposed to several with the for constructs. Well, first off, a list comprehension is not the same as list addition (the L + [X] mentioned), so the footnote you cite doesn't apply here. Nested list comps *can* look a bit confusing, but they tend to be *slightly* faster than a for-loop. However, you're not likely to notice this speed difference until you start doing several thousand iterations... In this case, you're probably best off using whichever method looks clearest to you. Don't worry much about how fast something is, until you've got something running and become aware that it's not fast enough. Keep in mind that you probably won't be creating this map very often, so saving a millisecond or two on its creation isn't going to affect your game much. :) Personally, I'd be inclined to take a hybrid approach in this situation: map_cells = [] for i in range(map_cols): map_cells.append( [map.Cell() for j in range(map_rows)] ) This uses a list comprehension to create each column, and a for-loop to specify how many columns to build. I personally find this to be the clearest to understand, but of course YMMV. (I've also reversed your rows and columns, so that you can refer to a given cell by map_cells[x][y]. If you prefer to think in terms of map_cells[row][col], then you can easily reverse them back.) Jeff Shannon Technician/Programmer Credit International From glingl@aon.at Tue Jan 22 02:03:57 2002 From: glingl@aon.at (Gregor Lingl) Date: Tue, 22 Jan 2002 03:03:57 +0100 Subject: [Tutor] Problem with division in Python22 Message-ID: <008001c1a2e9$0d6b4ca0$1664a8c0@mega> This is a multi-part message in MIME format. ------=_NextPart_000_007D_01C1A2F1.6EF71870 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable I extended Kirby's fracs to make them multiply and divide: ### Kirby's fraction-class, slightly enhanced class F: def __init__(self,numer,denom): # reduce inputs to lowest terms numer =3D long(numer) # for 'big fractions' denom =3D long(denom) gcd =3D self.gcd(numer,denom) self.num =3D numer//gcd self.den =3D denom//gcd def __add__(self,other): # find lowest common multiple a,b =3D self.num, other.num comden =3D self.lcm(self.den, other.den) if comden !=3D self.den: a *=3D comden//self.den if comden !=3D other.den: b *=3D comden//other.den return F(a+b,comden) def __sub__(self,other): return self + (-other) def __mul__(self,other): return F(self.num*other.num, self.den*other.den) def __div__(self,other): ##### HERE CRITICAL POINT !!!! ##### return F(self.num*other.den, self.den*other.num) ########## etc. --- see below When I use it with IDLE in Python22 I get as expected: >>> x =3D F(3,4) >>> y =3D F(5,6) >>> x*y (5/8) >>> x/y (9/10) >>>=20 However, if I use IDLE called by Python with the -Qnew switch which was so quickly enabled by Tim Peters one and a half months ago, i get: >>> x =3D F(3,4) >>> y =3D F(5,6) >>> x*y (5/8) >>> x/y Traceback (most recent call last): File "", line 1, in ? x/y TypeError: unsupported operand type(s) for /: 'instance' and 'instance' >>>=20 So I see that __div__ doesn't longer work and possibly is replaced by some other method, which I have to overwrite now. I searched for approx. half an hour, but couldn't find=20 it in the documentation (??). I guess, that perhaps the two operators / and // now have to have two different underlying methods. Couriously I noticed, that adding the import-statement from __future__ import division when using IDLE without switch -Qnew did not prevent / from working (i. e. this did not produce an error-message) When using the interactive Python-Interpreter alone (without IDLE) the problem remains exactly the same. How do I have to proceed correctly with this fracs when using the -Qnew - switch? Gregor ###### class F - Definition continued def __neg__(self): return F(-self.num,self.den) def __lt__(self,other): return (self.num*other.den) < (other.num*self.den) def __eq__(self,other): return (self.num*other.den) =3D=3D (other.num*self.den) def gcd(self,a,b): # find greatest common divisor of a,b if b=3D=3D0: return a else: return self.gcd(b,a%b) def lcm(self,a,b): # find lowest common multiple of a,b return a*b//self.gcd(a,b) def __repr__(self): # represent as (a/b) return "(%s/%s)" % (self.num, self.den) ------=_NextPart_000_007D_01C1A2F1.6EF71870 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
I extended Kirby's fracs to make them
multiply and divide:
 
### Kirby's fraction-class, slightly = enhanced
 
class F:
 
    def=20 __init__(self,numer,denom):
       = #=20 reduce inputs to lowest = terms
       =20 numer =3D=20 long(numer)          &n= bsp;   =20 # for 'big fractions'
        = denom =3D=20 long(denom)
        gcd =3D=20 self.gcd(numer,denom)
        = self.num =3D=20 numer//gcd
        self.den =3D=20 denom//gcd
 
    def=20 __add__(self,other):
        # = find lowest=20 common multiple
        a,b =3D = self.num,=20 other.num
        comden =3D=20 self.lcm(self.den, = other.den)
        if=20 comden !=3D=20 self.den:
          = a *=3D=20 comden//self.den
        if comden = !=3D=20 other.den:
          = ; b *=3D=20 comden//other.den
        return=20 F(a+b,comden)
 
    def=20 __sub__(self,other):
        = return self +=20 (-other)
 
    def=20 __mul__(self,other):
        = return=20 F(self.num*other.num, self.den*other.den)
 
    def = __div__(self,other):   =20 ##### HERE CRITICAL POINT !!!!=20 #####
        return = F(self.num*other.den,=20 self.den*other.num)
 
########## etc. --- see below
 
When I use it with IDLE in Python22 I get as=20 expected:
 
>>> x =3D F(3,4)
>>> y =3D=20 F(5,6)
>>> x*y
(5/8)
>>>=20 x/y
(9/10)
>>>
 
However, if I use IDLE called by Python with the = -Qnew=20 switch
which was so quickly enabled by Tim Peters one and a = half=20 months
ago, i get:
 
>>> x =3D F(3,4)
>>> y =3D=20 F(5,6)
>>> x*y
(5/8)
>>> x/y
Traceback = (most=20 recent call last):
  File "<pyshell#4>", line 1, in=20 ?
    x/y
TypeError: unsupported operand type(s) = for /:=20 'instance' and 'instance'
>>>
 
So I see that __div__ doesn't longer work and = possibly is=20 replaced by
some other method, which I have to overwrite = now.
I searched for approx. half an hour, but couldn't = find=20
it in the documentation (??). I guess, that perhaps = the two=20 operators
/ and // now have to have two different underlying=20 methods.
 
Couriously I noticed, that adding the=20 import-statement
 
from __future__ import division
 
when using IDLE without switch -Qnew did not prevent = / from=20 working
(i. e. this did not produce an = error-message)
 
When using the interactive Python-Interpreter alone = (without=20 IDLE)
the problem remains exactly the same.
 
How do I have to proceed correctly with this fracs = when=20 using
the -Qnew - switch?
 
Gregor
 
 
###### class F - Definition continued
 
    def=20 __neg__(self):
        return=20 F(-self.num,self.den)
 
    def=20 __lt__(self,other):
        return = (self.num*other.den) < (other.num*self.den)
 
    def=20 __eq__(self,other):
        return = (self.num*other.den) =3D=3D (other.num*self.den)
 
    def=20 gcd(self,a,b):
        # find = greatest=20 common divisor of a,b
        if = b=3D=3D0:=20 return a
        else: return=20 self.gcd(b,a%b)
 
    def=20 lcm(self,a,b):
        # find = lowest=20 common multiple of a,b
        = return=20 a*b//self.gcd(a,b)
 
    def=20 __repr__(self):
        # = represent as=20 (a/b)
        return "(%s/%s)" %=20 (self.num, self.den)
 
 
------=_NextPart_000_007D_01C1A2F1.6EF71870-- From urnerk@qwest.net Tue Jan 22 03:53:36 2002 From: urnerk@qwest.net (Kirby Urner) Date: Mon, 21 Jan 2002 19:53:36 -0800 Subject: [Tutor] Problem with division in Python22 In-Reply-To: <008001c1a2e9$0d6b4ca0$1664a8c0@mega> Message-ID: <4.2.0.58.20020121194920.00aa1710@pop3.norton.antivirus> I don't have the qnew program handy, but how about if you change __div__ to __truediv__ in your class def? That's supposed to be the interim thing to override when you've got futuristic division activated -- until it becomes the default. See (scroll down to API Changes): http://python.sourceforge.net/peps/pep-0238.html Kirby PS: another fun operator to override in the fraction class is __pow__, to allow F(2,3)**2 -> (4/9). But don't forget to implement negative powers, e.g. F(2,3)**(-1) -> (3/2). If this is implemented, then instead of x/y, you can alternatively write x * y**(-1). From karthikg@aztec.soft.net Tue Jan 22 04:12:05 2002 From: karthikg@aztec.soft.net (Karthik Gurumurthy) Date: Tue, 22 Jan 2002 09:42:05 +0530 Subject: [Tutor] is "fold" same as "reduce"? In-Reply-To: <008001c1a2e9$0d6b4ca0$1664a8c0@mega> Message-ID: This is a multi-part message in MIME format. ------=_NextPart_000_0000_01C1A329.0D2FFD40 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: 7bit I got introduced to functional programming through python and i like it now..it was'nt the case a couple of months back though. a "lambda" used to put me off. I was doing some reading and i was just wondering if the "fold" construct is same as "reduce" in python? and i took a look @ the functional programming article in IBM's website. that was a good introduction. Can someone tell me about other interesting sites that have a good discussion on functional programming...with examples. thanks karthik ------=_NextPart_000_0000_01C1A329.0D2FFD40 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
I got introduced to functional programming through python = and i like=20 it now..it was'nt the case a couple of months back = though.
a=20 "lambda" used to put me off.
I was=20 doing some reading and i was just wondering if the = "fold" construct is=20 same as "reduce" in python?
and i=20 took a look @ the functional programming article in IBM's website. that = was a=20 good introduction.
Can=20 someone tell me about other interesting sites that have a good = discussion on=20 functional programming...with examples.
 
thanks
karthik
 
------=_NextPart_000_0000_01C1A329.0D2FFD40-- From erikprice@mac.com Tue Jan 22 04:51:31 2002 From: erikprice@mac.com (Erik Price) Date: Mon, 21 Jan 2002 23:51:31 -0500 Subject: [Tutor] Truckers Log....Me Again In-Reply-To: <20020121063130.GA1560@sandra.lysator.liu.se> Message-ID: Well! I don't think I've ever been so warmly received by any online community before I introduced myself! I just wanted to take a minute to thank everyone who responded to my pondering of the 'while 1' statement. Every day I get a few pages further in learning about this language (well, starting not too long ago) from various online resources, though I haven't written anything functional with Python yet. I'm intrigued -- coming from PHP, which resembles Perl imho, and is interspersed with HTML, the code looks decidedly naked! I'm not used to seeing code without all the doo-dads (like bucks and braces). Today I learned about tuples and dictionaries. I'm not going to come to any conclusions about the language until I've gotten to play with it some (just too busy with Work at the moment), but I am initially surprised by the separate distinction of lists and dictionaries (which, unconsciously, I end up replacing with numeric and associative arrays -- a habit that I am trying to break). The questions are bottling up inside me. I'm going to wait until I finish reading, a few more days, to see if they answer themselves. But if not, I hope nobody minds the barrage I'll unleash -- I'm the curious sort! (It's curiosity that brought me around to Python.) The one that I really can't wait to ask, given the discussion about its absence in last night's pseudocode, is about the 'break' statement. Between the tutorials I'm reading and discussion on this list, it seems to be used more frequently than the 'break' statement which appears in PHP. Is this normal for Python? I'm new to programming, and everywhere I look, people are talking about "good habits". Naturally I want to make sure that I don't develop any bad ones. It's not considered "bad programming style" to depend heavily on the 'break' statement in Python, is it? I'm also a stickler for detail. A question about quoting -- I have seen double and single quotes used fairly interchangeably. My reference doesn't distinguish a difference between these (only that escaping singlequotes inside doublequotes or vice versa isn't necessary, or in triple (single|double) quotes). But in PHP/Perl/bash, variables expand in double-quotes so the difference is important. Where does Python stand on this subject? (I'm surprised that I didn't read something about this already.) And I apologize for constantly making reference to PHP or other languages, it's just that in programming, they're my only frame of reference. Thanks everyone, Erik From urnerk@qwest.net Tue Jan 22 05:29:08 2002 From: urnerk@qwest.net (Kirby Urner) Date: Mon, 21 Jan 2002 21:29:08 -0800 Subject: [Tutor] Truckers Log....Me Again In-Reply-To: References: <20020121063130.GA1560@sandra.lysator.liu.se> Message-ID: <4.2.0.58.20020121212523.00cec930@pop3.norton.antivirus> > >And I apologize for constantly making reference to PHP or other languages, >it's just that in programming, they're my only frame of reference. > >Thanks everyone, > >Erik Hi Erik -- it's pretty standard for a language to have a way to break out of a loop. Perl has it, and ways to break out to various levels (by naming loops), whereas Python's break only gets you out of the innermost. while 1: while 1: if 1: break is still infinite. On the whole, Python is pretty spare with looping constructs. No 'until' for example, because you can get the same result with while 1: if condition: break Kirby From dyoo@hkn.eecs.berkeley.edu Tue Jan 22 06:10:33 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 21 Jan 2002 22:10:33 -0800 (PST) Subject: [Tutor] is "fold" same as "reduce"? In-Reply-To: Message-ID: On Tue, 22 Jan 2002, Karthik Gurumurthy wrote: > I got introduced to functional programming through python and i like > it now..it was'nt the case a couple of months back though. a "lambda" > used to put me off. > I was doing some reading and i was just wondering if the "fold" > construct is same as "reduce" in python? Yes: Python's 'reduce' is a similar concept to 'fold' in a functional language. For example, here's a function that uses reduce to reverse a list: ### def reverse(l): return reduce(lambda x, y: [y] + x, [[]] + l) ### Let's see if it works: ### >>> reverse([1, 2, 3, 4]) [4, 3, 2, 1] >>> reverse(['larry', 'curly' 'moe']) ['curlymoe', 'larry'] ### reduce() is a surprisingly versatile function; it can be applied to things that can raise eyebrows. Here's another application to do filtering: ### def filter(test_f, l): def func(x, y): if test_f(y): return x + [y] return x return reduce(func, [[]] + l) ### Does this work? ### >>> filter(isEven, [3, 1, 4, 1, 5, 9, 2, 6]) [4, 2, 6] ### There's a series of articles of functional programming using Python on IBM's Developerworks web site: http://www-106.ibm.com/developerworks/library/l-prog.html http://www-106.ibm.com/developerworks/library/l-prog2.html http://www-106.ibm.com/developerworks/library/l-prog3.html Hey, there's some stuff here that I haven't seen before. Cool! *grin* I think I'll take a closer look at this too. > and i took a look @ the functional programming article in IBM's > website. that was a good introduction. Do you have a link to it? I'd like to take a look. > Can someone tell me about other interesting sites that have a good > discussion on functional programming...with examples. If you're interested in functional programming, you might want to look at the Haskell web site: http://www.haskell.org/ Haskell is focused on functional programming, and I've heard that it's a very good language for exploring functional ideas. You may also find this link handy: I just found it on Google, and it looks like good stuff: http://www.cs.chalmers.se/~rjmh/tutorials.html From dyoo@hkn.eecs.berkeley.edu Tue Jan 22 06:44:18 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 21 Jan 2002 22:44:18 -0800 (PST) Subject: [Tutor] <> Question re: list.append() In-Reply-To: <5.1.0.14.0.20020121124537.00a0dec0@mail> Message-ID: On Mon, 21 Jan 2002, Chris McCormick wrote: > I am working on a very small game/AI demo, and I want it to > have a tile-based map (let me stop here to say that I have scoured the > web in vain for Python-related tile-based map > code/techniques/tutorials, and if you have anything related, I would > _love_ to get my grubby hands on it). Amit Patel's web site on game programming is a treasure trove of information on this sort of stuff: http://www-cs-students.stanford.edu/~amitp/gameprog.html In fact, there's some information on doing grid/tile based stuff. Perhaps not coincidently, his web site has a section on Python: http://www-cs-students.stanford.edu/~amitp/gameprog.html The Pyplace project for pygame might be useful for you: http://www.mrexcessive.net/pyplace/ It looks like they have a framework for doing tiled maps that you might be able to reuse. Good luck! From dyoo@hkn.eecs.berkeley.edu Tue Jan 22 06:51:48 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 21 Jan 2002 22:51:48 -0800 (PST) Subject: [Tutor] <> Question re: list.append() In-Reply-To: <3C4CBDA4.46D6C161@ccvcorp.com> Message-ID: On Mon, 21 Jan 2002, Jeff Shannon wrote: > In this case, you're probably best off using whichever method looks > clearest to you. Don't worry much about how fast something is, until > you've got something running and become aware that it's not fast > enough. Keep in mind that you probably won't be creating this map > very often, so saving a millisecond or two on its creation isn't going > to affect your game much. :) Also, there are tools that we can use to find out to study the speed of our program. These "profiler" tools can take a look at a sample run of our program and point us toward sections that are critical for performance. There's some documentation on the Python profiler here: http://www.python.org/doc/current/lib/profile.html Good luck! From lonetwin@yahoo.com Tue Jan 22 07:08:48 2002 From: lonetwin@yahoo.com (lonetwin) Date: Tue, 22 Jan 2002 12:38:48 +0530 Subject: [Tutor] a quetion on"There should be one and preferabley one obvious way to do it" In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66C2CD@mbtlipnt02.btlabs.bt.co.uk> References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C2CD@mbtlipnt02.btlabs.bt.co.uk> Message-ID: <02012212384801.29276@mercury.worli> Hi All, On Tuesday 22 January 2002 05:30, alan.gauld@bt.com wrote: > > List comprehensions replace a lot of map(lambda...) > > garbage which is very unsightly. > > I disagree. I find the map(lambda... ) form much more > readable than the confusion that is comprehensions. > Every time I see a comprehension I have to mentally > rewrite it in a for loop form. Since I came in only after list comprehension was introduced, I preferred it from the very beginning (over map/lambda) and here's how I read a list comprehension. [ x.func() for x in SomeList ] Return a list filled with x.func()'s for every element x in SomeList That very closely resembles the python statement (at least I think so) :)!! Well, but I guess it's more about how one is introduced to the construct. Anyways, I just wanted to say (at least for me) list comprehensions are readable and *very* pythonic. :) Peace Steve -- Lawful Dungeon Master -- and they're MY laws! From glingl@aon.at Tue Jan 22 07:13:14 2002 From: glingl@aon.at (Gregor Lingl) Date: Tue, 22 Jan 2002 08:13:14 +0100 Subject: [Tutor] Problem with division in Python22 References: <4.2.0.58.20020121194920.00aa1710@pop3.norton.antivirus> Message-ID: <000b01c1a314$42431310$1664a8c0@mega> Thanks, this works! But hasn't this to be considered as a bug, as it breaks code developed for up to 2.2? Gregor ----- Original Message ----- From: "Kirby Urner" To: "Gregor Lingl" Cc: Sent: Tuesday, January 22, 2002 4:53 AM Subject: Re: [Tutor] Problem with division in Python22 > > I don't have the qnew program handy, but how about > if you change > > __div__ > > to > > __truediv__ > > in your class def? That's supposed to be the interim > thing to override when you've got futuristic division > activated -- until it becomes the default. > > See (scroll down to API Changes): > http://python.sourceforge.net/peps/pep-0238.html > > Kirby > > PS: another fun operator to override in the fraction > class is __pow__, to allow F(2,3)**2 -> (4/9). But > don't forget to implement negative powers, e.g. > F(2,3)**(-1) -> (3/2). If this is implemented, then > instead of x/y, you can alternatively write x * y**(-1). > > > > From dyoo@hkn.eecs.berkeley.edu Tue Jan 22 07:16:21 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 21 Jan 2002 23:16:21 -0800 (PST) Subject: [Tutor] Truckers Log....Me Again In-Reply-To: Message-ID: On Mon, 21 Jan 2002, Erik Price wrote: > Today I learned about tuples and dictionaries. I'm not going to come > to any conclusions about the language until I've gotten to play with > it some (just too busy with Work at the moment), but I am initially > surprised by the separate distinction of lists and dictionaries > (which, unconsciously, I end up replacing with numeric and associative > arrays -- a habit that I am trying to break). I'm not too familiar with PHP, but I read a little of: http://www.intranetjournal.com/articles/200005/phpe.html and I think I have a better idea about it. I believe that Python dictionaries are similar in concept to PHP's arrays, though PHP's arrays do allow you to keep the array in some sort of order. > its absence in last night's pseudocode, is about the 'break' > statement. Between the tutorials I'm reading and discussion on this > list, it seems to be used more frequently than the 'break' statement > which appears in PHP. Is this normal for Python? Yes, I think that Python programmers use 'break' quite a bit. > I'm also a stickler for detail. A question about quoting -- I have > seen double and single quotes used fairly interchangeably. My > reference doesn't distinguish a difference between these (only that > escaping singlequotes inside doublequotes or vice versa isn't > necessary, or in triple (single|double) quotes). In Python, double and single quotes are interchangable --- there is no difference between them. > But in PHP/Perl/bash, variables expand in double-quotes so the > difference is important. Where does Python stand on this subject? > (I'm surprised that I didn't read something about this already.) Expansion happens when we do string interpolation --- in Python terms, it's called "string formatting". Here's an example: ### >>> mygreeting = "Hello %s!" >>> mygreeting % ("Erik",) 'Hello Erik!' >>> mystory = "Once there was a %(adj)s monkey, who lived in a %(noun)s." >>> mystory % { 'adj' : 'chunky', ... 'noun' : 'beehive' } 'Once there was a chunky monkey, who lived in a beehive.' ### So we don't even need to worry about what happens with single or double quotes. String formatting is an operation that's separated from building a string literal. We can find out more information on string formatting here: http://www.python.org/doc/tut/node9.html#SECTION009100000000000000000 and there some more reference material here that might help: http://www.python.org/doc/current/lib/typesseq-strings.html If you have questions on it, please feel free to ask on Tutor, and people here can cook up more interesting examples. > And I apologize for constantly making reference to PHP or other > languages, it's just that in programming, they're my only frame of > reference. It's the right thing to learn something by borrowing ideas from something you already know. You don't have to apologize! Please feel free to make references to PHP and other languages; it's instructive to see how to get ideas to translate between languages. Good luck! From lonetwin@yahoo.com Tue Jan 22 07:32:19 2002 From: lonetwin@yahoo.com (lonetwin) Date: Tue, 22 Jan 2002 13:02:19 +0530 Subject: [Tutor] Extracting filenames from a List? In-Reply-To: <20020122004500.A32051@pino.selwerd.nl> References: <20020122004500.A32051@pino.selwerd.nl> Message-ID: <02012213021902.29276@mercury.worli> Hey Remco, On Tuesday 22 January 2002 05:15, Remco Gerlich wrote: > I don't know why I'm posting this since others already posted solutions, > but whatever :) Good thing you did Remco, b'cos I didn't know about this: > jpgs = [f for f in filelist if f.lower().endswith(".jpg")] ^^^^^^^^^ Another nice 'lil function, python is *so* cool !! Also, just wanted to tell all the tutors, please do post alternate ways of doing things, even if the questions are answered. People like me get to learn a bit that way :) Thanx Peace Steve -- Famous last words: (1) Don't unplug it, it will just take a moment to fix. (2) Let's take the shortcut, he can't see us from there. (3) What happens if you touch these two wires tog-- (4) We won't need reservations. (5) It's always sunny there this time of the year. (6) Don't worry, it's not loaded. (7) They'd never (be stupid enough to) make him a manager. (8) Don't worry! Women love it! From paulsid@shaw.ca Tue Jan 22 08:42:29 2002 From: paulsid@shaw.ca (Paul Sidorsky) Date: Tue, 22 Jan 2002 01:42:29 -0700 Subject: [Tutor] a quetionon"There should be one and preferabley one obvious way to do it" References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C2CD@mbtlipnt02.btlabs.bt.co.uk> Message-ID: <3C4D25F5.7802BDE1@shaw.ca> alan.gauld@bt.com wrote: > > List comprehensions replace a lot of map(lambda...) > > garbage which is very unsightly. > > I disagree. I find the map(lambda... ) form much more > readable than the confusion that is comprehensions. > Every time I see a comprehension I have to mentally > rewrite it in a for loop form. I consider that a big selling point of list comprehensions; that they are a compact representation of a for loop. I dunno, it seems like less of a jump to translate to me. Now I like to think I'm coming at this from a neutral point of view because I came from languages where both lambda and list comprehensions were completely unthinkable concepts. However, it could be that I'm too used to C where it's possible to do everything but cook dinner with a for loop, so I might not mind "for" cropping up in not-so-obvious places. > But then I spent a lot of time reading Lisp where every > function starts like: > > (define foo > (lambda x ....)) > > Which is directly equivalet to: > > foo = lambda x:.... > > in Python. I guess that's part of the problem I have with lambda; it seems me to have been added largely to appease the many Lisp converts. I have a great respect for Lisp, but Python Ain't Lisp. (Sometimes I get tempted to start a PAL club...) Not only that, but lambda just doesn't seem very Pythonic to me. It has its uses but often I think explicitly defining a function would have been more readable in the first place. Of course, list comprehensions were esentially stolen straight out of Haskell and they are admittedly trickier to read than an explicit for loop (at least, at first). So they're not really all that different than lambda in these respects. > To me a map looks much cleaner than a comprehension! > (But is less flexible I think) > > Maybe if comprehensions had clause delimiters somehow, like: Heh, I have the same problem with lambda. Its syntax seems too jumbly to me; that's why I called it "unsightly". (Calling lambda "garbarge" was definitely out of line though.) I get thrown by the way the arguments are specified, especially if default arguments are used. I would probably have an easier time with it if it worked almost like a function, maybe like this: f = lambda((a, b=0), a+b) More punctuation seems to make it easier for me to parse. > (Who is almost certainly in a minority of one on this! :-) Heh, that's true. But we need you to keep us from totally brainwashing the newbies that list comprehensions are the only True Way. :-) -- ====================================================================== Paul Sidorsky Calgary, Canada paulsid@shaw.ca http://members.shaw.ca/paulsid/ From paulsid@shaw.ca Tue Jan 22 09:29:34 2002 From: paulsid@shaw.ca (Paul Sidorsky) Date: Tue, 22 Jan 2002 02:29:34 -0700 Subject: [Tutor] Truckers Log....Me Again References: Message-ID: <3C4D30FE.AE9F9A0B@shaw.ca> Erik Price wrote: > Today I learned about tuples and dictionaries. I'm not going to come to > any conclusions about the language until I've gotten to play with it > some (just too busy with Work at the moment), but I am initially > surprised by the separate distinction of lists and dictionaries (which, > unconsciously, I end up replacing with numeric and associative arrays -- > a habit that I am trying to break). That's a keen observation, considering a dictionary-equivalent could be implemented with lists. (That might be a good learning project for those who were looking for one: implement a dictionary-like type using lists, entirely in Python.) For example: {"key1": 12, "key2": "hi", key3: [2, 4, 6], key4: (1, 2, 3)} could be viewed as: [["key1", 12], ["key2", "hi"], ["key3", [2, 4, 6]], ["key4", (1, 2, 3)]] or also this way, which is probably closer to how Python dicts actually work: keys = ["key1", "key2", "key3", "key4"] values = [12, "hi", [2, 4, 6], (1, 2, 3)] A big problem with using lists is, of course, that access and manipulation starts to get tricky. Another problem is you now have to search to find keys; this may involve traversing most of the list. Dictionaries use a hashtable so there is no search time involved (well except with chaining, but that's normally not a significant factor). The concept of subscripting with, say, a string (e.g. mydict["key1"]) may seem unusual at first, but it does become natural! Subscripting with a more complex object like a tuple or a class is even more bizzare the first time you do it but it does save tons of work! > It's not considered "bad programming > style" to depend heavily on the 'break' statement in Python, is it? I wouldn't go that far. If you've got a loop with a lot of breaks in it then it probably should be redesigned, no matter what language it's written in. In these cases the breaks may as well just be gotos - indeed, often the latter would at least make things more readable. However usually, if not always, things can be improved either via a better design or at worst by using exceptions. > I'm also a stickler for detail. A question about quoting -- I have seen > double and single quotes used fairly interchangeably. My reference > doesn't distinguish a difference between these (only that escaping > singlequotes inside doublequotes or vice versa isn't necessary, or in > triple (single|double) quotes). But in PHP/Perl/bash, variables expand > in double-quotes so the difference is important. Where does Python > stand on this subject? (I'm surprised that I didn't read something > about this already.) Check the Python Style Guide (PEP 8) if you want to know the "official" policy. For me, as a C (and C++) geek, I use C-like quoting methods. I use " for strings and ' for single characters, unless I need the " character in a string in which case I probably will use ' instead. I also use r" for regexps, and """ for docstrings or large display screens. I don't use ''', at least not yet. (Actually, the use of ''' seems to be extemely rare from what I have seen of other people's code.) For yourself, just try to adopt something that's consistent and comfortable, and revel in the fact that in Python you have the freedom to choose. :-) -- ====================================================================== Paul Sidorsky Calgary, Canada paulsid@shaw.ca http://members.shaw.ca/paulsid/ From karthikg@aztec.soft.net Tue Jan 22 10:13:17 2002 From: karthikg@aztec.soft.net (Karthik Gurumurthy) Date: Tue, 22 Jan 2002 15:43:17 +0530 Subject: [Tutor] is "fold" same as "reduce"? In-Reply-To: Message-ID: > ### > def filter(test_f, l): def func(x, y): if test_f(y): return x + [y] return x return reduce(func, [[]] + l) ### > This one was good. Of the 3, I found reduce a bit tricky to use though. > http://www-106.ibm.com/developerworks/library/l-prog.html > http://www-106.ibm.com/developerworks/library/l-prog2.html > http://www-106.ibm.com/developerworks/library/l-prog3.html Yeah i was referring to the same set of articles. This one from IBM site for haskell by mertz http://www-105.ibm.com/developerworks/education.nsf/linux-onlinecourse-bytit le/9A31A3C4A0CE683E86256AD400822942?OpenDocument > If you're interested in functional programming, you might want to look at > the Haskell web site: > http://www.haskell.org/ Just downloaded it. Am actually looking to pick up good functional programming skills and apply the same in Python. So am not sure if i have to start off with learning haskell for that. By the way the Scheme introduction talk (the link which you had sent earlier) along with presentation slides was great.Especially the way, the topic was presented was neat. >You may also find this link handy: I just found it on Google, and it looks >like good stuff: > http://www.cs.chalmers.se/~rjmh/tutorials.html yeah it seems useful. thanks karthik. From alan.gauld@bt.com Tue Jan 22 10:22:37 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Tue, 22 Jan 2002 10:22:37 -0000 Subject: [Tutor] is "fold" same as "reduce"? Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C2D3@mbtlipnt02.btlabs.bt.co.uk> ------_=_NextPart_001_01C1A32E.B70FE5A0 Content-type: text/plain; charset="ISO-8859-1" One of the best FP languages is Haskell and the haskell.org web site has a lot of fairly heavy weight articles. LISP is heavily functional in nature so you could look at the lisp and scheme sites. The two online books Structure and Interpretation of Computer Programs and How to Design Programs both take a FP approach thru Scheme and I recommend them both. Alan g. ------_=_NextPart_001_01C1A32E.B70FE5A0 Content-type: text/html; charset="ISO-8859-1"
One of the best FP languages is Haskell and the
haskell.org web site has a lot of fairly heavy
weight articles.
 
LISP is heavily functional in nature so you
could look at the lisp and scheme sites.
 
The two online books
 
Structure and Interpretation of Computer Programs
and
How to Design Programs
 
both take a FP approach thru Scheme and I recommend them both.
 
Alan g.
 
------_=_NextPart_001_01C1A32E.B70FE5A0-- From erikprice@mac.com Tue Jan 22 13:08:13 2002 From: erikprice@mac.com (Erik Price) Date: Tue, 22 Jan 2002 08:08:13 -0500 Subject: [Tutor] Truckers Log....Me Again In-Reply-To: <3C4D30FE.AE9F9A0B@shaw.ca> Message-ID: <17666AA2-0F39-11D6-BE25-00039351FE6A@mac.com> Paul, Let me see if I can follow along (just learning this so this is good exercise) ... On Tuesday, January 22, 2002, at 04:29 AM, Paul Sidorsky wrote: > (That might be a good learning project for > those who were looking for one: implement a dictionary-like type using > lists, entirely in Python.) For example: > > {"key1": 12, "key2": "hi", key3: [2, 4, 6], key4: (1, 2, 3)} Here you've set up a dictionary. > could be viewed as: > > [["key1", 12], ["key2", "hi"], ["key3", [2, 4, 6]], ["key4", (1, 2, 3)]] At this point, is it still a dictionary? Or have you performed some operation to make it a list? I see the square brackets, which if I recall correctly, surround lists. > or also this way, which is probably closer to how Python dicts actually > work: > > keys = ["key1", "key2", "key3", "key4"] > values = [12, "hi", [2, 4, 6], (1, 2, 3)] Two separate lists. > A big problem with using lists is, of course, that access and > manipulation starts to get tricky. Another problem is you now have to > search to find keys; this may involve traversing most of the list. > Dictionaries use a hashtable so there is no search time involved (well > except with chaining, but that's normally not a significant factor). > > The concept of subscripting with, say, a string (e.g. mydict["key1"]) > may seem unusual at first, but it does become natural! Subscripting > with a more complex object like a tuple or a class is even more bizzare > the first time you do it but it does save tons of work! I'm not sure that I follow you correctly -- I see what you're saying in the last paragraph but I haven't put together how it applies to the examples above. Especially confusing (to me) is how Python allows you to define a dictionary, but then split that up into a variable "keys" and a variable "values", as shown above. But then, it's possible that the reference I used hasn't gotten that far yet. Erik From dsh8290@rit.edu Tue Jan 22 15:34:28 2002 From: dsh8290@rit.edu (dman) Date: Tue, 22 Jan 2002 10:34:28 -0500 Subject: [Tutor] Problem with division in Python22 In-Reply-To: <000b01c1a314$42431310$1664a8c0@mega> References: <4.2.0.58.20020121194920.00aa1710@pop3.norton.antivirus> <000b01c1a314$42431310$1664a8c0@mega> Message-ID: <20020122153428.GA2798@localhost> On Tue, Jan 22, 2002 at 08:13:14AM +0100, Gregor Lingl wrote: | Thanks, this works! | | But hasn't this to be considered as a bug, | as it breaks code developed for up to 2.2? Not a bug, but an incompatible change. The whole "true division" thing is an incompatible change, so apparently the magic method name has changed correspondingly. Taking a look at the PEP shows the following snippets : During the transitional phase, we have to support *three* division operators within the same program: <...> In Python 3.0, the classic division semantics will be removed; the classic division APIs will become synonymous with true division. So yeah, old code will break, but it almost surely would have broken anyways and at least this way you get an exception to tell you. -D -- "GUIs normally make it simple to accomplish simple actions and impossible to accomplish complex actions." --Doug Gwyn (22/Jun/91 in comp.unix.wizards) From pythontutor@venix.com Tue Jan 22 15:37:20 2002 From: pythontutor@venix.com (Lloyd Kvam) Date: Tue, 22 Jan 2002 10:37:20 -0500 Subject: [Tutor] Which Py? References: <20020121.163254.-235547.3.kjphotog@juno.com> Message-ID: <3C4D8730.5080405@venix.com> > If you feel at risk? No, don't think so, er, well don't know what to > feel at risk about. http://starship.python.net/crew/mhammond/ index I assumed you had read the Privacy Concern notice. The COM extensions are vulnerable to the usual Microsoft security holes. In this case, a malicious web site could use your browser to run python scripts through Active Scripting. The Python scripting support will happily let the malicious site have read access to your computer's files. Mark Hammond's opinion is that a malicious site is unlikely to target Python scripting since the percentage of such vulnerable machines is so low. However, if you have any sensitive information on your computer: credit card numbers server passwords sensitive files (e.g. medical records, accounting or tax records, etc.) it would be prudent to update and eliminate the risk. It is, of course, a good idea to disable active scripting and avoid running active scripting clients. A Symantec security advisory recommended deleting WSH.exe. You need to decide the level of paranoia that is appropriate for you. (My paranoia level is fairly high. I am trying to get myself fully converted to Linux, with my NT system used only for those clients that insist on Windows.) kjphotog@juno.com wrote: > Lloyd, > > > > Thanks for all the info. > > > > And that's what I did exactly. A windows user gave me the Active State > site & discovered the version @python.org. And now I know the difference > between downloading from those 2 sites. . > > > > If you feel at risk? No, don't think so, er, well don't know what to > feel at risk about. > -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From dsh8290@rit.edu Tue Jan 22 15:38:22 2002 From: dsh8290@rit.edu (dman) Date: Tue, 22 Jan 2002 10:38:22 -0500 Subject: [Tutor] is "fold" same as "reduce"? In-Reply-To: References: Message-ID: <20020122153822.GB2798@localhost> On Tue, Jan 22, 2002 at 03:43:17PM +0530, Karthik Gurumurthy wrote: | This one was good. Of the 3, I found reduce a bit tricky to use though. reduce is also cool because you don't need any "sum" function : >>> import operator >>> print reduce( operator.add , [ 1 , 2 , 3 , 4 ] ) 10 -D -- No harm befalls the righteous, but the wicked have their fill of trouble. Proverbs 12:21 From paulsid@shaw.ca Tue Jan 22 18:11:46 2002 From: paulsid@shaw.ca (Paul Sidorsky) Date: Tue, 22 Jan 2002 11:11:46 -0700 Subject: [Tutor] Truckers Log....Me Again References: <17666AA2-0F39-11D6-BE25-00039351FE6A@mac.com> Message-ID: <3C4DAB62.DF978F74@shaw.ca> Erik Price wrote: > > {"key1": 12, "key2": "hi", key3: [2, 4, 6], key4: (1, 2, 3)} > > Here you've set up a dictionary. Right. (Except I left the quotes off of "key3" and "key4" - Oops.) > > [["key1", 12], ["key2", "hi"], ["key3", [2, 4, 6]], ["key4", (1, 2, 3)]] > > At this point, is it still a dictionary? Or have you performed some > operation to make it a list? I see the square brackets, which if I > recall correctly, surround lists. Yes, this is entirely a list of lists. There is no dictionary involved, but functionally these lists are similar. Accessing it is a real pain, though. (I can give an example if needed.) > > keys = ["key1", "key2", "key3", "key4"] > > values = [12, "hi", [2, 4, 6], (1, 2, 3)] > > Two separate lists. Right. As you might have seen already, dictionaries can actually be told to produce these lists, using mydict.keys() and mydict.values(). Accessing this is a bit easier, again I could provide an example if it would help > > The concept of subscripting with, say, a string (e.g. mydict["key1"]) > > may seem unusual at first, but it does become natural! Subscripting > > with a more complex object like a tuple or a class is even more bizzare > > the first time you do it but it does save tons of work! > > I'm not sure that I follow you correctly -- I see what you're saying in > the last paragraph but I haven't put together how it applies to the > examples above. mydict["key1"] would return just the number 12 in my example. Of course I was referring to how conceptionally unusual this is for people used to using only numbers inside the brackets. I didn't use any fancier indexing there, but if you want to you can do something like this: >>> d = {("Paul", "Sidorsky"): "paulsid@shaw.ca"} >>> print d[("Paul", "Sidorsky")] paulsid@shaw.ca This particular example isn't very practical, but when you need to attach some information to multiple identifying values it can be quite useful to set it up as a dictionary indexed using a tuple or other object. > Especially confusing (to me) is how Python allows you to define a > dictionary, but then split that up into a variable "keys" and a variable > "values", as shown above. But then, it's possible that the reference I > used hasn't gotten that far yet. Up to Python 2.1 this is often used for traversing an entire dictionary, say to print the data in it: for key in dict.keys(): print dict[key] Of course in 2.2 you can now do this instead: for key in dict: print dict[key] Unfortunately, I can't really think of a good way to view dictionaries conceptually, so I'll have to leave that to somebody else! -- ====================================================================== Paul Sidorsky Calgary, Canada paulsid@shaw.ca http://members.shaw.ca/paulsid/ From james2dope@yahoo.com Tue Jan 22 17:58:52 2002 From: james2dope@yahoo.com (james middendorff) Date: Tue, 22 Jan 2002 09:58:52 -0800 (PST) Subject: [Tutor] help Message-ID: <20020122175852.7519.qmail@web13906.mail.yahoo.com> hello, I have recently started reading a python book and there is a sample program in the book that looks like this password = "foobar" while password != "unicorn": password = raw_input("whats the password? ") print "welcome, user" I was wondering how I could take that and maybe ask for a username and then check the username and password to log the user in, and also maybe could someone add users at a later time? thanks ===== "I would kill everyone in this room for a drop of sweet beer." ----Homer Simpson---- __________________________________________________ Do You Yahoo!? Send FREE video emails in Yahoo! Mail! http://promo.yahoo.com/videomail/ From scarblac@pino.selwerd.nl Tue Jan 22 18:53:36 2002 From: scarblac@pino.selwerd.nl (Remco Gerlich) Date: Tue, 22 Jan 2002 19:53:36 +0100 Subject: [Tutor] help In-Reply-To: <20020122175852.7519.qmail@web13906.mail.yahoo.com>; from james2dope@yahoo.com on Tue, Jan 22, 2002 at 09:58:52AM -0800 References: <20020122175852.7519.qmail@web13906.mail.yahoo.com> Message-ID: <20020122195336.A1678@pino.selwerd.nl> On 0, james middendorff wrote: > hello, > I have recently started reading a python book and > there is a sample program in the book that looks like > this > > password = "foobar" > while password != "unicorn": > password = raw_input("whats the password? ") > print "welcome, user" > > I was wondering how I could take that and maybe ask > for a username and then check the username and > password to log the user in, and also maybe could > someone add users at a later time? We have to store pairs of username/password, and when we know the username we want to be able to lookup the correct password. The thing to store that in is called a dictionary. See the analogy? They're also explained in your Python book, but it would look something like this: pwdict = { "remco": "gerlich", # This is not my real password :) "another": "password", } Now we have to keep repeating the question while either the username he gives doesn't exist in our dictionary, or the password is wrong: password = username = None # Set to some value we don't have while not pwdict.has_key(username) or pwdict[username] != password: username = raw_input("Username: ") password = raw_input("Password: ") print "welcome, user" So we can use pwdict.has_key(username) to check if it is in the dictionary, and pwdict[username] to retrieve the password that belongs to this username. You can add another with pwdict["james"] = "middendorf" I hope this made it clear. If you haven't seen dictionaries yet, you might want to jump there in your book - dictionaries are good :) -- Remco Gerlich From bronto@pobox.com Mon Jan 21 20:22:25 2002 From: bronto@pobox.com (Anton Sherwood) Date: Mon, 21 Jan 2002 12:22:25 -0800 Subject: [Tutor] a quetion on "There should be one and preferabley oneobvious way to do it" References: Message-ID: <3C4C7881.78867700@pobox.com> > ### > >>> cube = lambda x: square(square(x)) > >>> cube(42) > 3111696 > ### > > is weird as heck. *grin* Of course we all know that the above-defined function is quartic, cube is really lambda x: x*square(x), and 42^3 = 74088. So I won't waste everyone's time by mentioning it. -- Anton Sherwood -- http://www.ogre.nu/ From idiot1@netzero.net Tue Jan 22 19:54:46 2002 From: idiot1@netzero.net (kirk Bailey) Date: Tue, 22 Jan 2002 14:54:46 -0500 Subject: [Tutor] error reporting disreputable Message-ID: <3C4DC386.793F0CF@netzero.net> ok, I included code to report errors to the postmaster. Lookee: try: server.sendmail(from_addr, to_addr, msg) # 400 send envlope and msg! except Exception, e: from_addr2="TLpost.py@"+domainname to_addr2="postmaster@"+domainname msg2="To: "+to_addr2+CRLF msg2=msg2+"From: "+from_addr2+CRLF msg2=msg2+"Subject: ERROR REPORT for list"+listname+CRLF+CRLF msg2=msg2+"There was an error when serving list "+listname+"."+CRLF msg2=msg2+"The returned error was:"+CRLF msg2=msg2+e+CRLF print "POSSIBLE Bad address='"+to_addr+"' ?" # local console display! server.sendmail(from_addr2, to_addr2, msg2) # send postmaster notice! I do NOT get a letter at the postmaster address. I DO get this back to the SENDER'S address, and it's NOT the message I coded!!! WTF?!? The original message was received at Tue, 22 Jan 2002 14:51:30 -0500 (EST) from www.howlermonkey.net [66.13.61.155] ----- The following addresses had permanent fatal errors ----- (reason: 550 Host unknown) ----- Transcript of session follows ----- 550 5.1.2 ... Host unknown (Name server: noplace.foo: host not found) -- -Respectfully, -Kirk D Bailey Consulting Loose Cannon end www.howlermonkey.net highprimate@howlermonkey.net www.sacredelectron.org idiot1@netzero.net www.tinylist.org grumpy@tinylist.org ---------------------------------------------------- Sign Up for NetZero Platinum Today Only $9.95 per month! http://my.netzero.net/s/signup?r=platinum&refcd=PT97 From arcege@speakeasy.net Tue Jan 22 20:05:33 2002 From: arcege@speakeasy.net (Michael P. Reilly) Date: Tue, 22 Jan 2002 15:05:33 -0500 Subject: [Tutor] a quetion on"There should be one and preferabley one obvious way to do it" In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66C2CD@mbtlipnt02.btlabs.bt.co.uk>; from alan.gauld@bt.com on Tue, Jan 22, 2002 at 12:00:00AM -0000 References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C2CD@mbtlipnt02.btlabs.bt.co.uk> Message-ID: <20020122150533.B913@speakeasy.net> On Tue, Jan 22, 2002 at 12:00:00AM -0000, alan.gauld@bt.com wrote: > > List comprehensions replace a lot of map(lambda...) > > garbage which is very unsightly. > > I disagree. I find the map(lambda... ) form much more > readable than the confusion that is comprehensions. > Every time I see a comprehension I have to mentally > rewrite it in a for loop form. > > But then I spent a lot of time reading Lisp where every > function starts like: > > (define foo > (lambda x ....)) > > Which is directly equivalet to: > > foo = lambda x:.... > > in Python. > > To me a map looks much cleaner than a comprehension! > (But is less flexible I think) > > Alan G > (Who is almost certainly in a minority of one on this! :-) I quite agree, Alan. I think list comprehensions make for a more confusing form. But then maybe it is because my favorite language used to be Lisp, where apply, map, etc. were common and elegant. Syntactically and semantically in Python, something is confusing between having "for var in seq" as both a statement AND and expression - and that really smells of Perl (which wasn't a pleasant thought to me). Map, filter, reduce, they all have the same simple, predictable form. But list comprehensions have a far more complicated form might want to use it. List comprehensions may make the code look cleaner, but I do not think that they make the algorithm much clearer for the most part. -Arcege From kauphlyn@speakeasy.org Tue Jan 22 20:21:24 2002 From: kauphlyn@speakeasy.org (Daniel Coughlin) Date: Tue, 22 Jan 2002 12:21:24 -0800 (PST) Subject: [Tutor] error reporting disreputable In-Reply-To: <3C4DC386.793F0CF@netzero.net> Message-ID: On Tue, 22 Jan 2002, kirk Bailey wrote: > ok, I included code to report errors to the postmaster. Lookee: > try: > server.sendmail(from_addr, to_addr, msg) # 400 > send envlope and msg! > except Exception, e: > from_addr2="TLpost.py@"+domainname > to_addr2="postmaster@"+domainname > msg2="To: "+to_addr2+CRLF > msg2=msg2+"From: "+from_addr2+CRLF > msg2=msg2+"Subject: ERROR REPORT for > list"+listname+CRLF+CRLF > msg2=msg2+"There was an error when serving list > "+listname+"."+CRLF > msg2=msg2+"The returned error was:"+CRLF > msg2=msg2+e+CRLF ^ One possible reason why this might fail is because you are adding an instance to a string. Try msg2=msg2+str(e)+CRLF or you could try putting the block of code under the above except statement in its own try, except control structure. Hope this helps Daniel From glingl@aon.at Tue Jan 22 20:45:43 2002 From: glingl@aon.at (Gregor Lingl) Date: Tue, 22 Jan 2002 21:45:43 +0100 Subject: [Tutor] New problem with -Qnew and IDLE? Message-ID: <001c01c1a385$c31e3840$1664a8c0@mega> This is a multi-part message in MIME format. ------=_NextPart_000_0019_01C1A38E.24B01E90 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Has anybody an explanation vor this: I started IDLE with the -Qnew switch. (I have a copy of the IDLE-Icon with this switch on my desktop) Then I did the following in IDLE's Python-Shell-Window: >>>def ggt(a,b): while b: ##### WHEN NOW I HIT ENTER, ##### THE RESULT WAS: >>> Exception in Tkinter callback Traceback (most recent call last): File "C:\Python22\lib\lib-tk\Tkinter.py", line 1292, in __call__ return apply(self.func, args) File "C:\Python22\Tools\idle\PyShell.py", line 588, in enter_callback self.auto.auto_indent(event) File "C:\Python22\Tools\idle\AutoIndent.py", line 301, in = newline_and_indent_event self.smart_indent_event(event) File "C:\Python22\Tools\idle\AutoIndent.py", line 208, in = smart_indent_event self.reindent_to(effective + self.indentwidth) File "C:\Python22\Tools\idle\AutoIndent.py", line 455, in reindent_to text.insert("insert", self._make_blanks(column)) File "C:\Python22\Tools\idle\AutoIndent.py", line 442, in _make_blanks return '\t' * ntabs + ' ' * nspaces TypeError: unsupported operand type(s) for *: 'str' and 'float' def ggt(a,b): while b: So the cryptic Error - backtrace appeard after the >>> - Prompt=20 and BEFORE the two lines I just had typed in. Moreover, I only could return to the >>> - prompt=20 by hitting ^C (Keybord-Interrupt) This strange behaviour doesn't appear in ordinarily started IDLE. It also does not appear when starting Python (with or without -Qnew) from the MS-DOS prompt. I feel more and more, that there is some strange instability in IDLE connected with the -Qnew switch . Gregor P.S.: I'm interested in these problems, because in my opinion it is an important, if not crucial point to have a not only simple but also stable and reliable programming environment, when working with=20 highschool students, who are just beginning to learn to program. ------=_NextPart_000_0019_01C1A38E.24B01E90 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
Has anybody an explanation vor this:
 
I started IDLE with the -Qnew switch.
(I have a copy of the IDLE-Icon with this switch on = my=20 desktop)
Then I did the following in IDLE's=20 Python-Shell-Window:
 
>>>def=20 ggt(a,b):
       while b:
 ##### WHEN NOW I HIT ENTER,
          &nbs= p;     =20 ##### THE RESULT WAS:
 
>>> Exception in Tkinter = callback
Traceback (most=20 recent call last):
  File "C:\Python22\lib\lib-tk\Tkinter.py", = line=20 1292, in __call__
    return apply(self.func, = args)
 =20 File "C:\Python22\Tools\idle\PyShell.py", line 588, in=20 enter_callback
    = self.auto.auto_indent(event)
  File=20 "C:\Python22\Tools\idle\AutoIndent.py", line 301, in=20 newline_and_indent_event
   =20 self.smart_indent_event(event)
  File=20 "C:\Python22\Tools\idle\AutoIndent.py", line 208, in=20 smart_indent_event
    self.reindent_to(effective +=20 self.indentwidth)
  File "C:\Python22\Tools\idle\AutoIndent.py", = line=20 455, in reindent_to
    text.insert("insert",=20 self._make_blanks(column))
  File=20 "C:\Python22\Tools\idle\AutoIndent.py", line 442, in=20 _make_blanks
    return '\t' * ntabs + ' ' *=20 nspaces
TypeError: unsupported operand type(s) for *: 'str' and=20 'float'
def ggt(a,b):
     while = b:
 
So the cryptic Error - backtrace appeard after = the=20 >>> - Prompt
and BEFORE the two lines I just had typed = in.
 
Moreover, I only could return to the >>> - = prompt=20
by hitting ^C (Keybord-Interrupt)
 
This strange behaviour doesn't appear in ordinarily = started=20 IDLE.
It also does not appear when starting Python (with = or without=20 -Qnew)
from the MS-DOS prompt.
 
I feel more and more, that there is some strange = instability=20 in IDLE
connected with the -Qnew = switch=20 .
 
Gregor
 
P.S.: I'm interested in these problems, because in = my opinion=20 it is
an important, if not crucial point to have a not = only simple=20 but also
stable and reliable programming=20 environment, when working with
highschool students, who are just beginning to learn = to=20 program.
 
------=_NextPart_000_0019_01C1A38E.24B01E90-- From urnerk@qwest.net Tue Jan 22 21:02:11 2002 From: urnerk@qwest.net (Kirby Urner) Date: Tue, 22 Jan 2002 13:02:11 -0800 Subject: [Tutor] List comprehension In-Reply-To: <20020122150533.B913@speakeasy.net> References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C2CD@mbtlipnt02.btlabs.bt.co.uk> <5104D4DBC598D211B5FE0000F8FE7EB20E66C2CD@mbtlipnt02.btlabs.bt.co.uk> Message-ID: <4.2.0.58.20020122123339.019d3100@pop3.norton.antivirus> I think of list comprehensions as replacing syntax like this: def lc(f,listb): output = [] for a in listb: output.append(f(a)) return output E.g.: >>> def f(x): return x*x >>> lc(f,[1,2,3,4,5]) [1, 4, 9, 16, 25] The lambda form would be: map(lambda a: expr(a), listb) >>> map(lambda x: x*x, [1,2,3,4,5]) [1, 4, 9, 16, 25] Using list comprehension syntax, we write: [expr(a) for a in listb] E.g.: >>> [x*x for x in [1,2,3,4,5]] [1, 4, 9, 16, 25] Since we've already specified expr(a), there's no need to use a colon i.e. we don't go: [for a in listb: expr(a)] which would also be expressive. But putting expr(a) first is more like map(lambda a: expr(a),list) in that it shows *what* you plan to do before you specify *over what* list you plan to iterate. Then there's the filtering 'if' clause. As an application I really like defining gcd(a,b) and then gathering totatives (positives relatively prime to N and < N) by going: >>> def gcd(a,b): while b: a,b = b, a%b return a totatives = [t for t in range(1,N) if gcd(t,N)==1] E.g.: >>> totatives = [t for t in range(1,28) if gcd(t,28)==1] >>> totatives [1, 3, 5, 9, 11, 13, 15, 17, 19, 23, 25, 27] The lambda form would be: >>> filter(lambda a: gcd(a,28)==1,range(28)) [1, 3, 5, 9, 11, 13, 15, 17, 19, 23, 25, 27] I don't find that any clearer than the list comprehension way of doing it. Finally, there's the ability to stack for clauses, effectively nesting them: >>> [a+b for a in ['a','b','c'] for b in ['c','d','e']] ['ac', 'ad', 'ae', 'bc', 'bd', 'be', 'cc', 'cd', 'ce'] That suggests a generic way of multiplying two integers: >>> reduce(add,[a*b for a in [400,20,3] for b in [300,20,1]]) 135783 >>> 423*321 135783 This shows that we can break two numbers into lists of terms which sum to the original numbers, and by adding all combinations (think of an n x n table), we get the product. You don't even need to break the two numbers into the same number of terms: >>> reduce(add,[a*b for a in [420,3] for b in [300,10,10,1]]) 135783 OK, now I'm really getting into Useless Python territory. But if you imagine kids in 7th or 8th grade, learning Python and math at the same time, you can see how insights such as the above might come in handy. Kirby From dsh8290@rit.edu Tue Jan 22 21:35:10 2002 From: dsh8290@rit.edu (dman) Date: Tue, 22 Jan 2002 16:35:10 -0500 Subject: [Tutor] a quetion on"There should be one and preferabley one obvious way to do it" In-Reply-To: <20020122150533.B913@speakeasy.net> References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C2CD@mbtlipnt02.btlabs.bt.co.uk> <20020122150533.B913@speakeasy.net> Message-ID: <20020122213510.GA5455@dman.ddts.net> On Tue, Jan 22, 2002 at 03:05:33PM -0500, Michael P. Reilly wrote: [I missed the beginning of the thread, BTW] | I quite agree, Alan. I think list comprehensions make for a more | confusing form. But then maybe it is because my favorite language used | to be Lisp, where apply, map, etc. were common and elegant. List comprehensions look a lot like the syntax found in discrete mathematics. For example, in VDM-SL (a formal modelling language) sets can be created with { expression | expression & predicate } Such as even numbers : { x | x in set int & x mod 2 = 0 } Sequences and maps can be created in the same way : (a sequence) [ x | x in set int & x mod 2 = 0 ] (the difference is that sequences have order and can be indexed and contain duplicates, sets do not) | List comprehensions may make the code look cleaner, but I do not think | that they make the algorithm much clearer for the most part. If the code is clearer, then what the algorithm is (though maybe not the algorithm itself) will be clearer. I agree with you that syntactically list comprehensions are weird, at first. Once you figure them out, they're a piece of cake and convenient too! -D -- The crucible for silver and the furnace for gold, but the Lord tests the heart. Proverbs 17:3 From AMoore4437@aol.com Tue Jan 22 22:08:35 2002 From: AMoore4437@aol.com (AMoore4437@aol.com) Date: Tue, 22 Jan 2002 17:08:35 EST Subject: [Tutor] interpreter Message-ID: <145.83c7135.297f3ce3@aol.com> --part1_145.83c7135.297f3ce3_boundary Content-Type: text/plain; charset="US-ASCII" Content-Transfer-Encoding: 7bit I am a newbie and wish to learn how to program in Python, I understand i need to download an Interpreter. could you please tell me where i find this and what it is called so i know exactly what i am looking for. I am running windows 95 is there anything else i need? thank you tony moore --part1_145.83c7135.297f3ce3_boundary Content-Type: text/html; charset="US-ASCII" Content-Transfer-Encoding: 7bit I am a newbie and wish to learn how to program in Python, I understand i need to download an Interpreter.

could you please tell me where i find this and what it is called so i know exactly what i am looking for.

I am running windows 95
is there anything else i need?

thank you
tony moore
--part1_145.83c7135.297f3ce3_boundary-- From wilson@visi.com Tue Jan 22 22:18:54 2002 From: wilson@visi.com (Tim Wilson) Date: Tue, 22 Jan 2002 16:18:54 -0600 (CST) Subject: [Tutor] interpreter In-Reply-To: <145.83c7135.297f3ce3@aol.com> Message-ID: On Tue, 22 Jan 2002 AMoore4437@aol.com wrote: > I am running windows 95 > is there anything else i need? Go to http://www.python.org/ftp/python/2.2/ and download Python-2.2.exe. Version 2.2 is the latest version and should include everything you need to begin writing programs. See you around. -Tim -- Tim Wilson | Visit Sibley online: | Check out: Henry Sibley HS | http://www.isd197.org | http://www.zope.com W. St. Paul, MN | | http://slashdot.org wilson@visi.com | | http://linux.com From arcege@speakeasy.net Tue Jan 22 22:28:53 2002 From: arcege@speakeasy.net (Michael P. Reilly) Date: Tue, 22 Jan 2002 17:28:53 -0500 Subject: [Tutor] a quetion on"There should be one and preferabley one obvious way to do it" In-Reply-To: <20020122213510.GA5455@dman.ddts.net>; from dsh8290@rit.edu on Tue, Jan 22, 2002 at 04:35:10PM -0500 References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C2CD@mbtlipnt02.btlabs.bt.co.uk> <20020122150533.B913@speakeasy.net> <20020122213510.GA5455@dman.ddts.net> Message-ID: <20020122172853.C913@speakeasy.net> On Tue, Jan 22, 2002 at 04:35:10PM -0500, dman wrote: > I agree with you that syntactically list comprehensions are weird, at > first. Once you figure them out, they're a piece of cake and > convenient too! My point was that it is actually anti-pythonic - making the syntax more "weird". I've understood the power and use of them for a long time. That still doesn't mean that I think it is very good syntactically when considering Python's history. -Arcege From dyoo@hkn.eecs.berkeley.edu Tue Jan 22 22:32:01 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 22 Jan 2002 14:32:01 -0800 (PST) Subject: [Tutor] a quetion on "There should be one and preferabley oneobvious way to do it" In-Reply-To: <3C4C7881.78867700@pobox.com> Message-ID: On Mon, 21 Jan 2002, Anton Sherwood wrote: > > ### > > >>> cube = lambda x: square(square(x)) > > >>> cube(42) > > 3111696 > > ### > > > > is weird as heck. *grin* > > Of course we all know that the above-defined function is quartic, > cube is really lambda x: x*square(x), and 42^3 = 74088. So I won't > waste everyone's time by mentioning it. You're right! *slap on forehead* Thank you for catching me on that. That's another good reason why Tutor is so wonderful --- we can catch each other's slipups. *grin* I was being way too hasty when I was typing that. The correct code should have been: ### cube = lambda x: square(x) * x ### Thanks again! From dyoo@hkn.eecs.berkeley.edu Tue Jan 22 22:36:19 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 22 Jan 2002 14:36:19 -0800 (PST) Subject: [Tutor] interpreter In-Reply-To: Message-ID: On Tue, 22 Jan 2002, Tim Wilson wrote: > On Tue, 22 Jan 2002 AMoore4437@aol.com wrote: > > > I am running windows 95 > > is there anything else i need? > > Go to http://www.python.org/ftp/python/2.2/ and download > Python-2.2.exe. Version 2.2 is the latest version and should include > everything you need to begin writing programs. See you around. By the way, here's a small tutorial that might help you get started once you have Python installed: http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro It's a small introduction to the IDLE text editor that comes bundled with Python. Good luck to you! From jeff@ccvcorp.com Tue Jan 22 22:43:42 2002 From: jeff@ccvcorp.com (Jeff Shannon) Date: Tue, 22 Jan 2002 14:43:42 -0800 Subject: [Tutor] New problem with -Qnew and IDLE? References: Message-ID: <3C4DEB1E.FA221AF4@ccvcorp.com> > "Gregor Lingl" wrote: > > Has anybody an explanation vor this: > > I started IDLE with the -Qnew switch. > (I have a copy of the IDLE-Icon with this switch on my desktop) > Then I did the following in IDLE's Python-Shell-Window: [snip traceback] > This strange behaviour doesn't appear in ordinarily started IDLE. > It also does not appear when starting Python (with or without -Qnew) > from the MS-DOS prompt. > > I feel more and more, that there is some strange instability in IDLE > connected with the -Qnew switch . My suspicion would be that Tkinter (which IDLE is based on) is somewhere relying on integer division semantics. This wouldn't affect things when using "from __future__ import division", because that works on the module level so that Tkinter's code itself would not use new division, but the -Qnew switch would force new division on *everything*, and apparently Tkinter (or IDLE) are not currently able to handle that. I would suggest trying to run Tkinter programs other than IDLE with the -Qnew switch. If you get the same sort of errors, then enter a bug report against Tkinter. If you *don't*, then enter a bug report against IDLE. One of them is choking on new division, and it definately needs to be fixed before Python 3.0 ;) Jeff Shannon Technician/Programmer Credit International From arcege@speakeasy.net Tue Jan 22 23:17:40 2002 From: arcege@speakeasy.net (Michael P. Reilly) Date: Tue, 22 Jan 2002 18:17:40 -0500 Subject: [Tutor] List comprehension In-Reply-To: <4.2.0.58.20020122123339.019d3100@pop3.norton.antivirus>; from urnerk@qwest.net on Tue, Jan 22, 2002 at 01:02:11PM -0800 References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C2CD@mbtlipnt02.btlabs.bt.co.uk> <5104D4DBC598D211B5FE0000F8FE7EB20E66C2CD@mbtlipnt02.btlabs.bt.co.uk> <20020122150533.B913@speakeasy.net> <4.2.0.58.20020122123339.019d3100@pop3.norton.antivirus> Message-ID: <20020122181740.A9696@speakeasy.net> On Tue, Jan 22, 2002 at 01:02:11PM -0800, Kirby Urner wrote: > Since we've already specified expr(a), there's no > need to use a colon i.e. we don't go: > > [for a in listb: expr(a)] > > which would also be expressive. This was my point. Python goes through great pains of saying that statements cannot be used in expressions; assignment being the largest 'pain' for many coming to Python. But here come list comprehession where you can now the syntax and semantics similar to 'for' and 'if' statements, with the keywords, inside an expression. That's confusing to the rules. And as for the argument of it being an exception, it's always been there Python has FEW exceptions without good reason - language exceptions have been for other languages. But then, this isn't necessarily a topic for "tutoring", except as it relates to "how easy is it for someone to learn a new language when there are some potentially confusing elements of the language". -Arcege From grimmtoothtoo@yahoo.com Tue Jan 22 23:47:48 2002 From: grimmtoothtoo@yahoo.com (Grimmtooth) Date: Tue, 22 Jan 2002 18:47:48 -0500 Subject: [Tutor] Extracting filenames from a List? In-Reply-To: Message-ID: > What I would like to do is to extract all files ending in '.jpg' > - the case > does not matter. Everything ending in '.JpG' should be extracted. for i in list: if len(i) > 4: if string.upper(i[-4:]) == '.JPG': process-file-stuff Hey, it isn't slick or anything, but it'll work 99 out of a hundred :-) _________________________________________________________ Do You Yahoo!? Get your free @yahoo.com address at http://mail.yahoo.com From dsh8290@rit.edu Wed Jan 23 00:09:00 2002 From: dsh8290@rit.edu (dman) Date: Tue, 22 Jan 2002 19:09:00 -0500 Subject: [Tutor] error reporting disreputable In-Reply-To: <3C4DC386.793F0CF@netzero.net> References: <3C4DC386.793F0CF@netzero.net> Message-ID: <20020123000900.GA6922@dman.ddts.net> On Tue, Jan 22, 2002 at 02:54:46PM -0500, kirk Bailey wrote: | ok, I included code to report errors to the postmaster. Lookee: | I do NOT get a letter at the postmaster address. I DO get this back to | the SENDER'S address, and it's NOT the message I coded!!! WTF?!? The bounce to the sender's address is per RFC2821. If sendmail got the message, then gives an error, it will send a bounce to the sender (or it should anyways). Check the Received: headers to see where it went. It is good for you to add a Received: header at the top of the list to show what/when your program handled the message. | The original message was received at Tue, 22 Jan 2002 14:51:30 -0500 | (EST) | from www.howlermonkey.net [66.13.61.155] | | ----- The following addresses had permanent fatal errors ----- | | (reason: 550 Host unknown) | | ----- Transcript of session follows ----- | 550 5.1.2 ... Host unknown (Name server: | noplace.foo: host not found) Perhaps if you enable VRFY in sendmail you can first VRFY the address before actually sending the message. That might help you catch errors. (BTW, it is _really_ annoying in the case where I send a messge to a list and get a bounce because some subscriber to the list hosed their setup. That shouldn't happen; the MAIL FROM: should be rewritten to send bounces to the list bot instead of me when the message is resent) -D -- For society, it's probably a good thing that engineers value function over appearance. For example, you wouldn't want engineers to build nuclear power plants that only _look_ like they would keep all the radiation inside. (Scott Adams - The Dilbert principle) From glingl@aon.at Wed Jan 23 01:10:48 2002 From: glingl@aon.at (Gregor Lingl) Date: Wed, 23 Jan 2002 02:10:48 +0100 Subject: [Tutor] Re: -Qnew - switch (was: New problem with -Qnew and IDLE?) References: <001c01c1a385$c31e3840$1664a8c0@mega> <1011746515.3171.2.camel@oberon> Message-ID: <00c201c1a3aa$cb31f060$1664a8c0@mega> > > To my knowledge, idle has never had a -Qnew switch. > Then - if you use Python2.2 - you have the opportunity now to extend your knowledge. Start IDLE with something like this: C:\Python22\pythonw.exe -Qnew "C:\Python22\Tools\idle\idle.pyw" Then at the IDLE-prompt write 3/4 and you will see the following result: Python 2.2 (#28, Dec 21 2001, 12:21:22) [MSC 32 bit (Intel)] on win32 Type "copyright", "credits" or "license" for more information. IDLE 0.8 -- press F1 for help >>> 3/4 0.75 >>> So you see IDLE at work with division from __future__ Best regards Gregor From elguavas@users.sourceforge.net Wed Jan 23 00:41:54 2002 From: elguavas@users.sourceforge.net (Stephen M. Gava) Date: 23 Jan 2002 11:41:54 +1100 Subject: [Tutor] Re: [Idle-dev] New problem with -Qnew and IDLE? In-Reply-To: <001c01c1a385$c31e3840$1664a8c0@mega> References: <001c01c1a385$c31e3840$1664a8c0@mega> Message-ID: <1011746515.3171.2.camel@oberon> On Wed, 2002-01-23 at 07:45, Gregor Lingl wrote: > I started IDLE with the -Qnew switch. To my knowledge, idle has never had a -Qnew switch. -- Stephen M. Gava IDLEfork ( http://idlefork.sourceforge.net ) " just like IDLE, only crunchy " From guido@python.org Wed Jan 23 02:11:38 2002 From: guido@python.org (Guido van Rossum) Date: Tue, 22 Jan 2002 21:11:38 -0500 Subject: [Tutor] Re: [Idle-dev] New problem with -Qnew and IDLE? In-Reply-To: Your message of "23 Jan 2002 11:41:54 +1100." <1011746515.3171.2.camel@oberon> References: <001c01c1a385$c31e3840$1664a8c0@mega> <1011746515.3171.2.camel@oberon> Message-ID: <200201230211.VAA00964@pcp742651pcs.reston01.va.comcast.net> > On Wed, 2002-01-23 at 07:45, Gregor Lingl wrote: > > I started IDLE with the -Qnew switch. Stephen > To my knowledge, idle has never had a -Qnew switch. But Python 2.2 does. I can reproduce Gregor's problem. Gregor, can you submit a sourceforge bug report for it? --Guido van Rossum (home page: http://www.python.org/~guido/) From elguavas@users.sourceforge.net Wed Jan 23 01:23:44 2002 From: elguavas@users.sourceforge.net (Stephen M. Gava) Date: 23 Jan 2002 12:23:44 +1100 Subject: [Tutor] Re: [Idle-dev] New problem with -Qnew and IDLE? In-Reply-To: <200201230211.VAA00964@pcp742651pcs.reston01.va.comcast.net> References: <001c01c1a385$c31e3840$1664a8c0@mega> <1011746515.3171.2.camel@oberon> <200201230211.VAA00964@pcp742651pcs.reston01.va.comcast.net> Message-ID: <1011749024.3381.7.camel@oberon> Guido van Rossum wrote: > > On Wed, 2002-01-23 at 07:45, Gregor Lingl wrote: > > > I started IDLE with the -Qnew switch. > > Stephen > > To my knowledge, idle has never had a -Qnew switch. > > But Python 2.2 does. > > I can reproduce Gregor's problem. Gregor, can you submit a > sourceforge bug report for it? Ah, the new division business in 2.2. Looks like it's choking AutoIndent.py's whitespace calculations. Ok, I submitted a bug (# 507298) in idlefork's tracker for this. -- Stephen M. Gava IDLEfork ( http://idlefork.sourceforge.net ) " just like IDLE, only crunchy " From elguavas@users.sourceforge.net Wed Jan 23 01:34:31 2002 From: elguavas@users.sourceforge.net (Stephen M. Gava) Date: 23 Jan 2002 12:34:31 +1100 Subject: [Tutor] Re: -Qnew - switch (was: New problem with -Qnew and IDLE?) In-Reply-To: <00c201c1a3aa$cb31f060$1664a8c0@mega> References: <001c01c1a385$c31e3840$1664a8c0@mega> <1011746515.3171.2.camel@oberon> <00c201c1a3aa$cb31f060$1664a8c0@mega> Message-ID: <1011749671.3880.12.camel@oberon> On Wed, 2002-01-23 at 12:10, Gregor Lingl wrote: > > > > To my knowledge, idle has never had a -Qnew switch. > > > > Then - if you use Python2.2 - you have the opportunity now > to extend your knowledge. Yep, you're quite right of course about the division switch in python 2.2, but it is a switch on python not on idle, so your statement "I started IDLE with the -Qnew switch" threw me there for a moment; apologies. I've entered a bug on this (# 507298) in the idlefork bug tracker at sourceforge. Regards, -- Stephen M. Gava IDLEfork ( http://idlefork.sourceforge.net ) " just like IDLE, only crunchy " From virketis@fas.harvard.edu Wed Jan 23 03:29:06 2002 From: virketis@fas.harvard.edu (Pijus Virketis) Date: Tue, 22 Jan 2002 22:29:06 -0500 Subject: [Tutor] Re: [Idle-dev] New problem with -Qnew and IDLE? Message-ID: <0a3201c1a3be$1ed67750$dbadf78c@virketis2> This is a multi-part message in MIME format. ------=_NextPart_000_0A2F_01C1A394.340FC2E0 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Excuse me for a completely unproductive email, but I think I just saw a = post from Guido on this email list. I have a T-shirt with him on it, so = I am a little in awe ... :) I guess this is the great thing about Open = Source: things can come to the right folks' attention quickly and get = fixed.=20 -P ------=_NextPart_000_0A2F_01C1A394.340FC2E0 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
Excuse me for a completely unproductive = email, but=20 I think I just saw a post from Guido on this email list. I have a = T-shirt with=20 him on it, so I am a little in awe ... :) I guess this is the = great=20 thing about Open Source: things can come to the right folks' attention = quickly=20 and get fixed.
 
-P
------=_NextPart_000_0A2F_01C1A394.340FC2E0-- From clickron@webtv.net Wed Jan 23 04:38:16 2002 From: clickron@webtv.net (Ron) Date: Tue, 22 Jan 2002 23:38:16 -0500 (EST) Subject: [Tutor] open files other than text? Message-ID: <28438-3C4E3E38-4976@storefull-168.iap.bryant.webtv.net> I have windows 98 Python2.2. Can you open files other than text files. I tried to open a .doc file and just got a line of giberish. What kind of things can be opened? From karthikg@aztec.soft.net Wed Jan 23 05:15:41 2002 From: karthikg@aztec.soft.net (Karthik Gurumurthy) Date: Wed, 23 Jan 2002 10:45:41 +0530 Subject: [Tutor] open files other than text? In-Reply-To: <28438-3C4E3E38-4976@storefull-168.iap.bryant.webtv.net> Message-ID: > I have windows 98 Python2.2. Can you open files other than text files. I > tried to open a .doc file and just got a line of giberish. What kind of > things can be opened? if you want to read a MS word file then you might want to use python bindings for windows (www.activestate.com). Then using MS word objects, the way it is normally used in VB / VBScript, you can work with word documents. But i c'd'nt find active python release for 2.2 There is one for 2.1 though. It ships with modules win32com and win32com.client and so on.. karthik _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From tim.one@home.com Wed Jan 23 05:15:09 2002 From: tim.one@home.com (Tim Peters) Date: Wed, 23 Jan 2002 00:15:09 -0500 Subject: [Tutor] New problem with -Qnew and IDLE? In-Reply-To: <001c01c1a385$c31e3840$1664a8c0@mega> Message-ID: [Gregor Lingl] > Has anybody an explanation vor this: Better, I checked in a fix , so it should work in 2.2.1 (when it's released). > I started IDLE with the -Qnew switch. > (I have a copy of the IDLE-Icon with this switch on my desktop) > Then I did the following in IDLE's Python-Shell-Window: > > >>> def ggt(a,b): > while b: ##### WHEN NOW I HIT ENTER, > ##### THE RESULT WAS: > > >>> Exception in Tkinter callback > ... > File "C:\Python22\Tools\idle\AutoIndent.py", line 442, in _make_blanks > return '\t' * ntabs + ' ' * nspaces > TypeError: unsupported operand type(s) for *: 'str' and 'float' > def ggt(a,b): > while b: IDLE is trying to figure out how to auto-indent the next line. At one point it does effective = (effective / tabwidth + 1) * tabwidth That doesn't work as intended under -Qnew, so I changed it to effective = (int(effective / tabwidth) + 1) * tabwidth (you can change that line similarly in your copy of AutoIndent.py, of course). > ... > I feel more and more, that there is some strange instability in IDLE > connected with the -Qnew switch . Not really strange. We had 2.2 alpha and beta releases for half a year, and AFAICT nobody even *tried* -Qnew until after 2.2 final was released (did you?). The only thing I personally tried under the combo of IDLE and -Qnew was a one-liner to make sure 3/2 returned 1.5; I'm afraid that's all I had time for. > P.S.: I'm interested in these problems, because in my opinion it is > an important, if not crucial point to have a not only simple but also > stable and reliable programming environment, when working with > highschool students, who are just beginning to learn to program. You should read the PEP for its warnings about using -Qnew. At this stage it's for pioneers; if you can't tolerate some early glitches, I advise that you simply leave it alone. Else you can be very helpful by using it and reporting what goes wrong. That you're the first person to report this bug means you're the first person to try typing a "def" into an IDLE shell under -Qnew! We need *somebody* brave enough to try that . From wesc@deirdre.org Wed Jan 23 07:04:04 2002 From: wesc@deirdre.org (Wesley Chun) Date: Tue, 22 Jan 2002 23:04:04 -0800 (PST) Subject: [Tutor] ANN: Python course in Silicon Valley (1/28-3/25) Message-ID: one last reminder that open enrollment for this course are still available. contact Mickal at the number below for information. details: monday nites, 6:30-9:30p, 1/28-3/25 (!2/18), sunnyvale in addition to the course description at the website below, there is a course website with the syllabus, schedule, topics, homework, handouts, etc. here: http://instruction.ucsc-extension.edu/wesc/013e44 finally, the website for the textbook is in the .sig below. feel free to contact me directly if you have any questions. hope to see some of you in class this coming week! -wesley > Wesley J. Chun wrote in a msg on Jan 9, 2002... > > After a 1 year hiatus, UC Santa Cruz Extension is once again > offering a Python course, Python Programming (I). The course > is 8 weeks in total, one night a week (Monday nights) from > January 28 - March 25 (no class on Presidents' Day, Feb 18). > > The class is taught in Sunnyvale. The course description and > enrollment information can be found below or by calling Mickal > at 408-566-4534: > > http://instruction.ucsc-extension.edu/wesc/013e44cd.htm > > if all goes well, i may be teaching a new course in the Spring, > Python Programming 2, which follows right after the 1st course. > if enrollments are not high enough for the advanced class, then > i will probably teach the 1st class again. i have also put in > a proposal for a "completely new to programming" course for > newbies, but that has yet to be approved. > > anyway, hope to see some of you in class later this month!! > > -wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall PTR, =A9 2001 http://starship.python.net/crew/wesc/cpp/ wesley.j.chun :: wesc@deirdre.org cyberweb.consulting :: silicon valley, ca && las vegas, nv http://www.dnai.com/~wesc/cyberweb/ From urnerk@qwest.net Wed Jan 23 07:48:40 2002 From: urnerk@qwest.net (Kirby Urner) Date: Tue, 22 Jan 2002 23:48:40 -0800 Subject: [Tutor] open files other than text? In-Reply-To: <28438-3C4E3E38-4976@storefull-168.iap.bryant.webtv.net> Message-ID: <4.2.0.58.20020122230655.01a06340@pop3.norton.antivirus> At 11:38 PM 1/22/2002 -0500, Ron wrote: >I have windows 98 Python2.2. Can you open files other than text files. I >tried to open a .doc file and just got a line of giberish. What kind of >things can be opened? Python will open any file, but the question is what do you do with it then? You need to poke around in the standard library, or download additional modules, that let you mess with file formats of various kinds. For example, a random search on google brought me to http://www.dotfunk.com/projects/mp3 as a place to grab a module for looking the mp3 (sound) file headers. I just tested it in the shell: >>> mp3.mp3info(r"d:/music/my music/Brian Eno and David Byrne - My Life in the Bush of Ghosts - 01 - America Is Waiting.mp3") {'SS': 37, 'STEREO': 1, 'VERSION': 1, 'MODE': 1, 'COPYRIGHT': 1, 'MM': 3, 'FREQUENCY': 44100, 'BITRATE': 128, 'LAYER': 3} You see it returns a dictionary with lots of info about the file. So you could use this in a program. Fredrik Lundh's Python Imaging Library (PIL) is where you'll find all kinds of modules for dealing with graphics files, like GIFs and JPEGs. If you're using Python 2.2, the relevant PIL is at http://www.pythonware.com/downloads/index.htm#pil Python Imaging Library 1.1.2 for Python 2.2b1 (Windows only) With it, you can do things like: >>> import PIL >>> help(PIL) >>> from PIL import JpegImagePlugin >>> help(JpegImagePlugin) >>> from JpegImagePlugin import JpegImageFile >>> ojpeg = JpegImageFile(r"E:\INTERNET\DOWNLOAD\worldgame.jpg") >>> ojpeg.histogram() [619, 248, 240, 278, 298, 264, 273, 227, 208... But when I try to go ojpeg.show(), Windows fusses that the invoked program wants to run in DOS real mode, which isn't supported in Windows. If I do the same in the DOS shell, however, I'm able to view the image (Python boots some native viewer). PIL would let me rotate, crop, and otherwise mess with this jpeg, all programmatically. I could write a Python program to convert an entire directory of pictures to thumbnails or something like that. Hope this gives you some idea of what's involved in exploring other kinds of files. Thousands of hours go into packages like PIL, because image files are complicated. So best to take advantage of what these experts have made available. Kirby From wheelege@hotmail.com Wed Jan 23 13:45:33 2002 From: wheelege@hotmail.com (Glen Wheeler) Date: Thu, 24 Jan 2002 00:45:33 +1100 Subject: [Tutor] List comprehension References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C2CD@mbtlipnt02.btlabs.bt.co.uk> <5104D4DBC598D211B5FE0000F8FE7EB20E66C2CD@mbtlipnt02.btlabs.bt.co.uk> <20020122150533.B913@speakeasy.net> <4.2.0.58.20020122123339.019d3100@pop3.norton.antivirus> <20020122181740.A9696@speakeasy.net> Message-ID: > > [for a in listb: expr(a)] > > > > which would also be expressive. > > This was my point. > > Python goes through great pains of saying that statements cannot > be used in expressions; assignment being the largest 'pain' for many > coming to Python. > > But here come list comprehession where you can now the syntax and > semantics similar to 'for' and 'if' statements, with the keywords, > inside an expression. > Just for the record, I also think that list comprehensions confuse many people with their contradictory nature. I personally quite enjoy using map, reduce and filter but list comprehensions seem to go against the nature of python. My 2c, Glen From AMoore4437@aol.com Wed Jan 23 14:05:00 2002 From: AMoore4437@aol.com (AMoore4437@aol.com) Date: Wed, 23 Jan 2002 09:05:00 EST Subject: [Tutor] tutorial Message-ID: <8e.21bb1469.29801d0c@aol.com> --part1_8e.21bb1469.29801d0c_boundary Content-Type: text/plain; charset="US-ASCII" Content-Transfer-Encoding: 7bit hello, i have just started to learn python (i haven't got very far with this tutorial) http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro i have tried to do the first few commands but have come unstuck (see below) >>> print "hello world" hello world >>> print "Here are the ten numbers from 0 to 9" Here are the ten numbers from 0 to 9 >>> for 1 in range(10): print 1, SyntaxError: can't assign to literal >>> what am i doing wrong?? i am running python 2.2 on wndows 95 thank you tony more --part1_8e.21bb1469.29801d0c_boundary Content-Type: text/html; charset="US-ASCII" Content-Transfer-Encoding: 7bit
hello,
i have just started to learn python (i haven't got very far with this tutorial)

http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro

i have tried to do the first few commands but have come unstuck (see below)

>>> print "hello world"
hello world
>>> print "Here are the ten numbers from 0 to 9"
Here are the ten numbers from 0 to 9
>>> for 1 in range(10):
   print 1,
   
SyntaxError: can't assign to literal
>>>

what am i doing wrong??

i am running python 2.2 on wndows 95



thank you
tony more
--part1_8e.21bb1469.29801d0c_boundary-- From scarblac@pino.selwerd.nl Wed Jan 23 14:09:34 2002 From: scarblac@pino.selwerd.nl (Remco Gerlich) Date: Wed, 23 Jan 2002 15:09:34 +0100 Subject: [Tutor] tutorial In-Reply-To: <8e.21bb1469.29801d0c@aol.com>; from AMoore4437@aol.com on Wed, Jan 23, 2002 at 09:05:00AM -0500 References: <8e.21bb1469.29801d0c@aol.com> Message-ID: <20020123150934.A3620@pino.selwerd.nl> On 0, AMoore4437@aol.com wrote: > i have tried to do the first few commands but have come unstuck (see below) > > >>> print "hello world" > hello world > >>> print "Here are the ten numbers from 0 to 9" > Here are the ten numbers from 0 to 9 > >>> for 1 in range(10): > print 1, > > SyntaxError: can't assign to literal > >>> > > what am i doing wrong?? Instead of 'for 1 in', it has to be 'for i in'. The character i (or another letter, but it was probably i in the tutorial), not the number 1. Similary, the print command should read "print i," I don't know that particular tutorial, but I assume that it already explains what is actually happening here, so I won't. -- Remco Gerlich From boud@valdyas.org Wed Jan 23 14:13:18 2002 From: boud@valdyas.org (Boudewijn Rempt) Date: Wed, 23 Jan 2002 15:13:18 +0100 (CET) Subject: [Tutor] tutorial In-Reply-To: <8e.21bb1469.29801d0c@aol.com> Message-ID: On Wed, 23 Jan 2002 AMoore4437@aol.com wrote: > >>> print "Here are the ten numbers from 0 to 9" > Here are the ten numbers from 0 to 9 > >>> for 1 in range(10): > print 1, > > SyntaxError: can't assign to literal > The range command produces a series of numbers, and tries to assign them to the variable following the keyword 'for'. It has to be a variable, because you can't assign something to anything that can't change -- like 1. 1 will always be 1, and you can never change it, and neither can 'range'. Now if you use _i_ instead of _1_, you'll have created a variable that can take any value, including the numbers 0 to 9. Boudewijn Rempt | http://www.valdyas.org From slime@vsnl.net Wed Jan 23 14:27:58 2002 From: slime@vsnl.net (Prahlad Vaidyanathan) Date: Wed, 23 Jan 2002 14:27:58 GMT Subject: [Tutor] Re: POP3 Help In-Reply-To: <20020121.163255.-235547.5.kjphotog@juno.com> References: <20020121.163255.-235547.5.kjphotog@juno.com> Message-ID: <20020123043030.GA4451@marvin.clone> Hi, On Mon, 21 Jan 2002 kjphotog@juno.com spewed into the ether: [-- snip --] > How do I decode my messages to read them? You might want to take a look at getmail : http://www.qcc.sk.ca/~charlesc/software/ pv. -- Prahlad Vaidyanathan Every word is like an unnecessary stain on silence and nothingness. -- Beckett From marcolinux@linuxbr.com.br Wed Jan 23 14:48:08 2002 From: marcolinux@linuxbr.com.br (Marco A. Sousa) Date: Wed, 23 Jan 2002 12:48:08 -0200 Subject: [Tutor] List comprehension In-Reply-To: <4.2.0.58.20020122123339.019d3100@pop3.norton.antivirus> References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C2CD@mbtlipnt02.btlabs.bt.co.uk> <5104D4DBC598D211B5FE0000F8FE7EB20E66C2CD@mbtlipnt02.btlabs.bt.co.uk> <4.2.0.58.20020122123339.019d3100@pop3.norton.antivirus> Message-ID: <20020123124807.A3592@marcolab.proconet> Kirby Urner (urnerk@qwest.net) wrote: > > >>> [x*x for x in [1,2,3,4,5]] > [1, 4, 9, 16, 25] Based on this example I started to play with list comprehension and make a "filter": >>> [x*x for x in [1,2,3,4,5] if x*x <= 15] [1, 4, 9] Then I changed the equation: >>> [2*x*x for x in [1,2,3,4,5] if 2*x*x <= 15] [2, 8] It works, but is hard to change the equation in two places. Furtermore I think it's inefficient since the equation is evaluated twice. Or not ? How can I make it more elegant? Thanks in advance and thanks for all that answered my previous question on removing itens from a list. -- Buy a copy of a baby naming book and you'll never be at a loss for variable names. - How To Write Unmaintainable Code From arcege@speakeasy.net Wed Jan 23 15:40:27 2002 From: arcege@speakeasy.net (Michael P. Reilly) Date: Wed, 23 Jan 2002 10:40:27 -0500 Subject: [Tutor] List comprehension In-Reply-To: <20020123124807.A3592@marcolab.proconet>; from marcolinux@linuxbr.com.br on Wed, Jan 23, 2002 at 12:48:08PM -0200 References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C2CD@mbtlipnt02.btlabs.bt.co.uk> <5104D4DBC598D211B5FE0000F8FE7EB20E66C2CD@mbtlipnt02.btlabs.bt.co.uk> <4.2.0.58.20020122123339.019d3100@pop3.norton.antivirus> <20020123124807.A3592@marcolab.proconet> Message-ID: <20020123104027.H913@speakeasy.net> On Wed, Jan 23, 2002 at 12:48:08PM -0200, Marco A. Sousa wrote: > Kirby Urner (urnerk@qwest.net) wrote: > > >>> [x*x for x in [1,2,3,4,5]] > > [1, 4, 9, 16, 25] > > Based on this example I started to play with list comprehension and make > a "filter": > >>> [x*x for x in [1,2,3,4,5] if x*x <= 15] > [1, 4, 9] > > Then I changed the equation: > >>> [2*x*x for x in [1,2,3,4,5] if 2*x*x <= 15] > [2, 8] > > It works, but is hard to change the equation in two places. Furtermore I > think it's inefficient since the equation is evaluated twice. Or not ? > How can I make it more elegant? Using solely list comprehensions, how about: >>> [x for x in [2*x*x for x in range(1, 6)] if x <= 15] [2, 8] >>> -Arcege From KellyPhe@logica.com Wed Jan 23 16:59:52 2002 From: KellyPhe@logica.com (Kelly, Phelim) Date: Wed, 23 Jan 2002 16:59:52 -0000 Subject: [Tutor] Variables in os.system() Message-ID: Hello, At the moment I'm using the os.system() functionality in a python program to output a command to the command line as follows: os.system(""+variable) The variable is pre-defined and is appended to the text in . I need to be able to add another variable, but have it in the middle of the , not just at the end, something like.... os.system(""+variable1""+variable2) Can't figure out a way to do it!! Hope you can help, Thanks & regards Phelim. This e-mail and any attachment is for authorised use by the intended recipient(s) only. It may contain proprietary material, confidential information and/or be subject to legal privilege. It should not be copied, disclosed to, retained or used by, any other party. If you are not an intended recipient then please promptly delete this e-mail and any attachment and all copies and inform the sender. Thank you. From jeff@ccvcorp.com Wed Jan 23 17:53:28 2002 From: jeff@ccvcorp.com (Jeff Shannon) Date: Wed, 23 Jan 2002 09:53:28 -0800 Subject: [Tutor] List comprehension References: Message-ID: <3C4EF898.5E236E2F@ccvcorp.com> > "Glen Wheeler" wrote: > > > Python goes through great pains of saying that statements cannot > > be used in expressions; assignment being the largest 'pain' for many > > coming to Python. > > > > But here come list comprehession where you can now the syntax and > > semantics similar to 'for' and 'if' statements, with the keywords, > > inside an expression. > > > > Just for the record, I also think that list comprehensions confuse many > people with their contradictory nature. I personally quite enjoy using map, > reduce and filter but list comprehensions seem to go against the nature of > python. FWIW, my personal experience is exactly the opposite. List comprehensions may be exceptions to some of the normal rules of Python syntax, but I can look at them and figure out what they mean--they are close enough to English to be able to reason out. Map and filter are fine by themselves, but they pretty much require using lambdas, and I have *never* been able to wrap my mind around lambda syntax--my brain consistently core-dumps as soon as I run into one. ;) In this case, I prefer something that's inconsistent but somewhat intuitive, to something that's somewhat consistent but is totally counterintuitive. (And I'm sure that someone will argue that lambdas aren't counterintuitive, but that's how I, and apparently more than a few others, have always found them.) Jeff Shannon Technician/Programmer Credit International From jeff@ccvcorp.com Wed Jan 23 18:05:14 2002 From: jeff@ccvcorp.com (Jeff Shannon) Date: Wed, 23 Jan 2002 10:05:14 -0800 Subject: [Tutor] List comprehension References: Message-ID: <3C4EFB5A.EAEEE365@ccvcorp.com> > "Michael P. Reilly" wrote: > > > Based on this example I started to play with list comprehension and make > > a "filter": > > >>> [x*x for x in [1,2,3,4,5] if x*x <= 15] > > [1, 4, 9] > > > > Then I changed the equation: > > >>> [2*x*x for x in [1,2,3,4,5] if 2*x*x <= 15] > > [2, 8] > > > > It works, but is hard to change the equation in two places. Furtermore I > > think it's inefficient since the equation is evaluated twice. Or not ? > > How can I make it more elegant? > > Using solely list comprehensions, how about: > > >>> [x for x in [2*x*x for x in range(1, 6)] if x <= 15] > [2, 8] > >>> List comprehensions do some less-than-obvious things with local variables, though, so just on principle I'd recommend against re-using the variable name. It might not make a difference in this case, but it might in some other... plus, I think it's a little more readable anyhow--makes it a little more clear which list-comp the various subexpressions apply to. [x for x in [2*y*y for y in range(1,6)] if x <= 15] Jeff Shannon Technician/Programmer Credit International From urnerk@qwest.net Wed Jan 23 18:10:07 2002 From: urnerk@qwest.net (Kirby Urner) Date: Wed, 23 Jan 2002 10:10:07 -0800 Subject: [Tutor] List comprehension In-Reply-To: <3C4EF898.5E236E2F@ccvcorp.com> References: Message-ID: <4.2.0.58.20020123100727.03975960@pop3.norton.antivirus> > >(And I'm sure that someone will argue that lambdas aren't >counterintuitive, but that's how I, and apparently more >than a few others, have always found them.) > >Jeff Shannon >Technician/Programmer >Credit International Well, they don't have to be mutually exclusive (lambdas and list comprehensions). Just for fun: >>> [apply(eval(x),(y,)) for x in \ ["lambda x: x*x","lambda x: x*x*x"] \ for y in [1,2,3]] [1, 4, 9, 1, 8, 27] (groan) Kirby From scarblac@pino.selwerd.nl Wed Jan 23 18:18:44 2002 From: scarblac@pino.selwerd.nl (Remco Gerlich) Date: Wed, 23 Jan 2002 19:18:44 +0100 Subject: [Tutor] List comprehension In-Reply-To: <4.2.0.58.20020123100727.03975960@pop3.norton.antivirus>; from urnerk@qwest.net on Wed, Jan 23, 2002 at 10:10:07AM -0800 References: <3C4EF898.5E236E2F@ccvcorp.com> <4.2.0.58.20020123100727.03975960@pop3.norton.antivirus> Message-ID: <20020123191844.A4011@pino.selwerd.nl> On 0, Kirby Urner wrote: > Well, they don't have to be mutually exclusive (lambdas and > list comprehensions). Well, no. > Just for fun: > > >>> [apply(eval(x),(y,)) for x in \ > ["lambda x: x*x","lambda x: x*x*x"] \ > for y in [1,2,3]] > > [1, 4, 9, 1, 8, 27] > > (groan) But, EEK! Why did you need the eval there?? [x(y) for x in [lambda x:x*x, lambda x:x*x*x] for y in [1,2,3]] works fine as well. -- Remco Gerlich From urnerk@qwest.net Wed Jan 23 18:30:18 2002 From: urnerk@qwest.net (Kirby Urner) Date: Wed, 23 Jan 2002 10:30:18 -0800 Subject: [Tutor] List comprehension In-Reply-To: <20020123191844.A4011@pino.selwerd.nl> References: <4.2.0.58.20020123100727.03975960@pop3.norton.antivirus> <3C4EF898.5E236E2F@ccvcorp.com> <4.2.0.58.20020123100727.03975960@pop3.norton.antivirus> Message-ID: <4.2.0.58.20020123102822.00c5cc60@pop3.norton.antivirus> > >But, EEK! Why did you need the eval there?? > >[x(y) for x in [lambda x:x*x, lambda x:x*x*x] for y in [1,2,3]] > >works fine as well. Good point! I was being unnecessarily obscure. Along same lines, we can iterate over predefined functions (in place of lambdas): >>> def f(x): return x*x >>> def g(x): return x*x*x >>> [k(x) for k in [f,g] for x in [1,2,3,4]] [1, 4, 9, 16, 1, 8, 27, 64] Kirby From polb@cableinet.co.uk Wed Jan 23 08:48:57 2002 From: polb@cableinet.co.uk (paul) Date: Wed, 23 Jan 2002 08:48:57 -0000 Subject: [Tutor] exceptional behaviour Message-ID: Hello list, I've been looking at exceptions (using a gauld's fine book) with python2.1, but the examples wouldn't work until I removed the space from the raise string eg def div42(): denominator=input("What value will I divide 42 by?\n") if denominator == 0: raise "firstproblem" elif denominator == 1: raise "secondproblem" else: print 42/denominator works fine but def div42(): denominator=input("What value will I divide 42 by?\n") if denominator == 0: raise "first problem" elif denominator == 1: raise "second problem" else: print 42/denominator doesn't Is this a known bug or am I missing something? I can't see anything on Sourceforge and I would of thought this kind of error would jump out early, so I suspect the latter. cheers Paul Butler From dyoo@hkn.eecs.berkeley.edu Wed Jan 23 18:45:10 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 23 Jan 2002 10:45:10 -0800 (PST) Subject: [Tutor] tutorial In-Reply-To: <20020123150934.A3620@pino.selwerd.nl> Message-ID: On Wed, 23 Jan 2002, Remco Gerlich wrote: > > >>> print "hello world" > > hello world > > >>> print "Here are the ten numbers from 0 to 9" > > Here are the ten numbers from 0 to 9 > > >>> for 1 in range(10): > > print 1, > > > > SyntaxError: can't assign to literal > > >>> > > > > what am i doing wrong?? > > Instead of 'for 1 in', it has to be 'for i in'. The character i (or > another letter, but it was probably i in the tutorial), not the number > 1. > > Similary, the print command should read "print i," I'll see if I have the time to change the tutorial at: http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro to use the variable name 'number' instead of the visually confusing 'i'. From urnerk@qwest.net Wed Jan 23 19:00:55 2002 From: urnerk@qwest.net (Kirby Urner) Date: Wed, 23 Jan 2002 11:00:55 -0800 Subject: [Tutor] exceptional behaviour In-Reply-To: Message-ID: <4.2.0.58.20020123110005.0397e290@pop3.norton.antivirus> > >def div42(): > denominator=input("What value will I divide 42 by?\n") > if denominator == 0: > raise "first problem" > elif denominator == 1: > raise "second problem" > else: > print 42/denominator > >doesn't What error message to you get for the 2nd example? Seems to work fine in 2.2: >>> div42() What value will I divide 42 by? 0 Traceback (most recent call last): File "", line 1, in ? div42() File "", line 4, in div42 raise "first problem" first problem Kirby From AMoore4437@aol.com Wed Jan 23 22:02:44 2002 From: AMoore4437@aol.com (AMoore4437@aol.com) Date: Wed, 23 Jan 2002 17:02:44 EST Subject: [Tutor] me again Message-ID: <132.7e18617.29808d04@aol.com> --part1_132.7e18617.29808d04_boundary Content-Type: text/plain; charset="US-ASCII" Content-Transfer-Encoding: 7bit hello it's me again, i keep running into problems (is it me??) i have followed a tutorial step by step http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/ and have saved my work as directed to do so from the 'program window' when i try to save it offers me 'python 22' but i have saved it to 'C drive' as is shown in the tutorial. when i try to reopen my work in the way described in the tutorial my saved work does not come up automatically (as shown) the only place i can find it is on my 'C drive' by going through 'my computer' then when i try to open it through there i am asked what program would i like to run to open it. is this correct ? i hope i'm making sense tony moore --part1_132.7e18617.29808d04_boundary Content-Type: text/html; charset="US-ASCII" Content-Transfer-Encoding: 7bit hello it's me again,
i keep running into problems (is it me??)

i have followed a tutorial step by step

http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/

and have saved my work as directed to do so from the 'program window'
when i try to save it offers me 'python 22'
but i have saved it to 'C drive' as is shown in the tutorial.

when i try to reopen  my work
in the way described in the tutorial  my saved work does not come up automatically (as shown)

the only place i can find it is on my 'C drive' by going through 'my computer'
then when i try to open it through there
i am asked what program would i like to run to open it.
is this correct ?

i hope i'm making sense

tony moore
--part1_132.7e18617.29808d04_boundary-- From dyoo@hkn.eecs.berkeley.edu Wed Jan 23 22:10:31 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 23 Jan 2002 14:10:31 -0800 (PST) Subject: [Tutor] Variables in os.system() [string formatting] In-Reply-To: Message-ID: On Wed, 23 Jan 2002, Kelly, Phelim wrote: > At the moment I'm using the os.system() functionality in a > python program to output a command to the command line as follows: > > os.system(""+variable) > > The variable is pre-defined and is appended to the text in . > > I need to be able to add another variable, but have it in the middle > of the , not just at the end, something like.... > > os.system(""+variable1""+variable2) Hi Kelly, String concatenation is a good approach; I believe this should work. However, we need to be careful here: > os.system(""+variable1""+variable2) ^^^ The code here is missing a plus sign between the 'variable1' variable and the rest of the string, so you may get a SyntaxError out of this. Another thing that might bite us is that string concatenation between two things works only if both are strings: ### >>> "hello" + "world" 'helloworld' >>> "the magic number is " + 42 Traceback (most recent call last): File "", line 1, in ? TypeError: cannot add type "int" to string >>> "the magic number is " + str(42) 'the magic number is 42' ### The last example shows that we can bend 42 into a string, and that'll allow the concatenation to work. Another approach is to use string formatting to fill in the blanks: ### cmd = "%(var1)s%(var2)s" cmd = cmd % { 'var1' : variable1, 'var2' : variable2 } ### The important parts about string formatting is the "%(var1)s" and "%(var2)s" stuff. These are called "format strings", and when we use the string formatting operator '%', Python will substitute the format string with the values we want. Think Madlibs, and you'll get the general idea. Here's an example of string formatting in the interpreter: ### >>> "%(person)s is working on a program" % { 'person' : 'tidus' } 'tidus is working on a program' >>> '%(person1)s and %(person2)s %(verbed)s' % { 'person1': 'rikku', ... 'person2': 'auron', ... 'verbed': 'laughed' } 'rikku and auron laughed' ### String formatting is often nicer than doing a bunch of string concatenations, because it allows us to separate the form of the output from the particular values we're plugging. (It's also a bit more efficient for the computer.) String formatting is especially useful when we're doing things like templated forms or HTML generation. There's some examples of it in action in the Python tutorial. You might want to take a look at the "Fancier Output Formatting" chapter for more information: http://www.python.org/doc/tut/node9.html#SECTION009100000000000000000 and most Python tutorials should cover this topic since it is very useful. Can you give us a concrete example of a command in this form? That may help us tailor a useful example that uses string formatting. From urnerk@qwest.net Wed Jan 23 22:24:21 2002 From: urnerk@qwest.net (Kirby Urner) Date: Wed, 23 Jan 2002 14:24:21 -0800 Subject: [Tutor] Polynomial class (a beginning) In-Reply-To: <4.2.0.58.20020123110005.0397e290@pop3.norton.antivirus> References: Message-ID: <4.2.0.58.20020123142159.01726bf0@pop3.norton.antivirus> >>> class Poly: def __init__(self,coeffs): self.coeffs = coeffs self.degree = len(self.coeffs)-1 def __repr__(self): outstr = "" terms = ["+(("+str(self.coeffs[k])+")*x**"+str(self.degree-k)+")" \ for k in range(len(self.coeffs)) \ if self.coeffs[k]<>0] outstr = reduce(add,terms) return outstr def __call__(self,val): return apply(eval("lambda x:" + self.__repr__()), (val,)) >>> p = Poly([1,2,3]) # enter coefficients of x powers >>> p # get back a string representation (kinda messy) +((1)*x**2)+((2)*x**1)+((3)*x**0) >>> p(3) # the string may be evaluated for x = number 18 Possible next methods: Add two polynomials to get a polynomial Multiply two polynomials, making some use of already-defined add Kirby From dyoo@hkn.eecs.berkeley.edu Thu Jan 24 00:15:13 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 23 Jan 2002 16:15:13 -0800 (PST) Subject: [Tutor] Polynomial class (a beginning) In-Reply-To: <4.2.0.58.20020123142159.01726bf0@pop3.norton.antivirus> Message-ID: On Wed, 23 Jan 2002, Kirby Urner wrote: > >>> class Poly: > def __init__(self,coeffs): > self.coeffs = coeffs > self.degree = len(self.coeffs)-1 > def __repr__(self): > outstr = "" > terms = ["+(("+str(self.coeffs[k])+")*x**"+str(self.degree-k)+")" \ > for k in range(len(self.coeffs)) \ > if self.coeffs[k]<>0] > outstr = reduce(add,terms) > return outstr > def __call__(self,val): > return apply(eval("lambda x:" + self.__repr__()), (val,)) > > > >>> p = Poly([1,2,3]) # enter coefficients of x powers > >>> p # get back a string representation (kinda messy) > +((1)*x**2)+((2)*x**1)+((3)*x**0) > >>> p(3) # the string may be evaluated for x = number > 18 It might be nicer to sort the polynomials by ascending degree --- that is, to represent something like: x^2 + 2x^1 + 3x^0 we can use the list: [3, 2, 1] It might seem... backwards, but it's actually quite useful. I remember seeing this representation of polynomials in Jeffrey Ullmans "Fundamentals of ML Programming", and I thought it was a great demonstration of how data representation can make a difference. One reason this is a convenient representation is because finding the sum of two polynomials becomes pretty easy: we just add corresponding terms up! ### def add(self, other): """Adds two polynomials together, assuming the coeffs are ordered by ascending degree.""" sum_terms = [0] * max(len(self.coeffs), len(other.coeffs)) for i in range(len(self.coeffs)): sum_terms[i] = self.coeffs[i] for i in range(len(other.coeffs)): sum_terms[i] = sum_terms[i] + other.coeffs[i] return Poly(sum_terms) ### (Warning: I haven't tested this code yet. I'm just typing this from memory.) Multiplication, too, can become a much simpler operation if we order the coefficients this way. Let's have someone take a stab at that one. *grin* Talk to you later! From grimm.tooth@verizon.net Thu Jan 24 00:14:35 2002 From: grimm.tooth@verizon.net (Jeff Grimmett) Date: Wed, 23 Jan 2002 19:14:35 -0500 Subject: [Tutor] Sanity check -- making packages Message-ID: I am beating my head against the wall with regards to packages, desperately need a sanity check here. In my project directory I have TestPackage/ (dir) setup.py test.py (a program to test the package's features) In the package directory I have: __init__.py Module1.py Module2.py Setup.py looks like this: ################################## from distutils.core import setup setup ( name = "TestPackage", version = "1.0", url = 'http://www.python.org', # Just kidding author = 'Jeff Grimmett', packages = ["TestPackage"] ) ################################## __init__.py looks like this: ################################## __version__ = "1.0" __all__ = ['Module1', 'Module2', ] ################################## Now, if I understand the documentation aright, I *should* be able to run Python Setup.py Install for the install, then I can use the package in any module like this: from TestPackage import * At least, in theory, that is how I thought it worked. Is this right? I am having a few problems in easilly accessing classes defined within the modules, and am wondering if there's a crucial step I have missed. At any rate, the desired capability is to be able to access any classes within the two modules transparently -- i.e. not have to do: from testpackage.Module1 import * or anything like that. Any comments links or pointers are appreciated. From urnerk@qwest.net Thu Jan 24 00:45:49 2002 From: urnerk@qwest.net (Kirby Urner) Date: Wed, 23 Jan 2002 16:45:49 -0800 Subject: [Tutor] Sanity check -- making packages In-Reply-To: Message-ID: <4.2.0.58.20020123163026.0172e570@pop3.norton.antivirus> At 07:14 PM 1/23/2002 -0500, Jeff Grimmett wrote: >I am beating my head against the wall with regards to packages, desperately >need a sanity check here. <> >Any comments links or pointers are appreciated. > I think you should separate the two challenges: (1) getting a package to work on your own box and (2) packaging it up for distribution via disutils. Regarding (1), the purpose of __init__.py in the package subdirectory is to do the importing of what you want your public (or yourself) to see of your package. For example, I have a subdirectory called mathobjects under which I have such .py files as polynomial.py simplematrix.py and fraction.py. My __init__.py looks like this: ==== """ By K. Urner Last modified: May 20, 2001 """ from simplematrix import Matrix, Sqmatrix from pyfraction import Fraction from polynomial import Poly, deriv ==== So say I'm in the shell, having just booted Python, and I go: >>> dir() ['__builtins__', '__doc__', '__name__'] OK, the basics. Clean slate. Now I go: >>> from mathobjects import * And check my namespace: >>> dir() ['Fraction', 'Matrix', 'Poly', 'Sqmatrix', '__builtins__', '__doc__', '__name__', 'deriv', 'polynomial', 'pyfraction', 'simplematrix'] Aha, so the things I imported in __init__.py have now become top level. So in the shell, I can now use Poly directly: >>> p = Poly([1,2,3,4,5]) # fancier version than on tutor list >>> p x**4 + 2*x**3 + 3*x**2 + 4*x + 5 Regarding (2), using dsutils, that's a different challenge. There, you want to create setup.py in a directory just above the package subdir, which will look something like: #!/usr/bin/env python from distutils.core import setup setup(name="mathobjects", version="1.1", description="Math Objects: Fraction, Matrix, Polynomial", author="Kirby Urner", author_email="urnerk@qwest.net", url="http://www.intearena.com/~pdx4d/ocn/", packages=['mathobjects'], ) Then the command: python setup.py sdist should create a .zip file (the default on Windows -- check docs for other params). If your end user then goes: python setup.py install from within the unzipped zip, the package will be installed. Kirby From urnerk@qwest.net Thu Jan 24 01:03:24 2002 From: urnerk@qwest.net (Kirby Urner) Date: Wed, 23 Jan 2002 17:03:24 -0800 Subject: [Tutor] Polynomial class (a beginning) In-Reply-To: References: <4.2.0.58.20020123142159.01726bf0@pop3.norton.antivirus> Message-ID: <4.2.0.58.20020123162500.01726e40@pop3.norton.antivirus> > >It might be nicer to sort the polynomials by ascending degree --- that >is, to represent something like: > > x^2 + 2x^1 + 3x^0 > >we can use the list: > > [3, 2, 1] Yes, I think this is good advice. I wonder if it'd be OK to let the user enter [1,2,3] but then internally store the reverse. Also, whereas I think it was kinda clever to evaluate the string form of a poly to get its value at a variable (which may be done more easily than the lambda way I showed, using exec to assign x=val), it's also slower and more cumbersome than just evaluating against the coefficients. So.... incorporating your suggestion, and a very slightly reworked version of your __add__ method (which worked right the first time -- but I'm unreversing the reversed coefficients), I provide a 2nd draft of Poly: from operator import add class Poly: def __init__(self,coeffs): self.degree = len(coeffs)-1 self.rep = self.__str(coeffs) coeffs.reverse() self.coeffs = coeffs def __str(self,coeffs): terms = [" + ("+str(coeffs[k])+"*x**" + \ str(self.degree-k)+")" \ for k in range(len(coeffs)) \ if coeffs[k]<>0] return reduce(add,terms) def __repr__(self): return self.rep def __call__(self,val): sum = 0 return reduce(add,[self.coeffs[i]*val**i \ for i in range(len(self.coeffs))]) def __add__(self,other): """Adds two polynomials together, assuming the coeffs are ordered by ascending degree.""" sum_terms = [0] * max(len(self.coeffs), len(other.coeffs)) for i in range(len(self.coeffs)): sum_terms[i] = self.coeffs[i] for i in range(len(other.coeffs)): sum_terms[i] = sum_terms[i] + other.coeffs[i] sum_terms.reverse() return Poly(sum_terms) Usage: >>> reload(poly) >>> p = poly.Poly([1,2,3]) >>> q = poly.Poly([3,1,2,3]) >>> p + (1*x**2) + (2*x**1) + (3*x**0) >>> q + (3*x**3) + (1*x**2) + (2*x**1) + (3*x**0) >>> r = p+q >>> r + (3*x**3) + (2*x**2) + (4*x**1) + (6*x**0) >>> r(3) 117 Cool. Kirby From karthikg@aztec.soft.net Thu Jan 24 02:18:43 2002 From: karthikg@aztec.soft.net (Karthik Gurumurthy) Date: Thu, 24 Jan 2002 07:48:43 +0530 Subject: [Tutor] exceptional behaviour In-Reply-To: Message-ID: >def div42(): > denominator=input("What value will I divide 42 by?\n") if denominator == 0: raise "first problem" elif denominator == 1: raise "second problem" else: > print 42/denominator >examples wouldn't work until I removed the >space from the raise string i tried on python2.1 and it's working fine. what is the error you are getting? try a simpler one.. def func(): raise "hello world" func() karthik. From e.kotyk@shaw.ca Thu Jan 24 02:07:37 2002 From: e.kotyk@shaw.ca (Eve Kotyk) Date: Thu, 24 Jan 2002 02:07:37 +0000 Subject: [Tutor] Need help with dict.calculation References: <3C482912.382FAC24@shaw.ca> <001901c1a0d6$31c51690$da00a8c0@Sun> Message-ID: <3C4F6C69.CA28E42@shaw.ca> Hi Andy..and the rest of you. Thank you for your suggestions. > # > def gather_data(): > items = raw_input("Add food item: ") > portion = input("Enter number of portions: ") > cal_portion = input("Enter calories per portion: ") > return items,portion,cal_portion > > def get_total_calories(): > print "Enter all foods you have eaten today." > > more="" > while more!="n": > items,portion,cal_portion = gather_data() > total_calories[items]=portion * cal_portion > more = raw_input("Do you want to continue? y/n: ") > > for i in total_calories.values(): > total = total + i > print "Total calories: ",total This part still doesn't work for me. I get the following error: Traceback (innermost last): File "bmi2.py", line 47, in ? get_total_calories() File "bmi2.py", line 33, in get_total_calories total_calories [items] = portion * cal_portion NameError: total_calories > # > > As a side note, you don't even need to put it in a dictionary, you can just > have a running total in an integer variable. > I said I wouldn't make drastic changes though :o) Andy I appreciate your not making drastic changes because this is a learning project. But now that I understand dictionaries just a bit better (and I still haven't figured out how to add up the subtotals for each item in a total overall). I'd really appreciate a lesson how to have a running total in an integer variable. E > > Andy > > > > > def food_add(): > > print "Enter all foods you have eaten today." > > > > items = raw_input("Add Food Item: ") > > portion = input("Enter number of portions: ") > > cal_portion = input("Enter calories per portion: ") > > > > more = raw_input("Do you wish to continue? y/n: ") > > while more != 'n': > > food_add() > > break > > total_calories[items] = portion * cal_portion > > total = 0 > > for i in total_calories.values(): > > total = total + i > > print "Total calories: ",total > > > > My output is: > > > > Total calories: 120 > > Total calories: 254 > > > > The total calories for each item entered with the last entry first, > > rather than just a Total calories: 374 > > -- > > > > ekotyk > > > > http://members.shaw.ca/e.kotyk/virtualstudio.htm > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > -- ekotyk http://members.shaw.ca/e.kotyk/virtualstudio.htm From dyoo@hkn.eecs.berkeley.edu Thu Jan 24 02:39:22 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 23 Jan 2002 18:39:22 -0800 (PST) Subject: [Tutor] Need help with dict.calculation In-Reply-To: <3C4F6C69.CA28E42@shaw.ca> Message-ID: On Thu, 24 Jan 2002, Eve Kotyk wrote: > > def get_total_calories(): > > print "Enter all foods you have eaten today." > > > > more="" > > while more!="n": > > items,portion,cal_portion = gather_data() > > total_calories[items]=portion * cal_portion > > more = raw_input("Do you want to continue? y/n: ") > > > > for i in total_calories.values(): > > total = total + i > > print "Total calories: ",total > > This part still doesn't work for me. I get the following error: > > Traceback (innermost last): > File "bmi2.py", line 47, in ? > get_total_calories() > File "bmi2.py", line 33, in get_total_calories > total_calories [items] = portion * cal_portion > NameError: total_calories One other thing we'll need to do is define what "total_calories" is --- Python doesn't know that it's a dictionary until we actually initialize one. It's a related idea to setting the 'more' value initially to the empty string. ### def get_total_calories(): print "Enter all foods you have eaten today." more="" total_calories = {} ## <--- here's the change while more != "n": items, portion, cal_portion = gather_data() total_calories[items] = portion * cal_portion more = raw_input("Do you want to continue? y/n: ") for i in total_calories.values(): total = total + i print "Total calories: ", total ### Hope this helps! > > > # > > > > As a side note, you don't even need to put it in a dictionary, you can just > > have a running total in an integer variable. > > I said I wouldn't make drastic changes though :o) > > Andy I appreciate your not making drastic changes because this is a > learning project. But now that I understand dictionaries just a bit > better (and I still haven't figured out how to add up the subtotals for > each item in a total overall). I'd really appreciate a lesson how to > have a running total in an integer variable. > > E > > > > Andy > > > > > > > > def food_add(): > > > print "Enter all foods you have eaten today." > > > > > > items = raw_input("Add Food Item: ") > > > portion = input("Enter number of portions: ") > > > cal_portion = input("Enter calories per portion: ") > > > > > > more = raw_input("Do you wish to continue? y/n: ") > > > while more != 'n': > > > food_add() > > > break > > > total_calories[items] = portion * cal_portion > > > total = 0 > > > for i in total_calories.values(): > > > total = total + i > > > print "Total calories: ",total > > > > > > My output is: > > > > > > Total calories: 120 > > > Total calories: 254 > > > > > > The total calories for each item entered with the last entry first, > > > rather than just a Total calories: 374 > > > -- > > > > > > ekotyk > > > > > > http://members.shaw.ca/e.kotyk/virtualstudio.htm > > > > > > _______________________________________________ > > > Tutor maillist - Tutor@python.org > > > http://mail.python.org/mailman/listinfo/tutor > > > > > From clickron@webtv.net Thu Jan 24 02:58:19 2002 From: clickron@webtv.net (Ron) Date: Wed, 23 Jan 2002 21:58:19 -0500 (EST) Subject: [Tutor] open files other than text? Message-ID: <25258-3C4F784B-909@storefull-165.iap.bryant.webtv.net> Thanks for all the info. I was curious as I'm at the point where I'm learning how to work with files, and was experimenting a little bit. Thanks again Ron From SWidney@ci.las-vegas.nv.us Thu Jan 24 02:56:14 2002 From: SWidney@ci.las-vegas.nv.us (Scott Widney) Date: Wed, 23 Jan 2002 18:56:14 -0800 Subject: [Tutor] facing a new project Message-ID: > ... The thing that seems most difficult is the > 'generating' schedules bit ... No joke! For two years, I scheduled a 1500-seat call center where 85% of the staff were allowed to dictate both the days, and the hours on those days, that they were available to work. It was like assembling a puzzle without any assurance that the pieces would fit together in the end. > If I ever wished to seriously face a new project of this > sort, what is the best way to go about it ? First make a gross > design of the whole thing ( database schema, classes etc. ) > and then start tackling it, or start with small bits of code > like the truck drivers log book and then just try to extend > it bit by bit ? Not that I'm yet really convinced I mean to > do this ... Can I toss a third option in here? Of the scheduling programs that I have seen, most generate a rough schedule, then provide the schedulers with a way to rearrange things to fit their needs more accurately. It really is a puzzle! So the first step is figuring out /how/ our brains do this puzzle thing. I mean, I successfully assembled the pieces each week for 104 weeks, and I taught my replacements how to do the same thing. But I don't know if I could represent the decisions I made in programming code. I never gave a thought as to how I thought, so to speak. I think what I'm trying to suggest is: you need to fully grasp your core paradigm and be able to express it algorithmically, as a first step. Comments anyone? Scott From david@verso.org Thu Jan 24 03:51:24 2002 From: david@verso.org (David Maclagan) Date: Thu, 24 Jan 2002 13:51:24 +1000 Subject: [Tutor] creating variables at runtime Message-ID: <3C50115C.15530.C0BB53@localhost> Is is possible in python to create variables at runtime? What I'm wanting to do is create instances of classes, given names based on user input ie userinput = "NARF" (something done to userinput) = MyClass(), such that NARF will be an instance of MyClass. There would need to be some munging of the input, to prevent the created object from overwriting already existing stuff. Is such a thing possible? Is it Bad and Wrong? I'm a relatively raw newcomer using Py 2.1 under windows David ------- David Maclagan David@verso.org From urnerk@qwest.net Thu Jan 24 04:30:12 2002 From: urnerk@qwest.net (Kirby Urner) Date: Wed, 23 Jan 2002 20:30:12 -0800 Subject: [Tutor] creating variables at runtime In-Reply-To: <3C50115C.15530.C0BB53@localhost> Message-ID: <4.2.0.58.20020123201503.01a4b560@pop3.norton.antivirus> > >Is such a thing possible? Is it Bad and Wrong? > >I'm a relatively raw newcomer using Py 2.1 under windows > > >David You can do it, and many do, but I always advise that it's safer and easier to use a dictionary to hold user-created objects. For example: class Thing: def __init__(self, name): self.myname = name def getuser(): global userobjs while 1: objname = raw_input("Gimme an object (or q to quit) > ") if not objname in ['q','Q']: userobjs[objname] = Thing(objname) else: break In the shell (or from a script): >>> userobjs = {} >>> getuser() Gimme an object (or q to quit) > NARF Gimme an object (or q to quit) > q >>> userobjs {'NARF': <__main__.Thing instance at 0x0113E4F0>} >>> obj = userobjs['NARF'] >>> obj.myname 'NARF' If you user wants to interact with the objects she or he named, then you simply have your code look it up by name in the userobjs dictionary, where they'll all be together. Kirby From urnerk@qwest.net Thu Jan 24 04:41:53 2002 From: urnerk@qwest.net (Kirby Urner) Date: Wed, 23 Jan 2002 20:41:53 -0800 Subject: [Tutor] Sanity check -- making packages In-Reply-To: References: <4.2.0.58.20020123163026.0172e570@pop3.norton.antivirus> Message-ID: <4.2.0.58.20020123203734.01a3d260@pop3.norton.antivirus> > >I'll have to give this a try tommorrow due to the time, but thanks! Sure. disutils is about packaging your package for others to install, or for installing packages by others which were packaged with disutils. But on your own machine, there's no need to see running disutils as a necessary step. That's all about distribution, not local development. As for where to put your packages, anywhere in the Python path is OK. But Python does provide the subdir site-packages, under Lib, as a kind of default place for installed packages to go. Kirby From paulsid@shaw.ca Thu Jan 24 04:58:18 2002 From: paulsid@shaw.ca (Paul Sidorsky) Date: Wed, 23 Jan 2002 21:58:18 -0700 Subject: [Tutor] creating variables at runtime References: <3C50115C.15530.C0BB53@localhost> Message-ID: <3C4F946A.138FD4D1@shaw.ca> David Maclagan wrote: > What I'm wanting to do is create instances of classes, given names > based on user input > > ie > userinput = "NARF" > > (something done to userinput) = MyClass(), such that NARF will be an > instance of MyClass. > Is such a thing possible? This is indeed doable: >>> class MyClass: pass >>> userinput = "NARF" >>> exec(userinput + " = MyClass()") >>> NARF <__main__.MyClass instance at 00B59A8C> >>> > Is it Bad and Wrong? I'm not qualified to comment on the rightness of it, but here's a technical point of view: It sounds like the program will probably need to keep track of all of these names (like NARF) to refer back to them later. Thus there is now have a bunch of names and associated with each name is an instance of a class. Whenever I get a situation like this, I immediately think DICTIONARY! This may be more feasible: >>> instances = {} >>> instances[userinput] = MyClass() >>> instances {'NARF': <__main__.MyClass instance at 00B6172C>} >>> instances["NARF"] <__main__.MyClass instance at 00B6172C> No munging is required either, other than possibly checking if userinput is already in instances.keys() (or just instances in Python 2.2) before storing. Of course I don't know what the intentions are here, so if some special requirement is involved then just ignore this part. -- ====================================================================== Paul Sidorsky Calgary, Canada paulsid@shaw.ca http://members.shaw.ca/paulsid/ From urnerk@qwest.net Thu Jan 24 05:16:00 2002 From: urnerk@qwest.net (Kirby Urner) Date: Wed, 23 Jan 2002 21:16:00 -0800 Subject: [Tutor] creating variables at runtime In-Reply-To: <3C4F946A.138FD4D1@shaw.ca> References: <3C50115C.15530.C0BB53@localhost> Message-ID: <4.2.0.58.20020123211317.00b2ee60@pop3.norton.antivirus> At 09:58 PM 1/23/2002 -0700, Paul Sidorsky wrote: >This is indeed doable: > > >>> class MyClass: pass > > >>> userinput = "NARF" > >>> exec(userinput + " = MyClass()") > >>> NARF ><__main__.MyClass instance at 00B59A8C> > >>> I think if you want to show how to create user-named objects top-level, you should do so from within an input loop using raw_input("prompt"). The way you show above, as a shell interaction, doesn't really address the problem, because you're at top level in the shell already. In this context, it makes no sense to use the exec(), as you can just as well go: >>> NARF = MyClass() and be done with it. How to create top-level user-named objects from within a raw_input() loop is actually a little more difficult. It takes some rather tricky Python. Kirby From paulsid@shaw.ca Thu Jan 24 06:00:45 2002 From: paulsid@shaw.ca (Paul Sidorsky) Date: Wed, 23 Jan 2002 23:00:45 -0700 Subject: [Tutor] creating variables at runtime References: <3C50115C.15530.C0BB53@localhost> <4.2.0.58.20020123211317.00b2ee60@pop3.norton.antivirus> Message-ID: <3C4FA30D.59DE2661@shaw.ca> Kirby Urner wrote: > I think if you want to show how to create user-named > objects top-level, you should do so from within an > input loop using raw_input("prompt"). Well, to me it seemed as though he already knew how to get the input. I was showing how any string could be turned into a variable name. > How to create top-level user-named objects from within > a raw_input() loop is actually a little more difficult. > It takes some rather tricky Python. I may be setting myself up for a big fall here because I have almost no experience with this kind of thing. However, this program seems to work: class C: pass names = [] while 1: i = raw_input("Name: ") if not i: break names.append(i) exec(i + " = C()") for s in names: print s, eval(s) Sample session: Wed 01-23-2002 22:36:56.22, Path: E:\Python21 -- python namevar.py Name: NARF Name: test Name: a Name: b Name: NARF <__main__.C instance at 0079297C> test <__main__.C instance at 007928DC> a <__main__.C instance at 0079286C> b <__main__.C instance at 007927FC> I realize if you need to mix namespaces then things start to get a lot trickier, but for a one-module program the basic concept still seems the same as in the interpreter. Please do correct me if I'm wrong, though! -- ====================================================================== Paul Sidorsky Calgary, Canada paulsid@shaw.ca http://members.shaw.ca/paulsid/ From shalehperry@attbi.com Thu Jan 24 06:32:48 2002 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Wed, 23 Jan 2002 22:32:48 -0800 (PST) Subject: [Tutor] Need help with dict.calculation In-Reply-To: <3C482912.382FAC24@shaw.ca> Message-ID: On 18-Jan-2002 Eve Kotyk wrote: > In the script below I would like to add up the totals for each item into > one final total. So far I haven't come up with anything. Help. > I have been writing a program at work which reads a log and keeps a running count of machine reboots per machine. A nifty way to handle the increment is the get() method of dictionaries. dict[key] = dict.get(key, 0) + 1 OK, so this doesn't help directly, but I thought I would share. Onto the real help. Another useful python function is 'reduce'. reduce takes a list and runs a function on each item in the list plus a running variable. from above I have: import operator count = reduce(operator.add, dict.values()) print "Total reboot count for all machines was " + count What reduce does is more clear if I show you what operator.add looks like: def add(x, y): return x + y so what the reduce function does internally is basically: value = 0 for item in list: value = function(value, item) return value Hope this gives you some glimpses of python's abilities. From urnerk@qwest.net Thu Jan 24 06:34:59 2002 From: urnerk@qwest.net (Kirby Urner) Date: Wed, 23 Jan 2002 22:34:59 -0800 Subject: [Tutor] creating variables at runtime In-Reply-To: <3C4FA30D.59DE2661@shaw.ca> References: <3C50115C.15530.C0BB53@localhost> <4.2.0.58.20020123211317.00b2ee60@pop3.norton.antivirus> Message-ID: <4.2.0.58.20020123222725.00bd5270@pop3.norton.antivirus> > >I may be setting myself up for a big fall here because I have >almost no experience with this kind of thing. However, this >program seems to work: > >class C: > pass > >names = [] Ah, but you're adding his new objects to a list now. Not top level. names is top-level, but the new objects inside are not. How do you add his named objects at the same level as your names variable? >I realize if you need to mix namespaces then things start to get a lot >trickier, but for a one-module program the basic concept still seems the >same as in the interpreter. Please do correct me if I'm wrong, though! You printed the list contents, which isn't that different from adding objects to a dictionary (what I suggested doing). The challenge is to use a raw_input loop to create user-named objects that are not contained inside any list, tuple or map. It's not that you're doing anything wrong. I'm just trying to make clear the distinction between creating new variables at the top level, versus inside a program-provided data structure. Kirby From idiot1@netzero.net Thu Jan 24 06:37:51 2002 From: idiot1@netzero.net (kirk Bailey) Date: Thu, 24 Jan 2002 01:37:51 -0500 Subject: [Tutor] TinyList.org site update Message-ID: <3C4FABBF.E3DB2BF7@netzero.net> Working on version 1.1.0 of TL, and updated website. http://www.tinylist.org/ -- -Respectfully, -Kirk D Bailey Consulting Loose Cannon end www.howlermonkey.net highprimate@howlermonkey.net www.sacredelectron.org idiot1@netzero.net www.tinylist.org grumpy@tinylist.org ---------------------------------------------------- Sign Up for NetZero Platinum Today Only $9.95 per month! http://my.netzero.net/s/signup?r=platinum&refcd=PT97 From toodles@yifan.net Thu Jan 24 06:38:10 2002 From: toodles@yifan.net (Andy W) Date: Thu, 24 Jan 2002 14:38:10 +0800 Subject: [Tutor] Need help with dict.calculation References: <3C482912.382FAC24@shaw.ca> <001901c1a0d6$31c51690$da00a8c0@Sun> <3C4F6C69.CA28E42@shaw.ca> Message-ID: <004f01c1a4a1$b2611000$da00a8c0@Sun> > Hi Andy..and the rest of you. > > Thank you for your suggestions. > > # > > def gather_data(): > > items = raw_input("Add food item: ") > > portion = input("Enter number of portions: ") > > cal_portion = input("Enter calories per portion: ") > > return items,portion,cal_portion > > > > def get_total_calories(): > > print "Enter all foods you have eaten today." > > > > more="" > > while more!="n": > > items,portion,cal_portion = gather_data() > > total_calories[items]=portion * cal_portion > > more = raw_input("Do you want to continue? y/n: ") > > > > for i in total_calories.values(): > > total = total + i > > print "Total calories: ",total > > This part still doesn't work for me. I get the following error: > > Traceback (innermost last): > File "bmi2.py", line 47, in ? > get_total_calories() > File "bmi2.py", line 33, in get_total_calories > total_calories [items] = portion * cal_portion > NameError: total_calories Sorry, I thought you had total_calories defined somewhere else. Danny has already shown the solution to this though. (Look down for the running total approach) > > > # > > > > As a side note, you don't even need to put it in a dictionary, you can just > > have a running total in an integer variable. > > I said I wouldn't make drastic changes though :o) > > Andy I appreciate your not making drastic changes because this is a > learning project. But now that I understand dictionaries just a bit > better (and I still haven't figured out how to add up the subtotals for > each item in a total overall). I'd really appreciate a lesson how to > have a running total in an integer variable. Do you intend to use the contents of the dictionary after you've calculated the total calories? If not, it isn't really necessary to ask what type of food it is, nor even to keep the data in a dictionary. This is all you would need: def gather_data(): portion=input("Enter number of portions: ") cal_portion=input("Enter calories per portion: ") return portion,cal_portion def get_total_calories(): print "Enter all the foods you have eaten today." total_calories=0 #It's now an integer instead of a dictionary, just to hold the number of calories more="" while more!="n": portion,cal_portion=gather_data() total_calories=total_calories+portion*cal_portion more=raw_input("Do you want to continue? y/n: ") print "Total calories: ",total_calories But if you need to know what the names of the foods and such things afterwards... stick to your first approach. HTH, Andy > > E > > > > Andy > > > > > > > > def food_add(): > > > print "Enter all foods you have eaten today." > > > > > > items = raw_input("Add Food Item: ") > > > portion = input("Enter number of portions: ") > > > cal_portion = input("Enter calories per portion: ") > > > > > > more = raw_input("Do you wish to continue? y/n: ") > > > while more != 'n': > > > food_add() > > > break > > > total_calories[items] = portion * cal_portion > > > total = 0 > > > for i in total_calories.values(): > > > total = total + i > > > print "Total calories: ",total > > > > > > My output is: > > > > > > Total calories: 120 > > > Total calories: 254 > > > > > > The total calories for each item entered with the last entry first, > > > rather than just a Total calories: 374 > > > -- > > > > > > ekotyk > > > > > > http://members.shaw.ca/e.kotyk/virtualstudio.htm > > > > > > _______________________________________________ > > > Tutor maillist - Tutor@python.org > > > http://mail.python.org/mailman/listinfo/tutor > > > > > -- > > ekotyk > > http://members.shaw.ca/e.kotyk/virtualstudio.htm > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From urnerk@qwest.net Thu Jan 24 06:57:11 2002 From: urnerk@qwest.net (Kirby Urner) Date: Wed, 23 Jan 2002 22:57:11 -0800 Subject: [Tutor] creating variables at runtime In-Reply-To: <4.2.0.58.20020123222725.00bd5270@pop3.norton.antivirus> References: <3C4FA30D.59DE2661@shaw.ca> <3C50115C.15530.C0BB53@localhost> <4.2.0.58.20020123211317.00b2ee60@pop3.norton.antivirus> Message-ID: <4.2.0.58.20020123224716.015d4170@pop3.norton.antivirus> > >It's not that you're doing anything wrong. I'm just trying >to make clear the distinction between creating new variables >at the top level, versus inside a program-provided data >structure. > >Kirby Actually, I wasn't being all that clear myself. You *are* creating new instances at the top level *in a module* (the container). That satisfies the initial question. exec() is creating new variables in the namespace of the containing module, and you're just using the names list to keep track of the names. The while loop is internal to the module, but not internal to a function, so the entire module is its scope, which is why the exec() statement works to populate the module itself. So I take it back. You did it. I apologize. But what I was trying to do is a little different: write in interactive raw_input loop *in the shell* that creates new top-level variables: Note shell prompts: >>> def shell(): while 1: i = raw_input("Name: ") if not i: break names.append(i) exec(i + " = C()") >>> class C: pass >>> names = [] >>> shell() Name: A Name: B Name: C Name: >>> dir() ['C', '__builtins__', '__doc__', '__name__', 'names', 'shell'] A,B and C are gone -- the ones I created in the loop (the C here is the original class definition). Because the exec(i + " = C()") statement creates new variables *locally* to the shell() function -- then they get tossed. So that was my challenge: how do you write a raw_input loop function *in the shell* that creates new variables at the top level? Sorry again for not being clear. Kirby From urnerk@qwest.net Thu Jan 24 07:13:59 2002 From: urnerk@qwest.net (Kirby Urner) Date: Wed, 23 Jan 2002 23:13:59 -0800 Subject: [Tutor] creating variables at runtime In-Reply-To: <4.2.0.58.20020123224716.015d4170@pop3.norton.antivirus> References: <4.2.0.58.20020123222725.00bd5270@pop3.norton.antivirus> <3C4FA30D.59DE2661@shaw.ca> <3C50115C.15530.C0BB53@localhost> <4.2.0.58.20020123211317.00b2ee60@pop3.norton.antivirus> Message-ID: <4.2.0.58.20020123230120.015d4ad0@pop3.norton.antivirus> > >So that was my challenge: how do you write a raw_input loop >function *in the shell* that creates new variables at the >top level? And a parallel challenge would be: how to create new top-level variables in a module, *when the raw_input loop is a function*. Because if it's not in a function, then just loading the module via an import statement is going to cause the loop to start. I was trying to use the shell to envision a module in which the raw_input loop would be invoked/triggered by something other than simply the module being loaded. It all comes back to the fact that I tend to program to the shell, i.e. I treat the Python shell as a mini-OS and sit there invoking things in modules interactively, using the shell as a scratchpad to store interim results (as if it were a calculator with any number of memory locations). I rarely think in terms of scripts which run, top to bottom, with Python merely doing the interpreting, then exiting automatically at the end. That's how I get around wanting to write GUI interfaces -- I have direct access to all the variables and objects at the command line. People who come to Python from VB or C++ are more likely to think in terms of self-contained programs that either take arguments at the top, or prompt for a few inputs, then go. But I come from a Visual FoxPro background which boots to a command window. Half the time I'm just sitting at the command line, opening data tables, sorting, listing. Modifying structure. If I need a utility, I write it quickly, then run it. No need to exit the shell. I bring this same psychology to Python. I go into all this because I think newcomers especially should appreciate the two modes. I think sometimes people who program professionally get so used to whatever mode they use that they forget... Kirby Kirby >Sorry again for not being clear. > >Kirby > > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > From dyoo@hkn.eecs.berkeley.edu Thu Jan 24 07:34:15 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 23 Jan 2002 23:34:15 -0800 (PST) Subject: [Tutor] Learning Python using other languages --- round two Message-ID: [For people who are beginning to learn Python; skip this message. This is about something else. *grin*] Hi everyone, A while back, I wrote about thinking about writing a Scheme interpreter in Python. http://aspn.activestate.com/ASPN/Mail/Message/811896 Well, I just couldn't hold back from unleashing this monstrosity. I bring to you... Pyscheme! http://hkn.eecs.berkeley.edu/~dyoo/python/pyscheme/ I thought it might be interesting for anyone who'd like to see an example of writing one language in terms of another. Here's an example of it in action: ### dyoo@einfall:~/pyscheme-1.0/pyscheme$ python scheme.py Welcome to PyScheme! Type: (QUIT) to quit. [PyScheme] >>> (define (square x) (* x x)) ok [PyScheme] >>> (define (cube x) (* (square x) x)) ok [PyScheme] >>> square (compound-procedure (x) ((* x x)) ) [PyScheme] >>> cube (compound-procedure (x) ((* (square x) x)) ) [PyScheme] >>> (cube 2) 8 [PyScheme] >>> (cube 2000) 8000000000 [PyScheme] >>> (define (factorial x) [......1)] >>> (if (= x 0) [......2)] >>> 1 [......2)] >>> (* x (factorial (- x 1))))) ok [PyScheme] >>> (factorial 2) 2 [PyScheme] >>> (factorial 3) 6 [PyScheme] >>> (factorial 4) 24 [PyScheme] >>> (quit) BYE ### So if you ever wanted to look into the guts of a really ugly program, Pyscheme is now a candidate. *grin* I'll have to study Python a little more, but I'd be really happy if I can get tail recursion to work properly... Anyway, this was my side project for the winter, so I wanted to share it with the people here. From paulsid@shaw.ca Thu Jan 24 07:42:11 2002 From: paulsid@shaw.ca (Paul Sidorsky) Date: Thu, 24 Jan 2002 00:42:11 -0700 Subject: [Tutor] creating variables at runtime References: <4.2.0.58.20020123222725.00bd5270@pop3.norton.antivirus> <3C4FA30D.59DE2661@shaw.ca> <3C50115C.15530.C0BB53@localhost> <4.2.0.58.20020123211317.00b2ee60@pop3.norton.antivirus> <4.2.0.58.20020123230120.015d4ad0@pop3.norton.antivirus> Message-ID: <3C4FBAD3.5323728C@shaw.ca> Kirby Urner wrote: > >So that was my challenge: how do you write a raw_input loop > >function *in the shell* that creates new variables at the > >top level? > > And a parallel challenge would be: how to create new top-level > variables in a module, *when the raw_input loop is a function*. Ah okay so you were indeed talking about mixing namespaces. You're right, that's much trickier, and usually more trouble than it's worth. Your tangential remarks caught my eye though... > People who come to Python from VB or C++ are more likely > to think in terms of self-contained programs that either > take arguments at the top, or prompt for a few inputs, > then go. But I come from a Visual FoxPro background which > boots to a command window. Half the time I'm just sitting > at the command line, opening data tables, sorting, listing. > Modifying structure. If I need a utility, I write it > quickly, then run it. No need to exit the shell. I bring > this same psychology to Python. > I go into all this because I think newcomers especially > should appreciate the two modes. I think sometimes people > who program professionally get so used to whatever mode > they use that they forget... As it happens, I took a two-day course in S-PLUS (a statistical programming language for those who don't know) a few weeks ago and we learned by doing everything in the interpreter. It was a very powerful way to program. Not once did we ever type code into an editor and save it to a file and run it. The environment even saved the whole interpreter session so on the second day when we restarted the program all of our variables from the first day were still there. Sadly it never occured to me to try such a thing with Python. Like you said it's just not the way people tend to think of doing things with most programming languages. Heck, for a while I kept forgetting the Python interpreter even existed! (I started out with interactive BASIC interpreters, but C does weird things to the mind...) I use it quite often now but probably not nearly as much as I should. -- ====================================================================== Paul Sidorsky Calgary, Canada paulsid@shaw.ca http://members.shaw.ca/paulsid/ From polb@cableinet.co.uk Thu Jan 24 08:11:30 2002 From: polb@cableinet.co.uk (paul) Date: Thu, 24 Jan 2002 08:11:30 -0000 Subject: [Tutor] exceptional behaviour In-Reply-To: <4.2.0.58.20020123110005.0397e290@pop3.norton.antivirus> References: Message-ID: Date sent: Wed, 23 Jan 2002 11:00:55 -0800 To: "paul" From: Kirby Urner Subject: Re: [Tutor] exceptional behaviour Copies to: tutor@python.org Here's the code for the catcher: import raiserr try: raiserr.div42() except "problem": print "number must be greater than zero" except "problem 2": print"42, obviously" Here's the code for the thrower (raiserr.py): def div42(): denominator=input("What value will I divide 42 by?\n") if denominator == 0: raise "problem" elif denominator == 1: raise "problem 2" else: print 42/denominator the first exception works fine, the second gives me this: Traceback (most recent call last): File "", line 1, in ? raiserr.div42() File "D:\Python21\raiserr.py", line 6, in div42 raise "problem 2" problem 2 removing the space from the raise string allows it to work just fine, it's not a problem, but it's hard to see why it should differentiate between strings with spaces and those without. cheers Paul > > > > >def div42(): > > denominator=input("What value will I divide 42 by?\n") > > if denominator == 0: > > raise "first problem" > > elif denominator == 1: > > raise "second problem" > > else: > > print 42/denominator > > > >doesn't > > What error message to you get for the 2nd example? > Seems to work fine in 2.2: > > >>> div42() > What value will I divide 42 by? > 0 > Traceback (most recent call last): > File "", line 1, in ? > div42() > File "", line 4, in div42 > raise "first problem" > first problem > > Kirby > From toodles@yifan.net Thu Jan 24 08:46:54 2002 From: toodles@yifan.net (Andy W) Date: Thu, 24 Jan 2002 16:46:54 +0800 Subject: [Tutor] creating variables at runtime References: <3C4FA30D.59DE2661@shaw.ca> <3C50115C.15530.C0BB53@localhost> <4.2.0.58.20020123211317.00b2ee60@pop3.norton.antivirus> <4.2.0.58.20020123224716.015d4170@pop3.norton.antivirus> Message-ID: <004701c1a4b3$ae78fb30$da00a8c0@Sun> Sorry for butting in and all, but I couldn't help but throw my two cents in :o) (A solution) > Note shell prompts: > > >>> def shell(): > while 1: > i = raw_input("Name: ") > if not i: > break > names.append(i) > exec(i + " = C()") > > > >>> class C: > pass > > >>> names = [] > >>> shell() > Name: A > Name: B > Name: C > Name: > > >>> dir() > ['C', '__builtins__', '__doc__', '__name__', 'names', 'shell'] > > A,B and C are gone -- the ones I created in the loop (the > C here is the original class definition). > > Because the exec(i + " = C()") statement creates new variables > *locally* to the shell() function -- then they get tossed. > > So that was my challenge: how do you write a raw_input loop > function *in the shell* that creates new variables at the > top level? >>> def shell(): while 1: i = raw_input("Name: ") if not i: break globals()[i]=C() >>> class C: pass >>> shell() Name: a Name: b Name: c Name: >>> dir() ['C', '__builtins__', '__doc__', '__name__', 'a', 'b', 'c', 'shell'] Andy > > Sorry again for not being clear. > > Kirby > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From scarblac@pino.selwerd.nl Thu Jan 24 09:02:14 2002 From: scarblac@pino.selwerd.nl (Remco Gerlich) Date: Thu, 24 Jan 2002 10:02:14 +0100 Subject: [Tutor] exceptional behaviour In-Reply-To: ; from polb@cableinet.co.uk on Thu, Jan 24, 2002 at 08:11:30AM -0000 References: <4.2.0.58.20020123110005.0397e290@pop3.norton.antivirus> Message-ID: <20020124100214.A5364@pino.selwerd.nl> On 0, paul wrote: > Here's the code for the catcher: (snip code) Ok, confirmed. String exceptions with a space don't work, at least not with these strings, haven't tested much more. > removing the space from the raise string allows it to work just fine, > it's not a problem, but it's hard to see why it should differentiate > between strings with spaces and those without. Surprisingly, the final answer is that "problem2" is a valid name for a Python identifier, but "problem 2" is not. Let's quote a bit from the Language Reference, http://www.python.org/doc/current/ref/exceptions.html , verse 5: "Exceptions are handled by string objects or class instances. Selection of a matching except clause is based on object identity (i.e., two different string objects with the same value represent different exceptions!)" Now usually, if you have two string literals in different parts of your program, they will *not* be the same object. So by default, this kind of raise/except would not work at all. However. Since strings are immutable, Python is allowed to intern() them, put all strings with a certain value in the same memory, so that they *are* the same object. It does the optimization with certain strings only, ones that are likely to occur often - prime example: identifiers, or rather strings that could be identifiers. You can not rely on this, the Python implementation is free to change the choice of strings it interns from version to version. So basically the anomaly isn't that "problem 2" doesn't work, but rather that "problem2" does, because it looks like an identifier, is therefore interned, and therefore it's the same object both times you use it. Try typing e.g. id("a test") id("a test") id("a test") id("atest") id("atest") id("atest") "a test" will give three different numbers, "atest" three times the same. I agree that all of this is *very* counter intuitive, but string exceptions are basically deprecated anyway. Solutions: - Define your errors at the top of the file, like Problem_2_exception = "problem 2" and use 'raise Problem_2_exception' and 'except Problem_2_exception' - Use class exceptions. You know you want to. Avoiding spaces in exceptions is probably good enough, but *might* fail in the future, if Python decides to stop interning strings that look like identifiers, or when string exceptions are finally removed. -- Remco Gerlich From toodles@yifan.net Thu Jan 24 09:23:42 2002 From: toodles@yifan.net (Andy W) Date: Thu, 24 Jan 2002 17:23:42 +0800 Subject: [Tutor] exceptional behaviour References: <4.2.0.58.20020123110005.0397e290@pop3.norton.antivirus> <20020124100214.A5364@pino.selwerd.nl> Message-ID: <005f01c1a4b8$d2162950$da00a8c0@Sun> > Let's quote a bit from the Language Reference, > http://www.python.org/doc/current/ref/exceptions.html , verse 5: > > "Exceptions are handled by string objects or class instances. Selection > of a matching except clause is based on object identity (i.e., two > different string objects with the same value represent different > exceptions!)" That's odd. >>> try: raise "abc 1" except "abc 1": print "interesting..." interesting... >>> Maybe I'm missing something? The previous test led me to thinking that perhaps within the try except statements, the id of a string might be the same (I really have no idea about the internals). So I did another test, proving my thoughts wrong. >>> try: raise str(id("abc 1")) except str(id("abc 1")): print "interesting..." Traceback (most recent call last): File "", line 2, in ? raise str(id("abc 1")) 10852208 >>> So... what's going on here? Any ideas? Andy From scarblac@pino.selwerd.nl Thu Jan 24 09:33:21 2002 From: scarblac@pino.selwerd.nl (Remco Gerlich) Date: Thu, 24 Jan 2002 10:33:21 +0100 Subject: [Tutor] exceptional behaviour In-Reply-To: <005f01c1a4b8$d2162950$da00a8c0@Sun>; from toodles@yifan.net on Thu, Jan 24, 2002 at 05:23:42PM +0800 References: <4.2.0.58.20020123110005.0397e290@pop3.norton.antivirus> <20020124100214.A5364@pino.selwerd.nl> <005f01c1a4b8$d2162950$da00a8c0@Sun> Message-ID: <20020124103321.A5462@pino.selwerd.nl> On 0, Andy W wrote: > > > Let's quote a bit from the Language Reference, > > http://www.python.org/doc/current/ref/exceptions.html , verse 5: > > > > "Exceptions are handled by string objects or class instances. Selection > > of a matching except clause is based on object identity (i.e., two > > different string objects with the same value represent different > > exceptions!)" > > That's odd. > > >>> try: > raise "abc 1" > except "abc 1": print "interesting..." > > interesting... > >>> Now try: def f(): raise "abc 1" try: f() except "abc 1": print "whee" That does fail! Also, try: raise "ab"+"c 1" except "abc 1": print "whee" Also fails! > Maybe I'm missing something? The previous test led me to thinking that > perhaps within the try except statements, the id of a string might be the > same (I really have no idea about the internals). So I did another test, > proving my thoughts wrong. Possibly it works when - The exception is raised in the try: block itself, not in some function - The exception is a string literal, not a result of an expression I can imagine an optimization in the code that makes that work even though it shouldn't if you only look at object identity. But it's certainly murky implemenation details. > >>> try: > raise str(id("abc 1")) > except str(id("abc 1")): print "interesting..." > > Traceback (most recent call last): > File "", line 2, in ? > raise str(id("abc 1")) > 10852208 > >>> This is an expression result like my 2nd example. So, even more than before, don't do that then!! Use class exceptions :-) -- Remco Gerlich From toodles@yifan.net Thu Jan 24 09:38:12 2002 From: toodles@yifan.net (Andy W) Date: Thu, 24 Jan 2002 17:38:12 +0800 Subject: [Tutor] exceptional behaviour References: <4.2.0.58.20020123110005.0397e290@pop3.norton.antivirus> <20020124100214.A5364@pino.selwerd.nl> <005f01c1a4b8$d2162950$da00a8c0@Sun> <20020124103321.A5462@pino.selwerd.nl> Message-ID: <007001c1a4ba$d8d514c0$da00a8c0@Sun> > So, even more than before, don't do that then!! Use class exceptions :-) *grin* Don't worry, I do :o) I just wanted to test it, thanks for the feedback! > > -- > Remco Gerlich > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From pythontutor@venix.com Thu Jan 24 13:52:54 2002 From: pythontutor@venix.com (Lloyd Kvam) Date: Thu, 24 Jan 2002 08:52:54 -0500 Subject: [Tutor] creating variables at runtime References: <3C4FA30D.59DE2661@shaw.ca> <3C50115C.15530.C0BB53@localhost> <4.2.0.58.20020123211317.00b2ee60@pop3.norton.antivirus> <4.2.0.58.20020123224716.015d4170@pop3.norton.antivirus> <004701c1a4b3$ae78fb30$da00a8c0@Sun> Message-ID: <3C5011B6.7090905@venix.com> An interesting thread. I've been using globals() in kind of the reverse way to create class instances based on the desired class name, sort of a quick Class Factory Method. instance = globals()['Classname']() I am enclosing a python snippet that (I think) shows why this makes sense. I have not found this in the text books. class Site(Table): fk_obj_list = ['Reservation','Siteprice'] class Siteprice(Table): class Reservation(Table): class Table(Record,DataSet): def __getattr__(self, key): ''' trap attempts to fetch related Table objects ''' if key in self.fk_obj_list: obj = globals()[key]() # <== Factory method ????? ... # run SQL to get relevant data into obj ... obj.Parent = self # remember where we came from return obj else: return Record.__getattr__(self, key) site = Site() # run SQL to choose a site reservations = site.Reservation # reservations contains DataSet of all reservations for the site The general approach was inspired by "Python Programming on Win32", but the obj = globals()[key]() must be blamed on me. It sort of seems like cheating, but has worked nicely for us. Andy W wrote: > Sorry for butting in and all, but I couldn't help but throw my two cents in > :o) > (A solution) > > >>Note shell prompts: >> >> >>> def shell(): >> while 1: >> i = raw_input("Name: ") >> if not i: >> break >> names.append(i) >> exec(i + " = C()") >> >> >> >>> class C: >> pass >> >> >>> names = [] >> >>> shell() >>Name: A >>Name: B >>Name: C >>Name: >> >> >>> dir() >>['C', '__builtins__', '__doc__', '__name__', 'names', 'shell'] >> >>A,B and C are gone -- the ones I created in the loop (the >>C here is the original class definition). >> >>Because the exec(i + " = C()") statement creates new variables >>*locally* to the shell() function -- then they get tossed. >> >>So that was my challenge: how do you write a raw_input loop >>function *in the shell* that creates new variables at the >>top level? >> > >>>>def shell(): >>>> > while 1: > i = raw_input("Name: ") > if not i: > break > globals()[i]=C() > > >>>>class C: >>>> > pass > > >>>>shell() >>>> > Name: a > Name: b > Name: c > Name: > > >>>>dir() >>>> > ['C', '__builtins__', '__doc__', '__name__', 'a', 'b', 'c', 'shell'] > > Andy > > >>Sorry again for not being clear. >> >>Kirby >> >> >> >>_______________________________________________ >>Tutor maillist - Tutor@python.org >>http://mail.python.org/mailman/listinfo/tutor >> >> > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From randytalbot@home.com Thu Jan 24 15:09:13 2002 From: randytalbot@home.com (Randy Talbot) Date: Thu, 24 Jan 2002 10:09:13 -0500 Subject: [Tutor] me again Message-ID: <000001c1a4e9$15d06a40$5b582144@aberdn01.md.comcast.net> This is a multi-part message in MIME format. ------=_NextPart_000_0001_01C1A4BF.2CFA6240 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: 7bit -----Original Message----- From: Randy Talbot [mailto:randytalbot@home.com] Sent: Thursday, January 24, 2002 2:17 AM To: 'AMoore4437@aol.com' Subject: RE: [Tutor] me again Tony I am new to python also. I was just at the site last night following the step by step tutorial. What is missing in the directions is to name the program with a period and py at the end. For example, if you want to name a program myprogram in python you would name it myprogram.py instead. On the website they named the program firstprogram.py. Once saved, the name of the program should be visible when you click on the Open command under the File menu. I am using python 2.2 and program is visible with a green python type symbol at the beginning of the program. Randy Talbot -----Original Message----- From: tutor-admin@python.org [mailto:tutor-admin@python.org] On Behalf Of AMoore4437@aol.com Sent: Wednesday, January 23, 2002 5:03 PM To: tutor@python.org Subject: [Tutor] me again hello it's me again, i keep running into problems (is it me??) i have followed a tutorial step by step http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/ and have saved my work as directed to do so from the 'program window' when i try to save it offers me 'python 22' but i have saved it to 'C drive' as is shown in the tutorial. when i try to reopen my work in the way described in the tutorial my saved work does not come up automatically (as shown) the only place i can find it is on my 'C drive' by going through 'my computer' then when i try to open it through there i am asked what program would i like to run to open it. is this correct ? i hope i'm making sense tony moore ------=_NextPart_000_0001_01C1A4BF.2CFA6240 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable

 

 

-----Original Message-----
From: Randy Talbot [mailto:randytalbot@home.com]
Sent: =
Thursday, January 24, = 2002 2:17 AM
To: = 'AMoore4437@aol.com'
Subject: RE: [Tutor] me = again

 

Tony

I am new to python also. I was = just at the site last night following the step by step tutorial. What is missing = in the directions is to name the program with a period and py at the end. For = example, if you want to name a program myprogram in python you would name it myprogram.py instead. On the website they named the program = firstprogram.py. Once saved, the name of the program should be visible when you click on = the Open command under the File menu. I am using python 2.2 and program is = visible with a green python type symbol at the beginning of the = program.

Randy = Talbot

 

-----Original Message-----
From: = tutor-admin@python.org [mailto:tutor-admin@python.org] On = Behalf Of AMoore4437@aol.com
Sent: =
Wednesday, January 23, = 2002 5:03 PM
To: tutor@python.org
Subject: [Tutor] me = again

 

hello it's me again,
i keep running into problems (is it me??)

i have followed a tutorial step by step

http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/

and have saved my work as directed to do so from the 'program window' =
when i try to save it offers me 'python 22'
but i have saved it to 'C drive' as is shown in the tutorial.

when i try to reopen  my work
in the way described in the tutorial  my saved work does not come = up automatically (as shown)

the only place i can find it is on my 'C drive' by going through 'my = computer'
then when i try to open it through there
i am asked what program would i like to run to open it.
is this correct ?

i hope i'm making sense

tony
moore =

------=_NextPart_000_0001_01C1A4BF.2CFA6240-- From wheelege@hotmail.com Thu Jan 24 16:23:28 2002 From: wheelege@hotmail.com (Glen Wheeler) Date: Fri, 25 Jan 2002 03:23:28 +1100 Subject: [Tutor] Learning Python using other languages --- round two Message-ID: > [For people who are beginning to learn Python; skip this message. This is > about something else. *grin*] > > [..] > > > So if you ever wanted to look into the guts of a really ugly program, > Pyscheme is now a candidate. *grin* I'll have to study Python a little > more, but I'd be really happy if I can get tail recursion to work > properly... Anyway, this was my side project for the winter, so I wanted > to share it with the people here. > > Wow !! This is incredibly cool. I must play with this :) Go Danny! From virketis@fas.harvard.edu Thu Jan 24 16:37:42 2002 From: virketis@fas.harvard.edu (Pijus Virketis) Date: Thu, 24 Jan 2002 11:37:42 -0500 Subject: [Tutor] ftp and python enabled editor Message-ID: <00a801c1a4f5$71c08630$18adf78c@virketis2> This is a multi-part message in MIME format. ------=_NextPart_000_00A5_01C1A4CB.88D4FA60 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Hi all,=20 A quick question about the tools of programming. I remember the long = discussion a few months ago about editors: my requirements are much = narrower here. Is there a program that can open and save files via FTP = on a remote location, supports Python syntax highlighting and works on = Windows? I usually use SciTE or just good old IDLE, but neither can do = FTP ... Cheers,=20 Pijus ------=_NextPart_000_00A5_01C1A4CB.88D4FA60 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
Hi all,
 
A quick question about the tools = of=20 programming. I remember the long discussion a few months ago about = editors: my=20 requirements are much narrower here. Is there a program that can open = and save=20 files via FTP on a remote location, supports Python syntax = highlighting and=20 works on Windows? I usually use SciTE or just good old IDLE, but neither = can do=20 FTP ...
 
Cheers,
 
Pijus
------=_NextPart_000_00A5_01C1A4CB.88D4FA60-- From scarblac@pino.selwerd.nl Thu Jan 24 16:43:46 2002 From: scarblac@pino.selwerd.nl (Remco Gerlich) Date: Thu, 24 Jan 2002 17:43:46 +0100 Subject: [Tutor] ftp and python enabled editor In-Reply-To: <00a801c1a4f5$71c08630$18adf78c@virketis2>; from virketis@fas.harvard.edu on Thu, Jan 24, 2002 at 11:37:42AM -0500 References: <00a801c1a4f5$71c08630$18adf78c@virketis2> Message-ID: <20020124174345.A6086@pino.selwerd.nl> On 0, Pijus Virketis wrote: > A quick question about the tools of programming. I remember the long > discussion a few months ago about editors: my requirements are much narrower > here. Is there a program that can open and save files via FTP on a remote > location, supports Python syntax highlighting and works on Windows? I > usually use SciTE or just good old IDLE, but neither can do FTP ... Emacs. Or actually, the Windows Emacs I used once was black and white, so it couldn't do colouring. Since I haven't had Windows for years I can't know for sure whether there is a version that does work well now, but there should be. -- Remco Gerlich From aschmidt@nv.cc.va.us Thu Jan 24 17:02:43 2002 From: aschmidt@nv.cc.va.us (Schmidt, Allen J.) Date: Thu, 24 Jan 2002 12:02:43 -0500 Subject: [Tutor] ftp and python enabled editor Message-ID: <5CDFEBB60E7FD311B9E30000F6D6090608CB8F1B@novamail2.nv.cc.va.us> HomeSite is my editor of choice for most everything these days. Works great for FTP and Python...but, no color coding. I use Zope extensively and it works great with it as I can FTP right into the Zope folder structure. Should be easy to build the color coding into HS for Python. It is very flexible that way. I have also heard that HTMLKit offers color coding in Python but I have not tried it. It will also do FTP as well. Allen -----Original Message----- From: Remco Gerlich [mailto:scarblac@pino.selwerd.nl] Sent: Thursday, January 24, 2002 11:44 AM To: tutor@python.org Subject: Re: [Tutor] ftp and python enabled editor On 0, Pijus Virketis wrote: > A quick question about the tools of programming. I remember the long > discussion a few months ago about editors: my requirements are much narrower > here. Is there a program that can open and save files via FTP on a remote > location, supports Python syntax highlighting and works on Windows? I > usually use SciTE or just good old IDLE, but neither can do FTP ... Emacs. Or actually, the Windows Emacs I used once was black and white, so it couldn't do colouring. Since I haven't had Windows for years I can't know for sure whether there is a version that does work well now, but there should be. -- Remco Gerlich _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From israel@lith.com Thu Jan 24 17:14:50 2002 From: israel@lith.com (Israel Evans) Date: Thu, 24 Jan 2002 09:14:50 -0800 Subject: [Tutor] ftp and python enabled editor Message-ID: HTMLKit (http://www.chami.com/html-kit/) is my Favorite editor for all things web related, though I still use Idle Extensively for Python Development. Adding a new Syntax Color set to HTMLKit is pretty easy and it has TONS of plug ins and tools to aid in development. And it's Free to boot! From John.Gouveia2@CIGNA.COM Thu Jan 24 17:33:29 2002 From: John.Gouveia2@CIGNA.COM (Gouveia, John M W44) Date: Thu, 24 Jan 2002 12:33:29 -0500 Subject: [Tutor] ftp and python enabled editor Message-ID: <1D7FF56FBD1FD511982D001083FD31720121B65F@WLDEXU15> Try UltraEdit, you can syntax highlight anything, has a built in ftp client, tons of features. It's only windows and not free but its only @ $30. John Gouveia CIGNA HealthCare IM&T IM Release 2 Decision Support Services > The information contained in this e-mail may be confidential and is > intended solely for the use of the named addressee. Access, copying or > re-use of the e-mail or any information contained therein by any other > person is not authorized. If you are not the intended recipient, please > notify us immediately by returning the e-mail to the originator. > Confidential, unpublished property of CIGNA > Do not duplicate or distribute > Use and distribution limited solely to authorized personnel > (c) Copyright 2002 (CIGNA Corporation) > > > -----Original Message----- > From: Pijus Virketis [SMTP:virketis@fas.harvard.edu] > Sent: Thursday, January 24, 2002 11:38 AM > To: tutor@python.org > Subject: [Tutor] ftp and python enabled editor > > Hi all, > > A quick question about the tools of programming. I remember the long > discussion a few months ago about editors: my requirements are much > narrower here. Is there a program that can open and save files via FTP on > a remote location, supports Python syntax highlighting and works on > Windows? I usually use SciTE or just good old IDLE, but neither can do FTP > ... > > Cheers, > > Pijus ------------------------------------------------------------------------------ CONFIDENTIALITY NOTICE: If you have received this e-mail in error, please immediately notify the sender by e-mail at the address shown. This e-mail transmission may contain confidential information. This information is intended only for the use of the individual(s) or entity to whom it is intended even if addressed incorrectly. Please delete it from your files if you are not the intended recipient. Thank you for your compliance. Copyright (c) 2002 CIGNA ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ From nidge@iprimus.com.au Thu Jan 24 14:26:38 2002 From: nidge@iprimus.com.au (Nigel Bennett) Date: Fri, 25 Jan 2002 00:26:38 +1000 Subject: [Tutor] learner Message-ID: <000801c1a4e3$244f6900$813c32d2@user> This is a multi-part message in MIME format. ------=_NextPart_000_0005_01C1A536.F4503A00 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable to whom it may concern, i would like to know how to write a program. i am relatively new to computers and have no prior programming = experience. i would like to know if python is a good place to begin and why? what type of applications can the python language be used for? i look forward to your reply. kind regards, nigel bennett. ------=_NextPart_000_0005_01C1A536.F4503A00 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
to whom it may=20 concern,
i would like to = know how to write=20 a program.
i am relatively new = to computers=20 and have no prior programming experience.
i would like to = know if python is=20 a good place to begin and why?
what type of = applications can the=20 python language be used for?
i look forward to = your=20 reply.
kind = regards,
nigel=20 bennett.
------=_NextPart_000_0005_01C1A536.F4503A00-- From kp87@lycos.com Thu Jan 24 16:54:19 2002 From: kp87@lycos.com (kevin parks) Date: Fri, 25 Jan 2002 01:54:19 +0900 Subject: [Tutor] Re: List Comprehensions again Message-ID: I have never been able to get my head around list comprehension and desperately want too. I wish that there was a *good* little 2-3 page toot on list comprehensions that start from the very clearest and simplest examples and built up from there with nice explanations in between. The www.python.org web site is a bit terse for me and none of the books that i have on hand (save Mr.Chun's excellent tome, which is out of reach at the moment) cover list comprehensions which were too new at the time. I really feel like i need to know this as I am constantly working with lists that I want to transform in some way an element at a time. Does anyone know of such a toot? I hate to ask such a vague question. I know that it is easier to answer questions like: I have a a piece of code that does _____, but now it wont do ___, if i add ____ to the _____, see: [insert code here] etc..... Basically I am still using map and filter and lambda to do things cause he don't get the new list comprehension thing, yet I come across code that uses list comprehensions constantly and I sometimes don't know what I am looking at. Anyone really got List comprehensions down cold or know off a good toot on the web? I would be grateful for any help in this matter. I need something that I can print out and stare at and type into the interpreter and really study. best wishes, kevin parks seoul, korea From kp87@lycos.com Thu Jan 24 17:10:57 2002 From: kp87@lycos.com (kevin parks) Date: Fri, 25 Jan 2002 02:10:57 +0900 Subject: [Tutor] please... Message-ID: Hi folks, I hate to be a wet blanket, but could we chill on the HTML mail and mime junk and just use ascii text. This is a huge problem for those of us who get the digest. The last (very large) digest had like 4 messages in it and seemingly miles of garbage that looked like this: >From: Randy Talbot >[mailto:randytalbot@home.com]
>Sent: = >
Month=3D"1" Day=3D"24" Year=3D"2002">style=3D'font-size: > 10.0pt;font-family:Tahoma'>Thursday, January 24, = >2002size=3D2 face=3DTahoma>style=3D'font-size:10.0pt;font-family:Tahoma'> Hour=3D"2" Minute=3D"17">style=3D'font-size:10.0pt; It is really easy if you just go into your preferences and set uncheck the "send as html" button. cheers, kevin From scarblac@pino.selwerd.nl Thu Jan 24 18:34:13 2002 From: scarblac@pino.selwerd.nl (Remco Gerlich) Date: Thu, 24 Jan 2002 19:34:13 +0100 Subject: [Tutor] learner In-Reply-To: <000801c1a4e3$244f6900$813c32d2@user>; from nidge@iprimus.com.au on Fri, Jan 25, 2002 at 12:26:38AM +1000 References: <000801c1a4e3$244f6900$813c32d2@user> Message-ID: <20020124193413.A6256@pino.selwerd.nl> On 0, Nigel Bennett wrote: > to whom it may concern, > i would like to know how to write a program. That's good! > i am relatively new to computers and have no prior programming experience. To be honest, if you are not yet comfortable just using a computer for many things, it may be hard to start programming immediately. Things like using the Internet, an editor, the Windows Explorer, maybe knowing how to do some DOS commands, installing software, in general feel comfortable using your computer. After that, you can learn how to program. It helps if you have a more precise goal though. Are you trying to get a job in programming? Anything specific you want to build? Is it just an intellectual challenge? There are several tutorials for beginners. You can find a list at http://www.python.org/doc/Newbies.html . I usually recommend Alan Gauld's tutor, since he is also on this list and if you don't understand something or if I think something needs changing, we can bug him with emails :-) http://www.freenetpages.co.uk/hp/alan.gauld/ > i would like to know if python is a good place to begin and why? Yes, it is a good place to begin. A full explanation would be very long, involve comparisons with other languages and go much too far. The three main points, for me: - Python is intentionally beginner friendly. That was a design goal. - Python is very powerful. Lots of different things are easy to do. - Python has this mailing list. > what type of applications can the python language be used for? Huge applications will not be made in pure Python, but may use Python in earlier stages or as an embedded language. Very low-level OS stuff will also not be in Python, but rather in C or C++, usually. Everything in between is fair game. Games, internet utilities, little GUIs, math, working with images, etc etc. -- Remco Gerlich From tjenkins@devis.com Thu Jan 24 18:37:17 2002 From: tjenkins@devis.com (Tom Jenkins) Date: 24 Jan 2002 13:37:17 -0500 Subject: [Tutor] Re: List Comprehensions again In-Reply-To: References: Message-ID: <1011897437.3875.3.camel@asimov> On Thu, 2002-01-24 at 11:54, kevin parks wrote: > I have never been able to get my head around list comprehension and desperately want too. I wish that there was a *good* little 2-3 page toot on list comprehensions that start from the very clearest and simplest examples and built up from there with nice explanations in between. The www.python.org web site is a bit terse for me and none of the books that i have on hand (save Mr.Chun's excellent tome, which is out of reach at the moment) cover list comprehensions which were too new at the time. I really feel like i need to know this as I am constantly working with lists that I want to transform in some way an element at a time. Does anyone know of such a toot? I hate to ask such a vague question. I know that it is easier to answer questions like: I have a a piece of code that does _____, but now it wont do ___, if i add ____ to the _____, see: > > [insert code here] > > etc..... Basically I am still using map and filter and lambda to do things cause he don't get the new list comprehension thing, yet I come across code that uses list comprehensions constantly and I sometimes don't know what I am looking at. > > Anyone really got List comprehensions down cold or know off a good toot on the web? I would be grateful for any help in this matter. I need something that I can print out and stare at and type into the interpreter and really study. > > best wishes, > i came to python before list comprehensions. it took me A LONG TIME to understand map/filter/lambda... actually i'll say i still don't really understand them. when i first saw list comprehensions, i thought "I have NO CLUE what this is doing". then i started playing. i took a map/lambda combination and tried to rewrite it in list comprehension. that worked... now i can do fairly well with LC's So that was a rambling way of saying... why don't you post some map/lambdas and we'll LC 'em together. (note I;ve found I learn by example) -- Tom Jenkins Development InfoStructure http://www.devis.com From urnerk@qwest.net Thu Jan 24 18:45:10 2002 From: urnerk@qwest.net (Kirby Urner) Date: Thu, 24 Jan 2002 10:45:10 -0800 Subject: [Tutor] creating variables at runtime In-Reply-To: <3C5011B6.7090905@venix.com> References: <3C4FA30D.59DE2661@shaw.ca> <3C50115C.15530.C0BB53@localhost> <4.2.0.58.20020123211317.00b2ee60@pop3.norton.antivirus> <4.2.0.58.20020123224716.015d4170@pop3.norton.antivirus> <004701c1a4b3$ae78fb30$da00a8c0@Sun> Message-ID: <4.2.0.58.20020124104416.01a45440@pop3.norton.antivirus> > >The general approach was inspired by "Python Programming on Win32", >but the > obj = globals()[key]() >must be blamed on me. It sort of seems like cheating, but has >worked nicely for us. That's pretty clever, I must say. Definitely a trick I'd not thought of. Kirby From urnerk@qwest.net Thu Jan 24 18:50:50 2002 From: urnerk@qwest.net (Kirby Urner) Date: Thu, 24 Jan 2002 10:50:50 -0800 Subject: [Tutor] creating variables at runtime In-Reply-To: <004701c1a4b3$ae78fb30$da00a8c0@Sun> References: <3C4FA30D.59DE2661@shaw.ca> <3C50115C.15530.C0BB53@localhost> <4.2.0.58.20020123211317.00b2ee60@pop3.norton.antivirus> <4.2.0.58.20020123224716.015d4170@pop3.norton.antivirus> Message-ID: <4.2.0.58.20020124104944.01b82ee0@pop3.norton.antivirus> > > globals()[i]=C() This too, from Andy. Way cool. I still advocate putting user-defined objects in a dictionary -- but if you insist on making this the globals dictionary, then here's how... Thanks to all who played on this thread -- most enlightening. Kirby From jeff@ccvcorp.com Thu Jan 24 19:01:01 2002 From: jeff@ccvcorp.com (Jeff Shannon) Date: Thu, 24 Jan 2002 11:01:01 -0800 Subject: [Tutor] creating variables at runtime References: Message-ID: <3C5059EC.F1DCBF22@ccvcorp.com> > Lloyd Kvam wrote: > > I've been using globals() in kind of the reverse way to create class instances based > on the desired class name, sort of a quick Class Factory Method. > instance = globals()['Classname']() Actually, this is much closer to the "right" way to use globals(), I think. I know that the corresponding locals() function returns a dictionary that should be considered read-only (effects of altering it are undefined), and my gut reaction is to try to treat globals() the same way (though, admittedly, I don't see a similar warning about globas() in the docs). Then again, in almost any case where something like this might be useful, I'd prefer to create a dictionary and just use that. For instance, in your sample code... > class Site(Table): > fk_obj_list = ['Reservation','Siteprice'] > class Siteprice(Table): > class Reservation(Table): I'd do this as: class Siteprice(Table): class Reservation(Table): class Site(Table): fk_objects = { 'Reservation': Reservation, 'Siteprice': Siteprice } and then when I needed to create the class, I could do if key in self.fk_objects.keys(): obj = self.fk_objects[key]() Of course, this may just be my personal style, and YMMV and all, but I think that this is more explicit, and cleaner, than using globals(). Jeff Shannon Technician/Programmer Credit International From scarblac@pino.selwerd.nl Thu Jan 24 19:04:18 2002 From: scarblac@pino.selwerd.nl (Remco Gerlich) Date: Thu, 24 Jan 2002 20:04:18 +0100 Subject: [Tutor] Re: List Comprehensions again In-Reply-To: ; from kp87@lycos.com on Fri, Jan 25, 2002 at 01:54:19AM +0900 References: Message-ID: <20020124200418.A6318@pino.selwerd.nl> On 0, kevin parks wrote: > I have never been able to get my head around list comprehension and > desperately want too. I wish that there was a *good* little 2-3 page toot on > list comprehensions that start from the very clearest and simplest examples > and built up from there with nice explanations in between. I have 20 minutes to kill, let's see where we get. In its simplest form, the list comprehension has just one 'for' clause and no 'if' clause. It's of the form: L = [expression for variable in list] What does this do? 'variable' gets all the values in 'list' in turn, and for each the expression is calculated and put in the list. They're equivalent to L = [] for variable in list: L.append(expression) An example is the list of squares of the numbers 0..9: L = [x*x for x in range(10)] # yields L == [0,1,4,9,16,25,36,49,64,81] So this is equivalent to: L = [] for x in range(10): L.append(x*x) With "old Python", this could be done with map and lambda, in case you know those. The lambda was used to make a 'square' function, and then it was map()-ed over the list of numbers: L = map(lambda x: x*x, range(10)) So this is the most basic form of list comprehensions. There are two things that you can add to make them more powerful: 'if' clauses, and multiple 'for' clauses. The 'if' clause lets you pick *some* of the values for the variable. The general form is L = [expression for variable in list if other_expression] which is equivalent to L = [] for variable in list: if other_expression: L.append(expression) To go back to the squares example: suppose we only want the odd squares. That's easy to write like L = [x*x for x in range(10) if x%2 == 1] That yields [1, 9, 25, 49, 81]. This is still easy with a for loop, although it still takes more lines: L = [] for x in range(10): if x%2 == 1: L.append(x*x) However, with the old functions, we need to add filter() and another lambda, that is 1 when a number is odd: L = map(lambda x: x*x, filter(lambda x: x%2 == 1, range(10))) Which already becomes rather obfuscated compared to the list comprehension. The other option is extra for clauses, like: L = [x+y for x in '123' for y in 'abc'] It looks a bit strange because I used strings instead of lists, but remember that strings are just sequences as well. This is equivalent to: L = [] for x in '123': for y in 'abc': L.append(x+y) So it results in ['1a','1b','1c','2a','2b','2c','3a','3b','3c'] People who want to do this with map are welcome to, but I'm not going to. Now the list comprehension I posted yesterday that seems to have baffled some people: [x(y) for x in [lambda x:x*x, lambda x:x*x*x] for y in [1,2,3]] What is this? We see that x takes values from the list with the two lambdas - that's a list with two functions, the first squares its argument, the second cubes it. So x is the square function first, then the cube function. y simple takes values from 1, 2, 3. For each of these values, x(y) is computed, that is, x is called with y as its argument. That means, first 1, 2 and 3 are squared, and then they are cubed. The result is [1, 4, 9, 1, 8, 27]. Also, given the general form of the list comprehension above, we see that we can write it as L = [] for function in [lambda x:x*x, lambda x:x*x*x]: for y in [1,2,3]: L.append(function(y)) Which may be a little clearer. It can, in this case, also be simply written [x*x for x in [1,2,3]] + [x*x*x for x in [1,2,3]] of course :) Twenty minutes are over, I hope this at least clears it up a little, maybe we can edit this with the reactions people have and put it on a webpage somewhere after it's evolved enough... -- Remco Gerlich From israel@lith.com Thu Jan 24 20:59:24 2002 From: israel@lith.com (Israel Evans) Date: Thu, 24 Jan 2002 12:59:24 -0800 Subject: [Tutor] Python in Apache? Message-ID: Has anyone here ever attempted to get Python cgi files to run in an apache server? I seem to be having trouble though everything looks right and I don't know whether it's python or apache that's causing me problems. The following is a bit long but I think it's thorough These are the things I have set up. This is my script alias in httpd.config which I think is set up correctly. The path I've set up is correct, but I'm new to the options so I may be off. ############################################ ScriptAlias /cgi-bin/ "C:/Weblish/cgi-bin/" AllowOverride None Options +ExecCGI Order allow,deny Allow from all ############################################ I don't have Perl on my machine, but I do have Python, which I like much better so I'm using that as the language for my cgi programs. My super simple introductory cgi is as follows. I've got Python in my Path and using this Shebang line I'm able to run python scripts just fine by clicking on them. ###################################### #! % python header = "Content-type: text/html\n\n" content = "Hello, Baby." print header, content ###################################### I access this cgi file by entering "http://localhost/cgi-bin/test.cgi" into my browser after having made sure that the Server is running. I get the following error message: #################################### Internal Server Error The server encountered an internal error or misconfiguration and was unable to complete your request. Please contact the server administrator, Israel@lith.com and inform them of the time the error occurred, and anything you might have done that may have caused the error. More information about this error may be available in the server error log. _____ Apache/1.3.20 Server at ISREAL.lith.com Port 80 ########################################## And when I look into the Error logs I find these tidbitsof information: ############################################# [Thu Jan 24 08:08:42 2002] [error] [client 127.0.0.1] attempt to invoke directory as script: c:/weblish/cgi-bin [Thu Jan 24 08:11:28 2002] [error] [client 127.0.0.1] couldn't spawn child process: c:/weblish/cgi-bin/test.cgi ############################################# From printers@sendme.cz Thu Jan 24 21:11:15 2002 From: printers@sendme.cz (A) Date: Thu, 24 Jan 2002 22:11:15 +0100 Subject: [Tutor] How to avoid socket timeout Message-ID: <3C508683.26583.90E6FB@localhost> Hi, I use httplib modul and sometimes, if my dial up connection is slow, receive error: (10060, 'Operation timed out') How can I increase the timeout? Thank you for help. Ladislav From vcardon@siue.edu Thu Jan 24 21:06:01 2002 From: vcardon@siue.edu (Victor R. Cardona) Date: Thu, 24 Jan 2002 15:06:01 -0600 Subject: [Tutor] Python in Apache? In-Reply-To: ; from israel@lith.com on Thu, Jan 24, 2002 at 12:59:24PM -0800 References: Message-ID: <20020124150601.B1517@client156-52.ll.siue.edu> --l76fUT7nc3MelDdI Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Thu, Jan 24, 2002 at 12:59:24PM -0800, Israel Evans wrote: >=20 > Has anyone here ever attempted to get Python cgi=20 > files to run in an apache server? I seem to be having=20 > trouble though everything looks right and I don't know=20 > whether it's python or apache that's causing me problems. It works just like any other CGI script. > ###################################### >=20 > #! % python >=20 > header =3D "Content-type: text/html\n\n" > content =3D "Hello, Baby." >=20 > print header, content >=20 > ###################################### That should work. > I get the following error message: > #################################### >=20 > Internal Server Error >=20 > The server encountered an internal error or=20 > misconfiguration and was unable to complete your request. >=20 > Please contact the server administrator, Israel@lith.com=20 > and inform them of the time the error occurred, and anything=20 > you might have done that may have caused the error. >=20 > More information about this error may be available in the=20 > server error log. What does the log say? The http-errors log will actually list the python error messages. At least it does on UNIX. -v --=20 Victor R. Cardona Powered by SuSE Linux 7.1 (i386) Professional GPG key ID E81B3A1C Key fingerprint =3D 0147 A234 99C3 F4C5 BC64 F501 654F DB49 E81B 3A1C --l76fUT7nc3MelDdI Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iD8DBQE8UHc5ZU/bSegbOhwRAji9AKCAp8WX+HwKgum7sl/gujfzATub+gCgjoNq eCPpQozNt1r5VvUebcPzatk= =5Mw3 -----END PGP SIGNATURE----- --l76fUT7nc3MelDdI-- From israel@lith.com Thu Jan 24 21:16:06 2002 From: israel@lith.com (Israel Evans) Date: Thu, 24 Jan 2002 13:16:06 -0800 Subject: [Tutor] Python in Apache? Message-ID: > What does the log say? The http-errors log will actually list the python > error messages. At least it does on UNIX. it tells me this:: [Thu Jan 24 08:08:42 2002] [error] [client 127.0.0.1] attempt to invoke directory as script: c:/weblish/cgi-bin [Thu Jan 24 08:11:28 2002] [error] [client 127.0.0.1] couldn't spawn child process: c:/weblish/cgi-bin/test.cgi From James.Alexander.McCarney@Cognicase.com Thu Jan 24 21:18:11 2002 From: James.Alexander.McCarney@Cognicase.com (McCarney, James Alexander) Date: Thu, 24 Jan 2002 16:18:11 -0500 Subject: [Tutor] RE: Python in Apache Message-ID: <23FD7B1A77E8D211BCB900001D108C02018B2952@camelot> Hi Israel. It worked for me when I tried I saved your code as baby.py and put it in my cgi-bin. James Alexander McCarney, technical writer (450) 928-3386 x2262 Cognicase - M3i Systems, 1111 Saint-Charles Avenue West 11th Floor, East Tower, Longueuil, Quebec, J4K 5G4 Canada http://www.m3isystems.com mailto:James.Alexander.McCarney@Cognicase.com From israel@lith.com Thu Jan 24 21:25:48 2002 From: israel@lith.com (Israel Evans) Date: Thu, 24 Jan 2002 13:25:48 -0800 Subject: [Tutor] RE: Python in Apache Message-ID: Darn,,,, well, that's good actually, but that means my Apache set up needs help... Back to the Depths of the Docs and On with the Guess-Work! :) ~Israel~ -----Original Message----- From: McCarney, James Alexander [mailto:James.Alexander.McCarney@Cognicase.com] Sent: Thursday, January 24, 2002 1:18 PM To: 'israel@lith.com' Cc: 'tutor@python.org' Subject: [Tutor] RE: Python in Apache Hi Israel. It worked for me when I tried I saved your code as baby.py and put it in my cgi-bin. James Alexander McCarney, technical writer (450) 928-3386 x2262 Cognicase - M3i Systems, 1111 Saint-Charles Avenue West 11th Floor, East Tower, Longueuil, Quebec, J4K 5G4 Canada http://www.m3isystems.com mailto:James.Alexander.McCarney@Cognicase.com _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From virketis@fas.harvard.edu Thu Jan 24 21:57:07 2002 From: virketis@fas.harvard.edu (Pijus Virketis) Date: Thu, 24 Jan 2002 16:57:07 -0500 Subject: [Tutor] Python vs. PHP Message-ID: <200201242156.g0OLuoZ31076@smtp3.fas.harvard.edu> Looking around, I find what seem like two different kinds of dynamic webpages. Some are written in Perl (Slashcode) or Python (Yahoo search, for instance), i.e. "proper" scripting languages, and others are done in ASP/PHP. I guess the former are CGI scripts, and the latter are active server pages. What are the relative merits of doing things one way or the other? If I have a database, which I want to make accessible from the web, and I can choose between Python or PHP, what should I consider on the design/performance level? Think in the broadest of terms, because I have little understanding of even the spectrum of options available between good old static HTML and PHP, which I currently use and which is totaly dynamic. Cheers, Pijus p.s. I finally managed to get Python, MySQLdb and MySQL to work together on my ISP's server, which is why I suddenly have the luxury of choice. :) ------------------------------------------------------------ PGP PUBLIC KEY: www.fas.harvard.edu/~virketis/links My weblog: www.fas.harvard.edu/~virketis From miracle@paradise.net.nz Thu Jan 24 21:28:00 2002 From: miracle@paradise.net.nz (Matthew) Date: Fri, 25 Jan 2002 10:28:00 +1300 Subject: [Tutor] Re: How to avoid socket timeout References: <3C508683.26583.90E6FB@localhost> Message-ID: <002001c1a51e$00e082c0$0100a8c0@Jonah> I think theres something in the windows registry, and also in the API. It's called Time To Live (TTL) this won't help much with time out but it'll reduce the chances of it happening. If I remember rightly, when a socket in Windows is trying to connect, it sends 4 connection request packet thingies, with a certain time between them, and if it doesn't receive an acknoledge packet, it times out. Each time a packet passes through a router, it's TTL (Time to Live) is decremented, if there's a blockage or bad routes, the packet might have to take an extra long route to get to the other computer. If you increase the TTL, this will stop timeout's in this situation. Also sometimes timeouts are caused by [cable] modems dialling, or sleeping equipment waking up. To avoid this, just eat the first couple of exceptions and try again ;) GBU Matthew ----- Original Message ----- From: "A" To: ; ; Sent: Friday, January 25, 2002 10:11 AM Subject: How to avoid socket timeout > Hi, > I use httplib modul and sometimes, if my dial up connection is > slow, receive > error: (10060, 'Operation timed out') > How can I increase the timeout? > Thank you for help. > Ladislav > > _______________________________________________ > ActivePython mailing list > ActivePython@listserv.ActiveState.com > http://listserv.ActiveState.com/mailman/listinfo/activepython > From lkvam@venix.com Thu Jan 24 22:11:09 2002 From: lkvam@venix.com (Lloyd Kvam) Date: Thu, 24 Jan 2002 17:11:09 -0500 Subject: [Tutor] creating variables at runtime References: <3C5059EC.F1DCBF22@ccvcorp.com> Message-ID: <3C50867D.2030400@venix.com> I believe you are right about creating specific dictionaries to support this. I went to the trouble of creating a list to avoid checking every __getattr__ key argument against globals(). Using a dictionary to provide both the check and the function reference makes a lot of sense. Thank you very much! Jeff Shannon wrote: >>Lloyd Kvam wrote: >> > >>I've been using globals() in kind of the reverse way to create class instances based >>on the desired class name, sort of a quick Class Factory Method. >> instance = globals()['Classname']() >> > > Actually, this is much closer to the "right" way to use globals(), I think. I know that > the corresponding locals() function returns a dictionary that should be considered > read-only (effects of altering it are undefined), and my gut reaction is to try to treat > globals() the same way (though, admittedly, I don't see a similar warning about globas() > in the docs). Then again, in almost any case where something like this might be useful, > I'd prefer to create a dictionary and just use that. For instance, in your sample code... > > > > >>class Site(Table): >> fk_obj_list = ['Reservation','Siteprice'] >>class Siteprice(Table): >>class Reservation(Table): >> > > I'd do this as: > > class Siteprice(Table): > class Reservation(Table): > > class Site(Table): > fk_objects = { 'Reservation': Reservation, 'Siteprice': Siteprice } > > and then when I needed to create the class, I could do > > if key in self.fk_objects.keys(): > obj = self.fk_objects[key]() > > Of course, this may just be my personal style, and YMMV and all, but I think that this is > more explicit, and cleaner, than using globals(). > > Jeff Shannon > Technician/Programmer > Credit International > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From pythontutor@venix.com Thu Jan 24 22:43:27 2002 From: pythontutor@venix.com (Lloyd Kvam) Date: Thu, 24 Jan 2002 17:43:27 -0500 Subject: [Tutor] Python vs. PHP References: <200201242156.g0OLuoZ31076@smtp3.fas.harvard.edu> Message-ID: <3C508E0F.1090309@venix.com> Yet another choice is a web server written in your scripting language. The server is also the application. ZOPE is a great example of this approach. You can use your own Python scripts to implement functions or configure / program ZOPE's facilities. ZOPE comes with DB access built in. Executing an SQL command and embedding the results in a web page is very easy. There are (finally) books that offer reasonable guidance in using ZOPE as well as many online references. If you already have working Python scripts that generate HTML and simply need to be hooked up to an HTTP server, CGI may be much simpler. Pijus Virketis wrote: > Looking around, I find what seem like two different kinds of dynamic > webpages. Some are written in Perl (Slashcode) or Python (Yahoo search, for > instance), i.e. "proper" scripting languages, and others are done in > ASP/PHP. I guess the former are CGI scripts, and the latter are active > server pages. What are the relative merits of doing things one way or the > other? If I have a database, which I want to make accessible from the web, > and I can choose between Python or PHP, what should I consider on the > design/performance level? Think in the broadest of terms, because I have > little understanding of even the spectrum of options available between good > old static HTML and PHP, which I currently use and which is totaly dynamic. > > Cheers, > > Pijus > > p.s. I finally managed to get Python, MySQLdb and MySQL to work together on > my ISP's server, which is why I suddenly have the luxury of choice. :) > ------------------------------------------------------------ > PGP PUBLIC KEY: www.fas.harvard.edu/~virketis/links > My weblog: www.fas.harvard.edu/~virketis > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From fallen@leveltwo.com Thu Jan 24 22:45:27 2002 From: fallen@leveltwo.com (Fred Allen) Date: Thu, 24 Jan 2002 14:45:27 -0800 Subject: [Tutor] Gaining Multiprocessor Systems' Throughput Benefits Message-ID: <4BB02C541824D311921600902765DB7B445BDE@LTISERVER> Dear Sirs and Mesdames: I understand that Python's interpreter sets a global lock that bars concurrently active multiple threads. Thus, Python's threading model provides no direct means to benefit from multiprocessors. I've related questions and a request. I fear this mayn't be the forum for either. If it isn't, I'd be just as pleased by the identity of a preferable forum. 1. I cannot find a PEP describing any change that might enable Python's threading model to gain the benefits of multiple processors. Has such a change been considered and rejected? Tabled for later consideration, e.g., Python 3.0? 2. Have any among you used multiple instantiations of the Python interpreter to gain some of the benefits multiprocessor systems offer? If so, would you please bare the code by which you did so and some estimate of the marginal gain per additional processor? With thanks in advance for any help, I am, Respectfully, Fred Allen From dyoo@hkn.eecs.berkeley.edu Thu Jan 24 23:18:23 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 24 Jan 2002 15:18:23 -0800 (PST) Subject: [Tutor] thanks (fwd) Message-ID: (Keith said it was ok to forward his thanks to everyone on Tutor.) ---------- Forwarded message ---------- Date: Sun, 20 Jan 2002 19:30:36 -0800 From: kjphotog@juno.com To: tutor-admin@python.org Subject: thanks I'm a newbie & quite impressed with ALL the info & support that's available to Python users. My POP3 question was quickly & correctly answered by one of your tutors, Tara. Thanks, Keith Johnson ________________________________________________________________ GET INTERNET ACCESS FROM JUNO! Juno offers FREE or PREMIUM Internet access for less! Join Juno today! For your FREE software, visit: http://dl.www.juno.com/get/web/. From dyoo@hkn.eecs.berkeley.edu Thu Jan 24 23:24:03 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 24 Jan 2002 15:24:03 -0800 (PST) Subject: [Tutor] Re: thanks (fwd) Message-ID: (... I'm still clearing out my mailbox, and I noticed that this wasn't sent to Tutor. Sorry about that! Keith, when you're replying, make sure to send to the tutor@python.org address, so that your questions won't get lost.) ---------- Forwarded message ---------- Date: Mon, 21 Jan 2002 09:02:50 -0800 From: kjphotog@juno.com To: dyoo@hkn.eecs.berkeley.edu Subject: Re: thanks Danny, Absolutely, feel to pass my thanks-alot message to all concerned. In fact, I may need to post another question... When I ran Tara's example, import poplib pop = poplib.POP3('server', 'port') pop.user('username') pop.pass_('password') num_msg_list = len(pop.list()[1]) # Iterate over all messages. for i in range(num_msg_list): # Loop over all lines of the message, except index 1, which is the response. for j in pop.retr(i+1)[1]: # Print the line. print j Then I got only a quick peek at my message list before my screen exploded into an alphabet soup (flood of letters). I wasn't able to save any of my script for show & tell, I had to CtrlAltD to stop the program. Do I need to decode my messages to read them? Thanks again. As for those newbies like me who want to learn Py in a hurry. Well, I've gone from printing 'hello world' (and why do I wanna do that?) to almost being able to get my e-mail in a short amount of time. As a high school photo instructor I can't wait to learn about Pythons imaging abilities. By the way, what do you do at Berkeley? Keith ------------------------------------------------------------------------- ------------------- On Sun, 20 Jan 2002 20:48:10 -0800 (PST) Danny Yoo writes: > On Sun, 20 Jan 2002 kjphotog@juno.com wrote: > > > I'm a newbie & quite impressed with ALL the info & support that's > > available to Python users. My POP3 question was quickly & > correctly > > answered by one of your tutors, Tara. > > No problem! > > Is it ok if I forward your thanks to the Tutor list itself? The > tutor-admin stuff goes to just three people: Deirdre, Wesley, and > me. > We're certainly not the responsible party here. *grin* > > From dyoo@hkn.eecs.berkeley.edu Thu Jan 24 23:25:07 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 24 Jan 2002 15:25:07 -0800 (PST) Subject: [Tutor] active state or py.org (fwd) Message-ID: ---------- Forwarded message ---------- Date: Wed, 23 Jan 2002 04:21:45 -0800 From: kjphotog@juno.com To: dyoo@hkn.eecs.berkeley.edu Subject: active state or py.org You recommend window users to download Python from their org -OR- is it better to download the windows version from Active State? Appreciate your tutorial link, I'll check it out. --By the way, from your cs.berk.edu I presume you're in the computer science dept. I teach at a small private school (k-12) here in Los Angeles & we're about to upgrade our lab. And we're currently seeking a computer teacher/guru type to get our technology program back on track-- Thanks Keith From dsh8290@rit.edu Thu Jan 24 23:33:29 2002 From: dsh8290@rit.edu (dman) Date: Thu, 24 Jan 2002 18:33:29 -0500 Subject: [Tutor] open files other than text? In-Reply-To: <28438-3C4E3E38-4976@storefull-168.iap.bryant.webtv.net> References: <28438-3C4E3E38-4976@storefull-168.iap.bryant.webtv.net> Message-ID: <20020124233329.GA5475@dman.ddts.net> On Tue, Jan 22, 2002 at 11:38:16PM -0500, Ron wrote: | I have windows 98 Python2.2. Can you open files other than text files. I | tried to open a .doc file and just got a line of giberish. What kind of | things can be opened? That "gibberish" is what word put in the file. The problem you have is that your code doesn't understand the gibberish. Plain text files are easier to handle because humans can read them too (usually). Regardless of the type of file, you must know the format to deal with it reasonably. For example, is it a flat list of items? is it XML? is it structured in some other way? is it an image? if so, what format (could be a standard one like jpeg or it could be a custom format no one else knows)? -D -- Dishonest money dwindles away, but he who gathers money little by little makes it grow. Proverbs 13:11 From dsh8290@rit.edu Thu Jan 24 23:34:25 2002 From: dsh8290@rit.edu (dman) Date: Thu, 24 Jan 2002 18:34:25 -0500 Subject: [Tutor] ftp and python enabled editor In-Reply-To: <00a801c1a4f5$71c08630$18adf78c@virketis2> References: <00a801c1a4f5$71c08630$18adf78c@virketis2> Message-ID: <20020124233425.GB5475@dman.ddts.net> On Thu, Jan 24, 2002 at 11:37:42AM -0500, Pijus Virketis wrote: | Hi all, | | A quick question about the tools of programming. I remember the long | discussion a few months ago about editors: my requirements are much | narrower here. Is there a program that can open and save files via | FTP on a remote location, supports Python syntax highlighting and | works on Windows? I usually use SciTE or just good old IDLE, but | neither can do FTP ... vim (or gvim if you want a gui) -D -- Many a man claims to have unfailing love, but a faithful man who can find? Proverbs 20:6 From dyoo@hkn.eecs.berkeley.edu Thu Jan 24 23:35:41 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 24 Jan 2002 15:35:41 -0800 (PST) Subject: [Tutor] active state or py.org (fwd) In-Reply-To: Message-ID: On Thu, 24 Jan 2002, Danny Yoo wrote: > You recommend window users to download Python from their org -OR- is > it better to download the windows version from Active State? > Appreciate your tutorial link, I'll check it out. Either distribution is ok. If you're planning to do Windows specific stuff, the ActiveState version seems nicer because it's bundled with some Windows-specific modules as well as a text editor called PythonWin. I have to say, though, that I'm not the best person to ask about this: I run Debian Linux on my home system, so I haven't really had too much experience with the Windows stuff. Sorry! > --By the way, from your cs.berk.edu I presume you're in the computer > science dept. I wish. *grin* I just graduated from Berkeley, and just have been able to retain my email address at hkn.eecs.berkeley.edu. Otherwise, I don't have a formal affiliation with Berkeley. From vcardon@siue.edu Thu Jan 24 23:34:21 2002 From: vcardon@siue.edu (Victor R. Cardona) Date: Thu, 24 Jan 2002 17:34:21 -0600 Subject: [Tutor] Python in Apache? In-Reply-To: ; from israel@lith.com on Thu, Jan 24, 2002 at 01:16:06PM -0800 References: Message-ID: <20020124173421.A2365@client156-52.ll.siue.edu> --d6Gm4EdcadzBjdND Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Thu, Jan 24, 2002 at 01:16:06PM -0800, Israel Evans wrote: > it tells me this:: >=20 > [Thu Jan 24 08:08:42 2002] [error] [client 127.0.0.1]=20 > attempt to invoke directory as script: c:/weblish/cgi-bin >=20 > [Thu Jan 24 08:11:28 2002] [error] [client 127.0.0.1]=20 > couldn't spawn child process: c:/weblish/cgi-bin/test.cgi Try renaming your cgi script to test.py. I think windows needs the ".py" extension in order to execute the script with the Python interpreter. -v --=20 Victor R. Cardona Powered by SuSE Linux 7.1 (i386) Professional GPG key ID E81B3A1C Key fingerprint =3D 0147 A234 99C3 F4C5 BC64 F501 654F DB49 E81B 3A1C --d6Gm4EdcadzBjdND Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iD8DBQE8UJn9ZU/bSegbOhwRAgp7AJ9hDYUNAyGcWIfTvM0FQ1LqcP5LywCdHXMe SRYkKKYEt5MofK0Dc8/T1jU= =i3TS -----END PGP SIGNATURE----- --d6Gm4EdcadzBjdND-- From dsh8290@rit.edu Thu Jan 24 23:44:51 2002 From: dsh8290@rit.edu (dman) Date: Thu, 24 Jan 2002 18:44:51 -0500 Subject: [Tutor] Gaining Multiprocessor Systems' Throughput Benefits In-Reply-To: <4BB02C541824D311921600902765DB7B445BDE@LTISERVER> References: <4BB02C541824D311921600902765DB7B445BDE@LTISERVER> Message-ID: <20020124234451.GC5475@dman.ddts.net> On Thu, Jan 24, 2002 at 02:45:27PM -0800, Fred Allen wrote: | Dear Sirs and Mesdames: | | I understand that Python's interpreter sets a global lock that | bars concurrently active multiple threads. The lock is for synchronization. It is only used when two (or more) threads require mutually exclusive access. | Thus, Python's threading model provides no direct means to benefit | from multiprocessors. If it uses kernel-level (or "system" level) threads instead of user-level (or "green") threads it can. | I've related questions and a request. I | fear this mayn't be the forum for either. If it isn't, I'd | be just as pleased by the identity of a preferable forum. | | 1. I cannot find a PEP describing any change that might | enable Python's threading model to gain the benefits of | multiple processors. Has such a change been considered and | rejected? Tabled for later consideration, e.g., Python 3.0? | | 2. Have any among you used multiple instantiations of the | Python interpreter to gain some of the benefits | multiprocessor systems offer? If so, would you please bare | the code by which you did so and some estimate of the | marginal gain per additional processor? I've done almost no parallel work with python, but I've done a fair amount of work with java threads. This article from Sun regarding the performance of java and solaris on multiprocessor machines may interest you : http://www.sun.com/software/white-papers/wp-realtime/ The concepts described are not java- or solaris-specific. You'll get multiprocessor advantage in any program if kernel-level threads or multiple processes are used. I don't know of cpython uses kernel-level threads (I think it does) on which platforms or if it has a "green" thread implementation. HTH, -D -- He who spares the rod hates his son, but he who loves him is careful to discipline him. Proverbs 13:24 From e.kotyk@shaw.ca Fri Jan 25 00:17:30 2002 From: e.kotyk@shaw.ca (Eve Kotyk) Date: Fri, 25 Jan 2002 00:17:30 +0000 Subject: [Tutor] Need help with dict.calculation References: Message-ID: <3C50A41A.8FFA7745@shaw.ca> Thanks Danny, > ### > def get_total_calories(): > print "Enter all foods you have eaten today." > more="" > total_calories = {} ## <--- here's the change Well that makes total sense, and I didn't have it defined properly. Its still not working but I'm going to continue withit for awhile. Want thing I do seem to be gifted with is persistence. > while more != "n": > items, portion, cal_portion = gather_data() > total_calories[items] = portion * cal_portion > more = raw_input("Do you want to continue? y/n: ") > for i in total_calories.values(): > total = total + i > print "Total calories: ", total This is giving me the total only of the last item entered. In another version I'm at least getting a total for each item entered. You know I can visualize this so well but I just don't know how to say: Look at each item see what values it has and add up all those values in to one number..in Python. E From e.kotyk@shaw.ca Fri Jan 25 00:22:01 2002 From: e.kotyk@shaw.ca (Eve Kotyk) Date: Fri, 25 Jan 2002 00:22:01 +0000 Subject: [Tutor] Need help with dict.calculation References: Message-ID: <3C50A529.E135D0F5@shaw.ca> Sean 'Shaleh' Perry wrote: Thanks I'll store this in my Python file for further reference. I can't say I totally understand it but will continue to think about it. > I have been writing a program at work which reads a log and keeps a running > count of machine reboots per machine. A nifty way to handle the increment is > the get() method of dictionaries. > > dict[key] = dict.get(key, 0) + 1 > > OK, so this doesn't help directly, but I thought I would share. Onto the real > help. > > Another useful python function is 'reduce'. reduce takes a list and runs a > function on each item in the list plus a running variable. > > from above I have: > > import operator > count = reduce(operator.add, dict.values()) > print "Total reboot count for all machines was " + count > > What reduce does is more clear if I show you what operator.add looks like: > > def add(x, y): > return x + y > > so what the reduce function does internally is basically: > > value = 0 > for item in list: > value = function(value, item) > return value > > Hope this gives you some glimpses of python's abilities. -- ekotyk http://members.shaw.ca/e.kotyk/virtualstudio.htm From jeff@ccvcorp.com Fri Jan 25 00:43:55 2002 From: jeff@ccvcorp.com (Jeff Shannon) Date: Thu, 24 Jan 2002 16:43:55 -0800 Subject: [Tutor] active state or py.org (fwd) References: Message-ID: <3C50AA4A.D613B1@ccvcorp.com> > Danny Yoo wrote: > > > Keith wrote: > > > You recommend window users to download Python from their org -OR- is > > it better to download the windows version from Active State? > > Appreciate your tutorial link, I'll check it out. > > Either distribution is ok. If you're planning to do Windows specific > stuff, the ActiveState version seems nicer because it's bundled with some > Windows-specific modules as well as a text editor called PythonWin. > > I have to say, though, that I'm not the best person to ask about this: I > run Debian Linux on my home system, so I haven't really had too much > experience with the Windows stuff. Sorry! If you're intending to run Python mostly on Windows (as I do), then I highly recommend getting the ActiveState distribution. It includes a number of Windows-specific extensions, as Danny noted, and I personally find the PythonWin IDE to be easier and more powerful than IDLE (though of course YMMV). You can also get these extensions (and PythonWin) for the Pythonlabs (python.org) distribution (as the win32all package), but it's simpler and cleaner to use ActiveState's. The Windows extensions include a COM framework, which lets you interact with a *huge* number of Windows applications (including controlling MS Office and interacting with the Windows Scripting Host), an NT Services framework (allowing you to create "always-on" background processes), and access to the Windows GUI through MFC (though in this case, I'd recommend using wxPython instead--a simpler-to-use, cross-platform GUI library). Jeff Shannon Technician/Programmer Credit International From e.kotyk@shaw.ca Fri Jan 25 00:32:24 2002 From: e.kotyk@shaw.ca (Eve Kotyk) Date: Fri, 25 Jan 2002 00:32:24 +0000 Subject: [Tutor] Need help with dict.calculation References: <3C482912.382FAC24@shaw.ca> <001901c1a0d6$31c51690$da00a8c0@Sun> <3C4F6C69.CA28E42@shaw.ca> <004f01c1a4a1$b2611000$da00a8c0@Sun> Message-ID: <3C50A798.770DA8C4@shaw.ca> > > Do you intend to use the contents of the dictionary after you've calculated > the total calories? If not, it isn't really necessary to ask what type of > food it is, nor even to keep the data in a dictionary. This is all you would > need: > > def gather_data(): > portion=input("Enter number of portions: ") > cal_portion=input("Enter calories per portion: ") > return portion,cal_portion > > def get_total_calories(): > print "Enter all the foods you have eaten today." > total_calories=0 #It's now an integer instead of a dictionary, just > to hold the number of calories > more="" > while more!="n": > portion,cal_portion=gather_data() > total_calories=total_calories+portion*cal_portion > more=raw_input("Do you want to continue? y/n: ") > print "Total calories: ",total_calories > > But if you need to know what the names of the foods and such things > afterwards... stick to your first approach. Thank you. I will look at this carefully too. Actually what I'm trying to do is essentially write a program that will be among other things a dietary diary. Because I'm a newbie to programming I'm taking it all in small bits in order to learn. So for starters I thought I'd write this module as a dictionary because after this I would like to write this so this can be done for each day of the week (like in the truckers schedule) then I want to learn to write it to a file. Eventually, this should all be kept in a food database from which you can select items rather then type them in and the calculations will not only be for calories but will compare other food values (% protein, fats, carbs etc.) to the recommended daily guidelines put out by the health dept. Of course by this time it should have GUI interface and then I'd like it to be accessible/usable from a website. =) Nothing like thinking big eh? E > > -- > > > > ekotyk > > > > http://members.shaw.ca/e.kotyk/virtualstudio.htm > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > -- ekotyk http://members.shaw.ca/e.kotyk/virtualstudio.htm From kimtitu@yahoo.com Fri Jan 25 01:24:01 2002 From: kimtitu@yahoo.com (Titu Kim) Date: Thu, 24 Jan 2002 17:24:01 -0800 (PST) Subject: [Tutor] Exporting an web report Message-ID: <20020125012401.22562.qmail@web14707.mail.yahoo.com> Hi all, I am trying to find an efficient way to allow web user to export a report into simple text file that he/she is viewing in a browser. How can i accomplish this goal ? Thanks Regards, Kim TItu __________________________________________________ Do You Yahoo!? Great stuff seeking new owners in Yahoo! Auctions! http://auctions.yahoo.com From bronto@pobox.com Fri Jan 25 02:29:58 2002 From: bronto@pobox.com (Anton Sherwood) Date: Thu, 24 Jan 2002 18:29:58 -0800 Subject: [Tutor] PNG pixels Message-ID: <3C50C326.AA910D31@pobox.com> I want to take two .png images from the commandline, convert them to lists of pixels (lists of lists of tuples if necessary), do stuff with them, make a new list of pixels and save it as a .png file. Is there library support to make this easy? -- -- Anton Sherwood -- http://www.ogre.nu/ -- "If nobody said anything unless he knew what he was talking about, a ghastly hush would descend upon the earth." ---Sir Alan Herbert From dyoo@hkn.eecs.berkeley.edu Fri Jan 25 03:25:45 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 24 Jan 2002 19:25:45 -0800 (PST) Subject: [Tutor] PNG pixels In-Reply-To: <3C50C326.AA910D31@pobox.com> Message-ID: On Thu, 24 Jan 2002, Anton Sherwood wrote: > I want to take two .png images from the commandline, convert them to > lists of pixels (lists of lists of tuples if necessary), do stuff with > them, make a new list of pixels and save it as a .png file. Is there > library support to make this easy? You may be interested in the Python Imaging Library: http://www.pythonware.com/products/pil/ I believe that PIL should have support for PNG images, and you should be able to manipulate your pngs with it. Good luck! From toodles@yifan.net Fri Jan 25 04:25:54 2002 From: toodles@yifan.net (Andy W) Date: Fri, 25 Jan 2002 12:25:54 +0800 Subject: [Tutor] Need help with dict.calculation References: <3C50A41A.8FFA7745@shaw.ca> Message-ID: <009501c1a558$626cd810$da00a8c0@Sun> > Well that makes total sense, and I didn't have it defined properly. Its > still not working but I'm going > to continue withit for awhile. Want thing I do seem to be gifted with > is persistence. def gather_data(): items = raw_input("Add food item: ") portion = input("Enter number of portions: ") cal_portion = input("Enter calories per portion: ") return items,portion,cal_portion def get_total_calories(): print "Enter all foods you have eaten today." more="" total_calories = {} ## <--- here's the change while more != "n": items, portion, cal_portion = gather_data() total_calories[items] = portion * cal_portion more = raw_input("Do you want to continue? y/n: ") total=0 #<--- this bit was missing this time! ;o) for i in total_calories.values(): total = total + i print "Total calories: ", total Let's test it! Hmm I need some fattening up, how about... >>> get_total_calories() Enter all foods you have eaten today. Add food item: Double Whopper with Cheese Enter number of portions: 1 Enter calories per portion: 960 Do you want to continue? y/n: y Add food item: Chinese Chicken Salad Large Enter number of portions: 1 Enter calories per portion: 191 Do you want to continue? y/n: n Total calories: 1151 >>> Looks like it's working! Andy From erikprice@mac.com Fri Jan 25 04:41:28 2002 From: erikprice@mac.com (Erik Price) Date: Thu, 24 Jan 2002 23:41:28 -0500 Subject: [Tutor] creating variables at runtime In-Reply-To: <3C4FBAD3.5323728C@shaw.ca> Message-ID: > Kirby Urner wrote: > >> People who come to Python from VB or C++ are more likely >> to think in terms of self-contained programs that either >> take arguments at the top, or prompt for a few inputs, >> then go. But I come from a Visual FoxPro background which >> boots to a command window. Half the time I'm just sitting >> at the command line, opening data tables, sorting, listing. >> Modifying structure. If I need a utility, I write it >> quickly, then run it. No need to exit the shell. I bring >> this same psychology to Python. >> I go into all this because I think newcomers especially >> should appreciate the two modes. I think sometimes people >> who program professionally get so used to whatever mode >> they use that they forget... > I'm very confused about this intriguing description, Kirby. Do you mean that you use the Python interactive mode as your interpretive shell for doing work on your system? And that when you need some sort of tool or functionality, you just whip it up on the spot? If that's what you're saying, I'm pretty awed. I know that theoretically, there's not much difference between, for instance, doing that and doing the same thing in the bash shell (I use bash on Darwin or Linux). But there are so many pre-built tools for bash ... wasn't POSIX developed so that we wouldn't have to write all of our own programs all the time? To be able to work at this level, if that's what you're saying, is mind boggling. Erik From erikprice@mac.com Fri Jan 25 04:52:05 2002 From: erikprice@mac.com (Erik Price) Date: Thu, 24 Jan 2002 23:52:05 -0500 Subject: [Tutor] Re: List Comprehensions again In-Reply-To: <1011897437.3875.3.camel@asimov> Message-ID: <476F88A9-114F-11D6-B3B1-00039351FE6A@mac.com> On Thursday, January 24, 2002, at 01:37 PM, Tom Jenkins wrote: > On Thu, 2002-01-24 at 11:54, kevin parks wrote: >> I have never been able to get my head around list comprehension and >> desperately want too. I wish that there was a *good* little 2-3 page >> toot on list comprehensions that start from the very clearest and >> simplest examples and built up from there with nice explanations in >> between. The www.python.org web site is a bit terse for me and none of (snip) > i came to python before list comprehensions. it took me A LONG TIME to > understand map/filter/lambda... actually i'll say i still don't really > understand them. > > when i first saw list comprehensions, i thought "I have NO CLUE what > this is doing". then i started playing. i took a map/lambda (snip) As a superfledgling, I have to say that I have no idea what you guys are talking about. For the first few messages I figured it was something that I could pick up later on. Now this thread has gone on for several days and I'm starting to wonder if I should learn this lambda / list comprehensions thing now before I run into the troubles that others describe (who seem to be saying that "they wish they'd learned it a different way" -- I want to learn it that way first so I can save the hassle). Where should I look for more info, or is this something that can wait until I am more comfortable with the language? (I am just finishing tutorials on syntax so you can see that I am really really green at this.) Thank you, Erik From erikprice@mac.com Fri Jan 25 05:17:35 2002 From: erikprice@mac.com (Erik Price) Date: Fri, 25 Jan 2002 00:17:35 -0500 Subject: [Tutor] Python vs. PHP In-Reply-To: <200201242156.g0OLuoZ31076@smtp3.fas.harvard.edu> Message-ID: On Thursday, January 24, 2002, at 04:57 PM, Pijus Virketis wrote: > Looking around, I find what seem like two different kinds of dynamic > webpages. Some are written in Perl (Slashcode) or Python (Yahoo search, > for > instance), i.e. "proper" scripting languages, and others are done in > ASP/PHP. I guess the former are CGI scripts, and the latter are active > server pages. What are the relative merits of doing things one way or > the > other? If I have a database, which I want to make accessible from the > web, > and I can choose between Python or PHP, what should I consider on the > design/performance level? Think in the broadest of terms, because I have > little understanding of even the spectrum of options available between > good > old static HTML and PHP, which I currently use and which is totaly > dynamic. Pijus, Let me say straight out that I am a novice to Python. I am subscribed to this mailing list because I have read a bit about programming languages and would like to learn more about programming, Python seems to be a well-supported language for beginners. So, without being able to compare Python to PHP, I would like to tell you a bit about PHP. I started learning PHP two months ago and have been picking it up part-time. Yet, I feel like I can do quite a bit with the PHP/MySQL combination. PHP is a very very easy language to start off with, in my experience. It's great because, when combined with HTML, it's like writing a program with a GUI from the get-go (admittedly a browser makes for a very limited GUI), so you get a great feeling that you're actually writing some USEFUL programs. And PHP's other advantage is that it's really oriented toward making dynamic web pages. Let's face it, besides a few folks who like to experiment for the sake of experimenting (the most noble kind of experimenting of all), no one uses PHP for much beyond dynamic web development. Another big advantage of PHP is that the code is embedded in the HTML (or vice versa, doesn't really matter) -- you can literally jump in and out of "PHP mode" using open and closing tags. This is really flexible, as you can write your entire page in HTML and add the PHP where it's needed, or you can write your entire page in PHP and include HTML where needed (or print it where needed). PHP is designed to be extraordinarily compatible with MySQL and Apache (hence the common LAMP acronym for Linux, Apache, MySQL, and PHP = great combination), and features many custom functions for accessing MySQL. In short, knowing NOTHING about web pages except very basic HTML, I started with PHP as my first programming language (except of course BASIC and a bit of bash scripting), and am well under way in developing a database-driven web application using LAMP -- learning Python is something that I am doing for myself, not for my boss. If you are looking for a language that you can start banging out dynamic content via the web very easily and quickly, PHP is a great one. But I would imagine that there is far more that you can do with Python, and a part of me wishes that I had started learning Python first and then moved on to PHP -- I have a difficult time thinking in terms of "traditional" programming because I am so accustomed to thinking about the "stateless" nature of web pages, where variables need to be passed from page to page. Good luck, Erik PS: I'm sure that you can use PHP for things that it works well for (MySQL connectivity, display stuff), and Python for more advanced programs that you wish to execute on the server. No need to choose one over the other! From erikprice@mac.com Fri Jan 25 05:20:52 2002 From: erikprice@mac.com (Erik Price) Date: Fri, 25 Jan 2002 00:20:52 -0500 Subject: [Tutor] Python vs. PHP In-Reply-To: <3C508E0F.1090309@venix.com> Message-ID: <4CC4C6E6-1153-11D6-B3B1-00039351FE6A@mac.com> > Pijus Virketis wrote: > >> Looking around, I find what seem like two different kinds of dynamic >> webpages. Some are written in Perl (Slashcode) or Python (Yahoo >> search, for >> instance), i.e. "proper" scripting languages, and others are done in >> ASP/PHP. I guess the former are CGI scripts, and the latter are active >> server pages. What are the relative merits of doing things one way or >> the >> other? If I have a database, which I want to make accessible from the >> web, >> and I can choose between Python or PHP, what should I consider on the >> design/performance level? Think in the broadest of terms, because I >> have >> little understanding of even the spectrum of options available between >> good >> old static HTML and PHP, which I currently use and which is totaly >> dynamic. ^^^^^ ^ ^^^^^^^^^ ^^^ Oh shoot, I was so glad to be able to help someone that I didn't even notice that you already know what PHP has to offer. I'm sorry, everyone. Erik From urnerk@qwest.net Fri Jan 25 05:40:08 2002 From: urnerk@qwest.net (Kirby Urner) Date: Thu, 24 Jan 2002 21:40:08 -0800 Subject: [Tutor] creating variables at runtime In-Reply-To: References: <3C4FBAD3.5323728C@shaw.ca> Message-ID: <4.2.0.58.20020124211704.01a42770@pop3.norton.antivirus> > >To be able to work at this level, if that's what you're saying, is mind >boggling. > > >Erik Well, I didn't really mean that, although I think it's quite possible to do, if you're already a shell guru in the OS. What I mean is, say I have this goal to generate polyhedra as text files suitable for ray tracing by Povray (a real life example). I don't start by thinking about single scripts that will take a whole lot of arguments. Rather, I imagine myself in the Python shell, needing a toolbox of goodies, where toolbox = module(s). I might write a superclass for polyhedra with a built in .display() method, and another class for writing Povray files that gets passed to .display() as an argument -- but then I'll do the importing, instancing and argument passing myself, as the "driver" or "pilot", with my Python "controls" and "instruments". Like, I'll just boot IDLE and go: >>> from polys import * >>> from povray import Povray >>> ico = Icosa() # hmmmmm, I'd like an Icosahedron today >>> ico.showfaces = 0 # but just show me edges and corners >>> outfile = Povray("myfile.pov") # this'll be the output file >>> ico.display(outfile) # ico, write yourself to the file >>> outfile.close() # I'll close the file myself (might have dumped more shapes into it). Then I'll boot Povray and render the icosahedron. According to the script mentality, I'd go to an X Window or DOS box and do something like: % > python makepoly.py Icosa, nofaces, myfile.pov or something like that. I'd be imagining gcc (a C++ compiler) which has pages and pages of command line switches -- the idea being that "launch time" is your one chance to tell the program everything it needs to know -- or maybe it'll prompt you through a bunch of steps. Or else you think you have to wrap the whole thing in a Tk GUI or something -- not supposing that the interactive shell provides a middle ground. Using Mathematica might be a good analogy. You do a lot of the work at the command line, asking for stuff. Want the 10th bernoulli number? Just ask for it, put it in a variable. Want to get this definite integral? Just type it in and hit enter. It's like the difference between APL and FORTRAN in my college years (long ago). FORTRAN was batch programming. I'd punch a stack of cards (icky) and they'd go through a card reader with a bunch of other programs (JCL cards in between to tell the jobs apart), and 20 minutes later, the line printer would come back with my results (and/or bug reports). APL was on a CRT, and I'd sit at the keyboard, enter a weird-looking expression that might do quite a lot in one line (like Python can), and zingo zango, I get a result immediately. If I want to batch a bunch of statements in an APL program, I do so as part of my session (can save a workspace too). They're probably short programs that build on each other. The feeling is of crafting an environment, a workspace, and importing stuff you don't have the time or ability or patience to write yourself (modules, Standard Library). That's how I best like to use Python. It's also how I like to learn/play with Python. Enter stuff and get an immediate reply. I think from a learning standpoint, having an interactive shell makes a *huge* difference. APL, Logo, Scheme, LISP, Python, FoxPro all have this feature -- Visual Basic to some extent in its lame 'immediate' or 'debug' window. Java and C++ natively do not, although some have written dynamic C interpreters. And as for Java, one reason people like Jython is the ability to work with Java class interactively, in a shell. It helps 'em learn regular Java. Kirby From israel@lith.com Fri Jan 25 05:43:25 2002 From: israel@lith.com (Israel Evans) Date: Thu, 24 Jan 2002 21:43:25 -0800 Subject: [Tutor] Python in Apache? Message-ID: Cool, Thanks... I've got python located and have set up the Shebang line to point to python. Right now I've got it set to #! % python which works to launch scripts when I click on them even though they aren't in the PATH or PYTHONPATH. I've also used #! c:/proj/Python22 which also works just launching the file by clicking on it. I'm not using any flavor of Unix unfortunatly, I'm using Win2000. This leads me to step 4 and how I don't know how to chmod anything on a windows machine. I can double click the file and it runs just fine. The error I seem to be getting in the Apache Error log is that the child process couldn't be launched. I'm pretty much stuck though. I've been reading the docs, but I can't seem to find anything more that I haven't done which is supposed to allow you to launch cgi's. Thanks though! The apache list seems less talkative than this one. Man I love you guys! :) ~Israel~ -----Original Message----- From: kirk Bailey [mailto:idiot1@netzero.net] Sent: Thursday, January 24, 2002 8:39 PM To: Israel Evans Subject: Re: [Tutor] Python in Apache? Sure thing. 1. ASSUMING a flavor of unix, locate python. $ whereis python python: /usr/local/bin/python /usr/local/man/man1/python.1.gz /usr/ports/lang/python $ The first one is the executable file we are intrested in. 2. Add the pouond-bang hack to the first line of your script: #!/usr/local/python # import cgi, smtp, os, string, glob # localhost='tinylist.org' # pathtostuff='/www/www.tinylist.org/cgi-bin' # etc... 3. save the file. Exact details depend on the editor used. Make sure it has the '.py' name extension in case your ggrandmother has to maintain the thing 4 years from now and has no idea which file is a python script. 4. Make sure the thing is executable. AT THE MINIMUM, turn on the X bit: $ chmod +x myscript.py BETTER is to make it 755, so the world cannot write to it, but can run it. $ chmod 755 myscript.py Hope this helps. Israel Evans wrote: > > Has anyone here ever attempted to get Python cgi > files to run in an apache server? I seem to be having > trouble though everything looks right and I don't know > whether it's python or apache that's causing me problems. > > The following is a bit long but I think it's thorough > These are the things I have set up. > > This is my script alias in httpd.config which I think is > set up correctly. The path I've set up is correct, but > I'm new to the options so I may be off. > ############################################ > > ScriptAlias /cgi-bin/ "C:/Weblish/cgi-bin/" > > > AllowOverride None > Options +ExecCGI > Order allow,deny > Allow from all > > > ############################################ > > I don't have Perl on my machine, but I do have Python, > which I like much better so I'm using that as the language > for my cgi programs. My super simple introductory cgi is > as follows. I've got Python in my Path and using this > Shebang line I'm able to run python scripts just fine by > clicking on them. > ###################################### > > #! % python > > header = "Content-type: text/html\n\n" > content = "Hello, Baby." > > print header, content > > ###################################### > > I access this cgi file by entering > "http://localhost/cgi-bin/test.cgi" > into my browser after having made sure that the Server > is running. > > I get the following error message: > #################################### > > Internal Server Error > > The server encountered an internal error or > misconfiguration and was unable to complete your request. > > Please contact the server administrator, Israel@lith.com > and inform them of the time the error occurred, and anything > you might have done that may have caused the error. > > More information about this error may be available in the > server error log. > > _____ > > Apache/1.3.20 Server at ISREAL.lith.com Port 80 > > ########################################## > > And when I look into the Error logs I find these tidbitsof information: > ############################################# > > [Thu Jan 24 08:08:42 2002] [error] [client 127.0.0.1] > attempt to invoke directory as script: c:/weblish/cgi-bin > [Thu Jan 24 08:11:28 2002] [error] [client 127.0.0.1] > couldn't spawn child process: c:/weblish/cgi-bin/test.cgi > > ############################################# > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- -Respectfully, -Kirk D Bailey Consulting Loose Cannon end www.howlermonkey.net highprimate@howlermonkey.net www.sacredelectron.org idiot1@netzero.net www.tinylist.org grumpy@tinylist.org ---------------------------------------------------- Sign Up for NetZero Platinum Today Only $9.95 per month! http://my.netzero.net/s/signup?r=platinum&refcd=PT97 From israel@lith.com Fri Jan 25 06:16:45 2002 From: israel@lith.com (Israel Evans) Date: Thu, 24 Jan 2002 22:16:45 -0800 Subject: [Tutor] Python in Apache? Message-ID: Thanks for the tip! I was able to set things up like you said and was able to get the alias to work, but after saving the file in the new aliased directory, I restarted the server and tried to execute the .py file, but I got a 404 and I was told that the file couldn't be found even though it's actually there??!! This is what the Error log tells me... (2)No such file or directory: script not found or unable to stat: c:/program files/apache group/apache/pyscriptstest.py HOLD IT! You are a SAINT! I noticed the error stated that it couldn't start the file pyscriptstest.py. What is missing here is a "/". I went in and made sure both the script alias and the directory paths in the .conf file ended with such a wonderful little character and afterwards my python file worked like a charm!!! Thanks! ~Israel~ -----Original Message----- From: Karthik Gurumurthy [mailto:karthikg@aztec.soft.net] Sent: Thursday, January 24, 2002 10:16 PM To: Israel Evans Subject: RE: [Tutor] Python in Apache? Importance: High i had sent this mail to someone who had asked this question earlier I have'nt read your mail fully. Try the steps i have enlisted here and hopefully it s'd work. am forwarding the contents of the mail. karthik. -----Original Message----- From: karthik Guru [mailto:karthikg@aztec.soft.net] Sent: Saturday, January 05, 2002 10:14 PM To: McCarney, James Alexander; 'tutor@python.org' Subject: RE: [Tutor] CGI and ODBC questions Importance: High for apache server, Look for the file httpd.conf under the directory where you installed apache in my case..this is the path. D:\Program Files\Apache Group\Apache\conf say Create a folder PythonScripts under \Apache look for an already exiting entry for ScriptAlias in httpd.conf file. You can copy the same and create a new one like this where you can put your python files .... ScriptAlias /python/ "d:/Program Files/Apache Group/Apache/PythonScripts/" .... Look for a AllowOverride None Options None Copy the same thing and change the folder name. So you will have another entry like this. AllowOverride None Options None Then add the following entry to the httpd.conf file: ScriptInterpreterSource Registry Now you can place all your python cgi files in the PythonScripts folder and acess it like this: http://localhost/python/test.py hope it works for you! karthik. From israel@lith.com Fri Jan 25 06:35:49 2002 From: israel@lith.com (Israel Evans) Date: Thu, 24 Jan 2002 22:35:49 -0800 Subject: [Tutor] Python in Apache? Message-ID: I think it went rather painlessly. I downloaded a binary, extracted and installed it. I don't really remember having to do too much other than follow the directions tweaking the httpd.conf file detailed in the docs that came with the installation. After following the Kind advice of the people of this list I was then able to get python cgi running. Now I'm off to get Webware and Webkit running and maybe to attempt to set up one of the various mod_python/snake/funkybidness doohickeys to boot. ~Israel~ -----Original Message----- From: Wesley Chun [mailto:wesc@deirdre.org] Sent: Thursday, January 24, 2002 9:54 PM To: Israel Evans Subject: RE: [Tutor] Python in Apache? great! i just read your last post and saw that things are working now. was that the only slip (the missing '/')? did you have to do anything else to setup Apache on Win2K? -wesley On Thu, 24 Jan 2002, Israel Evans wrote: > Thanks for the info! > > I'm actually running the Apache server for Educational Purposes so that when > I actually get my ancient little p1 200 computer successfully running linux > on it's second harddrive, I'll know how to get things going. Also I'd like > to know what's involved for when I actually scrape up the dough to pay for a > webhost that'll do apache/webware/python/postgresql or some other set up > I'll eventually learn how to use! > > Thanks for all the help! > > Israel From wesc@deirdre.org Fri Jan 25 05:47:01 2002 From: wesc@deirdre.org (Wesley Chun) Date: Thu, 24 Jan 2002 21:47:01 -0800 (PST) Subject: [Tutor] [Tutor]: Totally laughable basic questions In-Reply-To: <23FD7B1A77E8D211BCB900001D108C02018B290C@camelot> Message-ID: On Tue, 15 Jan 2002, McCarney, James Alexander wrote: > I am a programming neophyte. > > Yes in my day-to-day life I use tools (usually text editing, manipulation= , > etc.), and these tools often involve 'programming' of a sort; > but now I want to 'look under the hood.' congratulations for wanting to take the next step! you are definitely one of the users that Guido has been advocating all these years... giving everyone the ability to "scratch their own itch," or so he puts it! > I have heard of, and seen, the wonders of XML; and I am even aware [ gasp= ! > ;-) ] of basic OOP programming principles; > but I am often perplexed about how to tie everything together. right. you have all the pieces of the puzzle but just want to know how they play well together. > What is more embarrassing (for me at least) is knowing when (AND WHY!) to > use a dictionary, a tuple, a string object, etc. > And when (AND WHY!) to slice, dice, concatenate, or otherwise fr*g with t= he > contents of these groups. good question. software engineers are just problem-solvers and these are the tools they can use to help them achieve their goals. as others have pointed out, each of these types of "data structures" have their own unique features and uses. the hard part is figuring out which to use and where. the best answer that can be given is to think of solving a problem *like* a computer... which one of these are the "best fit" for the problem at hand to try and move it towards a solution. un4tunately, these things take time and experience for which there is no experience for. i would suggest you take a few simple problems and use Python to help solve them. that will give you a quick-start on the road to programming!! > Maybe Python-Tutor is not the place for these type of questions, and if so, > I apologise. If some kind soul out in Pythonland is aware of > completely pre-basic tutors that can help me out with various elementary > programming concepts I would be most grateful. the Tutor mailing list is the perfect place. let us know your progress!! -wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall PTR, =A9 2001 http://starship.python.net/crew/wesc/cpp/ wesley.j.chun :: wesc@deirdre.org cyberweb.consulting : henderson, nv : cyberweb@rocketmail.com http://www.roadkill.com/~wesc/cyberweb/ From wesc@deirdre.org Fri Jan 25 05:25:03 2002 From: wesc@deirdre.org (Wesley Chun) Date: Thu, 24 Jan 2002 21:25:03 -0800 (PST) Subject: [Tutor] Python in Apache? In-Reply-To: <20020124173421.A2365@client156-52.ll.siue.edu> Message-ID: On Thu, 24 Jan 2002, Victor R. Cardona wrote: > On Thu, Jan 24, 2002 at 01:16:06PM -0800, Israel Evans wrote: > > it tells me this:: > > > > [Thu Jan 24 08:08:42 2002] [error] [client 127.0.0.1] > > attempt to invoke directory as script: c:/weblish/cgi-bin > > > > [Thu Jan 24 08:11:28 2002] [error] [client 127.0.0.1] > > couldn't spawn child process: c:/weblish/cgi-bin/test.cgi > > Try renaming your cgi script to test.py. I think windows needs the ".py" > extension in order to execute the script with the Python interpreter. israel, your script definitely works under Unix with Apache, as others have noted. i'd try victor's suggestion above as i've never run apache under Windoze b4. another thought is that if you don't need the full power of Apache, you can run a simplistic Python web server using some of the modules in the standard library. i know that works for sure! :-) for example, here is how you can setup a webserver that can respond to CGI requests on port 8000 using only one real line of Python! ;-) -------------------------------------- #!/bin/env python from CGIHTTPServer import test test() -------------------------------------- good luck, and let us know how you solve your problem! -wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall PTR, =A9 2001 http://starship.python.net/crew/wesc/cpp/ wesley.j.chun :: wesc@deirdre.org cyberweb.consulting : henderson, nv : cyberweb@rocketmail.com http://www.roadkill.com/~wesc/cyberweb/ From paulsid@shaw.ca Fri Jan 25 06:52:51 2002 From: paulsid@shaw.ca (Paul Sidorsky) Date: Thu, 24 Jan 2002 23:52:51 -0700 Subject: [Tutor] Re: List Comprehensions again References: <476F88A9-114F-11D6-B3B1-00039351FE6A@mac.com> Message-ID: <3C5100C3.CD2D2382@shaw.ca> Erik Price wrote: > Where should I look for more info, or is this something that can wait > until I am more comfortable with the language? (I am just finishing > tutorials on syntax so you can see that I am really really green at > this.) As should be evident from the debate, neither list comprehensions nor map/lambda really make your code any nicer, so it's probably not critical to learn them any time soon. Better to write out what you're doing longhand and understand it than to get "confuzzled" by what are largely time-saving features. However the shorthands do save a lot of work, so do try to learn them at some point. But not 'til you think you're ready. When you are I'd suggest starting out slowly. For list comprehensions, start with basic ones that just do one thing to the object variable, and ignore if's and multiple for's. My favourite simple LC (probably because it would take so much C code to do) is this: f.writelines([line.replace(str1, str2) for line in f.readlines()]) If f is an open file, then this is a poor person's file-wide search and replace - in one line! Next try working just with the if's, like maybe this blank-line filterer: f.writelines([line for line in f.readlines() if line.strip()] Then combine them, then try multi-for's, etc. I think the hardest part is learning to deal with the above two cases, though, because they're the basics. Once you learn how LC's work then extending them isn't too much harder to learn. BTW, I have noticed a lot of people - especially myself - have a tendancy to use single-letter or other meaningless variable names in LC's. While this isn't too terrible since it keeps the LC brief, if you don't understand LC's it can make things more confusing. So it might make it clearer to spell out what the "object variable" in the LC is for, as I did above. -- ====================================================================== Paul Sidorsky Calgary, Canada paulsid@shaw.ca http://members.shaw.ca/paulsid/ From lonetwin@yahoo.com Fri Jan 25 07:08:35 2002 From: lonetwin@yahoo.com (lonetwin@yahoo.com) Date: Fri, 25 Jan 2002 02:08:35 -0500 Subject: [Tutor] (no subject) Message-ID: UIT Received: from mercury.worli (localhost.localdomain [127.0.0.1]) by mercury.worli (Postfix) with SMTP id 3B9D69137; Fri, 25 Jan 2002 12:29:43 +0530 (IST) Content-Type: text/plain; charset="iso-8859-1" From: lonetwin Reply-To: lonetwin@yahoo.com To: kp87@lycos.com, tutor@python.org Subject: Re: [Tutor] Re: List Comprehensions again Date: Fri, 25 Jan 2002 12:29:43 +0530 X-Mailer: KMail [version 1.2] References: In-Reply-To: MIME-Version: 1.0 Message-Id: <02012512294300.04555@mercury.worli> Content-Transfer-Encoding: 8bit Hey All, On Thursday 24 January 2002 22:24, kevin parks wrote: > I have never been able to get my head around list comprehension and > desperately want too. I wish that there was a *good* little 2-3 page toot > on list comprehensions that start from the very clearest and simplest > examples and built up from there with nice explanations in between. Ok, somehow I find it wierd how some of people find list comprehension un-pythonic ....like I said in my post, couple of days back, they make complete sense to me. Lemme see if I can probably get you to see it the way that I do : when I say: P = func(i) I'll get the return value of calling func(), called with the argument i, which is then assigned to P, Now suppose I have a list (or for that matter any sequence) called SomeSequence and I want to call the func() function for every element of SomeSequence, I do: for x in SomeSequence: func(x) Now, if I want to save all the return values in a list, I do: l = [] for x in SomeSeruence: l.append(func(x)) Still with me ?? The python way to express it is: o I want a list ..................... l = [] o which contains the return values... l = [ func(x) ] got by calling function func() o for every element in SomeSequence.. l = [ func(x) for x in SomeSequence ] like I said in my post earlier: [ func(x) for x in SomeList ] Return a list filled with func(x)'s for every x in SomeList Looks/Sounds almost the same in english as well as python, so does [ x.func() for x in SomeList if x == Something ] Return a list filled with func(x)'s for every x in SomeList that equals Something. I really hope that helps :) Peace Steve -- "'Tis true, 'tis pity, and pity 'tis 'tis true." -- Poloniouius, in Willie the Shake's _Hamlet, Prince of Darkness_ From lonetwin@yahoo.com Fri Jan 25 07:20:10 2002 From: lonetwin@yahoo.com (lonetwin@yahoo.com) Date: Fri, 25 Jan 2002 02:20:10 -0500 Subject: [Tutor] (no subject) Message-ID: UIT Received: from mercury.worli (localhost.localdomain [127.0.0.1]) by mercury.worli (Postfix) with SMTP id D755D9137 for ; Fri, 25 Jan 2002 12:53:27 +0530 (IST) Content-Type: text/plain; charset="iso-8859-1" From: lonetwin Reply-To: lonetwin@yahoo.com To: tutor@python.org Subject: Re: [Tutor] Re: List Comprehensions again Date: Fri, 25 Jan 2002 12:53:27 +0530 X-Mailer: KMail [version 1.2] References: In-Reply-To: MIME-Version: 1.0 Content-Transfer-Encoding: 8bit Message-Id: <02012512532700.04848@mercury.worli> Hey All, On Thursday 24 January 2002 22:24, kevin parks wrote: > I have never been able to get my head around list comprehension and > desperately want too. I wish that there was a *good* little 2-3 page toot > on list comprehensions that start from the very clearest and simplest > examples and built up from there with nice explanations in between. Ok, somehow I find it wierd how some of people find list comprehension un-pythonic ....like I said in my post, couple of days back, they make complete sense to me. Lemme see if I can probably get you to see it the way that I do : when I say: P = func(i) I'll get the return value of calling func(), called with the argument i, which is then assigned to P, Now suppose I have a list (or for that matter any sequence) called SomeSequence and I want to call the func() function for every element of SomeSequence, I do: for x in SomeSequence: func(x) Now, if I want to save all the return values in a list, I do: l = [] for x in SomeSeruence: l.append(func(x)) Still with me ?? The python way to express it is: o I want a list ..................... l = [] o which contains the return values... l = [ func(x) ] got by calling function func() o for every element in SomeSequence.. l = [ func(x) for x in SomeSequence ] like I said in my post earlier: [ func(x) for x in SomeList ] Return a list filled with func(x)'s for every x in SomeList Looks/Sounds almost the same in english as well as python, so does [ x.func() for x in SomeList if x == Something ] Return a list filled with func(x)'s for every x in SomeList that equals Something. I really hope that helps :) Peace Steve -- "'Tis true, 'tis pity, and pity 'tis 'tis true." -- Poloniouius, in Willie the Shake's _Hamlet, Prince of Darkness_ From dyoo@hkn.eecs.berkeley.edu Fri Jan 25 07:46:04 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 24 Jan 2002 23:46:04 -0800 (PST) Subject: [Tutor] Python in Apache? [should we set up a wiki?] In-Reply-To: Message-ID: On Thu, 24 Jan 2002, Israel Evans wrote: > I was able to set things up like you said and was able to get the alias > to work, but after saving the file in the new aliased directory, I restarted > the server and tried to execute the .py file, but I got a 404 and I was told > that the file couldn't be found even though it's actually there??!! > > This is what the Error log tells me... > > (2)No such file or directory: script not found or unable to stat: c:/program > files/apache group/apache/pyscriptstest.py > > HOLD IT! > > You are a SAINT! I noticed the error stated that it couldn't start the > file pyscriptstest.py. What is missing here is a "/". I went in and made > sure both the script alias and the directory paths in the .conf file ended > with such a wonderful little character and afterwards my python file worked > like a charm!!! We should archive this thread somewhere so that others don't have to go through the pain that you've just gone through. *grin* I've been thinking of setting up a Python-Tutor Wiki, but I don't have too much experience with Wikis yet to know if this would be useful. What do people think about this? From dyoo@hkn.eecs.berkeley.edu Fri Jan 25 08:00:31 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 25 Jan 2002 00:00:31 -0800 (PST) Subject: [Tutor] creating variables at runtime [interactivity and programming] In-Reply-To: <4.2.0.58.20020124211704.01a42770@pop3.norton.antivirus> Message-ID: On Thu, 24 Jan 2002, Kirby Urner wrote: > my college years (long ago). FORTRAN was batch programming. I'd punch > a stack of cards (icky) and they'd go through a card reader with a > bunch of other programs (JCL cards in between to tell the jobs apart), > and 20 minutes later, the line printer would come back with my results > (and/or bug reports). APL was on a CRT, and I'd sit at the keyboard, > enter a weird-looking expression that might do quite a lot in one line > (like Python can), and zingo zango, I get a result immediately. [... some text cut...] > That's how I best like to use Python. It's also how I like to > learn/play with Python. Enter stuff and get an immediate reply. I > think from a learning standpoint, having an interactive shell makes a > *huge* difference. There's a quote from Paul Graham's introduction to "ANSI Common Lisp" that seems somewhat relevant: "... [The pervasiveness of bugs] is just what the new model of programming does assume. Instead of hoping that people won't make mistakes, it tries to make the cost of mistakes very low. The cost of a mistake is the time required to correct it. With powerful languages and good programming environments, this cost can be greatly reduced. Programming style can then depend less on planning and more on exploration..." When we're learning something, that's especially a ripe time for making mistakes. *grin* But that's where an interpreter shines: it allows us to experiment with our mistakes, and makes casual exploration possible. From glingl@aon.at Fri Jan 25 08:25:17 2002 From: glingl@aon.at (Gregor Lingl) Date: Fri, 25 Jan 2002 09:25:17 +0100 Subject: [Tutor] Python in Apache? [should we set up a wiki?] References: Message-ID: <001401c1a579$d25164e0$1664a8c0@mega> ----- Original Message ----- From: "Danny Yoo" > ... I've been thinking > of setting up a Python-Tutor Wiki, but I don't have too much experience > with Wikis yet to know if this would be useful. What do people think > about this? > I find this a great idea. Moreover I would ask to do the setup publicly, so everybody could reproduce it for his own purposes. (I'd like to have one for young students in german language, so if you did it, I'd like to do it in parallel on a sever at my school). May I point you to moinmoin's page: http://moin.sourceforge.net/ There is a wiki written in Python, which looks rather versatile and attractive. (On the other hand a more primitive one, as for instance PikiPiki, would suffice and possibly would be easier to maintain?) At the same time this could be a an opportunity to do some practical Python programming (e.g. customizing the wiki concerning the user's language ...) Gregor From James.Alexander.McCarney@Cognicase.com Fri Jan 25 14:27:31 2002 From: James.Alexander.McCarney@Cognicase.com (McCarney, James Alexander) Date: Fri, 25 Jan 2002 09:27:31 -0500 Subject: [Tutor] Re: Apache w Py Message-ID: <23FD7B1A77E8D211BCB900001D108C02018B2954@camelot> I think if you have set up Python with Apache it's looking not for a .cgi extension, but rather an extension of .py. Put the following code in a py module, mine was "testcgi.py," save it in cgi-bin, and let it rip! :-) #!c:\python21 #or 22 or whateva import cgi cgi.test() Israel wrote: """ Darn,,,, well, that's good actually, but that means my Apache set up needs help... Back to the Depths of the Docs and On with the Guess-Work! :) ~Israel~ """ James Alexander McCarney, technical writer (450) 928-3386 x2262 Cognicase - M3i Systems, 1111 Saint-Charles Avenue West 11th Floor, East Tower, Longueuil, Quebec, J4K 5G4 Canada http://www.m3isystems.com mailto:James.Alexander.McCarney@Cognicase.com From israel@lith.com Fri Jan 25 17:34:55 2002 From: israel@lith.com (Israel Evans) Date: Fri, 25 Jan 2002 09:34:55 -0800 Subject: [Tutor] Python in Apache? [should we set up a wiki?] Message-ID: WIKI WIKI! Sounds like fun and very usefull. I've found Wikis to be a little easier to glean relevant information from than list archives. ~Israel~ -----Original Message----- From: Gregor Lingl [mailto:glingl@aon.at] Sent: Friday, January 25, 2002 12:25 AM To: Danny Yoo Cc: tutor@python.org Subject: Re: [Tutor] Python in Apache? [should we set up a wiki?] ----- Original Message ----- From: "Danny Yoo" > ... I've been thinking > of setting up a Python-Tutor Wiki, but I don't have too much experience > with Wikis yet to know if this would be useful. What do people think > about this? > I find this a great idea. Moreover I would ask to do the setup publicly, so everybody could reproduce it for his own purposes. (I'd like to have one for young students in german language, so if you did it, I'd like to do it in parallel on a sever at my school). May I point you to moinmoin's page: http://moin.sourceforge.net/ There is a wiki written in Python, which looks rather versatile and attractive. (On the other hand a more primitive one, as for instance PikiPiki, would suffice and possibly would be easier to maintain?) At the same time this could be a an opportunity to do some practical Python programming (e.g. customizing the wiki concerning the user's language ...) Gregor _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From urnerk@qwest.net Fri Jan 25 18:41:19 2002 From: urnerk@qwest.net (Kirby Urner) Date: Fri, 25 Jan 2002 10:41:19 -0800 Subject: [Tutor] Re: List Comprehensions again In-Reply-To: <3C5100C3.CD2D2382@shaw.ca> References: <476F88A9-114F-11D6-B3B1-00039351FE6A@mac.com> Message-ID: <4.2.0.58.20020125103821.01b8ca40@pop3.norton.antivirus> At 11:52 PM 1/24/2002 -0700, Paul Sidorsky wrote: >Erik Price wrote: > > > Where should I look for more info, or is this something that can wait > > until I am more comfortable with the language? (I am just finishing > > tutorials on syntax so you can see that I am really really green at > > this.) > >As should be evident from the debate, neither list comprehensions >nor map/lambda really make your code any nicer, so it's probably >not >critical to learn them any time soon. I think this syntax often *does* make code nicer and that mastery of both lambda/map/filter *and* LC is an important step when learning Python. I'd agree it can come later, but it should not be infinitely postponed. No time like the present. Also, I don't go along with casting the "debate" in the form of lambda OR list comprehensions. We have 'em both, we can use 'em both. That being said, I agree with Alan that lambda could be made more powerful, i.e. if it were allowed to contain multiple statements and such. But then we'd be doing Scheme. Kirby From James@BlahBlahJsRoberts.com Fri Jan 25 18:50:25 2002 From: James@BlahBlahJsRoberts.com (James Roberts) Date: Fri, 25 Jan 2002 10:50:25 -0800 Subject: [Tutor] readlines() ... problem Message-ID: <0r835uomdrns9cgdlrjev4ik1b91144ffg@4ax.com> I have a file, a text file, that has 15 or so lines of text, each line ending in hard-return (Windows). None of the lines are quoted, nor are they delimited by comma's, or anything else. When I execute, in Komodo, a script that goes: list =3D open("list") s =3D list.read() print s ... I get the entire contents of the file printed out, just as it was in the source file. This I expect. But, if I do the following: list =3D open("list") s =3D list.readlines() print list ... then, all I get is several of the lines from the source file. The lines do output as a list, with the lines of the source presented as strings, with newlines at the end of each of the source lines, but the ouput is only a few of the lines from the source.=20 However: Iif do the same two operations above -- but do it in Idle, entering each command individually on the command line -- I get the results I expect. That is, the readlines() will output the entire source file as expected.=20 Why won't the script in Komodo do the same? Any help would be appreciated. -- Jim From dsh8290@rit.edu Fri Jan 25 23:20:14 2002 From: dsh8290@rit.edu (dman) Date: Fri, 25 Jan 2002 18:20:14 -0500 Subject: [Tutor] Re: List Comprehensions again In-Reply-To: <476F88A9-114F-11D6-B3B1-00039351FE6A@mac.com> References: <1011897437.3875.3.camel@asimov> <476F88A9-114F-11D6-B3B1-00039351FE6A@mac.com> Message-ID: <20020125232014.GA7250@dman.ddts.net> On Thu, Jan 24, 2002 at 11:52:05PM -0500, Erik Price wrote: | As a superfledgling, I have to say that I have no idea what you guys are | talking about. For the first few messages I figured it was something | that I could pick up later on. Now this thread has gone on for several | days and I'm starting to wonder if I should learn this lambda / list | comprehensions thing now before I run into the troubles that others | describe (who seem to be saying that "they wish they'd learned it a | different way" -- I want to learn it that way first so I can save the | hassle). | | Where should I look for more info, or is this something that can wait | until I am more comfortable with the language? (I am just finishing | tutorials on syntax so you can see that I am really really green at | this.) You can wait on these features for now. For a really brief, but hopefully helpful, overview : map, filter, and reduce are functions that take a function object and a list object as arguments. The first two return a new list, the third returns something else (depends on what is in your list and the function object). The next step for you to do is to see what these functions do with their arguments and how the return value relates to the arguments. lambda is a keyword that creates a simple, unnamed, function object. It is "simple" because it can only contain a single expression. For example, the following are equivalent : def f( x ) : return x*x f = lambda x : x*x lambda is most often used in conjunction with map/filter/reduce, and the whole lot comes from the "functional" programming style (embodied in LISP, Scheme, and the ML family of languages). List comprehensions are another way of doing the same thing as map or filter. LCs are shorter, syntactically, and appear more mathematical. HTH, -D -- A wise servant will rule over a disgraceful son, and will share the inheritance as one of the brothers. Proverbs 17:2 From ddeuber@arri.de Fri Jan 25 15:05:50 2002 From: ddeuber@arri.de (David Deuber) Date: Fri, 25 Jan 2002 16:05:50 +0100 Subject: [Tutor] Tkinter GUI extension Message-ID: <3C51744E.C25E0F10@arri.de> This is a multi-part message in MIME format. Since your mail reader does not understand this format, some or all of this message may not be legible. --------------3E5E70FE9B6A96728982285A Content-Type: text/plain; charset=us-ascii Content-Transfer-Encoding: 7bit I'm running on an Irix system and having difficulties installing python with the Tkinter GUI extension. I've downloaded the following code from this url - http://sourceforge.net/project/showfiles.php?group_id=5470&release_id=66610. tcl8.0.5 tk8.0.5 Python-2.2 Thus far I'm able to start python interactive session but not able to import Tkinter- >>from Tkinter import * Traceback (most recent call last): File "", line 1, in ? File "/usr/Python-2.2/Lib/lib-tk/Tkinter.py", line 35, in ? import _tkinter # If this fails your Python may not be configured for Tk ImportError: No module named _tkinter Can you help me find a way to get this to work or point me in the correct documention location? Our system admin suggested I try to download a binary version of Python to avoid compiling it. I'm not able to find a binary version for unix , only windows . Thanx for any insights -david --------------3E5E70FE9B6A96728982285A Content-Type: text/x-vcard; charset=us-ascii; name="ddeuber.vcf" Content-Description: Card for David Deuber Content-Disposition: attachment; filename="ddeuber.vcf" Content-Transfer-Encoding: quoted-printable X-MIME-Autoconverted: from 8bit to quoted-printable by gate2.arri.de id g0PF8Bh04173 begin:vcard=20 n:Deuber;David tel;home:+49-89-89 99 79 60 tel;work:+49-89-38 09 12 69 x-mozilla-html:FALSE url:http://www.arri.com org:ARRI ;Digtial Film adr:;;T=FCrkenstr. 95;M=FCnchen;;80799;Germany version:2.1 email;internet:ddeuber@arri.de title:Technical Director x-mozilla-cpt:;28128 fn:David Deuber end:vcard --------------3E5E70FE9B6A96728982285A-- From dyoo@hkn.eecs.berkeley.edu Sat Jan 26 02:27:41 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 25 Jan 2002 18:27:41 -0800 (PST) Subject: [Tutor] readlines() ... problem [komodo weirdness / choose good variable names] In-Reply-To: <0r835uomdrns9cgdlrjev4ik1b91144ffg@4ax.com> Message-ID: On Fri, 25 Jan 2002, James Roberts wrote: > I have a file, a text file, that has 15 or so lines of text, each line > ending in hard-return (Windows). None of the lines are quoted, nor > are they delimited by comma's, or anything else. > > When I execute, in Komodo, a script that goes: > > list = open("list") > s = list.read() > print s > > ... I get the entire contents of the file printed out, just as it was > in the source file. This I expect. But, if I do the following: > > list = open("list") > s = list.readlines() > print list ^^^^ You probably mean: ### print s ### for the second example. To avoid typos like that, you may want to change the name of your variables to something like 'list_file' so that there's less of a temptation to write "print list"... *grin* > ... then, all I get is several of the lines from the source file. > The lines do output as a list, with the lines of the source presented > as strings, with newlines at the end of each of the source lines, but > the ouput is only a few of the lines from the source. This is very odd! You should be getting the whole file as a list of lines, and not just a partial list. Where does it cut off? Perhaps there's a strange character in there that Komodo is interpreting as a wacky character. I don't believe that Komodo should be doing that though. If you can show us the text file that you're using, one of us at Tutor can see if we can duplicate the error. Good luck to you. From dyoo@hkn.eecs.berkeley.edu Sat Jan 26 02:40:32 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 25 Jan 2002 18:40:32 -0800 (PST) Subject: [Tutor] Tkinter GUI extension [python installation issues with Tk] In-Reply-To: <3C51744E.C25E0F10@arri.de> Message-ID: On Fri, 25 Jan 2002, David Deuber wrote: > I'm running on an Irix system and having difficulties installing python > with the Tkinter GUI extension. I've downloaded the following code from > > this url - > > http://sourceforge.net/project/showfiles.php?group_id=5470&release_id=66610. > > tcl8.0.5 > tk8.0.5 > Python-2.2 Hi David, When one compiles Python, during the configuration step, there should be output that explains what the configurator can find out about your system. There should be a 'config.log' file that shows the results of the configuration. If you send us that log file, we can what choices the configurator is making, and, with luck, we might be able to find out what's going on. > Thus far I'm able to start python interactive session but not able to > import Tkinter- > >>from Tkinter import * > Traceback (most recent call last): > File "", line 1, in ? > File "/usr/Python-2.2/Lib/lib-tk/Tkinter.py", line 35, in ? > import _tkinter # If this fails your Python may not be configured > for Tk > ImportError: No module named _tkinter Most likely, the configurator wasn't able to find Tk on your system. Do you remember where you installed those libraries? Also, did you install the developmental include files? It might just be that the ./configure step is having a hard time autodetecting the Tk graphics library. If so, we can manually tell Python where to look for it. According to the README in the Python source distribution: """Starting with Python 2.1, the setup.py script at the top of the source distribution attempts to detect which modules can be built and automatically compiles them. Autodetection doesn't always work, so you can customize the configuration by editing the Modules/Setup file.""" So if worst comes to worse, we can hardcode the path to the Tk libraries within the Module/Setup file. But let's look at the log file first and see what's going on. > Can you help me find a way to get this to work or point me in the > correct documention location? Our system admin suggested I try to > download a binary version of Python to avoid compiling it. I'm not > able to find a binary version for unix , only windows . Hmmm... You may want to ask on the comp.lang.python newsgroup and see if anyone has constructed a binary package for Python. The web site: http://freeware.sgi.com/ appears to collect contributed binary packages for IRIX system, so you may be able to find Python there. Good luck to you! From dyoo@hkn.eecs.berkeley.edu Sat Jan 26 02:54:17 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 25 Jan 2002 18:54:17 -0800 (PST) Subject: [Tutor] [Tutor]: Totally laughable basic questions In-Reply-To: Message-ID: On Thu, 24 Jan 2002, Wesley Chun wrote: > > What is more embarrassing (for me at least) is knowing when (AND > WHY!) to > use a dictionary, a tuple, a string object, etc. > And when > (AND WHY!) to slice, dice, concatenate, or otherwise fr*g with the > > contents of these groups. > > good question. software engineers are just problem-solvers and these > are the tools they can use to help them achieve their goals. as By the way, if you see a bit of code that looks totally weird, if it's short, please feel free to post it to Tutor and ask questions about it. We'd be happy to talk about the code, and guess why the author chose a certain data structure over another. > un4tunately, these things take time and experience for which there is > no experience for. i would suggest you take a few simple problems and > use Python to help solve them. that will give you a quick-start on > the road to programming!! Fiddling around with examples should be very helpful. There's a lot of sample code that we can grab, and we can do experiments with it. There's a lot of good code in Useless Python: http://lowerstandard.com/python so take something that looks interesting to you, and see if it makes sense inside. > > Maybe Python-Tutor is not the place for these type of questions, and if > > so, I apologise. If some kind soul out in Pythonland is aware of > > completely pre-basic tutors that can help me out with various elementary > > programming concepts I would be most grateful. No, no, please feel free to ask your questions on Tutor. If you notice that the traffic on Tutor is getting very "theoretical", that just probably means that we're hoping that someone will step in and tell us that we're not making any sense. *grin* Anyway, hope to hear from you soon. Good luck! From dyoo@hkn.eecs.berkeley.edu Sat Jan 26 03:19:28 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 25 Jan 2002 19:19:28 -0800 (PST) Subject: [Tutor] Re: List Comprehensions again [an example with filter()] In-Reply-To: <476F88A9-114F-11D6-B3B1-00039351FE6A@mac.com> Message-ID: On Thu, 24 Jan 2002, Erik Price wrote: > > i came to python before list comprehensions. it took me A LONG TIME to > > understand map/filter/lambda... actually i'll say i still don't really > > understand them. > > > > when i first saw list comprehensions, i thought "I have NO CLUE what > > this is doing". then i started playing. i took a map/lambda > > (snip) > > > As a superfledgling, I have to say that I have no idea what you guys are > talking about. For the first few messages I figured it was something > that I could pick up later on. Now this thread has gone on for several > days and I'm starting to wonder if I should learn this lambda / list You can pick it up later. Basically, list comprehensions, maps, and filters are fancy ways of doing list processing. Often, we're looking at a list --- a sequence of things --- and we might want to do some mass action to that whole sequence. Comprehensions, map(), and filter() are all convenient ways of doing operations on whole sequences. Let's say, for example, that we have a list of words, and we'd like to figure out which words end with an 's'. If we've never heard of comprehensions, maps, or filters, we can still write something that'll help us find those s-words: ### for w in words: if w[-1] == 's': print w ### is an example of something we can do. If we wanted to be fancy, we could even do something like this: ### def endsWithS(word): return word[-1] == 's' for w in words: if endsWithS(w): print w ### What people have found out after working with lists is that there's often common patterns or things we do with lists. It's a very common thing to take a list, and fish out "good" elements out of that list. Let's take another example: if we had a list of words, it might be nice to grab all the words that are spelled the same, forwards and backwards: ### def reverse(word): letters = list(word) letters.reverse() return string.join(letters, '') def isPalindrome(word): reversed_word = reverse(word) return reversed_word == word def filterForPalindromes(words): palindromes = [] for w in words: if isPalindrome(w): palindromes.append(w) return palindromes ### Let's see how this might work: ### >>> filterForPalindromes(['pattern', 'dad', 'ocelot', 'pop']) ['dad', 'pop'] ### What the filter() function does is duplicate the behavior of filterForPalindromes(), but with a special twist: it leaves what it means to be a "good" elements out of its definition, and allows us to tell it what a good element should be! Here's how we'd grab all the palindromes if we used the filter() function: ### >>> filter(isPalindrome, ['pattern', 'dad', 'ocelot', 'pop']) ['dad', 'pop'] ### It's not surprising that we get the same answer... but it IS surpising that we did all that without writing a single loop ourselves. And that's pretty neat! All we need to do is give filter() the notion of what a good element is, and that's why we pass filter the function 'isPalindrome()'. You probably already feel comfortable passing around numbers and strings to functions, but other functions? If this is the first time you've seen it, it will probably seem pretty darn weird at first, but it'll make sense as you play with it. In summary, it's not that we can't do without list comprehensions or map() or filter() --- we can --- but they are very convenient functions to know about, and they often free us from worrying about iterating manually through a list. If you have questions, please feel free to ask. From dyoo@hkn.eecs.berkeley.edu Sat Jan 26 07:16:08 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 25 Jan 2002 23:16:08 -0800 (PST) Subject: [Tutor] [Tutor]: Totally laughable basic questions (fwd) Message-ID: ---------- Forwarded message ---------- Date: Fri, 25 Jan 2002 23:56:09 -0500 From: kirk Bailey To: Danny Yoo Subject: Re: [Tutor] [Tutor]: Totally laughable basic questions Danny is right, this IS the place to ask basic questions. I am DEEPLY impresed with the quality of support this service offers. When you as something basic, any number may play, and I may even crop up with a tidbit- not always right, but often. And when it gets into Phd country (Piled Higher & deeper), We have people like Danny and other MAVENS of snake charming. So fire away. Danny Yoo wrote: > > On Thu, 24 Jan 2002, Wesley Chun wrote: > > > > What is more embarrassing (for me at least) is knowing when (AND > > WHY!) to > use a dictionary, a tuple, a string object, etc. > And when > > (AND WHY!) to slice, dice, concatenate, or otherwise fr*g with the > > > contents of these groups. > > > > good question. software engineers are just problem-solvers and these > > are the tools they can use to help them achieve their goals. as > > By the way, if you see a bit of code that looks totally weird, if it's > short, please feel free to post it to Tutor and ask questions about it. > We'd be happy to talk about the code, and guess why the author chose a > certain data structure over another. > > > un4tunately, these things take time and experience for which there is > > no experience for. i would suggest you take a few simple problems and > > use Python to help solve them. that will give you a quick-start on > > the road to programming!! > > Fiddling around with examples should be very helpful. There's a lot of > sample code that we can grab, and we can do experiments with it. There's > a lot of good code in Useless Python: > > http://lowerstandard.com/python > > so take something that looks interesting to you, and see if it makes sense > inside. > > > > Maybe Python-Tutor is not the place for these type of questions, and if > > > so, I apologise. If some kind soul out in Pythonland is aware of > > > completely pre-basic tutors that can help me out with various elementary > > > programming concepts I would be most grateful. > > No, no, please feel free to ask your questions on Tutor. If you notice > that the traffic on Tutor is getting very "theoretical", that just > probably means that we're hoping that someone will step in and tell us > that we're not making any sense. *grin* > > Anyway, hope to hear from you soon. Good luck! > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- -Respectfully, -Kirk D Bailey Consulting Loose Cannon end www.howlermonkey.net highprimate@howlermonkey.net www.sacredelectron.org idiot1@netzero.net www.tinylist.org grumpy@tinylist.org ---------------------------------------------------- Sign Up for NetZero Platinum Today Only $9.95 per month! http://my.netzero.net/s/signup?r=platinum&refcd=PT97 From James@BlahBlahJsRoberts.com Sat Jan 26 09:49:27 2002 From: James@BlahBlahJsRoberts.com (James Roberts) Date: Sat, 26 Jan 2002 01:49:27 -0800 Subject: [Tutor] readlines() ... problem [komodo weirdness / choose good variable names] In-Reply-To: References: <0r835uomdrns9cgdlrjev4ik1b91144ffg@4ax.com> Message-ID: <1pt45uck2rgnv0jskl7dd566n4ag6vv5d3@4ax.com> On Fri, 25 Jan 2002 18:27:41 -0800 (PST), you wrote: >On Fri, 25 Jan 2002, James Roberts wrote: > >> I have a file, a text file, that has 15 or so lines of text, each line >> ending in hard-return (Windows). None of the lines are quoted, nor >> are they delimited by comma's, or anything else. >>=20 >> When I execute, in Komodo, a script that goes: >>=20 >> list =3D open("list") >> s =3D list.read() >> print s >>=20 >> ... I get the entire contents of the file printed out, just as it was >> in the source file. This I expect. But, if I do the following: >>=20 >> list =3D open("list") >> s =3D list.readlines() >> print list > ^^^^ > > >You probably mean: > >### >print s >### > >for the second example. To avoid typos like that, you may want to = change >the name of your variables to something like 'list_file' so that there's >less of a temptation to write "print list"... *grin* > > > >> ... then, all I get is several of the lines from the source file. =20 >> The lines do output as a list, with the lines of the source presented >> as strings, with newlines at the end of each of the source lines, but >> the ouput is only a few of the lines from the source. > > >This is very odd! You should be getting the whole file as a list of >lines, and not just a partial list. Where does it cut off? Perhaps >there's a strange character in there that Komodo is interpreting as a >wacky character. I don't believe that Komodo should be doing that = though. > >If you can show us the text file that you're using, one of us at Tutor = can >see if we can duplicate the error. > > >Good luck to you. > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor Danny,=20 I just figured out what was happening. When viewing the output, in Komodo, there is a scroll bar at the bottom. I was sliding the slide-bar all the way to the right, thinking that that is where the line ends. That is usually what happens in other programs. However with Komodo, sliding the horizontal scroll bar at the bottom of the screen all the way to the right does not show you the end of the line. You have to then use the right arrow on the scroll bar line, even after the bar is all the way to the right, in order to see the rest of the output. I found this out by "copying" the data to show it in this message to demonstrate the problem I was having. It was then that I saw all the data. In my view, this is a bug, in the sense that one would expect that sliding the scroll bar all the way to the right should show you all the data. Thanks for the tip regarding naming variables. I am brand new to Python, and I appreciate it. -- Jim=20 From printers@sendme.cz Sat Jan 26 13:09:21 2002 From: printers@sendme.cz (A) Date: Sat, 26 Jan 2002 14:09:21 +0100 Subject: [Tutor] What are security holes? Message-ID: <3C52B891.5984.1AE497@localhost> We are going to install Python on our Linux server. Are there any security holes for hackers? What would we be careful about and how we should set it up? Are there any guidelines for installing Python? Thank you for help. Ladislav From printers@sendme.cz Sat Jan 26 13:09:21 2002 From: printers@sendme.cz (A) Date: Sat, 26 Jan 2002 14:09:21 +0100 Subject: [Tutor] Httplib and Proxy Message-ID: <3C52B891.15886.1AE4C3@localhost> Can anybody please give me a working example how I can use httplib with a proxy if I use POST method? Thank you very much for help Ladislav From mennosimons@gmx.net Sat Jan 26 13:22:42 2002 From: mennosimons@gmx.net (Huuuuuu) Date: Sat, 26 Jan 2002 14:22:42 +0100 Subject: [Tutor] Source Code Formatter Message-ID: <20020126132309Z45640-8421+843@mail.uni-paderborn.de> Hi, is there a good code formatter for Python? With Highlighting. E.G. py->html? Thanks, willi From kjphotog@juno.com Sat Jan 26 14:30:34 2002 From: kjphotog@juno.com (kjphotog@juno.com) Date: Sat, 26 Jan 2002 06:30:34 -0800 Subject: [Tutor] working with images Message-ID: <20020126.065304.-261463.2.kjphotog@juno.com> I'm a high school photography instructor & a Python newbie with a skill level somewhere between "hello world" & fiddling with e-mail. What might be the best intro to start working with images? ________________________________________________________________ GET INTERNET ACCESS FROM JUNO! Juno offers FREE or PREMIUM Internet access for less! Join Juno today! For your FREE software, visit: http://dl.www.juno.com/get/web/. From kent@springfed.com Sat Jan 26 15:28:53 2002 From: kent@springfed.com (kent@springfed.com) Date: Sat, 26 Jan 2002 09:28:53 -0600 Subject: [Tutor] Python+CGI+MySQL performance Message-ID: <200201261535.g0QFZcBM008459@bucky.airstreamcomm.net> Howdy, I am currently using ASP to provide dynamic content and would like to convert to Python. Many hosting services offer PHP, but the only Python availability I've found is via CGI. If I access MySQL from a python.cgi what is the overhead? Is it true that every call to the script must open and close a connection to the DB? Is it possible to get good performance with a setup like this? Thanks, Kent -- , kent@springfed.com on 26/01/2002 From e.kotyk@shaw.ca Sat Jan 26 15:45:33 2002 From: e.kotyk@shaw.ca (Eve Kotyk) Date: Sat, 26 Jan 2002 15:45:33 +0000 Subject: [Tutor] Need help with dict.calculation References: <3C50A41A.8FFA7745@shaw.ca> <009501c1a558$626cd810$da00a8c0@Sun> Message-ID: <3C52CF1D.664E9E4A@shaw.ca> > > def gather_data(): > items = raw_input("Add food item: ") > portion = input("Enter number of portions: ") > cal_portion = input("Enter calories per portion: ") > return items,portion,cal_portion > > def get_total_calories(): > print "Enter all foods you have eaten today." > more="" > total_calories = {} ## <--- here's the change > while more != "n": > items, portion, cal_portion = gather_data() > total_calories[items] = portion * cal_portion > more = raw_input("Do you want to continue? y/n: ") > total=0 #<--- this bit was missing this time! ;o) > for i in total_calories.values(): > total = total + i > print "Total calories: ", total It works! It works! Do you know what I was doing wrong. I was calling gather_data() and then calling get_total_calories() and I would always get only the total calories for the last item entered. Maybe next time I should attach the whole code. Thank you so much for your help. E -- ekotyk http://members.shaw.ca/e.kotyk/virtualstudio.htm From idiot1@netzero.net Sat Jan 26 16:44:38 2002 From: idiot1@netzero.net (kirk Bailey) Date: Sat, 26 Jan 2002 11:44:38 -0500 Subject: [Tutor] Source Code Formatter References: <20020126132309Z45640-8421+843@mail.uni-paderborn.de> Message-ID: <3C52DCF6.59FE7889@netzero.net> Huuuuuu wrote: > > Date: Sat, 26 Jan 2002 14:22:42 +0100 > > Hi, > > is there a good code formatter for Python? > With Highlighting. E.G. py->html? > > Thanks, > willi > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor I don't know of one of those, but if you speak ssi there is another way. SSI. To list a script in the server: To insert a standard footer in a file: Same for a header: Notice the header and footer are themselves shtml, and can also include ssi! Be advised that imbedded htmls will still be interpeted as html, and in html some symbols do not display correctly, such as the '<', '>', and a small list of others, such as extra spaces, tabs, etc. One advantage of this is that it instantly updates the webpage when the script is modified and saved. For a project under delopment, this can be handy. SOME servers are configured so they only parse a page for ssi if the page has ther name extension '.shtml', others are set up so they parse ALL pages for ssi includes- which is a waste of cpu time if only domr hsve it in them. SSI can be a VERY handy thing to have around the codeshop, and I left several links to tutorials on it on the tinylist.org site. -- -Respectfully, -Kirk D Bailey Consulting Loose Cannon end www.howlermonkey.net highprimate@howlermonkey.net www.sacredelectron.org idiot1@netzero.net www.tinylist.org grumpy@tinylist.org ---------------------------------------------------- Sign Up for NetZero Platinum Today Only $9.95 per month! http://my.netzero.net/s/signup?r=platinum&refcd=PT97 From srichter@cbu.edu Sat Jan 26 16:57:25 2002 From: srichter@cbu.edu (Stephan Richter) Date: Sat, 26 Jan 2002 10:57:25 -0600 Subject: [Tutor] Source Code Formatter In-Reply-To: <3C52DCF6.59FE7889@netzero.net> References: <20020126132309Z45640-8421+843@mail.uni-paderborn.de> Message-ID: <5.1.0.14.2.20020126105639.023ecc88@mercury-1.cbu.edu> At 11:44 AM 1/26/2002 -0500, kirk Bailey wrote: > > is there a good code formatter for Python? > > With Highlighting. E.G. py->html? You can change HappyDoc to do that. It will be some work though. Oh wait, try ViewCVS, it has a Python code highlighter. Regards, Stephan -- Stephan Richter CBU - Physics and Chemistry Student Web2k - Web Design/Development & Technical Project Management From dsh8290@rit.edu Sat Jan 26 17:03:28 2002 From: dsh8290@rit.edu (dman) Date: Sat, 26 Jan 2002 12:03:28 -0500 Subject: [Tutor] Source Code Formatter In-Reply-To: <20020126132309Z45640-8421+843@mail.uni-paderborn.de> References: <20020126132309Z45640-8421+843@mail.uni-paderborn.de> Message-ID: <20020126170328.GA4292@dman.ddts.net> On Sat, Jan 26, 2002 at 02:22:42PM +0100, Huuuuuu wrote: | Hi, | | is there a good code formatter for Python? | With Highlighting. E.G. py->html? vim is great for on-screen use (editing or viewing). It can also print, though I haven't tried that out yet. enscript is a tool that can create highlighted postscript from plain text. For source code I like the following options : -2GrC -T 4 --mark-wrapped-lines=arrow --word-wrap --color --pretty-print -D -- It took the computational power of three Commodore 64s to fly to the moon. It takes at least a 486 to run Windows 95. Something is wrong here. From rufmetal@rogers.com Sat Jan 26 17:00:25 2002 From: rufmetal@rogers.com (Chris Keelan) Date: Sat, 26 Jan 2002 11:00:25 -0600 Subject: [Tutor] Source Code Formatter In-Reply-To: <3C52DCF6.59FE7889@netzero.net> References: <20020126132309Z45640-8421+843@mail.uni-paderborn.de> <3C52DCF6.59FE7889@netzero.net> Message-ID: <20020126110025.74139f14.rufmetal@rogers.com> On Sat, 26 Jan 2002 11:44:38 -0500, kirk Bailey spilled a can of spare bits all over the network, which arranged themselves like so: gvim has a "convert to html" option which preserves colorization. I just tested it and it works beautifully. - Chris From pythontutor@venix.com Sat Jan 26 17:38:37 2002 From: pythontutor@venix.com (Lloyd Kvam) Date: Sat, 26 Jan 2002 12:38:37 -0500 Subject: [Tutor] Python+CGI+MySQL performance References: <200201261535.g0QFZcBM008459@bucky.airstreamcomm.net> Message-ID: <3C52E99D.4080502@venix.com> I am supporting a web site that uses "this approach" to accessing MySQL. (this approach == Each 'submit button click' does a new connection to MySQL.) The CGI scripts are written in Perl and the ISP is using mod_perl to minimize script startup time. However, there is no reason to believe that Perl is any quicker than Python in this kind of application. User response time is fine, but the overall database load is light. There are never more than a couple of sessions trying to access the database at the same time. kent@springfed.com wrote: > Howdy, > > I am currently using ASP to provide dynamic content > and would like to convert to Python. > > Many hosting services offer PHP, but the only Python > availability I've found is via CGI. > > If I access MySQL from a python.cgi what is the overhead? > Is it true that every call to the script must open and close > a connection to the DB? > > Is it possible to get good performance with a setup like this? > > Thanks, > Kent > -- , kent@springfed.com on 26/01/2002 > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From srichter@cbu.edu Sat Jan 26 18:29:09 2002 From: srichter@cbu.edu (Stephan Richter) Date: Sat, 26 Jan 2002 12:29:09 -0600 Subject: [Tutor] Python+CGI+MySQL performance In-Reply-To: <3C52E99D.4080502@venix.com> References: <200201261535.g0QFZcBM008459@bucky.airstreamcomm.net> Message-ID: <5.1.0.14.2.20020126122137.023f0ef0@mercury-1.cbu.edu> At 12:38 PM 1/26/2002 -0500, Lloyd Kvam wrote: >I am supporting a web site that uses "this approach" to accessing MySQL. >(this approach == Each 'submit button click' does a new connection to MySQL.) >The CGI scripts are written in Perl and the ISP is using mod_perl >to minimize script startup time. However, there is no reason to believe >that Perl is any quicker than Python in this kind of application. > >User response time is fine, but the overall database load is light. There are >never more than a couple of sessions trying to access the database at >the same time. Well, why do you not look at Zope? It has a server and therefore keeps Python and the DB connections in memory. It also does much of the hard work for you, such as cookie and HTTP variables handling. Regards, Stephan -- Stephan Richter CBU - Physics and Chemistry Student Web2k - Web Design/Development & Technical Project Management From dsh8290@rit.edu Sat Jan 26 19:42:31 2002 From: dsh8290@rit.edu (dman) Date: Sat, 26 Jan 2002 14:42:31 -0500 Subject: [Tutor] What are security holes? In-Reply-To: <3C52B891.5984.1AE497@localhost> References: <3C52B891.5984.1AE497@localhost> Message-ID: <20020126194231.GA6098@dman.ddts.net> On Sat, Jan 26, 2002 at 02:09:21PM +0100, A wrote: | We are going to install Python on our Linux server. Are there any | security holes for hackers? What would we be careful about and | how we should set it up? Are there any guidelines for installing | Python? # apt-get install python2.2 :-) (well, if by "linux" you mean the "debian" distribution) The problem with having python is the same one you will have with perl, sh, gcc, g++, ruby, tcl, etc. Each of those allows a person to instruct the computer to do something. You certainly don't want to make your python binary SUID root or something. I am not aware of any "gotchas" wrt to installing python on a system. -D -- The heart is deceitful above all things and beyond cure. Who can understand it? I the Lord search the heart and examine the mind, to reward a man according to his conduct, according to what his deeds deserve. Jeremiah 17:9-10 From dsh8290@rit.edu Sat Jan 26 19:43:48 2002 From: dsh8290@rit.edu (dman) Date: Sat, 26 Jan 2002 14:43:48 -0500 Subject: [Tutor] working with images In-Reply-To: <20020126.065304.-261463.2.kjphotog@juno.com> References: <20020126.065304.-261463.2.kjphotog@juno.com> Message-ID: <20020126194348.GB6098@dman.ddts.net> On Sat, Jan 26, 2002 at 06:30:34AM -0800, kjphotog@juno.com wrote: | I'm a high school photography instructor & a Python newbie with a skill | level somewhere between "hello world" & fiddling with e-mail. What | might be the best intro to start working with images? PIL (Python Imaging Library) is a python extension for image manipulation. I haven't used it myself. The GIMP is also scriptable by python, if you have a system the GIMP will run on (www.gimp.org). HTH, -D -- Your beauty should not come from outward adornment, such as braided hair and the wearing of gold jewelry and fine clothes. Instead, it should be that of your inner self, the unfading beauty of a gentle and quiet spirit, which is of GREAT WORTH in God's sight. For this is the way the holy women of the past used to make themselves beautiful. I Peter 3:3-5 From virketis@fas.harvard.edu Sat Jan 26 21:51:20 2002 From: virketis@fas.harvard.edu (Pijus Virketis) Date: Sat, 26 Jan 2002 16:51:20 -0500 Subject: [Tutor] Python+CGI+MySQL performance References: <200201261535.g0QFZcBM008459@bucky.airstreamcomm.net> <3C52E99D.4080502@venix.com> Message-ID: <007d01c1a6b3$97292f20$18adf78c@virketis2> Hi, > I am supporting a web site that uses "this approach" to accessing MySQL. > (this approach == Each 'submit button click' does a new connection to MySQL.) > The CGI scripts are written in Perl and the ISP is using mod_perl > to minimize script startup time. However, there is no reason to believe > that Perl is any quicker than Python in this kind of application. Mind you, there is a mod_python plug-in for Apache as well. You can get it on Sourceforge: http://sourceforge.net/projects/modsnake/ If your ISP is willing to install it, you'll get great speed from your scripts. When it comes to the Python-MySQL connection, use the MySQLdb module: http://sourceforge.net/projects/mysql-python/ It works great with anything above and including Python 1.5.2 and from the tinkering around I have done so far, it looks to be pretty speedy. However, I have not used it for real work yet, and your mileage may vary. :) Cheers, Pijus From virketis@fas.harvard.edu Sat Jan 26 21:53:02 2002 From: virketis@fas.harvard.edu (Pijus Virketis) Date: Sat, 26 Jan 2002 16:53:02 -0500 Subject: [Tutor] Python+CGI+MySQL performance References: <200201261535.g0QFZcBM008459@bucky.airstreamcomm.net> <5.1.0.14.2.20020126122137.023f0ef0@mercury-1.cbu.edu> Message-ID: <008301c1a6b3$d3c25650$18adf78c@virketis2> > Well, why do you not look at Zope? It has a server and therefore keeps > Python and the DB connections in memory. It also does much of the hard work > for you, such as cookie and HTTP variables handling. I've always wondered about this: where does Zope live? Is it a CGI script, which I can install myself, or does my ISP have to install it? How does it interact with Apache, or whatever is serving the pages? Cheers, Pijus From pythontutor@venix.com Sat Jan 26 22:18:10 2002 From: pythontutor@venix.com (Lloyd Kvam) Date: Sat, 26 Jan 2002 17:18:10 -0500 Subject: [Tutor] Python+CGI+MySQL performance References: <200201261535.g0QFZcBM008459@bucky.airstreamcomm.net> <5.1.0.14.2.20020126122137.023f0ef0@mercury-1.cbu.edu> <008301c1a6b3$d3c25650$18adf78c@virketis2> Message-ID: <3C532B22.9040906@venix.com> Zope is the web server. It can be configured to run "behind" Apache, but it is a full blown http server written in Python. The beauty of Zope is that it is designed to collect bits and pieces of information and assemble them into a web page. These pieces of information can be stored in Zope's object database, retrieved from an SQL server, or retrieved by your own scripts. Because of the scripting involved, information can be computed or generated from the inputs. Now that Zope books are available to explain the processing, I expect it to become more widely used. Pijus Virketis wrote: >>Well, why do you not look at Zope? It has a server and therefore keeps >>Python and the DB connections in memory. It also does much of the hard >> > work > >>for you, such as cookie and HTTP variables handling. >> > > I've always wondered about this: where does Zope live? Is it a CGI script, > which I can install myself, or does my ISP have to install it? How does it > interact with Apache, or whatever is serving the pages? > > Cheers, > > Pijus > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From discuss@sendme.cz Sat Jan 26 13:09:21 2002 From: discuss@sendme.cz (A) Date: Sat, 26 Jan 2002 14:09:21 +0100 Subject: [Tutor] What are security holes? Message-ID: <3C52B891.24715.1AE46E@localhost> We are going to install Python on our Linux server. Are there any security holes for hackers? What would we be careful about and how we should set it up? Are there any guidelines for installing Python? Thank you for help. Ladislav From jgardn@alumni.washington.edu Sat Jan 26 15:56:11 2002 From: jgardn@alumni.washington.edu (Jonathan Gardner) Date: Sun, 27 Jan 2002 00:56:11 +0900 Subject: [Tutor] Re: What are security holes? In-Reply-To: <3C52B891.24715.1AE46E@localhost> References: <3C52B891.24715.1AE46E@localhost> Message-ID: <200201261601.g0QG16Y32658@my.knctv.co.kr> On Saturday 26 January 2002 10:09 pm, A wrote: > We are going to install Python on our Linux server. Are there any > security holes for hackers? What would we be careful about and > how we should set it up? Are there any guidelines for installing > Python? Just don't run scripts as root unless you know exactly what they do, just like you don't run any program as root unless you know exactly what it does. Also, be sure to check the MD5 checksums if you are really paranoid. Being paranoid is a Good Thing (TM). Jonathan From lkvam@venix.com Sat Jan 26 19:47:21 2002 From: lkvam@venix.com (Lloyd Kvam) Date: Sat, 26 Jan 2002 14:47:21 -0500 Subject: [Tutor] Python+CGI+MySQL performance References: <200201261535.g0QFZcBM008459@bucky.airstreamcomm.net> <5.1.0.14.2.20020126122137.023f0ef0@mercury-1.cbu.edu> Message-ID: <3C5307C9.6080002@venix.com> I am looking at ZOPE. The issues for this site are: it basically works OK as is it was developed years ago (by others) first in Mac AppleScript then in Perl CGI on Linux it may not be generating enough revenue to pay for another major reorganization the current hosting ISP does not support Zope or Python changes to the site are difficult due to dependancies between scripts and html My role is primarily one of script mechanic: adjusting scripts when changes are made. My point in the earlier posting was simply that lots of short connections could work OK. Stephan Richter wrote: > At 12:38 PM 1/26/2002 -0500, Lloyd Kvam wrote: > >> I am supporting a web site that uses "this approach" to accessing MySQL. >> (this approach == Each 'submit button click' does a new connection to >> MySQL.) >> The CGI scripts are written in Perl and the ISP is using mod_perl >> to minimize script startup time. However, there is no reason to believe >> that Perl is any quicker than Python in this kind of application. >> >> User response time is fine, but the overall database load is light. >> There are >> never more than a couple of sessions trying to access the database at >> the same time. > > > Well, why do you not look at Zope? It has a server and therefore keeps > Python and the DB connections in memory. It also does much of the hard > work for you, such as cookie and HTTP variables handling. > > Regards, > Stephan > > -- > Stephan Richter > CBU - Physics and Chemistry Student > Web2k - Web Design/Development & Technical Project Management > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From dyoo@hkn.eecs.berkeley.edu Sun Jan 27 00:02:31 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 26 Jan 2002 16:02:31 -0800 (PST) Subject: [Tutor] working with images In-Reply-To: <20020126.065304.-261463.2.kjphotog@juno.com> Message-ID: On Sat, 26 Jan 2002 kjphotog@juno.com wrote: > I'm a high school photography instructor & a Python newbie with a > skill level somewhere between "hello world" & fiddling with e-mail. > What might be the best intro to start working with images? The Python Imaging Library (PIL) is a very nice module for manipulating images. Try: http://www.pythonware.com/products/pil/ There's a tutorial on the Pythonware site that shows the basics of using PIL: http://www.pythonware.com/library/pil/handbook/tutorial.htm and I'm sure that several people on Tutor have experience with PIL, don't hesitate to ask questions. Good luck to you. From syrinx@simplecom.net Sun Jan 27 06:33:10 2002 From: syrinx@simplecom.net (Scott) Date: Sun, 27 Jan 2002 00:33:10 -0600 Subject: [Tutor] Suitable (not suitable), for Python... Message-ID: <20020127003310.0ba43f4b.syrinx@simplecom.net> I think this is covered in the docs, but I would be interested in hearing real-life examples of what would and wouldn't... For a laugh, if nothing else. From dyoo@hkn.eecs.berkeley.edu Sun Jan 27 09:33:33 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 27 Jan 2002 01:33:33 -0800 (PST) Subject: [Tutor] Httplib and Proxy In-Reply-To: <3C52B891.15886.1AE4C3@localhost> Message-ID: On Sat, 26 Jan 2002, A wrote: > Can anybody please give me a working example how I can use > httplib with a proxy if I use POST method? urllib.urlopen() may be what you're looking for: http://www.python.org/doc/current/lib/module-urllib.html If you're using an HTTP proxy, you can first set the 'http_proxy' environmental variable, and then urllib.urlopen() will use that when it retrieves http resources. urlllib.urlopen() also supports POST if we send the data as a second parameter to urlopen(). Good luck! From mikalzet@libero.it Sun Jan 27 14:05:25 2002 From: mikalzet@libero.it (mikalzet@libero.it) Date: Sun, 27 Jan 2002 15:05:25 +0100 (CET) Subject: [Tutor] date and time variables In-Reply-To: Message-ID: All right, I'm just toying around with my idea (see my previous post on starting a new project). So I wrote a very rudimentary piece of code: class Shift: def __init__(self, name="None", worker="None", begin="None", end="None"): self.name = name self.worker = worker self.begin = begin self.end = end def __str__(self): return str(self.name) + "\n" + str(self.worker) + "\n" + str(self.begin) + " - " + str(self.end) def hours(self): return abs(self.begin - self.end) Which works if I call it as follows: newshift = Shift("PN Int mt.","ALZ", 8, 14) print newshift print newshift.hours() However ! My PostgreSQL table at the moment looks something like this: Field Variable type Name text Begin datetime End datetime worker char datetime formats like this: 2002-01-28 14:00:00 I chose datetime instead of an int type variable because I'm sure to need actual time measurements in future. Now for the questions: 1) How can I get my Shift class to handle this type of data ? Is there an analogous data type in python ? Or do I have to 'translate' data to a different type when reading / writing to postgres ? 2) Where can I find documentation on how to interact with postgres from python ? -- Michele Alzetta From srichter@cbu.edu Sun Jan 27 17:47:53 2002 From: srichter@cbu.edu (Stephan Richter) Date: Sun, 27 Jan 2002 11:47:53 -0600 Subject: [Tutor] Python+CGI+MySQL performance In-Reply-To: <008301c1a6b3$d3c25650$18adf78c@virketis2> References: <200201261535.g0QFZcBM008459@bucky.airstreamcomm.net> <5.1.0.14.2.20020126122137.023f0ef0@mercury-1.cbu.edu> Message-ID: <5.1.0.14.2.20020127114512.02423490@mercury-1.cbu.edu> At 04:53 PM 1/26/2002 -0500, Pijus Virketis wrote: > > Well, why do you not look at Zope? It has a server and therefore keeps > > Python and the DB connections in memory. It also does much of the hard >work > > for you, such as cookie and HTTP variables handling. > >I've always wondered about this: where does Zope live? Is it a CGI script, >which I can install myself, or does my ISP have to install it? How does it >interact with Apache, or whatever is serving the pages? Well, Zope has its own HTTPServer or you can use PCGI tunneling or simple URL forwarding with Apache. There is no need for root permission to run Zope. You can start it on any port you like. The easiest thing is to try it out on your machine. Get the binary install from www.zope.org and you should be going in 15 mins. If you have troubles, make a post on zope@zope.org. Regards, Stephan -- Stephan Richter CBU - Physics and Chemistry Student Web2k - Web Design/Development & Technical Project Management From alan.gauld@bt.com Sun Jan 27 19:45:42 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Sun, 27 Jan 2002 19:45:42 -0000 Subject: [Tutor] Python vs. PHP Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB212562C37@mbtlipnt02.btlabs.bt.co.uk> > flexible, as you can write your entire page in HTML and add the PHP > where it's needed, or you can write your entire page in PHP > and include HTML where needed (or print it where needed). Python (or indeed Perl) can do this too usong CGI techniques: print '''The title here ''' So apart from adding a print statement and triple quotes it works pretty well. To add code just break the quoted sequence in two like so: print '''The title here ''' # break the html text here def foo(): print str(5*5) # prints 5 into the HTML print ''' # continues the HTML text ''' So you can insert code into the HTML almost like you do in PHP or ASP. If course you can use PSP too which works exactly like ASP/PHP but using: [% # Python code here print "foobar" %] And On IIS you can even use ASP: <% SCRIPT LANGUAGE='Python'> <% print 'foobar' %> Or whatever - I'm in an airport lounge without access to my ASP books! The point is that despite the hysteria generated, there is very little to choose between ASP or CGI style web scripting. Alan G From alan.gauld@bt.com Sun Jan 27 19:45:35 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Sun, 27 Jan 2002 19:45:35 -0000 Subject: [Tutor] List comprehension Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB212562C32@mbtlipnt02.btlabs.bt.co.uk> > As an application I really like defining gcd(a,b) and then > gathering totatives (positives relatively prime to N and < N) > by going: > > >>> def gcd(a,b): > while b: > a,b = b, a%b > return a > > totatives = [t for t in range(1,N) if gcd(t,N)==1] > > The lambda form would be: > > >>> filter(lambda a: gcd(a,28)==1,range(28)) > [1, 3, 5, 9, 11, 13, 15, 17, 19, 23, 25, 27] > > I don't find that any clearer than the list comprehension > way of doing it. But let's stop confusing two distinct structures. The lamda form is a diffrent way of defining a function object - one with no name. If you can create a named function(like gcd) then lambda is not needed, so the "equivalent" form could be: def gcd(a,b=28): while b: a,b = b, a%b return a == 1 filter(gcd, range(28)) lambda is only used as a quick n dirty way of defining a short function inine. Its not a necessary part of the map/filter/reduce syntax. The Lisp take on Lambdas is that every block of code is essentially a lambda block and every function is merely a name referring to a lambda. This in Lisp there is no difference between declaring a variable assignment and a function assignment: (define foo 8) (define bar (lambda x (+ x x))) Are completely consistent. Both expressions simply assign a value (8 and a lambda respectively) to a name (a variable if you like). That's why Lispers like lambdas because they bring consistency to the language. But the FP functions do not rely on lambdas, they rely on function objects which is a different and more powerful concept. Thus knowing Lisp makes lambdas readable but is not the reason I prefer map etc. I simply find: map(f, Lst) easier to read than [f for i in Lst] Partly coz my brain automatically parses the latter as (f for i) in Lst Which makes no sense! Thus I have to consciously back out and think the construct thru. Thats why I'd have liked a separator of some sort between the expression and the for > >>> reduce(add,[a*b for a in [400,20,3] for b in [300,20,1]]) > 135783 > >>> 423*321 > 135783 Now this is where I think LCs really do start to have an advantage even if I don't like the syntax. Alan G From alan.gauld@bt.com Sun Jan 27 19:45:41 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Sun, 27 Jan 2002 19:45:41 -0000 Subject: [Tutor] Python vs. PHP Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB212562C36@mbtlipnt02.btlabs.bt.co.uk> > Looking around, I find what seem like two different kinds of dynamic > webpages. Some are written in Perl (Slashcode) or Python > ...ASP/PHP. I guess the former are CGI scripts, and the > latter are active server pages. There are a couple of other types as well of which the best known is JSP or Jasva servlets. But for the sake of convenience I'll refer to the two types as CGI and ASP They all use the CGI interface but execute slightly differently. > What are the relative merits of doing things > one way or the other? Big religious arguments over this. In traditional CGI the cost of starting a new process for each request is a big performance hit - especially on Windows. So ASP was developed coz ASP runs inside the Web server engine and avoids the big startup cost. However CGI hit back with CGI launchers embedded in the server, thus mod-perl and mod-python came to be and virtually wiped out the startup issue. So now it comes down to whether embedding code inside html(ASP) was better or worse than embedding html in code(CGI). Now .NET is taking ASP one step further and totally separating the code and HTML(apart from some linking statements)... Personally I use ASP when I have a largely statioc HTML web page but want a bit of dynamic content. For example a date/time display or web counter. If the bulk of the page will be generated dynamically - like an Amazon book description say - then I use CGI. Finally, I'm sure somebody else will tell you about Zope... Alan G. (Still stuck in the snow :-) From alan.gauld@bt.com Sun Jan 27 19:45:38 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Sun, 27 Jan 2002 19:45:38 -0000 Subject: [Tutor] ftp and python enabled editor Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB212562C34@mbtlipnt02.btlabs.bt.co.uk> ------_=_NextPart_001_01C1A76B.31F0ABC0 Content-type: text/plain; charset="ISO-8859-1" This is an academic answer in that I've only ever read about it not tried it.... A quick question about the tools of programming. I remember the long discussion a few months ago about editors: my requirements are much narrower here. Is there a program that can open and save files via FTP on a remote location, supports Python syntax highlighting and works on Windows? I usually use SciTE or just good old IDLE, but neither can do FTP ... I think emacs can do this in something called archie mode(??) It goes and ftps a copy of the file and when you 'save' it it ftps it back again to the remote server. Emacs of course has a python mode so you simply run that on the file while editing to get syntax coloring etc. I think thats what you wanted? Alan g. (working offline waiting for a plane in a snow storm :-( ) ------_=_NextPart_001_01C1A76B.31F0ABC0 Content-type: text/html; charset="ISO-8859-1"
This is an academic answer in that I've only ever
read about it not tried it....
A quick question about the tools of programming. I remember the long discussion a few months ago about editors: my requirements are much narrower here. Is there a program that can open and save files via FTP on a remote location, supports Python syntax highlighting and works on Windows? I usually use SciTE or just good old IDLE, but neither can do FTP ...
I think emacs can do this in something called archie mode(??)
It goes and ftps a copy of the file and when you 'save' it it ftps it back again
to the remote server.
 
Emacs of course has a python mode so you simply run that on the file while
editing to get syntax coloring etc.
 
I think thats what you wanted?
 
Alan g.
(working offline waiting for a plane in a snow storm :-(  )
------_=_NextPart_001_01C1A76B.31F0ABC0-- From alan.gauld@bt.com Sun Jan 27 19:45:40 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Sun, 27 Jan 2002 19:45:40 -0000 Subject: [Tutor] learner Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB212562C35@mbtlipnt02.btlabs.bt.co.uk> ------_=_NextPart_001_01C1A76B.32F21630 Content-type: text/plain; charset="ISO-8859-1" > i would like to know how to write a program. > i am relatively new to computers and have no prior programming experience. Thats the target for my web tutor (url below) i would like to know if python is a good place to begin and why? I answer that. what type of applications can the python language be used for? And a bit of that Alan g. Author of the 'Learning to Program' web site http://www.freenetpages.co.uk/hp/alan.gauld ------_=_NextPart_001_01C1A76B.32F21630 Content-type: text/html; charset="ISO-8859-1"
 >  i would like to know how to write a program.
 >  i am relatively new to computers and have no prior programming experience. 
 
Thats the target for my web tutor (url below) 
i would like to know if python is a good place to begin and why? 
I answer that.
 
what type of applications can the python language be used for? 
 
And a bit of that
 

Alan g.
Author of the 'Learning to Program' web site
http://www.freenetpages.co.uk/hp/alan.gauld

------_=_NextPart_001_01C1A76B.32F21630-- From alan.gauld@bt.com Sun Jan 27 19:45:36 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Sun, 27 Jan 2002 19:45:36 -0000 Subject: [Tutor] creating variables at runtime Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB212562C33@mbtlipnt02.btlabs.bt.co.uk> > Is is possible in python to create variables at runtime? Yes. But... > What I'm wanting to do is create instances of classes, given names > based on user input > (something done to userinput) = MyClass(), such that NARF will be an > instance of MyClass. I would very strongly recommend using a dictionary instead: myClasses = {} # empty dict for class in range(5): name = raw_input('Gimme a name ') myClasses[name] = MyClass() Now we have 5 named instances of MyClass in myClasses dictionary. We access like so: for name in myClasses.keys(): print name # show me the names name = raw_input('Which one? ') print myClasses[name] and so on... [ FWIW Thats pretty much what Python does under the covers when you create variables in your code - it sticks them in a sdictionary. When you use dir() you ask Python to list the names... ] Alan g From dsh8290@rit.edu Sun Jan 27 21:24:34 2002 From: dsh8290@rit.edu (dman) Date: Sun, 27 Jan 2002 16:24:34 -0500 Subject: [Tutor] Suitable (not suitable), for Python... In-Reply-To: <20020127003310.0ba43f4b.syrinx@simplecom.net> References: <20020127003310.0ba43f4b.syrinx@simplecom.net> Message-ID: <20020127212434.GB5962@dman.ddts.net> On Sun, Jan 27, 2002 at 12:33:10AM -0600, Scott wrote: | I think this is covered in the docs, but I would | be interested in hearing real-life examples of what | would An application (pick your type -- gui, filter, file processor, cgi -- basically anything high-level) | and wouldn't... A linux device driver (or anything else really low level) | For a laugh, if nothing else. Does that make you laugh? ;-) -D -- A)bort, R)etry, D)o it right this time From shalehperry@attbi.com Sun Jan 27 21:51:04 2002 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Sun, 27 Jan 2002 13:51:04 -0800 (PST) Subject: [Tutor] date and time variables In-Reply-To: Message-ID: > I chose datetime instead of an int type variable because I'm sure to need > actual time measurements in future. > > Now for the questions: > > 1) How can I get my Shift class to handle this type of data ? Is there an > analogous data type in python ? Or do I have to 'translate' data to a > different type when reading / writing to postgres ? There is a mxdatetime module which does lots of nifty things with times and dates. > 2) Where can I find documentation on how to interact with postgres from > python ? > The python support for postgres is shipped with postgres, so check there for docs. From glingl@aon.at Sun Jan 27 22:05:15 2002 From: glingl@aon.at (Gregor Lingl) Date: Sun, 27 Jan 2002 23:05:15 +0100 Subject: [Tutor] Source Code Formatter References: <20020126132309Z45640-8421+843@mail.uni-paderborn.de> Message-ID: <00ae01c1a77e$b33afd30$1664a8c0@mega> Dear Willi Huuuuuu! I think there is (more or less) no need for a Python Source Code Formatter, since Python doesn't run if not properly formatted - (i.m.o.) one of its magnificent features! Concerning the other part of your question, there IS a program to produce syntaxhighliting of python-programs contained in html-pages (within
  ...  
  <(pre>
 tags)
It is part of the suite of perl programs, written 
by Jonah Cohen, which convert the 
How To Think Like a Computer Scientist - Books
from latex to html. IT's name is syntax.pl and they all
can be found at

http://www.ibiblio.org/obp/ltoh/

Unfortunately it is poorly documented
and uses regular expressions extensively --
and you know what this means for perl-programs. 

Nevertheless it works - and also for other languages ...

hope this helps,
Gregor


----- Original Message ----- 
From: "Huuuuuu" 
To: 
Sent: Saturday, January 26, 2002 2:22 PM
Subject: [Tutor] Source Code Formatter


> Hi,
> 
> is there a good code formatter for Python?
> With Highlighting. E.G. py->html?
> 
> Thanks,
> willi




From Kyuuketsiuki@aol.com  Sun Jan 27 05:54:17 2002
From: Kyuuketsiuki@aol.com (Kyuuketsiuki@aol.com)
Date: Sun, 27 Jan 2002 00:54:17 EST
Subject: [Tutor] Please read this and respond to me.
Message-ID: <16e.7ca3139.2984f009@aol.com>

I'm looking for a tutor (Teacher) on hacking, I've been meaning to learn and 
i have read many things, but i have never really learned, so i would like for 
you to teach me.    


From sstouden@thelinks.com  Sun Jan 27 21:00:00 2002
From: sstouden@thelinks.com (sterling stoudenmire)
Date: Sun, 27 Jan 2002 15:00:00 -0600
Subject: [Tutor] stupid beginning question
Message-ID: <5.0.2.1.0.20020127144845.00a5ee00@localhost>

	i created in the gui the following code
import string
def more(text, numlines=15):
     lines = string.split(text, '\n")
     while lines:
         chunk = lines[:numlines]
         lines = lines[numlines:]
         for line in chunk: print line
         if lines and raw_input('More?') not in ['Y', 'Y']: break
if __name__ == '__main__':
import sys
more(open(sys.argv[1]).read(), 10)
from page 16 and 17 of Programming Python: Oreily
I save it and then tried to run it and go a bunch of errors.

Python 2.1.2 (#31, Jan 15 2002, 17:28:11) [MSC 32 bit (Intel)] on win32
Type "copyright", "credits" or "license" for more information.
IDLE 0.8 -- press F1 for help
 >>> import string
def more(text, numlines=15):
     lines = string.split(text, '\n")
     while lines:
         chunk = lines[:numlines]
         lines = lines[numlines:]
         for line in chunk: print line
         if lines and raw_input('More?') not in ['Y', 'Y']: break
if __name__ == '__main__':
import sys
more(open(sys.argv[1]).read(), 10)
[DEBUG ON]
 >>>
[DEBUG OFF]
 >>>
and i get the message: the buffer for Python Shell is not saved. please 
save it first
what is the file extension name of the save file suppose to be also it does 
not appear in the list when i select file, option.
thanks your help.\




From rufmetal@rogers.com  Sun Jan 27 23:28:20 2002
From: rufmetal@rogers.com (Chris Keelan)
Date: Sun, 27 Jan 2002 17:28:20 -0600
Subject: [Tutor] Please read this and respond to me.
In-Reply-To: <16e.7ca3139.2984f009@aol.com>
References: <16e.7ca3139.2984f009@aol.com>
Message-ID: <20020127172820.5e36367e.rufmetal@rogers.com>

On Sun, 27 Jan 2002 00:54:17 EST, Kyuuketsiuki@aol.com spilled a can
of spare bits all over the network, which arranged themselves like so:

> I'm looking for a tutor (Teacher) on hacking, I've been meaning to
> learn and i have read many things, but i have never really learned,
> so i would like for you to teach me.

If you mean "script kiddie", you want to go to http://www.alt2600.com/

Enjoy your internet access and your freedom while you still have them.

If you mean "programmer", start here.

http://www.tuxedo.org/~esr/faqs/hacker-howto.html

- C


From idiot1@netzero.net  Sun Jan 27 23:43:25 2002
From: idiot1@netzero.net (kirk Bailey)
Date: Sun, 27 Jan 2002 18:43:25 -0500
Subject: [Tutor] learner
References: <5104D4DBC598D211B5FE0000F8FE7EB212562C35@mbtlipnt02.btlabs.bt.co.uk>
Message-ID: <3C54909D.5B1316AA@netzero.net>

> >  i would like to know how to write a program.
> >  i am relatively new to computers and have no prior programming experience. 

Wow, havy question.

0. Make sure you have a good idea of how your computer is built,
organized, and
   how the operating system works.

1. Devlop a good idea of what you want to do. Define a definate goal.

2. devlop a eries of steps it must do to accomplish your chosen goal.

3. Rough this out in a series of steps. Drawing pictures may help
here.

4. Go back and begin defining the details of each step. whenever you
need to
   keep track of some piece of information, give that thing a name, so
you can
   referr to it later. Use a name that helps you to keep track of just
WHAT
   that piece of information is.

5. Install IDLE so you can try out snippets of code to make sure they
do what
   you want.

6. Add them to the program under construction.

7. When it looks like it is done, run it from the command line and see
if it
   blows up- it probably will. READ THE ERROR MESSAGES CAREFULLY. They
are profound
   in meaning and will lead to endless amusement asd you hurl the CRT
out the window
   screaming incredible in inscruitable evil disparaging remarks. It's
as popular as
   politics for raising your blood pressure.

8. fix them. Try [7] again. Loop 7=8-7-8 until no more errors show up.

9. See if it actually does what you wanted. You may care to go back
and redefine
   the program, discovering it is doing something else very nicely,
but NOT what
   was wanted! If not, drop back as menay steps as it takes to get the
desired
   results. 

BE ADVISED this is THE place to show off how fallible and error prone
you are- like
me. Show us your goals, successes, failures, error reports, raw code.
POST the current script of the hour to the web so we can look at it!
SSI can be very helpful on this item. 

> Thats the target for my web tutor (url below) 

> >    i would like to know if python is a good place to begin and why? 
surely it is. Beats the whistling ASS off of C, perl, Assembler,
SNOBOL, FORTRAN...

> I answer that.

     
> >    what type of applications can the python language be used for? 
Except for run time critical apps and for Kernel hacking, image
procesing and
compression processing, or things into HEAVY bare metal bit whapping,
anyth8ng you like.
     

>And a bit of that
True, true, but let's not get technical with a newbie...   ;-) 

>Alan g.
>Author of the 'Learning to Program' web site
http://www.freenetpages.co.uk/hp/alan.gauld 



-- 
 

 -Respectfully,
              -Kirk D Bailey 
               Consulting Loose Cannon

end



  www.howlermonkey.net                 highprimate@howlermonkey.net
  www.sacredelectron.org                         idiot1@netzero.net
  www.tinylist.org                              grumpy@tinylist.org
----------------------------------------------------
Sign Up for NetZero Platinum Today
Only $9.95 per month!
http://my.netzero.net/s/signup?r=platinum&refcd=PT97


From idiot1@netzero.net  Sun Jan 27 23:51:30 2002
From: idiot1@netzero.net (kirk Bailey)
Date: Sun, 27 Jan 2002 18:51:30 -0500
Subject: [Tutor] Python vs. PHP
References: <5104D4DBC598D211B5FE0000F8FE7EB212562C37@mbtlipnt02.btlabs.bt.co.uk>
Message-ID: <3C549282.A046A78C@netzero.net>

Generally, I like to use SSI for web pages, sith just a touch of CSS
for seasoning. Howlermonkey.net is all SSI/CSS/custom scripts done by
a friend (in perl, which I intend to rectify SOON) and no pages EXCEPT
the web email interface and th pages for TinyList are entirely
generated by scripts.

As a scripting language, I strongly favor Python, and intend to
convert everything over.


alan.gauld@bt.com wrote:
> 
> > flexible, as you can write your entire page in HTML and add the PHP
> > where it's needed, or you can write your entire page in PHP
> > and include HTML where needed (or print it where needed).
> 
> Python (or indeed Perl) can do this too usong CGI techniques:
> 
> print '''The title here
> 
> 
> 
> '''
> 
> So apart from adding a print statement and triple quotes
> it works pretty well. To add code just break the quoted
> sequence in two like so:
> 
> print '''The title here
> 
> 
> '''   # break the html text here
> 
> def foo():
>    print str(5*5) # prints 5 into the HTML
> 
> print '''    # continues the HTML text
> 
> '''
> 
> So you can insert code into the HTML almost like you
> do in PHP or ASP.
> 
> If course you can use PSP too which works exactly
> like ASP/PHP but using:
> 
> [%
>      # Python code here
>      print "foobar"
> %]
> 
> And On IIS you can even use ASP:
> 
> <% SCRIPT LANGUAGE='Python'>
> 
> <%  print 'foobar' %>
> 
> Or whatever - I'm in an airport lounge without
> access to my ASP books!
> 
> The point is that despite the hysteria generated, there
> is very little to choose between ASP or CGI style web
> scripting.
> 
> Alan G
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

-- 
 

 -Respectfully,
              -Kirk D Bailey 
               Consulting Loose Cannon

end



  www.howlermonkey.net                 highprimate@howlermonkey.net
  www.sacredelectron.org                         idiot1@netzero.net
  www.tinylist.org                              grumpy@tinylist.org
----------------------------------------------------
Sign Up for NetZero Platinum Today
Only $9.95 per month!
http://my.netzero.net/s/signup?r=platinum&refcd=PT97


From arcege@speakeasy.net  Mon Jan 28 00:04:37 2002
From: arcege@speakeasy.net (Michael P. Reilly)
Date: Sun, 27 Jan 2002 19:04:37 -0500
Subject: [Tutor] Suitable (not suitable), for Python...
In-Reply-To: <20020127212434.GB5962@dman.ddts.net>; from dsh8290@rit.edu on Sun, Jan 27, 2002 at 04:24:34PM -0500
References: <20020127003310.0ba43f4b.syrinx@simplecom.net> <20020127212434.GB5962@dman.ddts.net>
Message-ID: <20020127190437.D915@speakeasy.net>

On Sun, Jan 27, 2002 at 04:24:34PM -0500, dman wrote:
> On Sun, Jan 27, 2002 at 12:33:10AM -0600, Scott wrote:
> | I think this is covered in the docs, but I would
> | be interested in hearing real-life examples of what
> | would
> 
> An application (pick your type -- gui, filter, file processor, cgi --
> basically anything high-level)
> 
> | and wouldn't...
> 
> A linux device driver (or anything else really low level)

Additionally, anything that requires VERY fast processing (could still be
high-level processing).  Don't try making OC3-OC48 speed network routing
software with Python (OC3 is about 155 Mbps, about 2776 times faster
than a 56K modem, OC48 is equivalent to sixteen times that).  *hehe*

I have seen very fast real-time virtual reality constructs written with
Python (at one of the Python conventions).  It was helped out with C
code for speed, but much of the actual VR code was still in Python.
The point is that, when mixed appropriately, Python can do most of what
you might want it to do.

But myself, I've written product boot software, device management software
and hardware/software upgrade mechanisms with Python (including updating
flash devices), frameworks for software and release management, call
tracking software.

  -Arcege



From syrinx@simplecom.net  Mon Jan 28 01:23:15 2002
From: syrinx@simplecom.net (Scott)
Date: Sun, 27 Jan 2002 19:23:15 -0600
Subject: [Tutor] pyslang question
Message-ID: <20020127192315.0631d2c9.syrinx@simplecom.net>

Hi all.  This would probably be better asked on alt.lang.s-lang, but
my news server has been down for weeks (arrgh; they say they're working
on it), but maybe someone here will know the answer.  Whenever I run
a pyslang program (even the samples that come with pyslang), I end up
with a file in the current directory called "pyslang.err" that says "this
is init."  This is even though there was no apparent error in the execution
of the program.  Can someone tell me what that is about?  Thank you.


From tj_ogrady@yahoo.com  Mon Jan 28 03:26:01 2002
From: tj_ogrady@yahoo.com (TJ O'Grady)
Date: Sun, 27 Jan 2002 19:26:01 -0800 (PST)
Subject: [Tutor] Zope OS X users
Message-ID: <20020128032601.87451.qmail@web11606.mail.yahoo.com>

I know I'm speaking to a small segment here- Is anyone
currently using a DB with Python and Zope on OS X? 

I have a scheduling script I want to migrate from
Windows Zope and MySQL to OS X Zope and anything. I
think I can work out any differences between python on
the different platforms, but first I have to find a DB
that will work.

Sorry if this is outside the scope of the list, I
figured it wouldn't hurt to ask.

Thanks,
TJ

__________________________________________________
Do You Yahoo!?
Great stuff seeking new owners in Yahoo! Auctions! 
http://auctions.yahoo.com


From erikprice@mac.com  Mon Jan 28 03:50:03 2002
From: erikprice@mac.com (Erik Price)
Date: Sun, 27 Jan 2002 22:50:03 -0500
Subject: [Tutor] Re: List Comprehensions again   [an example with filter()]
In-Reply-To: 
Message-ID: <1C3B5D5A-13A2-11D6-8529-00039351FE6A@mac.com>

Excellent!  I see what you're saying.  filter() basically lets you 
perform a function on another function, and returns only the results 
which are true for that second function.  Just like the name: filter.  
Filters out all results that are not true.  Or something to that effect.

Alright, that makes sense, but I noticed some other things in your 
response (sort of unrelated) that I'd like to ask for a bit of 
clarification on:

On Friday, January 25, 2002, at 10:19  PM, Danny Yoo wrote:

> ###
> for w in words:
>     if w[-1] == 's':
>         print w
> ###

Is using the three hashes a standard way of marking up example code in 
Python?  I see it a lot on this list, and was wondering if it was 
specific to the language or just a convention of this list.

> ###
> def endsWithS(word):
>     return word[-1] == 's'
>
> for w in words:
>     if endsWithS(w):
>         print w
> ###

This is something I haven't seen before -- using an expression as the 
return value of a function.  I take it that this means "return boolean 
value TRUE if the expression 'word[-1] == "s" ' ".  But I'm not sure.  
It could be that instead, it returns the words that match?  If it did 
that, then the second part, the "for" loop, wouldn't be necessary, so 
drawing from context I am assuming that the former is true.

> You probably already feel comfortable passing around numbers and strings
> to functions, but other functions?  If this is the first time you've 
> seen
> it, it will probably seem pretty darn weird at first, but it'll make 
> sense
> as you play with it.

You can create some pretty complicated constructs by passing functions 
to other functions in PHP -- I find that it's sometimes easier to 
conceptualize if I assign a function to a variable and then just pass 
variables to functions.  But over time I'm sure I'll trade in this 
clarity for convenience.

> On Thu, 24 Jan 2002, Erik Price wrote:
>> As a superfledgling, I have to say that I have no idea what you guys 
>> are
>> talking about.  For the first few messages I figured it was something
>> that I could pick up later on.  Now this thread has gone on for several
>> days and I'm starting to wonder if I should learn this lambda / list
>
> You can pick it up later.  Basically, list comprehensions, maps, and
> filters are fancy ways of doing list processing.  Often, we're looking 
> at
> a list --- a sequence of things --- and we might want to do some mass
> action to that whole sequence.  Comprehensions, map(), and filter() are
> all convenient ways of doing operations on whole sequences.

Okay, I'll learn about list comprehensions later.

Thanks Danny!


Erik









From erikprice@mac.com  Mon Jan 28 03:51:50 2002
From: erikprice@mac.com (Erik Price)
Date: Sun, 27 Jan 2002 22:51:50 -0500
Subject: [Tutor] Re: List Comprehensions again
In-Reply-To: <20020125232014.GA7250@dman.ddts.net>
Message-ID: <5BDEC430-13A2-11D6-8529-00039351FE6A@mac.com>

On Friday, January 25, 2002, at 06:20  PM, dman wrote:

> lambda is most often used in conjunction with map/filter/reduce, and
> the whole lot comes from the "functional" programming style (embodied
> in LISP, Scheme, and the ML family of languages).

Is this style of programming different from "procedural" and "object 
oriented" programming styles?  I haven't read about it before, although 
I have read of the difference between procedural and object oriented 
styles.


Erik



From erikprice@mac.com  Mon Jan 28 04:04:29 2002
From: erikprice@mac.com (Erik Price)
Date: Sun, 27 Jan 2002 23:04:29 -0500
Subject: [Tutor] Python+CGI+MySQL performance
In-Reply-To: <007d01c1a6b3$97292f20$18adf78c@virketis2>
Message-ID: <209B0238-13A4-11D6-8529-00039351FE6A@mac.com>

On Saturday, January 26, 2002, at 04:51  PM, Pijus Virketis wrote:

> Mind you, there is a mod_python plug-in for Apache as well.

I have a quick question about using an Apache plugin like this -- what 
is the functional difference between using mod_python and python as a 
CGI?  I understand that mod_python may be somewhat faster, but what I am 
wondering is, do you write the script differently for one from the other?


Erik



From urnerk@qwest.net  Mon Jan 28 04:05:46 2002
From: urnerk@qwest.net (Kirby Urner)
Date: Sun, 27 Jan 2002 20:05:46 -0800
Subject: [Tutor] Re: List Comprehensions again   [an example with
 filter()]
In-Reply-To: <1C3B5D5A-13A2-11D6-8529-00039351FE6A@mac.com>
References: 
Message-ID: <4.2.0.58.20020127200453.00d0ced0@pop3.norton.antivirus>

>
>This is something I haven't seen before -- using an expression
>as the return value of a function.  I take it that this means
>"return boolean value TRUE if the expression 'word[-1] == "s" ' ".
>But I'm not sure.

You are correct, sir!

Kirby



From wheelege@hotmail.com  Mon Jan 28 04:11:56 2002
From: wheelege@hotmail.com (Glen Wheeler)
Date: Mon, 28 Jan 2002 15:11:56 +1100
Subject: [Tutor] Re: List Comprehensions again
References: <5BDEC430-13A2-11D6-8529-00039351FE6A@mac.com>
Message-ID: 


>
> On Friday, January 25, 2002, at 06:20  PM, dman wrote:
>
> > lambda is most often used in conjunction with map/filter/reduce, and
> > the whole lot comes from the "functional" programming style (embodied
> > in LISP, Scheme, and the ML family of languages).
>
> Is this style of programming different from "procedural" and "object
> oriented" programming styles?  I haven't read about it before, although
> I have read of the difference between procedural and object oriented
> styles.
>

  Yup.  This is called Functional Programming - I'd check out Alan's tutor
for more info on that, a link can be found in one of his recent posts to
this list.

  Good luck!
  Glen


From dyoo@hkn.eecs.berkeley.edu  Mon Jan 28 04:35:20 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sun, 27 Jan 2002 20:35:20 -0800 (PST)
Subject: [Tutor] Re: List Comprehensions again   [an example with the
 interpreter]
In-Reply-To: <1C3B5D5A-13A2-11D6-8529-00039351FE6A@mac.com>
Message-ID: 

On Sun, 27 Jan 2002, Erik Price wrote:

> On Friday, January 25, 2002, at 10:19  PM, Danny Yoo wrote:
> 
> > ###
> > for w in words:
> >     if w[-1] == 's':
> >         print w
> > ###
> 
> Is using the three hashes a standard way of marking up example code in 
> Python?  I see it a lot on this list, and was wondering if it was 
> specific to the language or just a convention of this list.

It's a completely arbitrary convention.  The hash mark '#' is the comment
symbol in Python --- it comments the rest of the line.  I use it to mark
off code from the rest of an email message.

(When I'm quoting Scheme code, I'll often use the semicolon character ';'
for similar reasons.  *grin*)




> > ###
> > def endsWithS(word):
> >     return word[-1] == 's'
> >
> > for w in words:
> >     if endsWithS(w):
> >         print w
> > ###
> 
> This is something I haven't seen before -- using an expression as the
> return value of a function.  I take it that this means "return boolean
> value TRUE if the expression 'word[-1] == "s" ' ".  But I'm not sure. 


Let's say that we didn't know the answer to this, but we still wanted to
find out.  What's nice about Python is that it has an interactive
interpreter, and we can set up an experiment to see what happens:

###
>>> def endsWithS(word):
...     return word[-1] == 's'
... 
>>> endsWithS('the language instinct')
0
>>> endsWithS('soliloquies')
1
###

Yes, it returns a true value.  Oh, by the way, here are a list of values
that Python considers to be "false" values:

    ""
    []
    ()
    0
    {}

We can use the interpreter to play around with Python's idea of truth:

###
>>> def isTrue(x):
...     if x: print "true!"
...     else: print "false!"
... 
>>> isTrue("")
>>> isTrue("0")
true!
>>> isTrue(0)
false!
>>> isTrue([])
false!
>>> isTrue({})
false!
>>> isTrue(isTrue)
true!
###


Hope this helps!



From dyoo@hkn.eecs.berkeley.edu  Mon Jan 28 05:10:34 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sun, 27 Jan 2002 21:10:34 -0800 (PST)
Subject: [Tutor] Python+CGI+MySQL performance
In-Reply-To: <209B0238-13A4-11D6-8529-00039351FE6A@mac.com>
Message-ID: 

On Sun, 27 Jan 2002, Erik Price wrote:

> On Saturday, January 26, 2002, at 04:51  PM, Pijus Virketis wrote:
> 
> > Mind you, there is a mod_python plug-in for Apache as well.
> 
> I have a quick question about using an Apache plugin like this -- what
> is the functional difference between using mod_python and python as a
> CGI?  I understand that mod_python may be somewhat faster, but what I
> am wondering is, do you write the script differently for one from the
> other?

We can write it similarly if we're careful.


In regular CGI, the web server will execute the script, just as if we were
running in from the shell prompt.  In the CGI version, we pretty much
start from scratch every time someone looks at the page.


What's different about mod_python is that there's a Python interpreter
embedded right into Apache's mod_python module.  The advantage here is
that, instead of incurring the cost of starting up the interpreter every
time the user requests a resource, we can just do it once.


When we write a mod_python'ed script, we probably need to make a special
function called "service()" or something similar to that, so that
mod_python() knows how to call the script when there's an HTTP request.  
I'd have to check the mod_python site for the specific function mod_python
expects to call, but I think that's the general idea.  Let me check...

http://www.modpython.org/live/mod_python-2.7.6/doc-html/tut-what-it-do.html

Ah, ok, they expect to see a function called "handle()".  Close enough.  
*grin* If you've fiddled arround with graphical user interfaces (GUI's),
you're may already be familiar with this style of program: it's an
"event-driven" program!  In a GUI, the program waits until the user
touches a a widget.  Similarly, in mod_python, a script waits until the
web server calls handle().




If we wanted a script to run similarly as both a CGI and in mod_python, we
can possibly use the following hook at the bottom of our program:

###
if __name__ == '__main__':
    req = somehowCreateARequestObjectThatMimicsWhatModPythonDoes()
    service(req)
###

However, I haven't played around with mod_python, so I don't quite know
how to define somehowCreateARequestObjectThatMimicsWhatModPythonDoes().  
*grin* But I'm sure it's possible.  Another alternative is to use
mod_python's CGI emulation handler:

http://www.modpython.org/live/mod_python-2.7.6/doc-html/hand-cgi.html

which allows us to just write our scripts just like CGI's, and mod_python
will set things up properly for us.





From dyoo@hkn.eecs.berkeley.edu  Mon Jan 28 05:27:07 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sun, 27 Jan 2002 21:27:07 -0800 (PST)
Subject: [Tutor] Please read this and respond to me.
In-Reply-To: <16e.7ca3139.2984f009@aol.com>
Message-ID: 

On Sun, 27 Jan 2002 Kyuuketsiuki@aol.com wrote:

> I'm looking for a tutor (Teacher) on hacking, I've been meaning to
> learn and i have read many things, but i have never really learned, so
> i would like for you to teach me.


Hi Kyuuketsiuki.  What do you want to know about, and what questions do
you have?  One of us here can probably help to point you in some sort of
direction.

Granted, it might not be the _right_ direction.  *grin* But we'll do what
we can to help.


Are you thinking about learning to program?  If so, you might be
interested in this web site:

    http://python.org/doc/Intros.html

Magnus Lie Hetland has written a tutorial called "Instant Hacking" that
may be interesting for you:

   http://www.hetland.org/python/instant-hacking.php


The Tutor mailing list is set up so that, when you send mail to
"tutor@python.org", you reach basically everyone here, so you have a large
knowledable audience at your disposal.  Please feel free to ask questions.


Good luck to you.



From dyoo@hkn.eecs.berkeley.edu  Mon Jan 28 05:43:41 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sun, 27 Jan 2002 21:43:41 -0800 (PST)
Subject: [Tutor] learner           [what is Python good for?]
In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB212562C35@mbtlipnt02.btlabs.bt.co.uk>
Message-ID: 

On Sun, 27 Jan 2002 alan.gauld@bt.com wrote:

>  >  i would like to know how to write a program.
>  >  i am relatively new to computers and have no prior programming
> experience. 
>  
> Thats the target for my web tutor (url below) 
> 
> i would like to know if python is a good place to begin and why? 
> 
> I answer that.
> 
>  
> what type of applications can the python language be used for? 


The Useless Python web site collects a lot of good examples of things
people here have written in Python:

    http://www.lowerstandard.com/python

Python's good for a lot of recreational programming, because it's fairly
easy to play around with it in its interactive interpreter.  Someone has
even written a library to make games:

    http://pygame.org


If you want code of a more serious slant, the Vaults of Parnassus is
another repository:

    http://www.vex.net/parnassus


If you're a scientist or a biologist, you may be interested in these
links:

    http://www.scipy.org/
    http://biopython.org/


In short, you can do a lot with Python.  *grin* But to be fair, I have to
say that you can do a lot with any computer language.  What makes Python
special, what has attracted people from diverse backgrounds to use it, is
knowing that learning Python isn't too bad.


If you're interested in learning more, you can take a look at:

    http://python.org/Newbies.html

for a collection of tutorials that People have written for Python.  
Alan's tutorial is also linked from this web site.  If you have questions
while going through any of those tutorials, please feel free to ask your
questions.  We'll do what we can to make things less confusing.



By the way, your email client is sending messages as HTML text, but not
everyone here is using a client that strips off HTML.  Can you change your
email client to send just plain text?  That will make it easier for people
to read your questions.


Best of wishes!



From dyoo@hkn.eecs.berkeley.edu  Mon Jan 28 06:10:51 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sun, 27 Jan 2002 22:10:51 -0800 (PST)
Subject: [Tutor] pyslang question
In-Reply-To: <20020127192315.0631d2c9.syrinx@simplecom.net>
Message-ID: 

On Sun, 27 Jan 2002, Scott wrote:

> Hi all.  This would probably be better asked on alt.lang.s-lang, but
> my news server has been down for weeks (arrgh; they say they're
> working on it), but maybe someone here will know the answer.  
> Whenever I run a pyslang program (even the samples that come with
> pyslang), I end up with a file in the current directory called
> "pyslang.err" that says "this is init."  This is even though there was
> no apparent error in the execution of the program.  Can someone tell
> me what that is about?  Thank you.

Pyslang will redirect standard error to a file called 'pyslang.err', so
that even if we're doing weird things to the screen, we'll still be able
to look at the log file.  The very first thing that pyslang will do is
print out that it's initialized the error log, which is that "this is
init." message that you're seeing.


If you don't want it to create that file, you'll want to configure pyslang
to not redirect standard error to that 'pyslang.err' file.  If you use the
following:

    './configure --disable-stderr-redir'

that should do the trick.


Hope this helps!



From srichter@cbu.edu  Mon Jan 28 07:40:19 2002
From: srichter@cbu.edu (Stephan Richter)
Date: Mon, 28 Jan 2002 01:40:19 -0600
Subject: [Tutor] Zope OS X users
In-Reply-To: <20020128032601.87451.qmail@web11606.mail.yahoo.com>
Message-ID: <5.1.0.14.2.20020128013917.023d4de8@mercury-1.cbu.edu>

>Sorry if this is outside the scope of the list, I figured it wouldn't hurt 
>to ask.

Well, you should try the Zope Mailing List at zope@zope.org.

Regards,
Stephan

--
Stephan Richter
CBU - Physics and Chemistry Student
Web2k - Web Design/Development & Technical Project Management



From syrinx@simplecom.net  Mon Jan 28 07:36:14 2002
From: syrinx@simplecom.net (Scott)
Date: Mon, 28 Jan 2002 01:36:14 -0600
Subject: [Tutor] Re: Tutor digest, Vol 1 #1379 - 16 msgs
In-Reply-To: 
References: 
Message-ID: <20020128013614.11fa0df1.syrinx@simplecom.net>

> If you don't want it to create that file, you'll want to configure pyslang
> to not redirect standard error to that 'pyslang.err' file.  If you use the
> following:
> 
>     './configure --disable-stderr-redir'
> 

Recompile!  Heresey.  Kinda weird, you gotta admit.



From dyoo@hkn.eecs.berkeley.edu  Mon Jan 28 09:43:38 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Mon, 28 Jan 2002 01:43:38 -0800 (PST)
Subject: [Tutor] Re: Tutor digest, Vol 1 #1379 - 16 msgs
In-Reply-To: <20020128013614.11fa0df1.syrinx@simplecom.net>
Message-ID: 

[Warning: skip this message if you're not familiar with C programming.]


On Mon, 28 Jan 2002, Scott wrote:

> > If you don't want it to create that file, you'll want to configure pyslang
> > to not redirect standard error to that 'pyslang.err' file.  If you use the
> > following:
> > 
> >     './configure --disable-stderr-redir'
> > 
> 
> Recompile!  Heresey.  Kinda weird, you gotta admit.

I agree!


At the moment, pyslang is hardcoded to do this logging at the C level ---
without editing the C wrapper, I don't think there's much else we can do
from a Python standpoint.

However, I think it's very possible to change pyslang so that the
file-logging can be activated by a runtime switch instead.  The module is
a wrapper around slang, and written using the SWIG wrapper generator:

    http://swig.org


I'd need some time to read though the SWIG wrappers before I can
comfortably fiddle with it.  Hmmmm... It looks like the module's
initalizer calls a C function called stderr_redir().  For the curious,
here's what it does:

/*** in slang.i ***/
stderr_redir()
{
    FILE *xstderr = fopen("pyslang.err", "w");
    dup2(fileno(xstderr), 2);
    setvbuf(stderr, NULL, _IONBF,0);
    setvbuf(xstderr, NULL, _IONBF,0);
    fprintf(stderr, "This is init\n");
}
/***/

which is basically saying "Ok, let's set standard error to be this file
'pyslang.err'.  Also, let's make sure that it's in a non-buffered mode,
just like the original stderr.  Finally, let's say something to the stderr
and make sure that it works."  (I'm just paying attention to the UNIX
wrapper; the win32 wrapper probably does something similar.)


The thing is that, as pyslang is written at the moment, it does this
unconditionally, and it's hardcoded at compile time.  Perhaps it might be
better to have this as a user-accessible function instead, to be called
explicitely.  Or maybe have this function trigger if the user sets a
module attribute.  Maybe it would be nice to say something like:

###
pyslang.LOGGING = 1
###

and have pyslang "magically" do the stderr redirection then.


I haven't thought about this enough: I don't know what the "right" thing
to do is yet, since I haven't even played with pyslang yet.  *grin* I
don't think this behavior is "broken", so it's going to be a little harder
to see what a good solution would be.  Perhaps the author had good reasons
for doing it this way.



From kent@springfed.com  Mon Jan 28 12:38:59 2002
From: kent@springfed.com (kent@springfed.com)
Date: Mon, 28 Jan 2002 06:38:59 -0600
Subject: [Tutor] Python vs. PHP
Message-ID: <200201281245.g0SCjhBM000794@bucky.airstreamcomm.net>




--- Original Message ---
From: kent@springfed.com
To: =A0
Cc:
Sent: Mon, 28 Jan 2002 06:36:16 -0600
Subject: RE: [Tutor] Python vs. PHP

>
>>The point is that despite the hysteria generated, there
>>is very little to choose between ASP or CGI style web
>>scripting.
>>
>>Alan G
>
>My concern is performance, not scripting style.
>
>My understanding is that with CGI/Python/DB
>each call starts an interpreter, opens a db connection,
>makes the query, closes the connection, generates the
>page, ASP simply makes the call and generates the page.
>
>Zope sounds great, as does mod_python, however I want
>to program for cheap hosting, which means CGI or PHP.
>
>I'd love to hear stories of CGI/MySQL/Python sites being
>snappy and stable under heavy load, or a comparison of
>PHP and CGI performance.
>
>
>




From lonetwin@yahoo.com  Mon Jan 28 14:19:01 2002
From: lonetwin@yahoo.com (lonetwin)
Date: Mon, 28 Jan 2002 19:49:01 +0530
Subject: [Tutor] Source Code Formatter
In-Reply-To: <20020126132309Z45640-8421+843@mail.uni-paderborn.de>
References: <20020126132309Z45640-8421+843@mail.uni-paderborn.de>
Message-ID: <02012819490100.02165@mercury.worli>

Hey Huuuuuu,

On Saturday 26 January 2002 18:52, Huuuuuu wrote:
> Hi,
>
> is there a good code formatter for Python?
> With Highlighting. E.G. py->html?
>
> Thanks,
> willi

    Dunno if this is what you need, but I remembered seeing it sometime back, 
and thought it might interest all the people here who work with html 
regularly:

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52298

HTH

Peace
Steve

-- 
Love is being stupid together.
		-- Paul Valery


From alan.gauld@bt.com  Mon Jan 28 14:15:14 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Mon, 28 Jan 2002 14:15:14 -0000
Subject: [Tutor] Re: List Comprehensions again
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C2F1@mbtlipnt02.btlabs.bt.co.uk>

> > lambda is most often used in conjunction with map/filter/reduce, and
> > the whole lot comes from the "functional" programming style 

> Is this style of programming different from "procedural" and "object 
> oriented" programming styles?  

There are several styles. The most common are procedural
(often also called imperative) and object oriented.
Others include declarative(as personified by Prolog)
and functional.

My web tutor provides a brief description of FP with 
examples in Python. For me the main feature of FP is 
that every statement is an expression that has a value.

Thus the print statement in python is not a valid FP 
construct - it has no value. Lisp, Haskell, Erlang 
and a few others use FP heavily.

Alan g.
Author of the 'Learning to Program' web site
http://www.freenetpages.co.uk/hp/alan.gauld


From dsh8290@rit.edu  Mon Jan 28 14:25:46 2002
From: dsh8290@rit.edu (dman)
Date: Mon, 28 Jan 2002 09:25:46 -0500
Subject: [Tutor] Re: List Comprehensions again   [an example with filter()]
In-Reply-To: <1C3B5D5A-13A2-11D6-8529-00039351FE6A@mac.com>
References:  <1C3B5D5A-13A2-11D6-8529-00039351FE6A@mac.com>
Message-ID: <20020128142546.GB18435@dman.ddts.net>

On Sun, Jan 27, 2002 at 10:50:03PM -0500, Erik Price wrote:

| On Friday, January 25, 2002, at 10:19  PM, Danny Yoo wrote:
 
| Is using the three hashes a standard way of marking up example code in 
| Python?  I see it a lot on this list, and was wondering if it was 
| specific to the language or just a convention of this list.

Danny's convention.  Anything that is intuitively obvious works just
as well.  (I often use a bunch of tilde's, though usually I'm quoting
some config file or shell commands on a different list)

| >###
| >def endsWithS(word):
| >    return word[-1] == 's'
| >
| >for w in words:
| >    if endsWithS(w):
| >        print w
| >###
| 
| This is something I haven't seen before -- using an expression as the 
| return value of a function.

To be pedantic, you have seen an expression used in a return
statement.  Everything that isn't a statement (ie 'print' or 'import')
is an expression.  The only difference is that this expression is more
complicated than you've usually seen.

| I take it that this means "return boolean 
| value TRUE if the expression 'word[-1] == "s" ' ".  But I'm not sure.  
| It could be that instead, it returns the words that match?  If it did 
| that, then the second part, the "for" loop, wouldn't be necessary, so 
| drawing from context I am assuming that the former is true.

Yep.

| >You probably already feel comfortable passing around numbers and strings
| >to functions, but other functions?  If this is the first time you've 
| >seen
| >it, it will probably seem pretty darn weird at first, but it'll make 
| >sense
| >as you play with it.
| 
| You can create some pretty complicated constructs by passing functions 
| to other functions in PHP -- I find that it's sometimes easier to 
| conceptualize if I assign a function to a variable and then just pass 
| variables to functions.  But over time I'm sure I'll trade in this 
| clarity for convenience.

Sometimes it is clearer to give the function a new name.  It all
depends on the context -- what name does it already have and how do
you spell that name (ie is it a convoluted function call with complex
arguments or just a simple name?).

-D

-- 

If your company is not involved in something called "ISO 9000" you
probably have no idea what it is.  If your company _is_ involved in ISO
9000 then you definitely have no idea what it is.
                                (Scott Adams - The Dilbert principle)



From printers@sendme.cz  Mon Jan 28 16:14:50 2002
From: printers@sendme.cz (A)
Date: Mon, 28 Jan 2002 17:14:50 +0100
Subject: [Tutor] URLLIB and PROXY
Message-ID: <3C55870A.3706.9564F7@localhost>

Hi,
Is there anybody who has ever used 
URLLIB together with PROXY successfully?
I tried 

import os,urllib
os.environ["http_proxy"]='http://209.242.141.249:8080'
RUR=urllib.urlretrieve('http://www.seznam.cz/index.html','Saved.htm'
)

but I do not think  it does  work.
I will get the page but it does not go through proxy.

Thank you for help
Ladislav


From ak@silmarill.org  Mon Jan 28 13:46:27 2002
From: ak@silmarill.org (Andrei Kulakov)
Date: Mon, 28 Jan 2002 08:46:27 -0500
Subject: [Tutor] Please read this and respond to me.
In-Reply-To: <16e.7ca3139.2984f009@aol.com>
References: <16e.7ca3139.2984f009@aol.com>
Message-ID: <20020128134627.GA5832@silmarill.org>

On Sun, Jan 27, 2002 at 12:54:17AM -0500, Kyuuketsiuki@aol.com wrote:
> I'm looking for a tutor (Teacher) on hacking, I've been meaning to learn and 
> i have read many things, but i have never really learned, so i would like for 
> you to teach me.    

I don't think anyone is gonna do that, for two reasons:

1. Hacking (in this context) is illegal and the person who tried to
teach you would expose himself. You may report him now or later, for all
he knows.

2. If you couldn't pick up anything by yourself, this must not be "your
thing". Teaching you would be a waste of effort - like teaching a snake
to fly or an armadillo to ride a bycicle or a hippy to superwise a cleaning
detergent plant.

-- 
Cymbaline: intelligent learning mp3 player - python, linux, console.
get it at: cy.silmarill.org


From arcege@speakeasy.net  Mon Jan 28 18:32:11 2002
From: arcege@speakeasy.net (Michael P. Reilly)
Date: Mon, 28 Jan 2002 13:32:11 -0500
Subject: [Tutor] URLLIB and PROXY
In-Reply-To: <3C55870A.3706.9564F7@localhost>; from printers@sendme.cz on Mon, Jan 28, 2002 at 05:14:50PM +0100
References: <3C55870A.3706.9564F7@localhost>
Message-ID: <20020128133211.L915@speakeasy.net>

On Mon, Jan 28, 2002 at 05:14:50PM +0100, A wrote:
> Hi,
> Is there anybody who has ever used 
> URLLIB together with PROXY successfully?
> I tried 
> 
> import os,urllib
> os.environ["http_proxy"]='http://209.242.141.249:8080'
> RUR=urllib.urlretrieve('http://www.seznam.cz/index.html','Saved.htm'
> )
> 
> but I do not think  it does  work.
> I will get the page but it does not go through proxy.

I traced through the code and found what happens is that a request is
sent to port 8080 at 209.242.141.249 with the request (in HTTP 1.0,
which is the default with urllib/httplib):

  GET http://www.seznam.cz/index.html HTTP/1.0

If your proxy server is expecting some other form, i.e. a different
proxy mechanism, then you'll need to handle that much differently.
You'll probably want to use the raw httplib module (similar to how
urllib does).

  -Arcege



From kalle@gnupung.net  Mon Jan 28 18:46:56 2002
From: kalle@gnupung.net (Kalle Svensson)
Date: Mon, 28 Jan 2002 19:46:56 +0100
Subject: [Tutor] Please read this and respond to me.
In-Reply-To: <20020128134627.GA5832@silmarill.org>
References: <16e.7ca3139.2984f009@aol.com> <20020128134627.GA5832@silmarill.org>
Message-ID: <20020128184656.GA25891@sandra.lysator.liu.se>

[Andrei Kulakov]
> On Sun, Jan 27, 2002 at 12:54:17AM -0500, Kyuuketsiuki@aol.com wrote:
> > I'm looking for a tutor (Teacher) on hacking, I've been meaning to learn and 
> > i have read many things, but i have never really learned, so i would like for 
> > you to teach me.    
> 
> I don't think anyone is gonna do that, for two reasons:
> 
> 1. Hacking (in this context) is illegal and the person who tried to

In what context?  The context of this list?

> 2. If you couldn't pick up anything by yourself, this must not be "your
> thing". Teaching you would be a waste of effort - like teaching a snake
> to fly or an armadillo to ride a bycicle or a hippy to superwise a cleaning
> detergent plant.

I disagree.  I believe that everyone can learn programming, but not
that everyone can learn by themselves.

Peace,
  Kalle
-- 
Kalle Svensson (kalle@gnupung.net) - Laziness, impatience, hubris: Pick two!
English: http://www.gnupung.net/  Svenska: http://www.lysator.liu.se/~kalle/
Stuff: ["http://www.%s.org/" % x for x in "gnu debian python emacs".split()]


From jimmy_130@lycos.com  Mon Jan 28 22:09:13 2002
From: jimmy_130@lycos.com (James M Lang)
Date: Mon, 28 Jan 2002 17:09:13 -0500
Subject: [Tutor] Need help with Hello World (Laughing in the background)
Message-ID: 

OK, I've got Windows Python 2.2 on a Celeron 700mhz computer. I run the IDLE and put in Hello, World! I save it as hello.py on the desktop and then say run script from the edit menu. It says
  File "C:/WINDOWS/Desktop/hello.py", line 1
    Python 2.2 (#28, Dec 21 2001, 12:21:22) [MSC 32 bit (Intel)] on win32
             ^
SyntaxError: invalid syntax
So, the question is, what's wrong with it?





From randytalbot@home.com  Mon Jan 28 22:42:57 2002
From: randytalbot@home.com (Randy Talbot)
Date: Mon, 28 Jan 2002 17:42:57 -0500
Subject: [Tutor] Need help with Hello World (Laughing in the background)
In-Reply-To: 
Message-ID: <000201c1a84d$2263d280$5b582144@aberdn01.md.comcast.net>

Did it run OK before you saved it. Another words did you write
print "Hello, World!" before you saved it.

Randy Talbot

-----Original Message-----
From: tutor-admin@python.org [mailto:tutor-admin@python.org] On Behalf
Of James M Lang
Sent: Monday, January 28, 2002 5:09 PM
To: tutor@python.org
Subject: [Tutor] Need help with Hello World (Laughing in the background)

OK, I've got Windows Python 2.2 on a Celeron 700mhz computer. I run the
IDLE and put in Hello, World! I save it as hello.py on the desktop and
then say run script from the edit menu. It says
  File "C:/WINDOWS/Desktop/hello.py", line 1
    Python 2.2 (#28, Dec 21 2001, 12:21:22) [MSC 32 bit (Intel)] on
win32
             ^
SyntaxError: invalid syntax
So, the question is, what's wrong with it?




_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor



From sunyata@propaganda-arts.org  Mon Jan 28 22:50:28 2002
From: sunyata@propaganda-arts.org (c schwan)
Date: 28 Jan 2002 14:50:28 -0800
Subject: [Tutor] functions
Message-ID: <1012258229.14133.35.camel@milarepa>

--=-HvK4vepv9ggKhUDhGXEO
Content-Type: text/plain
Content-Transfer-Encoding: quoted-printable

OK.

I dont know why I am having such trouble with this and I have a little
perl and php experience, but i am having the roughest time figuring out
functions. Basically my trouble arises in understanding how things get
passed into and what the return statement returns.

I hope I am being clear. can anyone offer some tips?


TIA.




--=20

^^-:-->>

cschwan: open source advocate/hacker

gnupg key available here: http://propaganda.phpwebhosting.com/key

"life today presents itself to us as an accumulation of spectacles,
 images, and events, alienating us from life as a directly lived
experience."

				- the hermenaut

"Nothing would be what it is,
 Because everything would be what it isn't.
 And contrary-wise -what it is, it wouldn't be.
 And what it wouldn't be, it would. You see?"
				-Alice in Wonderland

		        	<--::@::-->
\
\
mail-from: evolution-1.0.1 ximian.gnome.linux
::-->>>

--=-HvK4vepv9ggKhUDhGXEO
Content-Type: application/pgp-signature; name=signature.asc
Content-Description: This is a digitally signed message part

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iD8DBQA8VdW0376UEuD/b58RAthpAJsG2N1BF9VuPy30Pznj01vr78x+zwCgqJto
9ZJnqUrJKU0neG+gNd1pUSw=
=u/RJ
-----END PGP SIGNATURE-----

--=-HvK4vepv9ggKhUDhGXEO--



From ainsoph3@attbi.com  Mon Jan 28 22:58:26 2002
From: ainsoph3@attbi.com (chris schwan)
Date: 28 Jan 2002 14:58:26 -0800
Subject: [Tutor] functions
Message-ID: <1012258706.14133.39.camel@milarepa>

I apologize for the double post. I sent first time under another
account.

Here is my question.


OK.

I don't know why I am having such trouble with this and I have a little
perl and php experience, but i am having the roughest time figuring out
functions. Basically my trouble arises in understanding how things get
passed into and what the return statement returns.

I hope I am being clear. can anyone offer some tips?


TIA.





From dyoo@hkn.eecs.berkeley.edu  Mon Jan 28 22:54:28 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Mon, 28 Jan 2002 14:54:28 -0800 (PST)
Subject: [Tutor] Need help with Hello World (Laughing in the background)
In-Reply-To: 
Message-ID: 

On Mon, 28 Jan 2002, James M Lang wrote:

> OK, I've got Windows Python 2.2 on a Celeron 700mhz computer. I run the IDLE and put in Hello, World! I save it as hello.py on the desktop and then say run script from the edit menu. It says
>   File "C:/WINDOWS/Desktop/hello.py", line 1
>     Python 2.2 (#28, Dec 21 2001, 12:21:22) [MSC 32 bit (Intel)] on win32
>              ^
> SyntaxError: invalid syntax
> So, the question is, what's wrong with it?

Ah!  You don't need to literally put in that particular line in your file
--- that's just information that Python spits out when we're running in
interactive mode. All your file needs to contain are the program
statements, like

###
print "Hello world"
###


So if you do a copy/paste from your interpreter to a separate file, you'll
need to do some quick editing to get rid of the decorations that the
interactive interpreter uses.  Here's a page that has an example of this:

    http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro


If you have more questions, please feel free to ask.



From samd94969801@ala.net  Mon Jan 28 23:33:43 2002
From: samd94969801@ala.net (Laminack/McIntyre)
Date: Mon, 28 Jan 2002 17:33:43 -0600
Subject: [Tutor] Need help with Hello World (Laughing in the background)
In-Reply-To: 
Message-ID: 

1/28/02 4:09:13 PM, "James M Lang"  
wrote:

>OK, I've got Windows Python 2.2 on a Celeron 700mhz 
computer. I run the IDLE and put in Hello, World! I save it as 
hello.py on the desktop and then say run script from the edit 
menu. It says
>  File "C:/WINDOWS/Desktop/hello.py", line 1
>    Python 2.2 (#28, Dec 21 2001, 12:21:22) [MSC 32 bit 
(Intel)] on win32
>             ^
>SyntaxError: invalid syntax
>So, the question is, what's wrong with it?

Hi there, I just started with python a couple of days ago 
(having given up on both C++ and Java, for now anyway). It 
seems to me that you may have saved what was in the 
interactive *python shell* window. If so, just click the File 
button, go to New Window, and type your code in that 
window and save it. That way you don't have to worry about 
all the extra stuff that the interactive mode puts in there.
Hope this helps.
Laminack




From christine_wilson_@hotmail.com  Tue Jan 29 00:47:05 2002
From: christine_wilson_@hotmail.com (Christine Wilson)
Date: Mon, 28 Jan 2002 19:47:05 -0500
Subject: [Tutor] python scripting and unix
Message-ID: 

I am writing a python script set to execute upon login to my unix account.  
The user is prompted for further information - if the answer is correct, 
they may continue.  If the answer is wrong (meaning that it is not me) I 
want the session to exit/logout.

How can I do this?  I'm just becoming familiar with Python and scripting.  
Any ideas?

The script is executing before the user actually is prompted with the Unix 
prompt.

----------------------------------------------------------------------
#!/usr/bin/env python

import os
os.system("clear")

from sudialg import *
if ask_who():   #gets user input for first answer, returns 1 if correct
  #continues

else:
   exit   #I want the telnet session to end with NO access to my account
            #but this is just exiting the script

_________________________________________________________________
Send and receive Hotmail on your mobile device: http://mobile.msn.com



From shalehperry@attbi.com  Tue Jan 29 01:34:53 2002
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Mon, 28 Jan 2002 17:34:53 -0800 (PST)
Subject: [Tutor] python scripting and unix
In-Reply-To: 
Message-ID: 

> 
> else:
>    exit   #I want the telnet session to end with NO access to my account
>             #but this is just exiting the script
> 

you need to kill the session.  Find the pid of your parent and kill it.

Silly question -- are just trying to make sure that even if someone knows your
password they still can not get in?


From urnerk@qwest.net  Tue Jan 29 03:49:12 2002
From: urnerk@qwest.net (Kirby Urner)
Date: Mon, 28 Jan 2002 19:49:12 -0800
Subject: [Tutor] functions
In-Reply-To: <1012258706.14133.39.camel@milarepa>
Message-ID: <4.2.0.58.20020128193201.03a4e640@pop3.norton.antivirus>

>
>Here is my question.
>
>
>OK.
>
>I don't know why I am having such trouble with this and I have a little
>perl and php experience, but i am having the roughest time figuring out
>functions. Basically my trouble arises in understanding how things get
>passed into and what the return statement returns.
>
>I hope I am being clear. can anyone offer some tips?
>
>
>TIA.

Just the basic function is like this:

    def f(x):
       return x*x

So f(3) returns 9 and like that.

If you want a default value for x, so the user needn't
give one, go:

    def f(x=3):
       return x*x

Now the user can go f() and get 9, or f(3) and get 9,
or f(5) and get 25.

Can you have several such variables, all with defaults?
Yes.

Can you have optional variables?  Yeah.  Define a
function like this:

     def f(*args):
        return args

   >>> f(10)
   (10,)
   >>> f(10,1,'a',12.3)
   (10, 1, 'a', 12.300000000000001)

Oh, so like all the parameters get lumped into a single
tuple named args.  And you can combine these:

     def f(x=3,*args):  etc.

Finally, a function can be set up to accept a dictionary:

   def f(x=3,*args1,**args2):
         return x*x, args1, args2

   >>> f(10,"the","talk",a=2,c=5,d=10)
   (100, ('the', 'talk'), {'a': 2, 'c': 5, 'd': 10})

"the" and "talk" go to *args1, while all the remaining
variable assignments get put into a single dictionary,
associated with **args2 (dictionary argument must come
after any others).

You can return anything.  You can even return another
function:

   >>> def f(x=3):
           def g(y):
              return y**x
           return g

   >>> h = f(2)
   >>> h
   
   >>> h(5)
   25

That's another aspect of functional programming -- the
ability to treat functions like variables, e.g. as
returned values, or as arguments to other functions.

There's a whole other discussion regarding arguments
passed from outside Python, or as part of an URL.

Perhaps you were asking in a cgi context, in which case
I was a little off target.  Also, when a module loads, it
executes, so you can have statements not inside a function
or class definition executing.  This is also important to
understand, when writing cgi scripts.

Kirby



From erikprice@mac.com  Tue Jan 29 04:16:55 2002
From: erikprice@mac.com (Erik Price)
Date: Mon, 28 Jan 2002 23:16:55 -0500
Subject: [Tutor] functions
In-Reply-To: <4.2.0.58.20020128193201.03a4e640@pop3.norton.antivirus>
Message-ID: <077E9640-146F-11D6-BF49-00039351FE6A@mac.com>

On Monday, January 28, 2002, at 10:49  PM, Kirby Urner wrote:

> Perhaps you were asking in a cgi context, in which case
> I was a little off target.  Also, when a module loads, it
> executes, so you can have statements not inside a function
> or class definition executing.  This is also important to
> understand, when writing cgi scripts.

This seems important to understand in general too.  Is it possible for 
someone to write a module and publish it [online] and then someone else 
can come along, download it, and import it -- and then it turns out that 
the module executes some malicious code on their system?  Obviously it 
would be wise to read the source of anything that you don't know for 
sure about.  But if I invoked python (in Unix), wouldn't the Python 
interpreter then inherit my own environment variables, therefore being 
able to perform actions within my account that otherwise it would not be 
able to do?  I am talking about a Trojan Horse.


Erik



From urnerk@qwest.net  Tue Jan 29 04:24:47 2002
From: urnerk@qwest.net (Kirby Urner)
Date: Mon, 28 Jan 2002 20:24:47 -0800
Subject: [Tutor] functions
In-Reply-To: <077E9640-146F-11D6-BF49-00039351FE6A@mac.com>
References: <4.2.0.58.20020128193201.03a4e640@pop3.norton.antivirus>
Message-ID: <4.2.0.58.20020128202236.03a498b0@pop3.norton.antivirus>

>
>This seems important to understand in general too.  Is it possible
>for someone to write a module and publish it [online] and then
>someone else can come along, download it, and import it -- and
>then it turns out that the module executes some malicious code
>on their system?

Yes, anything executable is a potential danger.  Don't
run code you don't trust.

Kirby



From kojo@hal-pc.org  Tue Jan 29 05:00:17 2002
From: kojo@hal-pc.org (Kojo Idrissa)
Date: Mon, 28 Jan 2002 23:00:17 -0600
Subject: [Tutor] functions
In-Reply-To: <4.2.0.58.20020128193201.03a4e640@pop3.norton.antivirus>
References: <1012258706.14133.39.camel@milarepa>
Message-ID: <5.1.0.14.0.20020128225521.00b13998@Pop3.norton.antivirus>

At 07:49 PM 1/28/2002 -0800, Kirby Urner wrote:

Whoa!

Not to clog the list with fan-boy praise, but from someone who's on Chapter 
4 of "Learning Python" (Functions)...that was amazing!

Kirby, thinks for the response.  Chris, thanks for asking the question.

To everyone else on the list, thanks for your involvement, asking or 
answering.  I learn so much by just reading my email as it come in...I 
think that's part of the reason I'm moving through "Learning Python" so 
slowly.  I don't need it as much.

Thanks to all,

****************************
Kojo Idrissa

kojo@hal-pc.org
http://www.hal-pc.org/~kojo/
****************************



From fignmary@swbell.net  Tue Jan 29 04:51:03 2002
From: fignmary@swbell.net (William L. Bonfiglio)
Date: Mon, 28 Jan 2002 22:51:03 -0600
Subject: [Tutor] REMOVE
In-Reply-To: <3C55870A.3706.9564F7@localhost>
Message-ID: 


-----Original Message-----
From: activepython-admin@listserv.ActiveState.com
[mailto:activepython-admin@listserv.ActiveState.com]On Behalf Of A
Sent: Monday, January 28, 2002 10:15 AM
To: python-list@python.org; tutor@python.org;
activepython@listserv.ActiveState.com
Subject: URLLIB and PROXY


Hi,
Is there anybody who has ever used 
URLLIB together with PROXY successfully?
I tried 

import os,urllib
os.environ["http_proxy"]='http://209.242.141.249:8080'
RUR=urllib.urlretrieve('http://www.seznam.cz/index.html','Saved.htm'
)

but I do not think  it does  work.
I will get the page but it does not go through proxy.

Thank you for help
Ladislav
_______________________________________________
ActivePython mailing list
ActivePython@listserv.ActiveState.com
http://listserv.ActiveState.com/mailman/listinfo/activepython


From sunyata@propaganda-arts.org  Tue Jan 29 05:34:26 2002
From: sunyata@propaganda-arts.org (c schwan)
Date: 28 Jan 2002 21:34:26 -0800
Subject: [Tutor] functions
In-Reply-To: <5.1.0.14.0.20020128225521.00b13998@Pop3.norton.antivirus>
References: <1012258706.14133.39.camel@milarepa>
 <5.1.0.14.0.20020128225521.00b13998@Pop3.norton.antivirus>
Message-ID: <1012282467.1602.87.camel@milarepa>

--=-HuGQB+dbZQ4gBYPXroT0
Content-Type: text/plain
Content-Transfer-Encoding: quoted-printable

On Mon, 2002-01-28 at 21:00, Kojo Idrissa wrote:
> At 07:49 PM 1/28/2002 -0800, Kirby Urner wrote:
> 
> Whoa!
>=20
> Not to clog the list with fan-boy praise, but from someone who's on Chapt=
er=20
> 4 of "Learning Python" (Functions)...that was amazing!
>=20

Kojo: I agree! Yes thanks Kirby. I think after that, I got it. I dunno
what my problem was (I am using Quick Python Book) and it expects
previous knowledge of functions. Which I had a year and a half ago,
dunno where it went.

Again, thanks.. no to go furthur.. Here here to fan-boy praise!

Chris


--=-HuGQB+dbZQ4gBYPXroT0
Content-Type: application/pgp-signature; name=signature.asc
Content-Description: This is a digitally signed message part

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iD8DBQA8VjRi376UEuD/b58RAsiHAJ9jPMBG1ch7G/UxEm3Nx/EpbYqJtQCeJj/3
JRE4N/LBZjTuOCDdsifzdAk=
=Ue4G
-----END PGP SIGNATURE-----

--=-HuGQB+dbZQ4gBYPXroT0--



From idiot1@netzero.net  Tue Jan 29 07:19:08 2002
From: idiot1@netzero.net (kirk Bailey)
Date: Tue, 29 Jan 2002 02:19:08 -0500
Subject: [Tutor] Confirmation messages on manager
Message-ID: <3C564CEC.FE91C683@netzero.net>

Seems all of them are now working. Traps attempting to enact a already
condition, and reports this via email to the so worthy user, reports
successful command completions, BAD command attempts, and eats replys
not coming from the address specified in the original request.
TinyList 1.1.1 is coming along nicely. Intrested parties are
encourages to make requests or suggestions or at least submit evil
humor for my enlightenment.
 
-- 
 

 -Respectfully,
              -Kirk D Bailey 
               Consulting Loose Cannon

end



  www.howlermonkey.net                 highprimate@howlermonkey.net
  www.sacredelectron.org                         idiot1@netzero.net
  www.tinylist.org                              grumpy@tinylist.org
----------------------------------------------------
Sign Up for NetZero Platinum Today
Only $9.95 per month!
http://my.netzero.net/s/signup?r=platinum&refcd=PT97


From m_konermann@gmx.de  Tue Jan 29 08:48:58 2002
From: m_konermann@gmx.de (Keule)
Date: Tue, 29 Jan 2002 09:48:58 +0100
Subject: [Tutor] Combination of Extending and Embedding Python with C++ ? (your opinion)
Message-ID: <3C5661FA.5080608@gmx.de>

Hi @ All !

I´m working in a greater project. This project exsist of a C++ part an 
two parts coding in Python.
The C++ part is the basic of this project and have to be build up 
modular in future releases. One Part of Python Code is the user 
Interface, which i want to create with TKinter and the other python part 
is a search routine, which is called up from the C++ part.
So, my opinion, is, to combine these three parts:

1. Step:   I´m using SWIG to extend the C++ part with the User 
Interface, programmed in Python. I let create a shadow class from SWIG.
2. Step:   I want to use an Embedding method to integrate the search 
routine (programmed in python) in the C++ part.
or alternativly:
2.Step:    Is it possible just calling the search routine from the 
Shadow Class ?

What do you think is the best Method to combine these three parts ?

Thank´s a lot
Marcus



From Ecevit.Karakus@aprimus.de  Tue Jan 29 09:31:20 2002
From: Ecevit.Karakus@aprimus.de (Karakus, Ecevit)
Date: Tue, 29 Jan 2002 10:31:20 +0100
Subject: [Tutor] LISP and Python
Message-ID: 

Hello Python Fans !

I would like to know if someone of you has experience with interfacing and
extending Python
with LISP (any Lisp .. ).

I would like to do more with Lisp but there are very few Libraries for Lisp
, but Python has many Libraries
so ...

Thanks


From lha2@columbia.edu  Tue Jan 29 10:26:52 2002
From: lha2@columbia.edu (Lloyd Hugh Allen)
Date: Tue, 29 Jan 2002 05:26:52 -0500
Subject: [Fwd: Re: [Tutor] LISP and Python]
Message-ID: <3C5678EC.1ED93328@mail.verizon.net>

One of these days I'll get a hang of the "hey, idjit, change 'To:' to
'tutor@python.org'" thing.

-------- Original Message --------
From: Lloyd Hugh Allen 
Subject: Re: [Tutor] LISP and Python
To: "Karakus, Ecevit" 

"Karakus, Ecevit" wrote:
> 
> Hello Python Fans !
> 
> I would like to know if someone of you has experience with interfacing and
> extending Python
> with LISP (any Lisp .. ).
> 
> I would like to do more with Lisp but there are very few Libraries for Lisp
> , but Python has many Libraries
> so ...
> 
> Thanks
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

This appeared last week. Haven't looked at it, but would guess that it's
what you seek.
============
From: Danny Yoo 
Thu 2:34 AM
Subject: [Tutor] Learning Python using other languages --- round two
To: tutor@python.org

[For people who are beginning to learn Python; skip this message.  This
is
about something else.  *grin*]


Hi everyone,

A while back, I wrote about thinking about writing a Scheme interpreter
in
Python.

    http://aspn.activestate.com/ASPN/Mail/Message/811896


Well, I just couldn't hold back from unleashing this monstrosity.  I
bring
to you... Pyscheme!

    http://hkn.eecs.berkeley.edu/~dyoo/python/pyscheme/


From scarblac@pino.selwerd.nl  Tue Jan 29 10:37:49 2002
From: scarblac@pino.selwerd.nl (Remco Gerlich)
Date: Tue, 29 Jan 2002 11:37:49 +0100
Subject: [Fwd: Re: [Tutor] LISP and Python]
In-Reply-To: <3C5678EC.1ED93328@mail.verizon.net>; from l.h.allen@verizon.net on Tue, Jan 29, 2002 at 05:26:52AM -0500
References: <3C5678EC.1ED93328@mail.verizon.net>
Message-ID: <20020129113749.A14611@pino.selwerd.nl>

On  0, Lloyd Hugh Allen  wrote:
> One of these days I'll get a hang of the "hey, idjit, change 'To:' to
> 'tutor@python.org'" thing.

Yeah, it's irritating :(

(snipped freely below)

> > Hello Python Fans !
> > 
> > I would like to know if someone of you has experience with interfacing and
> > extending Python
> > with LISP (any Lisp .. ).
> > 
> > I would like to do more with Lisp but there are very few Libraries for Lisp
> > , but Python has many Libraries
> > so ...
> 
> This appeared last week. Haven't looked at it, but would guess that it's
> what you seek.
> ============
> From: Danny Yoo 
> Thu 2:34 AM
> Subject: [Tutor] Learning Python using other languages --- round two
> To: tutor@python.org

> Well, I just couldn't hold back from unleashing this monstrosity.  I
> bring
> to you... Pyscheme!

This is a cool project to make a Scheme interpreter in Python, but I don't
really believe it's a good option if you want to write serious Lisp that
uses the Python libraries :-)

I don't know much about Lisp. I suppose you have to put a layer on C in
between; if you can call C functions from Lisp, you can have it run the
Python interpreter to make library calls. But it's not going to be much fun,
I think.

Are you sure there aren't many libraries for Lisp? I had expected it to have
lots. Maybe only commercial or not all those newfangled Internet protocols...

A Google search turns up nothing useful for me right now.

-- 
Remco Gerlich


From alan.gauld@bt.com  Tue Jan 29 10:46:37 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Tue, 29 Jan 2002 10:46:37 -0000
Subject: [Tutor] Need help with Hello World (Laughing in the backgroun d)
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C303@mbtlipnt02.btlabs.bt.co.uk>

> OK, I've got Windows Python 2.2 on a Celeron 700mhz computer. 
> I run the IDLE and put in Hello, World! I save it as hello.py 
> on the desktop and then say run script from the edit menu. It says
>   File "C:/WINDOWS/Desktop/hello.py", line 1
>     Python 2.2 (#28, Dec 21 2001, 12:21:22) [MSC 32 bit 
> (Intel)] on win32
>              ^
> SyntaxError: invalid syntax
> So, the question is, what's wrong with it?

You saveed the interpreter(Python shell) session.

You need to do File|New to open a new file window 
and type the program in there.

What has happened is you saved the shell(with the >>> prompt) 
and Python tried to execute the welcome message as if it 
were a program, it couldn't so gave you an error...

Alan g.


From alan.gauld@bt.com  Tue Jan 29 10:53:07 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Tue, 29 Jan 2002 10:53:07 -0000
Subject: [Tutor] functions
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C304@mbtlipnt02.btlabs.bt.co.uk>

> I dont know why I am having such trouble with this 
> and I have a little perl and php experience, 

Ok, you might try my tutor, reading the topic on 
modules and functions(url below).

> functions. Basically my trouble arises in understanding how things get
> passed into and what the return statement returns.

def function(param1, param2):

Says create a function called 'function' that takes 2
"parameters" called, in this case, "param1" and "param2"

You then write a mini program that treats param1 & 2 as 
if they were local variables.

At some point you can return a result to the outside world
using the "return" keyword.

Thus:

# define a function to add two numbers
def add( x, y):
   return x+y

# now call that function, store result in res
res = add(3,4)  # x,y take on values 3,4
print res       # should print 7

We can also pass variables in:

a = 5
b = 7
print add(a,b)  # prints return value of add(5,7) => 12

Now with that basis what specifically is confusing you?

Alan g.
Author of the 'Learning to Program' web site
http://www.freenetpages.co.uk/hp/alan.gauld



From alan.gauld@bt.com  Tue Jan 29 10:56:32 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Tue, 29 Jan 2002 10:56:32 -0000
Subject: [Tutor] python scripting and unix
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C305@mbtlipnt02.btlabs.bt.co.uk>

> import os
> os.system("clear")

So you already know about system()

> 
> from sudialg import *
> if ask_who():   #gets user input for first answer, returns 1 
> if correct
>   #continues
> 
> else:
>    exit   #I want the telnet session to end 
>             #but this is just exiting the script

Have you tried os.system('logout') or os.system('exit')?

Just a thought, I haven't tried.

Alan g.


From alan.gauld@bt.com  Tue Jan 29 11:03:10 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Tue, 29 Jan 2002 11:03:10 -0000
Subject: [Tutor] functions
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C306@mbtlipnt02.btlabs.bt.co.uk>

> This seems important to understand in general too.  Is it 
> possible for someone to write a module and publish it 

Of course that's what's on Useless Python and the 
Vaults of Parnassus- lots of published modules that 
you can download.

> can come along, download it, and import it -- and then it 
> turns out that the module executes some malicious code 
> on their system?  

Absolutely, caveat emptor.
You should always check and understand modules that you 
download.

> would be wise to read the source of anything that you don't know for 
> sure about.  But if I invoked python (in Unix), wouldn't the Python 
> interpreter then inherit my own environment variables, 
> therefore being able to perform actions within my account 
> that otherwise it would not be able to do?  

No the interpreter remains exacrtly the same. But if the module
was malicious it could run under the interpreter and scrape of 
a list of valid user IDs for your system and mail them to 
somebody say.... or more directly just delete all the files on 
your disk!


> I am talking about a Trojan Horse.

No, nothing so subtle. Just malicious code that you naively 
downloaded and ran. Its no different to blindly downloading 
an EXE from a web site and running it - you just hope it 
does what it says on the label. The difference with Python 
modules is at least you can read the code!

Alan g.


From dsh8290@rit.edu  Tue Jan 29 12:04:22 2002
From: dsh8290@rit.edu (dman)
Date: Tue, 29 Jan 2002 07:04:22 -0500
Subject: [Fwd: Re: [Tutor] LISP and Python]
In-Reply-To: <20020129113749.A14611@pino.selwerd.nl>
References: <3C5678EC.1ED93328@mail.verizon.net> <20020129113749.A14611@pino.selwerd.nl>
Message-ID: <20020129120422.GA2845@dman.ddts.net>

On Tue, Jan 29, 2002 at 11:37:49AM +0100, Remco Gerlich wrote:
| On  0, Lloyd Hugh Allen  wrote:
| > One of these days I'll get a hang of the "hey, idjit, change 'To:' to
| > 'tutor@python.org'" thing.
| 
| Yeah, it's irritating :(

Here's how to make it not irritating at all :

1)  pick up mutt (www.mutt.org)
2)  tell it you're subscribed to the list --
        (put
            subscribe tutor@python.org
        in ~/.muttrc)
3)  adjust the index-format so you don't see the list address for
    every message that comes from the list (you already sort it into
    its own folder, right?)
        (put 
            set index_format="%3C %Z %[%b%d] %-17.17n(%?M?#%3M&%4c?) %s"
        in ~/.muttrc)

Then simply press "L" to reply on-list, "r" to reply off-list, and "g"
to send a copy both places.

Enjoy :-).

-D

-- 

One man gives freely, yet gains even more;
another withholds unduly, but comes to poverty.
        Proverbs 11:24



From kjphotog@juno.com  Tue Jan 29 13:18:27 2002
From: kjphotog@juno.com (kjphotog@juno.com)
Date: Tue, 29 Jan 2002 05:18:27 -0800
Subject: [Tutor] zope?
Message-ID: <20020129.052058.-166825.6.kjphotog@juno.com>

This message is in MIME format.  Since your mail reader does not understand
this format, some or all of this message may not be legible.

----__JNP_000_412f.6523.59e1
Content-Type: text/plain; charset=us-ascii  
Content-Transfer-Encoding: 7bit

Noticed zope mentioned here a number of times, what is it?  
----__JNP_000_412f.6523.59e1
Content-Type: text/html; charset=us-ascii  
Content-Transfer-Encoding: quoted-printable





Noticed=
 zope=20
mentioned here a number of times, what is it?  

----__JNP_000_412f.6523.59e1--

________________________________________________________________
GET INTERNET ACCESS FROM JUNO!
Juno offers FREE or PREMIUM Internet access for less!
Join Juno today!  For your FREE software, visit:
http://dl.www.juno.com/get/web/.


From printers@sendme.cz  Tue Jan 29 13:57:15 2002
From: printers@sendme.cz (A)
Date: Tue, 29 Jan 2002 14:57:15 +0100
Subject: [Tutor] Nobody knows? But why?
Message-ID: <3C56B84B.20246.85561E@localhost>


Hi,
For already some time I am trying to use  
modules, HTTPLIB or URLLIB to get a page through proxy but so 
far I have not been successfull
I also browsed Python group but the samples given there did not 
work.
Can anybody give me a WORKING example how I can grab a web 
page through proxy?
I tried this example
########################
#######################

import httplib
h = httplib.HTTP('209.242.141.249:8080') #proxy

h.putrequest('GET', 'http://www.autoplzen.info/index.php')

h.putheader('Accept', 'text/html')
h.putheader('Accept', 'text/plain')

#h.putrequest('Proxy-Connection', 'Keep-Alive') # it does not work, 
#so  I commented

#h.putrequest('Host', 'www.autoplzen.info')  the same,otherwise I 
#receive File "C:\PYTHON21\lib\httplib.py", line 430, in putrequest  
#  raise CannotSendRequest()

h.endheaders()
errcode, errmsg, headers = h.getreply()
print errcode # Should be 200


#######################################
The above example works as if there were no proxy because in 
web server log there is not  IP of Proxy but mine.

Any help would be appreciated.
thanks
Ladislav


------- End of forwarded message -------


From wilson@visi.com  Tue Jan 29 14:11:53 2002
From: wilson@visi.com (Tim Wilson)
Date: Tue, 29 Jan 2002 08:11:53 -0600 (CST)
Subject: [Tutor] zope?
In-Reply-To: <20020129.052058.-166825.6.kjphotog@juno.com>
Message-ID: 

On Tue, 29 Jan 2002 kjphotog@juno.com wrote:

> Noticed zope mentioned here a number of times, what is it?  

Zope is a Python-based Web application platform. Check out
http://www.zope.org/ and http://www.zope.com/ for more details.

-Tim

--
Tim Wilson      |   Visit Sibley online:   | Check out:
Henry Sibley HS |  http://www.isd197.org   | http://www.zope.com
W. St. Paul, MN |                          | http://slashdot.org
wilson@visi.com |    | http://linux.com



From arcege@speakeasy.net  Tue Jan 29 14:22:07 2002
From: arcege@speakeasy.net (Michael P. Reilly)
Date: Tue, 29 Jan 2002 09:22:07 -0500
Subject: [Tutor] functions
In-Reply-To: <4.2.0.58.20020128193201.03a4e640@pop3.norton.antivirus>; from urnerk@qwest.net on Mon, Jan 28, 2002 at 07:49:12PM -0800
References: <1012258706.14133.39.camel@milarepa> <4.2.0.58.20020128193201.03a4e640@pop3.norton.antivirus>
Message-ID: <20020129092207.P915@speakeasy.net>

On Mon, Jan 28, 2002 at 07:49:12PM -0800, Kirby Urner wrote:
> You can return anything.  You can even return another
> function:
> 
>    >>> def f(x=3):
>            def g(y):
>               return y**x
>            return g
> 
>    >>> h = f(2)
>    >>> h
>    
>    >>> h(5)
>    25

A good explanation for the newbies, Kirby.

At the risk of confusing people that will only see Python 2.2 code,
and never really have to worry about reading through old stuff or
are not required to use an older release.  There is something missing
from this piece tho.

You might want to note that the above will break on earlier versions of
Python.  The g() function does not keep the "x" variable in Python 2.1,
in fact you get a syntax warning and a NameError exception being raised.

Python 2.1 (#1, Jun  1 2001, 19:52:18)
[GCC 2.96 20000731 (Red Hat Linux 7.0)] on linux2
Type "copyright", "credits" or "license" for more information.
>>> def f(x=3):
...   def g(y):
...     return y**x
...   return g
...
:1: SyntaxWarning: local name 'x' in 'f' shadows use of 'x' as global in nested scope 'g'
>>> h = f(2)
>>> h(5)
Traceback (most recent call last):
  File "", line 1, in ?
  File "", line 3, in g
NameError: global name 'x' is not defined
>>>

You can get it to work in Python 2.1 by added 'from __future__ import
nested_scopes'.  But it won't work on releases earlier than that.  The
function would need to use the "default arguments" you mentioned.

Python 1.5.2 (#1, Aug 25 2000, 09:33:37)  [GCC 2.96 20000731 (experimental)] on linux-i386
Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
>>> def f(x=3):
...   def g(y, x=x):
...     return y**x
...   return g
...
>>> h = f(2)
>>> h(5)
25
>>>

The "x=x" takes the value from the f() function and puts it inside the
g() function.  Remember that functions follow the LGB rule.

The LGB namespace rule stands for Local-Global-Builtins.  It shows in
which namespace Python would find a variable: in the local namespace,
the global namespace (the module) or in __builtins__.  If a function
wants to carry a value from another function's local namespace, the new
function needs to explicitly hold the value, for example, by the default
arguments above.

Have fun.

  -Arcege



From alan.gauld@bt.com  Tue Jan 29 17:33:04 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Tue, 29 Jan 2002 17:33:04 -0000
Subject: [Tutor] LISP and Python
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C309@mbtlipnt02.btlabs.bt.co.uk>

> I would like to know if someone of you has experience with 
> interfacing and extending Python with LISP (any Lisp .. ).

Interesting prospect!

> I would like to do more with Lisp but there are very few 
> Libraries for Lisp, but Python has many Libraries

What variant of Lisp are you using?
Common Lisp has lots of modules (Try the CLISP freeware 
version) for OS, networking, web, GUI etc etc.

Is there anything specific you can't find a module for?

Alan g.


From ak@silmarill.org  Tue Jan 29 11:14:02 2002
From: ak@silmarill.org (Andrei Kulakov)
Date: Tue, 29 Jan 2002 06:14:02 -0500
Subject: [Tutor] Please read this and respond to me.
In-Reply-To: <20020128184656.GA25891@sandra.lysator.liu.se>
References: <16e.7ca3139.2984f009@aol.com> <20020128134627.GA5832@silmarill.org> <20020128184656.GA25891@sandra.lysator.liu.se>
Message-ID: <20020129111402.GA11620@silmarill.org>

On Mon, Jan 28, 2002 at 07:46:56PM +0100, Kalle Svensson wrote:
> [Andrei Kulakov]
> > On Sun, Jan 27, 2002 at 12:54:17AM -0500, Kyuuketsiuki@aol.com wrote:
> > > I'm looking for a tutor (Teacher) on hacking, I've been meaning to learn and 
> > > i have read many things, but i have never really learned, so i would like for 
> > > you to teach me.    
> > 
> > I don't think anyone is gonna do that, for two reasons:
> > 
> > 1. Hacking (in this context) is illegal and the person who tried to
> 
> In what context?  The context of this list?

No, in the contest of his post. If he meant hacking as programming, he'd
say "programming".

> 
> > 2. If you couldn't pick up anything by yourself, this must not be "your
> > thing". Teaching you would be a waste of effort - like teaching a snake
> > to fly or an armadillo to ride a bycicle or a hippy to superwise a cleaning
> > detergent plant.
> 
> I disagree.  I believe that everyone can learn programming, but not
> that everyone can learn by themselves.

I agree with that. That's not what I meant, though.

> 
> Peace,
>   Kalle
> -- 
> Kalle Svensson (kalle@gnupung.net) - Laziness, impatience, hubris: Pick two!
> English: http://www.gnupung.net/  Svenska: http://www.lysator.liu.se/~kalle/
> Stuff: ["http://www.%s.org/" % x for x in "gnu debian python emacs".split()]
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

-- 
Cymbaline: intelligent learning mp3 player - python, linux, console.
get it at: cy.silmarill.org


From Benjamin.Schollnick@usa.xerox.com  Tue Jan 29 14:53:18 2002
From: Benjamin.Schollnick@usa.xerox.com (Schollnick, Benjamin)
Date: Tue, 29 Jan 2002 09:53:18 -0500
Subject: [Tutor] RE: Nobody knows? But why?
Message-ID: 

>From what I am reading in the Python Documentation....
(See Index, Proxy, Page 288)

You need to use URLLIB2, instead of Httplib, and set the
ProxyHandler method...

Httplib just does not have the intelligence to deal with proxies,
unless my docs have become outdated...

It's (httplib) is just the basic functions for accessing the URL's.
Urllib & Urllib2 are "extendors", which build upon the functionality
of the httplib.

		- Benjamin

-----Original Message-----
From: A [mailto:printers@sendme.cz]
Sent: Tuesday, January 29, 2002 8:57 AM
To: python-list@python.org; tutor@python.org;
activepython@listserv.ActiveState.com
Subject: Nobody knows? But why?




Hi,
For already some time I am trying to use  
modules, HTTPLIB or URLLIB to get a page through proxy but so 
far I have not been successfull
I also browsed Python group but the samples given there did not 
work.
Can anybody give me a WORKING example how I can grab a web 
page through proxy?
I tried this example
########################
#######################

import httplib
h = httplib.HTTP('209.242.141.249:8080') #proxy

h.putrequest('GET', 'http://www.autoplzen.info/index.php')

h.putheader('Accept', 'text/html')
h.putheader('Accept', 'text/plain')

#h.putrequest('Proxy-Connection', 'Keep-Alive') # it does not work, 
#so  I commented

#h.putrequest('Host', 'www.autoplzen.info')  the same,otherwise I 
#receive File "C:\PYTHON21\lib\httplib.py", line 430, in putrequest  
#  raise CannotSendRequest()

h.endheaders()
errcode, errmsg, headers = h.getreply()
print errcode # Should be 200


#######################################
The above example works as if there were no proxy because in 
web server log there is not  IP of Proxy but mine.

Any help would be appreciated.
thanks
Ladislav


------- End of forwarded message -------
_______________________________________________
ActivePython mailing list
ActivePython@listserv.ActiveState.com
To unsubscribe:
http://listserv.ActiveState.com/mailman/listinfo/activepython


From dhorkoff@genusrmt.ca  Tue Jan 29 17:57:33 2002
From: dhorkoff@genusrmt.ca (Horkoff, Dave)
Date: Tue, 29 Jan 2002 09:57:33 -0800
Subject: [Tutor] RE: Nobody knows? But why?
Message-ID: 

This message is in MIME format. Since your mail reader does not understand
this format, some or all of this message may not be legible.

------_=_NextPart_001_01C1A8EE.6D8F8690
Content-Type: text/plain;
	charset="iso-8859-1"

You could also take a look at the code for the NTML Proxy Server, which is a
proxy server writen in python designed to tunnel through an MS proxy server.
I've tried it and it works quite well.

http://www.geocities.com/rozmanov/ntlm/

Hope this helps give you some ideas,
David.

-----Original Message-----
From: Schollnick, Benjamin [mailto:Benjamin.Schollnick@usa.xerox.com]
Sent: January 29, 2002 6:53 AM
To: 'printers@sendme.cz'; python-list@python.org; tutor@python.org;
activepython@listserv.ActiveState.com
Subject: RE: Nobody knows? But why?


>From what I am reading in the Python Documentation....
(See Index, Proxy, Page 288)

You need to use URLLIB2, instead of Httplib, and set the
ProxyHandler method...

Httplib just does not have the intelligence to deal with proxies,
unless my docs have become outdated...

It's (httplib) is just the basic functions for accessing the URL's.
Urllib & Urllib2 are "extendors", which build upon the functionality
of the httplib.

		- Benjamin

-----Original Message-----
From: A [mailto:printers@sendme.cz]
Sent: Tuesday, January 29, 2002 8:57 AM
To: python-list@python.org; tutor@python.org;
activepython@listserv.ActiveState.com
Subject: Nobody knows? But why?




Hi,
For already some time I am trying to use  
modules, HTTPLIB or URLLIB to get a page through proxy but so 
far I have not been successfull
I also browsed Python group but the samples given there did not 
work.
Can anybody give me a WORKING example how I can grab a web 
page through proxy?
I tried this example
########################
#######################

import httplib
h = httplib.HTTP('209.242.141.249:8080') #proxy

h.putrequest('GET', 'http://www.autoplzen.info/index.php')

h.putheader('Accept', 'text/html')
h.putheader('Accept', 'text/plain')

#h.putrequest('Proxy-Connection', 'Keep-Alive') # it does not work, 
#so  I commented

#h.putrequest('Host', 'www.autoplzen.info')  the same,otherwise I 
#receive File "C:\PYTHON21\lib\httplib.py", line 430, in putrequest  
#  raise CannotSendRequest()

h.endheaders()
errcode, errmsg, headers = h.getreply()
print errcode # Should be 200


#######################################
The above example works as if there were no proxy because in 
web server log there is not  IP of Proxy but mine.

Any help would be appreciated.
thanks
Ladislav


------- End of forwarded message -------
_______________________________________________
ActivePython mailing list
ActivePython@listserv.ActiveState.com
To unsubscribe:
http://listserv.ActiveState.com/mailman/listinfo/activepython
_______________________________________________
ActivePython mailing list
ActivePython@listserv.ActiveState.com
To unsubscribe:
http://listserv.ActiveState.com/mailman/listinfo/activepython

------_=_NextPart_001_01C1A8EE.6D8F8690
Content-Type: text/html;
	charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable






RE: Nobody knows? But why?



You could also take a look at the code for the NTML = Proxy Server, which is a proxy server writen in python designed to = tunnel through an MS proxy server. I've tried it and it works quite = well.

http://www.geocities.com/rozmanov/ntlm/

Hope this helps give you some ideas,
David.

-----Original Message-----
From: Schollnick, Benjamin [mailto:Benjamin.Scholl= nick@usa.xerox.com]
Sent: January 29, 2002 6:53 AM
To: 'printers@sendme.cz'; python-list@python.org; = tutor@python.org;
activepython@listserv.ActiveState.com
Subject: RE: Nobody knows? But why?


From what I am reading in the Python = Documentation....
(See Index, Proxy, Page 288)

You need to use URLLIB2, instead of Httplib, and set = the
ProxyHandler method...

Httplib just does not have the intelligence to deal = with proxies,
unless my docs have become outdated...

It's (httplib) is just the basic functions for = accessing the URL's.
Urllib & Urllib2 are "extendors", = which build upon the functionality
of the httplib.

        =         - = Benjamin

-----Original Message-----
From: A [mailto:printers@sendme.cz]=
Sent: Tuesday, January 29, 2002 8:57 AM
To: python-list@python.org; tutor@python.org;
activepython@listserv.ActiveState.com
Subject: Nobody knows? But why?




Hi,
For already some time I am trying to use  =
modules, HTTPLIB or URLLIB to get a page through = proxy but so
far I have not been successfull
I also browsed Python group but the samples given = there did not
work.
Can anybody give me a WORKING example how I can grab = a web
page through proxy?
I tried this example
########################
#######################

import httplib
h =3D httplib.HTTP('209.242.141.249:8080') = #proxy

h.putrequest('GET', 'http://www.autoplzen.info/index.php')

h.putheader('Accept', 'text/html')
h.putheader('Accept', 'text/plain')

#h.putrequest('Proxy-Connection', 'Keep-Alive') # it = does not work,
#so  I commented

#h.putrequest('Host', 'www.autoplzen.info')  the = same,otherwise I
#receive File = "C:\PYTHON21\lib\httplib.py", line 430, in putrequest  =
#  raise CannotSendRequest()

h.endheaders()
errcode, errmsg, headers =3D h.getreply()
print errcode # Should be 200


#######################################
The above example works as if there were no proxy = because in
web server log there is not  IP of Proxy but = mine.

Any help would be appreciated.
thanks
Ladislav


------- End of forwarded message -------
_______________________________________________
ActivePython mailing list
ActivePython@listserv.ActiveState.com
To unsubscribe:
http://listserv.ActiveState.com/mailman/listinfo/activ= epython
_______________________________________________
ActivePython mailing list
ActivePython@listserv.ActiveState.com
To unsubscribe: http://listserv.ActiveState.com/mailman/listinfo/activ= epython

------_=_NextPart_001_01C1A8EE.6D8F8690-- From cmccormick@thestate.com Tue Jan 29 19:59:54 2002 From: cmccormick@thestate.com (Chris McCormick) Date: Tue, 29 Jan 2002 14:59:54 -0500 Subject: [Tutor] ** Newbie ** - Dumb input() question ... In-Reply-To: Message-ID: Ok, I know I have done this before, but I can't get input() to work. Here's the transcript of a PythonWin interactive session: >>> response = input('Write something here.') *** A dialog box comes up, and I enter the text 'hello' ** Traceback (most recent call last): File "", line 1, in ? File "C:\Python21\Pythonwin\pywin\framework\app.py", line 362, in Win32Input return eval(raw_input(prompt)) File "", line 0, in ? NameError: name 'hello' is not defined What's up? I get this when running modules, too. It seems to be trying to use the collected input as the name of a variable? Thanks in advance, Chris From arcege@speakeasy.net Tue Jan 29 20:28:05 2002 From: arcege@speakeasy.net (Michael P. Reilly) Date: Tue, 29 Jan 2002 15:28:05 -0500 Subject: [Fwd: Re: [Tutor] LISP and Python] In-Reply-To: <20020129120422.GA2845@dman.ddts.net>; from dsh8290@rit.edu on Tue, Jan 29, 2002 at 07:04:22AM -0500 References: <3C5678EC.1ED93328@mail.verizon.net> <20020129113749.A14611@pino.selwerd.nl> <20020129120422.GA2845@dman.ddts.net> Message-ID: <20020129152805.A4948@speakeasy.net> On Tue, Jan 29, 2002 at 07:04:22AM -0500, dman wrote: > On Tue, Jan 29, 2002 at 11:37:49AM +0100, Remco Gerlich wrote: > | On 0, Lloyd Hugh Allen wrote: > | > One of these days I'll get a hang of the "hey, idjit, change 'To:' to > | > 'tutor@python.org'" thing. > | > | Yeah, it's irritating :( > > Here's how to make it not irritating at all : > > 1) pick up mutt (www.mutt.org) > 2) tell it you're subscribed to the list -- > (put > subscribe tutor@python.org > in ~/.muttrc) > 3) adjust the index-format so you don't see the list address for > every message that comes from the list (you already sort it into > its own folder, right?) > (put > set index_format="%3C %Z %[%b%d] %-17.17n(%?M?#%3M&%4c?) %s" > in ~/.muttrc) > > Then simply press "L" to reply on-list, "r" to reply off-list, and "g" > to send a copy both places. I also have a folder-hook that changes the "r" to reply on-list. -Arcege From arcege@speakeasy.net Tue Jan 29 20:36:00 2002 From: arcege@speakeasy.net (Michael P. Reilly) Date: Tue, 29 Jan 2002 15:36:00 -0500 Subject: [Tutor] python scripting and unix In-Reply-To: ; from christine_wilson_@hotmail.com on Mon, Jan 28, 2002 at 07:47:05PM -0500 References: Message-ID: <20020129153600.B4948@speakeasy.net> On Mon, Jan 28, 2002 at 07:47:05PM -0500, Christine Wilson wrote: > I am writing a python script set to execute upon login to my unix account. > The user is prompted for further information - if the answer is correct, > they may continue. If the answer is wrong (meaning that it is not me) I > want the session to exit/logout. > > How can I do this? I'm just becoming familiar with Python and scripting. > Any ideas? > > The script is executing before the user actually is prompted with the Unix > prompt. > > ---------------------------------------------------------------------- > #!/usr/bin/env python > > import os > os.system("clear") > > from sudialg import * > if ask_who(): #gets user input for first answer, returns 1 if correct > #continues > > else: > exit #I want the telnet session to end with NO access to my account > #but this is just exiting the script I assume you want to have this in the user's dot file. Instead of "exit", you will want os.kill(os.getppid, 1) Which sends a hang-up signal to the login shell, logging the user out. -Arcege From dyoo@hkn.eecs.berkeley.edu Tue Jan 29 20:59:15 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 29 Jan 2002 12:59:15 -0800 (PST) Subject: [Tutor] ** Newbie ** - Dumb input() question ... In-Reply-To: Message-ID: On Tue, 29 Jan 2002, Chris McCormick wrote: > Ok, I know I have done this before, but I can't get input() to work. Here's the transcript of a PythonWin interactive session: > > > > >>> response = input('Write something here.') > > *** A dialog box comes up, and I enter the text 'hello' ** There's a distinct differenct between input() and raw_input(): input() will try to actually evaluate whatever you type in. Here's an example in the interpreter that demonstrates this: ### >>> x = 42 >>> y = input("Enter something: ") Enter something: x >>> y 42 ### input() actually tries to do something with what we type in! Usually, this isn't what we want --- we'd rather just get what the user literally typed. For that, we can use raw_input(): ### >>> z = raw_input("Enter something: ") Enter something: y >>> z 'y' ### > Traceback (most recent call last): > File "", line 1, in ? > File "C:\Python21\Pythonwin\pywin\framework\app.py", line 362, in Win32Input > return eval(raw_input(prompt)) > File "", line 0, in ? > NameError: name 'hello' is not defined > > What's up? I get this when running modules, too. It seems to be > trying to use the collected input as the name of a variable? Yes, exactly. The error message is a consequence of input() trying to figure out what the value of 'hello' is. Hope this helps! If you have more questions, please feel free to ask. From dsh8290@rit.edu Tue Jan 29 21:23:17 2002 From: dsh8290@rit.edu (dman) Date: Tue, 29 Jan 2002 16:23:17 -0500 Subject: [Tutor] python scripting and unix In-Reply-To: References: Message-ID: <20020129212317.GA7805@dman.ddts.net> On Mon, Jan 28, 2002 at 07:47:05PM -0500, Christine Wilson wrote: | I am writing a python script set to execute upon login to my unix account. | The user is prompted for further information - if the answer is correct, | they may continue. If the answer is wrong (meaning that it is not me) I | want the session to exit/logout. | | How can I do this? I'm just becoming familiar with Python and scripting. | Any ideas? | | The script is executing before the user actually is prompted with the Unix | prompt. In your script (.bash_login or whatever it is for your shell) use ~~~~~~~~~~ ./path/to/your_script || exit ~~~~~~~~~~ If your script exits with a non-zero (success) exit status then the command after the "or" ('||') will execute. | ---------------------------------------------------------------------- | #!/usr/bin/env python | | import os | os.system("clear") # the above line isn't important, really # probably better to stick it in your login file instead anyways import sys | from sudialg import * | if ask_who(): #gets user input for first answer, returns 1 if correct | #continues sys.exit( 0 ) | | else: sys.exit( 1 ) | exit #I want the telnet session to end with NO access to my account | #but this is just exiting the script FWIW you can probably just stick it in your login file as read -p "the question" FOO if [ "$FOO" != "the magic answer" ] ; then exit || logout fi ('man bash' and look through the relevant parts for a very terse explanation of shell scripting) HTH, -D -- The teaching of the wise is a fountain of life, turning a man from the snares of death. Proverbs 13:14 From dyoo@hkn.eecs.berkeley.edu Tue Jan 29 21:26:01 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 29 Jan 2002 13:26:01 -0800 (PST) Subject: [Tutor] ** Newbie ** - Dumb input() question ... In-Reply-To: Message-ID: On Tue, 29 Jan 2002, Danny Yoo wrote: > On Tue, 29 Jan 2002, Chris McCormick wrote: > > > Ok, I know I have done this before, but I can't get input() to work. Here's the transcript of a PythonWin interactive session: > > > > > > > > >>> response = input('Write something here.') > > > > *** A dialog box comes up, and I enter the text 'hello' ** > > There's a distinct differenct between input() and raw_input(): input() ^^^^^^^^^^ My brain seized. I got caught between the word "different" and "difference". *grin* By the way, input() would have worked ok if we had been careful to use quotes when we typed at the prompt: ### >>> response = input("Write something here.") Write something here.'hello' >>> response 'hello' ### since we're inputting a string literal. But remembering to put quotes is a burden that shouldn't be on the user's shoulders; raw_input() is probably a better function to use in this case. From AKolinski@nriindustries.com Tue Jan 29 21:35:10 2002 From: AKolinski@nriindustries.com (Andrzej Kolinski) Date: Tue, 29 Jan 2002 16:35:10 -0500 Subject: [Tutor] my pet project (long) Message-ID: --0__=85256B5000765EF78f9e8a93df938690918c85256B5000765EF7 Content-type: text/plain; charset=us-ascii I am a total newbie surrounded by Python books and tutorials. Before I became the one (this was not difficult :-)) I tried to learn a bit of C (I am glad I did not). I found Python and this mailing are the best things for what I dream to do. This is my pet project. I would like to write a python program that allows me to maintain players' ranking for our bridge club. I run weekly duplicate games and use a designated program to score these games. Among other things it creates text files (see examples attached) with the game results. I want to use the players' Pct (second column) and Names (last column) to do my calculations. The first things I want to know is: - how to get the data from the results file, i.e. how to create a table/file with each player's name associated with the pair's Pct (what type of file/string operation applies)? - how to use this individual player result to update the ranking table/file? This would take: - player's current ranking (first entry = 50.00), - partner's current ranking, - last game Pct for this pair, and maybe - the average ranking of all players in the game. I want to include the last 8 games in these calculations and produce a current club ranking list for players that participated at least in 4 out of the last 8 games. I've gone through several tutorials, concentrating especially on file operations/string manipulations but I do not know where to start and I would appreciate any advice from you. By the way, are there any duplicate bridge players on this mailing list *grin*? (See attached file: game0116.txt) (See attached file: game0123.txt) _/_/ _/ _/ _/ _/ _/ _/ _/_/_/_/ _/_/ _/ _/ _/ _/ _/ _/ _/ _/ Andrzej Kolinski --0__=85256B5000765EF78f9e8a93df938690918c85256B5000765EF7 Content-type: application/octet-stream; name="game0116.txt" Content-Disposition: attachment; filename="game0116.txt" Content-transfer-encoding: base64 DQpUdXJuaWVqIFBhcmFtaSAoTUFYLVkpIFdlZG5lc2RheSBFdmUgU2Vzc2lvbiBKYW51YXJ5IDE2 LCAyMDAyDQoNCg0KU2NvcmVzIGFmdGVyIDI4IGJvYXJkcyAgQXZlcmFnZTogICA4NC4wICAgICAg U2VjdGlvbiAgQSAgTm9ydGgtU291dGgNClBhaXIgICAgUGN0ICAgU2NvcmUgIFJhbmsgICBNUHMg ICAgIA0KICA3ICAgNjYuOTYgIDExMi41MCAgIDEgICAgMC44MCAgICAgQWRhbSBLb2h1dCAtIFpi aWduaWV3IFN0YW5raWV3aWN6DQogIDEgICA1NS4wNiAgIDkyLjUwICAgMiAgICAwLjU2ICAgICBU YWt5IEJvaG9zc2lhbiAtIFN0YW5pc2xhdyBSYWxjZXdpY3oNCiAgMiAgIDQ4LjUxICAgODEuNTAg IDMvNCAgIDAuMzQgICAgIFN0YW5pc2xhdyBHcnVkemluc2tpIC0gQW5kcnplaiBIZW1wZWwNCiAg MyAgIDQ4LjUxICAgODEuNTAgIDMvNCAgIDAuMzQgICAgIEhlbnJ5ayBSYXN0b24gLSBUYWRldXN6 IFdpZG1vbnQNCiAgNiAgIDQ2LjQzICAgNzguMDAgICAgICAgICAgICAgICAgIERhbmllbGEgQWxl anNrYSAtIFpvZmlhIEtvbml0emVyDQogIDQgICA0Ni4xMyAgIDc3LjUwICAgICAgICAgICAgICAg ICBKdWxpYW4gR2FsYXMgLSBXYW5kYSBHYWxhcw0KICA1ICAgMzguMzkgICA2NC41MCAgICAgICAg ICAgICAgICAgSmFudXN6IEhhbnVzIC0gTWFsZ29yemF0YSBMdWthc2lhaw0KDQpUdXJuaWVqIFBh cmFtaSAoTUFYLVkpIFdlZG5lc2RheSBFdmUgU2Vzc2lvbiBKYW51YXJ5IDE2LCAyMDAyDQpTY29y ZXMgYWZ0ZXIgMjggYm9hcmRzICBBdmVyYWdlOiAgIDg0LjAgICAgICBTZWN0aW9uICBBICBFYXN0 LVdlc3QNClBhaXIgICAgUGN0ICAgU2NvcmUgIFJhbmsgICBNUHMgICAgIA0KICA1ICAgNTkuMzgg ICA5OS43NSAgIDEgICAgMC44MCAgICAgWnlnbXVudCBLdWJpc3p5biAtIFJ5c3phcmQgTGV3YW5k b3dza2kNCiAgNyAgIDU2Ljk1ICAgOTUuNjcgICAyICAgIDAuNTYgICAgIElyZW5hIEpha3Vib3dz a2EgLSBXb2pjaWVjaCBTYW1ib3INCiAgMSAgIDU0LjE3ICAgOTEuMDAgICAzICAgIDAuNDAgICAg IElyZW5ldXN6IEJhY3playAtIEZyZWQgU3pvYmxpaw0KICA4ICAgNTEuNzQgICA4Ni45MiAgICAg ICAgICAgICAgICAgSmFjZWsgQ3lwZXJsaW5nIC0gQW5kcnplaiBLb2xpbnNraQ0KICA2ICAgNDku NjUgICA4My40MiAgICAgICAgICAgICAgICAgS3J6eXN6dG9mIEtvd2Fsc2tpIC0gTWllY3p5c2xh dyBMYXNrb3dza2kNCiAgMyAgIDQ3LjIyICAgNzkuMzMgICAgICAgICAgICAgICAgIFJhZGVrIENo cmFiYWxvd3NraSAtIEJydW5vIFpkemllbmlja2kNCiAgNCAgIDQ1LjE0ICAgNzUuODMgICAgICAg ICAgICAgICAgIEJhcmJhcmEgRmlsaXBjenVrIC0gSmVyenkgSHJ5bmlld2llY2tpDQogIDIgICAz NS4wNyAgIDU4LjkyICAgICAgICAgICAgICAgICBXaWVzbGF3IFN6Y3plcmJvd3NraSAtIFpiaWdu aWV3IFppb2xrb3dza2kNCg== --0__=85256B5000765EF78f9e8a93df938690918c85256B5000765EF7 Content-type: application/octet-stream; name="game0123.txt" Content-Disposition: attachment; filename="game0123.txt" Content-transfer-encoding: base64 VHVybmllaiBQYXJhbWkgKE1BWC1ZKSBXZWRuZXNkYXkgRXZlIFNlc3Npb24gSmFudWFyeSAyMywg MjAwMg0KU2NvcmVzIGFmdGVyIDI0IGJvYXJkcyAgQXZlcmFnZTogICA4NC4wICAgICAgU2VjdGlv biAgQQ0KUGFpciAgICBQY3QgICBTY29yZSAgUmFuayAgIE1QcyAgICAgDQogIDYgICA2Mi44OCAg MTA1LjY0ICAgMSAgICAxLjUwICAgICBEYW5pZWxhIEFsZWpza2EgLSBab2ZpYSBLb25pdHplcg0K ICAyICAgNjEuMTggIDEwMi43OSAgIDIgICAgMS4wNSAgICAgQW5kcnplaiBLb2xpbnNraSAtIFN0 YW5pc2xhdyBSYWxjZXdpY3oNCiAxNiAgIDU1LjkxICAgOTMuOTMgICAzICAgIDAuNzUgICAgIEFs ZWtzYW5kZXIgQ2ljaG9ja2kgLSBaYmlnbmlldyBQYW5raWV3aWN6DQogMTEgICA1NS40OSAgIDkz LjIyICAgNCAgICAwLjUzICAgICBXaWVzbGF3IFN6Y3plcmJvd3NraSAtIFpiaWduaWV3IFppb2xr b3dza2kNCiAgMyAgIDU1LjQ4ICAgOTMuMjEgICA1ICAgIDAuMzAgICAgIEhlbnJ5ayBSYXN0b24g LSBUYWRldXN6IFdpZG1vbnQNCiAxMyAgIDUzLjAyICAgODkuMDcgICA2ICAgIDAuMjUgICAgIEty enlzenRvZiBLb3dhbHNraSAtIE1pZWN6eXNsYXcgTGFza293c2tpDQogMTQgICA1Mi40MiAgIDg4 LjA2ICAgICAgICAgICAgICAgICBBZGFtIFphY2hhcmEgLSBCcnVubyBaZHppZW5pY2tpDQogMTAg ICA1Mi4yMSAgIDg3LjcyICAgICAgICAgICAgICAgICBSYWRlayBDaHJhYmFsb3dza2kgLSBBbmRy emVqIEtpdGENCiAxMiAgIDQ5LjMxICAgODIuODQgICAgICAgICAgICAgICAgIEJhcmJhcmEgRmls aXBjenVrIC0gSmVyenkgSHJ5bmlld2llY2tpDQogIDUgICA0Ni44OSAgIDc4Ljc4ICAgICAgICAg ICAgICAgICBKYW51c3ogSGFudXMgLSBNYWxnb3J6YXRhIEx1a2FzaWFrDQogIDEgICA0NS45NiAg IDc3LjIxICAgICAgICAgICAgICAgICBTdGFuaXNsYXcgR3J1ZHppbnNraSAtIEFuZHJ6ZWogSGVt cGVsDQogIDcgICA0NC4xMyAgIDc0LjE0ICAgICAgICAgICAgICAgICBLcnlzdHluYSBTemFka293 c2thIC0gUm9iZXJ0IFN6Y3p1cmVrDQogMTUgICA0Mi45MCAgIDcyLjA3ICAgICAgICAgICAgICAg ICBJcmVuZXVzeiBCYWN6ZWsgLSBGcmVkIFN6b2JsaWsNCiAgOCAgIDQyLjAyICAgNzAuNjAgICAg ICAgICAgICAgICAgIFJ5c3phcmQgTGV3YW5kb3dza2kgLSBaYmlnbmlldyBTZWt1bGENCiAgNCAg IDQwLjM5ICAgNjcuODYgICAgICAgICAgICAgICAgIEp1bGlhbiBHYWxhcyAtIFdhbmRhIEdhbGFz DQogIDkgICAzOS44MCAgIDY2Ljg3ICAgICAgICAgICAgICAgICBXb2pjaWVjaCBTYW1ib3IgLSBN YXJ5bGEgV2FjaG93aWFrDQo= --0__=85256B5000765EF78f9e8a93df938690918c85256B5000765EF7-- From dyoo@hkn.eecs.berkeley.edu Tue Jan 29 21:38:50 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 29 Jan 2002 13:38:50 -0800 (PST) Subject: [Fwd: Re: [Tutor] LISP and Python] In-Reply-To: <20020129113749.A14611@pino.selwerd.nl> Message-ID: On Tue, 29 Jan 2002, Remco Gerlich wrote: > I don't know much about Lisp. I suppose you have to put a layer on C > in between; if you can call C functions from Lisp, you can have it run > the Python interpreter to make library calls. But it's not going to be > much fun, I think. > > Are you sure there aren't many libraries for Lisp? I had expected it > to have lots. Maybe only commercial or not all those newfangled > Internet protocols... You may want to check PLT Scheme: http://www.plt-scheme.org/ PLT Scheme definitely has support for networking protocols and other utilities. It would definitely be a cool project to create some hybrid Lisp bridge that could access Python functions, and vice versa. I don't recall ever hearing anyone doing this yet. From kimtitu@yahoo.com Wed Jan 30 02:05:24 2002 From: kimtitu@yahoo.com (Titu Kim) Date: Tue, 29 Jan 2002 18:05:24 -0800 (PST) Subject: [Tutor] Request Timeout Message-ID: <20020130020524.97741.qmail@web14704.mail.yahoo.com> I am writing a cgi script in python which posts a query to Oracle db. WHen the query takes long time, my browser get timeout message. How can i fix this problem to avoid timeout? I am not sure which side issue timeout(either browser, apache, or python cgi script). How can i fix this problem to make browser waits as long as it takes for oracle to return result? Thanks. Kim TItu __________________________________________________ Do You Yahoo!? Great stuff seeking new owners in Yahoo! Auctions! http://auctions.yahoo.com From shalehperry@attbi.com Wed Jan 30 02:24:58 2002 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Tue, 29 Jan 2002 18:24:58 -0800 (PST) Subject: [Tutor] my pet project (long) In-Reply-To: Message-ID: On 29-Jan-2002 Andrzej Kolinski wrote: > > I am a total newbie surrounded by Python books and tutorials. Before I > became the one (this was not difficult :-)) I tried to learn a bit of C (I > am glad I did not). I found Python and this mailing are the best things for > what I dream to do. > > This is my pet project. I would like to write a python program that allows > me to maintain players' ranking for our bridge club. I run weekly > duplicate games and use a designated program to score these games. Among > other things it creates text files (see examples attached) with the game > results. I want to use the players' Pct (second column) and Names (last > column) to do my calculations. > This is quite a complicated project for someone just starting out. It sounds like what you really need is to learn how to write simple programs in python and build up to this. Break the problem into small pieces and try to solve them one at a time. From rufmetal@rogers.com Wed Jan 30 03:26:41 2002 From: rufmetal@rogers.com (Chris Keelan) Date: Tue, 29 Jan 2002 21:26:41 -0600 Subject: [Tutor] Please read this and respond to me. In-Reply-To: <20020129111402.GA11620@silmarill.org> References: <16e.7ca3139.2984f009@aol.com> <20020128134627.GA5832@silmarill.org> <20020128184656.GA25891@sandra.lysator.liu.se> <20020129111402.GA11620@silmarill.org> Message-ID: <20020129212641.61b159f6.rufmetal@rogers.com> Tue, 29 Jan 2002 06:14:02 -0500: In attempt to throw the authorities off his trail, Andrei Kulakov transmitted: > On Mon, Jan 28, 2002 at 07:46:56PM +0100, Kalle Svensson wrote: > > > 1. Hacking (in this context) is illegal and the person who tried to > > > > In what context? The context of this list? > > No, in the contest of his post. If he meant hacking as programming, he'd > say "programming". I read it that way, as well. That's why I posted the Eric Raymond link. > > I disagree. I believe that everyone can learn programming, but not > > that everyone can learn by themselves. > > I agree with that. That's not what I meant, though. This list is hands-down the most generous and supportive environment I've ever participated in. I guess that's why is was exceptionally jarring to see what seemed like a script-kiddie wannabe posting here. My appologies if I'm completely misreading this situation. - C From p.hartley@spitech.com Wed Jan 30 03:39:46 2002 From: p.hartley@spitech.com (Paul Hartley) Date: Wed, 30 Jan 2002 11:39:46 +0800 Subject: [Tutor] my pet project (long) References: Message-ID: <00b201c1a93f$f39a6420$ebe710ac@pc7345> On 29-Jan-2002 Andrzej Kolinski wrote: > > I am a total newbie surrounded by Python books and tutorials. Before I > became the one (this was not difficult :-)) I tried to learn a bit of C (I > am glad I did not). I found Python and this mailing are the best things for > what I dream to do. > > This is my pet project. I would like to write a python program that allows > me to maintain players' ranking for our bridge club. I run weekly > duplicate games and use a designated program to score these games. Among > other things it creates text files (see examples attached) with the game > results. I want to use the players' Pct (second column) and Names (last > column) to do my calculations. > > The first things I want to know is: > - how to get the data from the results file, i.e. how to create a > table/file with each player's name associated with the pair's Pct (what > type of file/string operation applies)? > - how to use this individual player result to update the ranking > table/file? This would take: > - player's current ranking (first entry = 50.00), > - partner's current ranking, > - last game Pct for this pair, and maybe > - the average ranking of all players in the game. > > I want to include the last 8 games in these calculations and produce a > current club ranking list for players that participated at least in 4 out > of the last 8 games. > > I've gone through several tutorials, concentrating especially on file > operations/string manipulations but I do not know where to start and I > would appreciate any advice from you. > > By the way, are there any duplicate bridge players on this mailing list > *grin*? > Sean Perry is right, this is a large task for a beginner, and you should break it down into smaller tasks. I am a duplicate bridge player and an experienced programmer, but fairly new to Python - so perhaps we can work together to help me extend my python experience and for you to understand more about programming. The help available at this python tutor mailing lst is excellent - so there should be no problem getting further help when needed. From erikprice@mac.com Wed Jan 30 03:55:22 2002 From: erikprice@mac.com (Erik Price) Date: Tue, 29 Jan 2002 22:55:22 -0500 Subject: [Tutor] Please read this and respond to me. In-Reply-To: <20020129111402.GA11620@silmarill.org> Message-ID: <2F35490C-1535-11D6-BCB1-00039351FE6A@mac.com> On Tuesday, January 29, 2002, at 06:14 AM, Andrei Kulakov wrote: > No, in the contest of his post. If he meant hacking as programming, he'd > say "programming". Unless he was referred to Python from ESR: http://www.tuxedo.org/~esr/faqs/hacker-howto.html It specifically recommends that newbies start w/Python, and uses "hacking" as synonymous for "programming" throughout. Erik From dsh8290@rit.edu Wed Jan 30 05:15:37 2002 From: dsh8290@rit.edu (dman) Date: Wed, 30 Jan 2002 00:15:37 -0500 Subject: [Tutor] Request Timeout In-Reply-To: <20020130020524.97741.qmail@web14704.mail.yahoo.com> References: <20020130020524.97741.qmail@web14704.mail.yahoo.com> Message-ID: <20020130051537.GA13432@dman.ddts.net> On Tue, Jan 29, 2002 at 06:05:24PM -0800, Titu Kim wrote: | I am writing a cgi script in python which posts a | query to Oracle db. WHen the query takes long time, my | browser get timeout message. How can i fix this | problem to avoid timeout? I am not sure which side | issue timeout(either browser, apache, or python cgi | script). How can i fix this problem to make browser | waits as long as it takes for oracle to return result? | Thanks. It's the browser that times out -- it figures the web server ain't there if it's not saying anything. The best solution is to use some sort of persistant handler with a pool of db connections. When a request arrives it is given to a running process (persistant cgi, zope object, whatever middleware you choose) that already has a connection to Oracle. Thus the time to create a connection is eliminated. (a not-really-a-solution solution is to increase the timeout values in your browser, but then every visitor of your site has to do that too) HTH, -D -- The fear of the Lord leads to life: Then one rests content, untouched by trouble. Proverbs 19:23 From idiot1@netzero.net Wed Jan 30 05:41:33 2002 From: idiot1@netzero.net (kirk Bailey) Date: Wed, 30 Jan 2002 00:41:33 -0500 Subject: [Tutor] Update posted Message-ID: <3C57878D.74358D9D@netzero.net> tinylist.1.1.1.tar.gz AND tinylist.1.1.1.zip now posted for downloading at the site. http://www.tinylist.org/ -- -Respectfully, -Kirk D Bailey Consulting Loose Cannon end www.howlermonkey.net highprimate@howlermonkey.net www.sacredelectron.org idiot1@netzero.net www.tinylist.org grumpy@tinylist.org ---------------------------------------------------- Sign Up for NetZero Platinum Today Only $9.95 per month! http://my.netzero.net/s/signup?r=platinum&refcd=PT97 From urnerk@qwest.net Wed Jan 30 06:54:44 2002 From: urnerk@qwest.net (Kirby Urner) Date: Tue, 29 Jan 2002 22:54:44 -0800 Subject: [Tutor] Please read this and respond to me. In-Reply-To: <20020129212641.61b159f6.rufmetal@rogers.com> References: <20020129111402.GA11620@silmarill.org> <16e.7ca3139.2984f009@aol.com> <20020128134627.GA5832@silmarill.org> <20020128184656.GA25891@sandra.lysator.liu.se> <20020129111402.GA11620@silmarill.org> Message-ID: <4.2.0.58.20020129225351.00aabdf0@pop3.norton.antivirus> > >My appologies if I'm completely misreading this situation. > >- C You're just another victim of the culture fact that "hacking" has become highly ambiguous in its meaning. People join a list and say they want to become hackers. What do they mean? GodifIknow. Kirby From kalle@gnupung.net Wed Jan 30 09:44:12 2002 From: kalle@gnupung.net (Kalle Svensson) Date: Wed, 30 Jan 2002 10:44:12 +0100 Subject: [Tutor] Please read this and respond to me. In-Reply-To: <20020129111402.GA11620@silmarill.org> References: <16e.7ca3139.2984f009@aol.com> <20020128134627.GA5832@silmarill.org> <20020128184656.GA25891@sandra.lysator.liu.se> <20020129111402.GA11620@silmarill.org> Message-ID: <20020130094412.GA10351@sandra.lysator.liu.se> [Andrei Kulakov] > On Mon, Jan 28, 2002 at 07:46:56PM +0100, Kalle Svensson wrote: > > [Andrei Kulakov] > > > On Sun, Jan 27, 2002 at 12:54:17AM -0500, Kyuuketsiuki@aol.com wrote: > > > > I'm looking for a tutor (Teacher) on hacking [...] > > > > > > I don't think anyone is gonna do that, for two reasons: > > > > > > 1. Hacking (in this context) is illegal and the person who tried to > > > > In what context? The context of this list? > > No, in the contest of his post. If he meant hacking as programming, he'd > say "programming". Well, it seems plausible, but I'd like more evidence. Especially if I'm going to proceed by comparing the poster with various animals doing tricks, and saying that helping him/her would be a waste of time. Peace, Kalle -- Kalle Svensson (kalle@gnupung.net) - Laziness, impatience, hubris: Pick two! English: http://www.gnupung.net/ Svenska: http://www.lysator.liu.se/~kalle/ Stuff: ["http://www.%s.org/" % x for x in "gnu debian python emacs".split()] From dyoo@hkn.eecs.berkeley.edu Wed Jan 30 10:27:05 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 30 Jan 2002 02:27:05 -0800 (PST) Subject: [Tutor] Please read this and respond to me. [what to do with "hacker" requests?] In-Reply-To: <20020129212641.61b159f6.rufmetal@rogers.com> Message-ID: On Tue, 29 Jan 2002, Chris Keelan wrote: > > > In what context? The context of this list? > > > > No, in the contest of his post. If he meant hacking as programming, he'd > > say "programming". > > I read it that way, as well. That's why I posted the Eric Raymond link. > [... some text cut] > > My appologies if I'm completely misreading this situation. We do get quite a lot people here who use the work "hacker" in the positive sense. Eric Raymond's recommendation that beginner hackers pick up a language like Python is also a factor that makes the situation ambiguous. I personally felt the reprimand was a little too sharp... But in hindsight, Andrei read the situation accurately. Anyway, if this situation happens again, let's do make sure that they get the link to ESR's essay. If they're truly interested in learning, they'll come back and tell us we're just a bunch of worry warts, and that of course they mean "hacker" in the finest sense of the word. And if they're looking for ways to crack systems, they'll quickly get bored by our discussion of list comprehension syntax. From sarney@bigpond.com Wed Jan 30 10:41:54 2002 From: sarney@bigpond.com (Sarney) Date: Wed, 30 Jan 2002 21:41:54 +1100 Subject: [Tutor] Spurious primes Message-ID: <000701c1a97b$18dea300$7a1a8690@sarney> Dear list members, I'm attempting to 'think like a computer scientist'. To this end, I set myself a trivial exercise of generating a list of primes. I thought I had succeeded with the function below (after much gnashing of teeth & re-reading tutorials). My pride was dashed when my I asked for 7 primes and got (2,3,5,7,11,13,16). After some more testing, I realised it was spitting out these spurious primes after testing a number with more than one factor in the list 'a' (e.g 15 & 21). Where have I gone wrong? Regards, Robert ________________________ a = [2] def test(x,a): for i in a: if x%i == 0: x = x + 1 test(x,a) else: return x num = int(raw_input("how many primes do you want? ")) while len(a) <= num - 1: a.append(test(a[-1]+1,a)) print a From dyoo@hkn.eecs.berkeley.edu Wed Jan 30 11:04:42 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 30 Jan 2002 03:04:42 -0800 (PST) Subject: [Tutor] Spurious primes In-Reply-To: <000701c1a97b$18dea300$7a1a8690@sarney> Message-ID: On Wed, 30 Jan 2002, Sarney wrote: > I'm attempting to 'think like a computer scientist'. To this end, I set > myself a trivial exercise of generating a list of primes. I thought I had > succeeded with the function below (after much gnashing of teeth & re-reading > tutorials). My pride was dashed when my I asked for 7 primes and got > (2,3,5,7,11,13,16). Let's take a look at the program. After that, I'm going to bed. *grin* > a = [2] Ah, ok, so whenever I see 'a', I'll think "the list of primes we've found". You might want to use a more descriptive name than 'a', since you also use a few other one-letter variables. > def test(x,a): > for i in a: > if x%i == 0: > x = x + 1 > test(x,a) > else: > return x Be careful --- if we want test() to return the very next prime that it finds, we need to see that every possible twisty path will eventually "return" a value. In the code above, if 'x%i == 0' is true, test() does does a recursive call, but it tosses away the result by not doing anything with it. Here's a version of test(x, a) that corrects that bug. I've taken the libery of renaming the variables, but you can change them back, of course. *grin*: ### def findNextPrime(candidate, primes): for prime in primes: if candidate % prime == 0: candidate = candidate + 1 return findNextPrime(candidate, primes) else: return candidate ### There's still a bug in here --- see what happens when we do something like: findNextPrime(9, [2,3,5,7]) Don't worry, you'll see it in time. Good luck to you, and if you have more questions, please ask them. From scarblac@pino.selwerd.nl Wed Jan 30 11:06:53 2002 From: scarblac@pino.selwerd.nl (Remco Gerlich) Date: Wed, 30 Jan 2002 12:06:53 +0100 Subject: [Tutor] Spurious primes In-Reply-To: <000701c1a97b$18dea300$7a1a8690@sarney>; from sarney@bigpond.com on Wed, Jan 30, 2002 at 09:41:54PM +1100 References: <000701c1a97b$18dea300$7a1a8690@sarney> Message-ID: <20020130120653.A16875@pino.selwerd.nl> On 0, Sarney wrote: > Dear list members, > > I'm attempting to 'think like a computer scientist'. To this end, I set > myself a trivial exercise of generating a list of primes. I thought I had > succeeded with the function below (after much gnashing of teeth & re-reading > tutorials). My pride was dashed when my I asked for 7 primes and got > (2,3,5,7,11,13,16). After some more testing, I realised it was spitting out > these spurious primes after testing a number with more than one factor in > the list 'a' (e.g 15 & 21). > > Where have I gone wrong? > > Regards, Robert > ________________________ > > a = [2] > > def test(x,a): > for i in a: > if x%i == 0: > x = x + 1 > test(x,a) > > else: > return x The problem is here. Say, you test 15, the list of primes so far is [2,3,5,7,11,13]. 15 is not divisable by 2, but it is divisable by 3. Now what happens? x is increased, so we start testing 16. Also, test(16,a) is a called again - but its result is thrown away, so that call does nothing! Now the bug: we're still counting i, so 16 won't be tested against 2 and 3, but the first test is if it's divisable by 5. > num = int(raw_input("how many primes do you want? ")) > > while len(a) <= num - 1: > a.append(test(a[-1]+1,a)) > > > print a You're making it too complicated by making a function that tests if the number is prime, *and* tries to find the next prime in case it isn't. Do just one thing. If you turn test(x, a) into a function that returns 1 if the number is prime and 0 if it isn't, you can change the loop into x = 3 a = [2] while len(a) < num: if test(x, a): a.append(x) x += 1 I think you can write the test function yourself. Also - please use better variable names. Often just chosing a good variable name makes it obvious that a function or variable is trying to be two things instead of one. Like "candidate" and "primelist" for x and a would make the code clearer already. There are more efficient ways to get primes - for instance, to get all the primes between 2 and n, start with range(2,n+1). Then repeat: 1.The first number is prime, add it to primelist 2.Delete all multiples of this number rom the list. This is called the Sieve of Eratosthenes. -- Remco Gerlich From rufmetal@rogers.com Wed Jan 30 13:54:28 2002 From: rufmetal@rogers.com (Chris Keelan) Date: Wed, 30 Jan 2002 08:54:28 -0500 Subject: [Tutor] Please read this and respond to me. [what to do with "hacker" requests?] In-Reply-To: References: <20020129212641.61b159f6.rufmetal@rogers.com> Message-ID: <20020130085428.66d7a31b.rufmetal@rogers.com> Wed, 30 Jan 2002 02:27:05 -0800 (PST): In attempt to throw the authorities off his trail, Danny Yoo transmitted: > We do get quite a lot people here who use the work "hacker" in the > positive sense. Eric Raymond's recommendation that beginner hackers pick > up a language like Python is also a factor that makes the situation > ambiguous. Yes, I recognize this now. > I personally felt the reprimand was a little too sharp... But in > hindsight, Andrei read the situation accurately. Mea maxima culpa. > Anyway, if this situation happens again, let's do make sure that they get > the link to ESR's essay. If they're truly interested in learning, they'll > come back and tell us we're just a bunch of worry warts, and that of > course they mean "hacker" in the finest sense of the word. As I hinted, the overwhelming generosity of most people "here" and the fact that they will offer it to the "beginningest" of beginners puts my attitude to shame. I've apparently spent just a little too much time on usenet and have more to learn than just programming. ~ C From alan.gauld@bt.com Wed Jan 30 13:23:32 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Wed, 30 Jan 2002 13:23:32 -0000 Subject: [Tutor] my pet project (long) Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C30E@mbtlipnt02.btlabs.bt.co.uk> Some initial ideas.... > program that allows me to maintain players' ranking players => a list of some kind ranking => sorting said list according to some criteria Fortunately the list class contains a methjod to sort contents. Better still it allows us to pass in a selection function to control how the sort operates. > duplicate games and use a designated program to score these > games. Among other things it creates text files Need to read files, extract the info needed and create list readlines(), string.split(), and maybe string.strip() should come in handy. > - how to use this individual player result to update the ranking > table/file? This would take: > - player's current ranking (first entry = 50.00), > - partner's current ranking, > - last game Pct for this pair, and maybe > - the average ranking of all players in the game. This needs to be turned into the selection function passed to sort() > I want to include the last 8 games in these calculations > and produce a current club ranking list for players that > participated at least in 4 out of the last 8 games. Lets leave this bit till we get the other stuff working? > would appreciate any advice from you. Some pointers for places to look, I'm sure others will go further :-) Alan g. Author of the 'Learning to Program' web site http://www.freenetpages.co.uk/hp/alan.gauld From pythontutor@venix.com Wed Jan 30 13:31:27 2002 From: pythontutor@venix.com (Lloyd Kvam) Date: Wed, 30 Jan 2002 08:31:27 -0500 Subject: [Tutor] Request Timeout References: <20020130020524.97741.qmail@web14704.mail.yahoo.com> <20020130051537.GA13432@dman.ddts.net> Message-ID: <3C57F5AF.1030204@venix.com> I have been to sites that do sometimes take a long time to return results. http://www.traceroute.org/#USA traceroute.org http://www.net.cmu.edu/cgi-bin/netops.cgi Network Group Services I believe there is a way for the web server to return a "keep-alive" so the browser does not time out. Unfortunately, I do not know where to send you to get documentation on this. I presume it is part of HTTP 1.1. [repeated because the first try used the wrong reply-to address.] dman wrote: > On Tue, Jan 29, 2002 at 06:05:24PM -0800, Titu Kim wrote: > | I am writing a cgi script in python which posts a > | query to Oracle db. WHen the query takes long time, my > | browser get timeout message. How can i fix this > | problem to avoid timeout? I am not sure which side > | issue timeout(either browser, apache, or python cgi > | script). How can i fix this problem to make browser > | waits as long as it takes for oracle to return result? > | Thanks. > > It's the browser that times out -- it figures the web server ain't > there if it's not saying anything. The best solution is to use some > sort of persistant handler with a pool of db connections. When a > request arrives it is given to a running process (persistant cgi, zope > object, whatever middleware you choose) that already has a connection > to Oracle. Thus the time to create a connection is eliminated. > > (a not-really-a-solution solution is to increase the timeout values in > your browser, but then every visitor of your site has to do that too) > > HTH, > -D > > -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From m_konermann@gmx.de Wed Jan 30 16:34:53 2002 From: m_konermann@gmx.de (Keule) Date: Wed, 30 Jan 2002 17:34:53 +0100 Subject: [Tutor] Binding problems with a new .dll file under windowsXP Message-ID: <3C5820AD.9090501@gmx.de> --------------020709000701010500090308 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 8bit Hi @ All ! I´ve got an .dll file, produced by Visual C++ named simannealfilec.dll and i also produced a shadow class named simannealfile.py. The article in the `SWIG Users Guide` says, that the only thing i have to do for using the new extension module is, that i have to import it in my main program by the usual import routine, but after running it under Pythonwin the following error appears: PythonWin 2.1.1 (#20, Jul 20 2001, 01:19:29) [MSC 32 bit (Intel)] on win32. Portions Copyright 1994-2001 Mark Hammond (MarkH@ActiveState.com) - see 'Help/About PythonWin' for further copyright information. >>> Traceback (most recent call last): File "C:\Python21\Pythonwin\pywin\framework\scriptutils.py", line 396, in ImportFile reload(sys.modules[modName]) File "C:\Arbeit_Diplomarbeit\__Optimierer\AG_TEMdll\mainko.py", line 2, in ? import simannealfile File "C:\Arbeit_Diplomarbeit\__Optimierer\AG_TEMdll\simannealfile.py", line 2, in ? import simannealfilec ImportError: No module named simannealfilec Traceback (most recent call last): File "C:\Python21\Pythonwin\pywin\framework\scriptutils.py", line 301, in RunScript exec codeObject in __main__.__dict__ File "C:\Arbeit_Diplomarbeit\__Optimierer\AG_TEMdll\mainko.py", line 5, in ? instance1=simannealfile.simulated_annealing AttributeError: 'simannealfile' module has no attribute 'simulated_annealing' >>> I think there are binding problems with the new simannealfilec.dll . Have anyone got an idea ? Thanks a lot Marcus --------------020709000701010500090308 Content-Type: text/html; charset=us-ascii Content-Transfer-Encoding: 7bit Hi @ All !

I´ve got an .dll file, produced by Visual C++ named simannealfilec.dll and i also produced a shadow class named simannealfile.py.
The article in the `SWIG Users Guide` says, that the only thing i have to do for using the new extension module is, that i have to import it in my main program by the usual
import routine, but after running it under Pythonwin the following error appears:


PythonWin 2.1.1 (#20, Jul 20 2001, 01:19:29) [MSC 32 bit (Intel)] on win32.
Portions Copyright 1994-2001 Mark Hammond (MarkH@ActiveState.com) - see 'Help/About PythonWin' for further copyright information.
>>> Traceback (most recent call last):
  File "C:\Python21\Pythonwin\pywin\framework\scriptutils.py", line 396, in ImportFile
    reload(sys.modules[modName])
  File "C:\Arbeit_Diplomarbeit\__Optimierer\AG_TEMdll\mainko.py", line 2, in ?
    import simannealfile
  File "C:\Arbeit_Diplomarbeit\__Optimierer\AG_TEMdll\simannealfile.py", line 2, in ?
    import simannealfilec
ImportError: No module named simannealfilec
Traceback (most recent call last):
  File "C:\Python21\Pythonwin\pywin\framework\scriptutils.py", line 301, in RunScript
    exec codeObject in __main__.__dict__
  File "C:\Arbeit_Diplomarbeit\__Optimierer\AG_TEMdll\mainko.py", line 5, in ?
    instance1=simannealfile.simulated_annealing
AttributeError: 'simannealfile' module has no attribute 'simulated_annealing'
>>>

I think there are binding problems with the new simannealfilec.dll .
Have anyone got an idea ?

Thanks a lot
Marcus
--------------020709000701010500090308-- From James.Alexander.McCarney@Cognicase.com Wed Jan 30 17:13:32 2002 From: James.Alexander.McCarney@Cognicase.com (McCarney, James Alexander) Date: Wed, 30 Jan 2002 12:13:32 -0500 Subject: [Tutor] When you write the script how is it interpreted? Message-ID: <23FD7B1A77E8D211BCB900001D108C02018B296E@camelot> This is something I have wondered. When I write a script and Py interprets it, how does Py compile it? Could anyone direct me to some FAQs or really high-level dirt on the matter. TiA. James Alexander McCarney, technical writer (450) 928-3386 x2262 Cognicase - M3i Systems, 1111 Saint-Charles Avenue West 11th Floor, East Tower, Longueuil, Quebec, J4K 5G4 Canada http://www.m3isystems.com mailto:James.Alexander.McCarney@Cognicase.com From scarblac@pino.selwerd.nl Wed Jan 30 17:16:41 2002 From: scarblac@pino.selwerd.nl (Remco Gerlich) Date: Wed, 30 Jan 2002 18:16:41 +0100 Subject: [Tutor] When you write the script how is it interpreted? In-Reply-To: <23FD7B1A77E8D211BCB900001D108C02018B296E@camelot>; from James.Alexander.McCarney@Cognicase.com on Wed, Jan 30, 2002 at 12:13:32PM -0500 References: <23FD7B1A77E8D211BCB900001D108C02018B296E@camelot> Message-ID: <20020130181641.A17829@pino.selwerd.nl> On 0, "McCarney, James Alexander" wrote: > This is something I have wondered. When I write a script and Py interprets > it, how does Py compile it? > Could anyone direct me to some FAQs or really high-level dirt on the matter. > TiA. How do you mean? It parses the code, then compiles it to Python bytecode. The bytecodes are run by the Python interpreter (they're stored in the .pyc file so the same .py file only has to be compiled once if it doesn't change). I'm not sure what part of this you need high level information on. Basically this is the highest level view, as a next step you could look at the C source :) -- Remco Gerlich From kimtitu@yahoo.com Wed Jan 30 18:39:23 2002 From: kimtitu@yahoo.com (Titu Kim) Date: Wed, 30 Jan 2002 10:39:23 -0800 (PST) Subject: [Tutor] Request Timeout In-Reply-To: <3C57F5AF.1030204@venix.com> Message-ID: <20020130183923.73818.qmail@web14708.mail.yahoo.com> Thank you very much dman and Lloyd. I will look into it. --- Lloyd Kvam wrote: > I have been to sites that do sometimes take a long > time to return results. > > http://www.traceroute.org/#USA > traceroute.org > http://www.net.cmu.edu/cgi-bin/netops.cgi > Network Group Services > > I believe there is a way for the web server to > return a "keep-alive" so the browser > does not time out. Unfortunately, I do not know > where to send you to > get documentation on this. I presume it is part of > HTTP 1.1. > > [repeated because the first try used the wrong > reply-to address.] > > dman wrote: > > > On Tue, Jan 29, 2002 at 06:05:24PM -0800, Titu Kim > wrote: > > | I am writing a cgi script in python which posts > a > > | query to Oracle db. WHen the query takes long > time, my > > | browser get timeout message. How can i fix this > > | problem to avoid timeout? I am not sure which > side > > | issue timeout(either browser, apache, or python > cgi > > | script). How can i fix this problem to make > browser > > | waits as long as it takes for oracle to return > result? > > | Thanks. > > > > It's the browser that times out -- it figures the > web server ain't > > there if it's not saying anything. The best > solution is to use some > > sort of persistant handler with a pool of db > connections. When a > > request arrives it is given to a running process > (persistant cgi, zope > > object, whatever middleware you choose) that > already has a connection > > to Oracle. Thus the time to create a connection > is eliminated. > > > > (a not-really-a-solution solution is to increase > the timeout values in > > your browser, but then every visitor of your site > has to do that too) > > > > HTH, > > -D > > > > > > > -- > Lloyd Kvam > Venix Corp. > 1 Court Street, Suite 378 > Lebanon, NH 03766-1358 > > voice: > 603-443-6155 > fax: > 801-459-9582 > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor __________________________________________________ Do You Yahoo!? Great stuff seeking new owners in Yahoo! Auctions! http://auctions.yahoo.com From Daniel.Kinnaer@Advalvas.be Wed Jan 30 19:05:21 2002 From: Daniel.Kinnaer@Advalvas.be (Daniel Kinnaer) Date: Wed, 30 Jan 2002 20:05:21 +0100 Subject: [Tutor] Setting the system time In-Reply-To: Message-ID: There are various ways to _get_ the system time >>> time1 = time.localtime(time.time()) >>> print time1 (2002, 1, 30, 19, 56, 8, 2, 30, 0) What is the way to _set_ a system time (to another value)? I suppose I'll need mktime() for this as well? >>> print time.mktime(time1) 1012416968.0 All help greatly appreciated! best regards, Daniel From dyoo@hkn.eecs.berkeley.edu Thu Jan 31 01:01:01 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 30 Jan 2002 17:01:01 -0800 (PST) Subject: [Tutor] When you write the script how is it interpreted? [parsing/compiling] In-Reply-To: <20020130181641.A17829@pino.selwerd.nl> Message-ID: On Wed, 30 Jan 2002, Remco Gerlich wrote: > On 0, "McCarney, James Alexander" wrote: > > This is something I have wondered. When I write a script and Py interprets > > it, how does Py compile it? > > Could anyone direct me to some FAQs or really high-level dirt on the matter. > > TiA. > > How do you mean? > > It parses the code, Parsing takes chunks of the program text, and figures out the relationships between all the pieces. As an analogy, we can form a "tree" out of a sentence, like "I am Tarzan!": sentence +------+-------+ / | \ / | \ subject verb object | | | I am Tarzan! A large part of understanding a language is figuring out the structure and relationships between the words. Likewise, a Python parser needs to do the same sort of tree-building with the Python grammar as one of the first steps in generating bytecode. If we're interested in this sort of stuff, we can take a look at: http://www.python.org/doc/current/ref/ref.html where the docs explain Python grammatical structure in more detail. There's also a module called 'parser' that will do the tree building for us: http://www.python.org/doc/lib/module-parser.html Parsing is an involving topic, but it's been so well developed that we can use parsing tools without really having to worry about how these tools actually work. *grin* It's quite cool that parsing technology is very much related to the work of linguists like Noam Chomsky. Anyway, once Python parses source code into a tree, it now has it in a form that's more digestible. Now it can reduce it into even smaller chunks called "bytecodes". We can see an example of what bytecode looks like by using the 'dis' module: ### >>> import dis >>> def gcd(a, b): ... if b == 0: return a ... return gcd(b, a % b) ... >>> dis.dis(gcd) 0 SET_LINENO 1 3 SET_LINENO 2 6 LOAD_FAST 1 (b) 9 LOAD_CONST 1 (0) 12 COMPARE_OP 2 (==) 15 JUMP_IF_FALSE 11 (to 29) 18 POP_TOP [... rest of the decompiled code cut for brevity.] ### The compiler probably does a case-by-case analysis of a program when it translates a parse tree into these elementary bytecodes --- if it's processing an 'if', then it needs to set up a way of jumping around code if the test returns false. Take a look at: http://www.python.org/doc/lib/module-dis.html for a list of the primitive bytecodes that Python uses. It's a surprising fact that the high level concepts that we work with in Python can be reduced to such simple operations as LOADing and JUMPing. > then compiles it to Python bytecode. The bytecodes are run by the > Python interpreter (they're stored in the .pyc file so the same .py > file only has to be compiled once if it doesn't change). I'm not sure > what part of this you need high level information on. Basically this > is the highest level view, as a next step you could look at the C > source :) Python 2.2 now comes with a 'compiler' module that implements the Python bytecode compiler in Python: http://www.python.org/doc/lib/compiler.html (I'm actually trying to learn how the compiler works myself; I'd love to do a project that compiles Scheme into Python bytecodes just for the perversity of it all. *grin*) From dyoo@hkn.eecs.berkeley.edu Thu Jan 31 01:18:16 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 30 Jan 2002 17:18:16 -0800 (PST) Subject: [Tutor] A Portuguese translations of "One Day of IDLE Toying" now up Message-ID: Hi everyone, Fernando Manas Ferreira has contributed the Portuguese translation to the "One Day of IDLE Toying" tutorial. I'm very floored and happy about this. Fernando's translation has been linked to the main site here: http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/index.html Thank you again for your help! From dsh8290@rit.edu Thu Jan 31 03:41:51 2002 From: dsh8290@rit.edu (dman) Date: Wed, 30 Jan 2002 22:41:51 -0500 Subject: [Tutor] Setting the system time In-Reply-To: References: Message-ID: <20020131034151.GA25837@dman.ddts.net> On Wed, Jan 30, 2002 at 08:05:21PM +0100, Daniel Kinnaer wrote: | | | There are various ways to _get_ the system time | >>> time1 = time.localtime(time.time()) | >>> print time1 | (2002, 1, 30, 19, 56, 8, 2, 30, 0) Yeah, this is easy. | What is the way to _set_ a system time (to another value)? What's your system and what privileges do you have? On *nix (well, linux at least) systems the 'date' program can be used (by root only) to set the current system time and the 'hwclock' program can be used (also by root only) to set the hardware clock's time and/or to update the system clock with the data from the hardware clock. On windows you right click on the clock in the task bar and click some more buttons to specify the new current time. If you have a NT variant you must have administrator privileges to change the time. The reason for the restriction is you don't want any Joe User to fiddle with the clock. After all, time marches on (from our perspective anyways) and there is no reason to have user intervention. The only time a human must change the clock's settings is if the clock goes haywire for some reason (CMOS battery dies, timezone has changed and your sytem doesn't understand that[1]). I'm sure that each system has a programmatic interface for resetting the clock, but that will be very system dependent and will also require that your program run with the privileges needed for tweaking the system's clock. Normally programs don't try and reset time anyways. Why do you want to be able to set the system clock? Is it just so you can do some sort of calculations with time objects? There's no need to change the system clock for just that -- simply create the time objects you want and pass them around. -D [1] This means all Windows systems -- they *assume* the hardware clock is in local time and changing the timezone setting in windows has no effect on that (it just assumes it means the local time for the new timezone you pick). This contrasts with my linux boxes which I have (choosen to) set the hardware clock to UTC and changing the timezone on the system causes a new calculation of local time and thus localtime is always local without resetting the clock. -- Better a little with righteousness than much gain with injustice. Proverbs 16:8 From paulsid@shaw.ca Wed Jan 30 23:32:10 2002 From: paulsid@shaw.ca (Paul Sidorsky) Date: Wed, 30 Jan 2002 16:32:10 -0700 Subject: [Fwd: Re: [Tutor] When you write the script how is it interpreted?] Message-ID: <3C58827A.CD0CF8DB@shaw.ca> Whoops, I knew some day I'd reply to the wrong list... -------- Original Message -------- Subject: Re: [Tutor] When you write the script how is it interpreted? Date: Wed, 30 Jan 2002 16:31:39 -0700 From: Paul Sidorsky To: "python-list@python.org" References: <23FD7B1A77E8D211BCB900001D108C02018B296E@camelot> "McCarney, James Alexander" wrote: > This is something I have wondered. When I write a script and Py interprets > it, how does Py compile it? This doesn't seem too clear. If you mean how the syntax and stuff is processed, the language reference is probably where you should go: http://www.python.org/doc/current/ref/ref.html If you mean how things actually work internally, then you probably should start with the docs for the dis module: http://www.python.org/doc/current/lib/module-dis.html (Specifically, the byte code reference might be useful.) > Could anyone direct me to some FAQs or really high-level dirt on the matter. The above aren't all that high-level but you probably aren't going to find much better since this kind of thing isn't exactly an area of general interest. -- ====================================================================== Paul Sidorsky Calgary, Canada paulsid@shaw.ca http://members.shaw.ca/paulsid/ From idiot1@netzero.net Thu Jan 31 06:48:08 2002 From: idiot1@netzero.net (kirk Bailey) Date: Thu, 31 Jan 2002 01:48:08 -0500 Subject: [Tutor] CHORTLING OVER MY KEYBOARD Message-ID: <3C58E8A8.859210E6@netzero.net> AS I POISON VENEMOUS RATS, I HUM A LOVELY TUNE, WITH A SMILE UPON MY FACE, FOR A PROGRAM IS NOT OFFERED TO FEED SO MUCH BILGE TO SPAMBOTS HARVESTING EMAIL THAT IT SURPASSES IMAGINING. In breif, I have now a little script which cranks out entirely plausible email addresses by the SCORE on demand. Actually, about 50 at a shot. And if you were so rash as toclick on them, you would get a letter popup. Every last one is randomly generated, intended to poison spambots harvesting email addresses. Now some spambots do not visit pages generated by scripts, but a html page with a ssi looks like normal html to a browser- or a bot- and therefore one could run this with MINOR modifications in a ssi include page, and poison the spam harvesting community. Just for giggles, here's the url. Script offered on request. http://www.tinylist.org/cgi-bin/poison.py -- -Respectfully, -Kirk D Bailey Consulting Loose Cannon end www.howlermonkey.net highprimate@howlermonkey.net www.sacredelectron.org idiot1@netzero.net www.tinylist.org grumpy@tinylist.org ---------------------------------------------------- Sign Up for NetZero Platinum Today Only $9.95 per month! http://my.netzero.net/s/signup?r=platinum&refcd=PT97 From flash1210@hotmail.com Thu Jan 31 06:49:47 2002 From: flash1210@hotmail.com (Frank Holmes) Date: Wed, 30 Jan 2002 22:49:47 -0800 Subject: [Tutor] class question Message-ID: I have a question concerning one of the class examples given in O'Reilly's book "Learning Python" the following example is given: >>>class adder: def __init__(self, value=0): self.data=value #initialize data def __add__(self, other): self.data=self.data + other #add other in-place def __repr__(self): return `self.data` #convert to string ... ... >>>x=adder(1) #__init__ >>>x=2; x=2 #__add__ >>>x #__repr__ 5 I am not understanding this at all. In assigning x=adder(1), self.data is given the value 1, right? x+2; x+2 should = 1+2; 1+2 ??? I am missing the point completely..... help _________________________________________________________________ Get your FREE download of MSN Explorer at http://explorer.msn.com/intl.asp. From glingl@aon.at Thu Jan 31 08:14:50 2002 From: glingl@aon.at (Gregor Lingl) Date: Thu, 31 Jan 2002 09:14:50 +0100 Subject: [Tutor] class question References: Message-ID: <004f01c1aa2f$5ae70940$1664a8c0@mega> Dear Frank! > I have a question concerning one of the class examples given in O'Reilly's > book "Learning Python" > > the following example is given: > > >>>class adder: > def __init__(self, value=0): > self.data=value #initialize data > def __add__(self, other): > self.data=self.data + other #add other in-place > def __repr__(self): > return `self.data` #convert to string > ... > ... > >>>x=adder(1) #__init__ > >>>x=2; x=2 #__add__ > >>>x #__repr__ > 5 > This certainly is a typo! It should read: >>> x = adder(1) >>> x+2; x+2 >>> x 5 >>> which is equivalent to >>> x = adder(1) >>> x+2 >>> x+2 >>> x 5 >>> >>> x+2 is a call of the __add__()-method of the adder-object x so it changes the x.data first to 3 then to 5 The last statement >>> x is a call of x.__repr__() and produces a printable representation of x.data, i. e. 5 (in this case). Because of the lack of a return-statement in __add__() (a somewhat strange feature) the statement x+2 returns None and you cannot use >>> x = x+2 as one would expect. Hope that helps Gregor From karthikg@aztec.soft.net Thu Jan 31 16:51:57 2002 From: karthikg@aztec.soft.net (Karthik Gurumurthy) Date: Thu, 31 Jan 2002 22:21:57 +0530 Subject: [Tutor] looking for source code In-Reply-To: <20020130181641.A17829@pino.selwerd.nl> Message-ID: hi all, where can i find the source code for map(), filter() , reduce() ,property(),staticmethod() etc? i know that it is in the __builtins__ module. I thought every module has an attribute something along the lines "__file__" which w'd give the actual location of the module. But i c'd'nt find one for __builtins__ OR I might be wrong! OR have these constructs been implemented in C ? so am not able to find one? thanks, karthik. From kalle@gnupung.net Thu Jan 31 16:48:44 2002 From: kalle@gnupung.net (Kalle Svensson) Date: Thu, 31 Jan 2002 17:48:44 +0100 Subject: [Tutor] looking for source code In-Reply-To: References: <20020130181641.A17829@pino.selwerd.nl> Message-ID: <20020131164844.GB20520@sandra.lysator.liu.se> [Karthik Gurumurthy] > where can i find the source code for map(), filter() , reduce() > ,property(),staticmethod() etc? [...] > have these constructs been implemented in C ? so am not able to find one? Yes, they are implemented in C. The source code is available, and is relatively easy to read (compared to other C code I've encountered). Peace, Kalle -- Kalle Svensson (kalle@gnupung.net) - Laziness, impatience, hubris: Pick two! English: http://www.gnupung.net/ Svenska: http://www.lysator.liu.se/~kalle/ Stuff: ["http://www.%s.org/" % x for x in "gnu debian python emacs".split()] From alan.gauld@bt.com Thu Jan 31 17:14:35 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Thu, 31 Jan 2002 17:14:35 -0000 Subject: [Tutor] Setting the system time Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C324@mbtlipnt02.btlabs.bt.co.uk> > There are various ways to _get_ the system time > >>> time1 = time.localtime(time.time()) > What is the way to _set_ a system time (to another value)? I'm not sure Python has a module function for this - but based on past experience someone will find one somewhere! However one thing to rememnber is that on most OSs this is an administrator or root privilege thing and so if your program doesn't run as root it won't work... Assuming Python doesn't do it I guess you might be able to use os.system to do it. Certainly on DOS/Win 9x that would work with the "time" command. On *nix you would use the "date" command as root. Also be aware that on networks the time is often set on bootup from a central timeserver so setting it locally will only work until next bootup. > I suppose I'll need mktime() for this as well? > >>> print time.mktime(time1) > 1012416968.0 I don't tink mktime will help here, it just creates a local 'time object' within your program. Alan g. From alan.gauld@bt.com Thu Jan 31 17:21:37 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Thu, 31 Jan 2002 17:21:37 -0000 Subject: [Tutor] class question Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C325@mbtlipnt02.btlabs.bt.co.uk> > >>>class adder: > def __init__(self, value=0): > self.data=value #initialize data > def __add__(self, other): > self.data=self.data + other #add other in-place So adding updates the internal value, see below... > def __repr__(self): > return `self.data` #convert to string > ... > ... > >>>x=adder(1) #__init__ > >>>x=2; x=2 #__add__ Assuming x=2 should be x+2.... This adds 2 to x twice, so after the first time x=3, then second time round x = 5 > >>>x #__repr__ > 5 Which is what we see here. Alan g. Author of the 'Learning to Program' web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld@bt.com Thu Jan 31 18:06:57 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Thu, 31 Jan 2002 18:06:57 -0000 Subject: [Tutor] looking for source code Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C326@mbtlipnt02.btlabs.bt.co.uk> > where can i find the source code for map(), filter() , reduce() > ,property(),staticmethod() etc? In the C source for Python. > i know that it is in the __builtins__ module. Which is actually built in to Python, as the name suggests. > I thought every module has an attribute something along the > lines "__file__" which w'd give the actual location of the module. But builtins is actually built in, its not a normal module. In fact its not really a module at all it just looks like one from the outside! > have these constructs been implemented in C ? so am not able > to find one? Yes, they are in C. As are many of the other modules, like sys... Alan g. From overlord@netdoor.com Thu Jan 31 19:11:40 2002 From: overlord@netdoor.com (Jim Ragsdale) Date: Thu, 31 Jan 2002 13:11:40 -0600 Subject: [Tutor] read file and match string Message-ID: <009201c1aa8b$1d48f060$8cd91282@echo6> Warning: Novice python programmer :) I was suggested this snippet of code to read a possible long file and do a string match. it is supposed to be faster. import mmap, re def search(filename, rx): f = open(filename, 'r+') mem = mmap.mmap(f.fileno(), 0) for match in rx.finditer(mem): print match.group(0) mem.close() f.close() This is what i am running now. import sys, re, os, time p = re.compile('PLAYER_JOIN') ReadFile = sys.argv[1] WriteFile = sys.argv[2] rf = open(ReadFile, 'r') wf = open(WriteFile, 'w') for line in rf.xreadlines(): m = p.search(line) if m: wf.writelines(line) wf.close rf.close Can someone explain the top snippet to me? looks like a function that takes a filename argument and what is the rx? What is the string to match the file against? Is that the rx arg? Is this what is needed for what i am doing or is it slightly different? The mem line looks like it opens the file like xreadlines. Any help would be appreciated. Thanks! Jim Ragsdale From tbost@ifarm.com Thu Jan 31 20:40:41 2002 From: tbost@ifarm.com (Tracy Bost) Date: Thu, 31 Jan 2002 14:40:41 -0600 (CST) Subject: [Tutor] Opening a file in Windows Enviroment Message-ID: <1012509641.3c59abc953031@mail.ifarm.com> I'm having a hard time opening a file in windows using the "open" function. It seems it doesn't like the ":" in the path name. for example filename = 'C:\test.txt' open(filename,'r+') gives me an ugly error everytime : IOError: [Errno 22] Invalid argument: 'C:\text.txt' Please help. Thank you ------------------------------------------------------------------------------ Visit "The Most Powerful Tool on the Farm" at http://www.ifarm.com Get the latest on Ag News, Market Reports, FREE email, and much more. From israel@lith.com Thu Jan 31 20:53:14 2002 From: israel@lith.com (Israel Evans) Date: Thu, 31 Jan 2002 12:53:14 -0800 Subject: [Tutor] Opening a file in Windows Enviroment Message-ID: You've got a couple of options here. You can make the string you are passing a "raw" string by prepending the string with r as follows::: r'C:\text.txt' This keeps the string as it is with no magical backspace/escape character fun. The one problem can be when you end your string with a \ . This will escape the trailing ' . which can be bad. You can also just use forward slashes. Windows also like those, though it doesn't like to talk about it. Your problem is actually with the backslashes. They, coupled with whatever follows them are parsed as special characters. \n Is end of line. \t is tab. And so on... ~Israel~ -----Original Message----- From: Tracy Bost [mailto:tbost@ifarm.com] Sent: 31 January 2002 12:41 PM To: Python Tutor Mailing List Subject: [Tutor] Opening a file in Windows Enviroment I'm having a hard time opening a file in windows using the "open" function. It seems it doesn't like the ":" in the path name. for example filename = 'C:\test.txt' open(filename,'r+') gives me an ugly error everytime : IOError: [Errno 22] Invalid argument: 'C:\text.txt' Please help. Thank you ---------------------------------------------------------------------------- -- Visit "The Most Powerful Tool on the Farm" at http://www.ifarm.com Get the latest on Ag News, Market Reports, FREE email, and much more. _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From cheshire_cat_sf@yahoo.com Thu Jan 31 21:15:25 2002 From: cheshire_cat_sf@yahoo.com (Britt Green) Date: Thu, 31 Jan 2002 13:15:25 -0800 (PST) Subject: [Tutor] List of Objects? In-Reply-To: Message-ID: <20020131211525.40906.qmail@web14101.mail.yahoo.com> Say I have a class called Rooms that looks something like this: class Rooms: def __init__(self, name, desc, exits): self.name = name self.desc = desc self.exits = exits Now, what I'm trying to do is to create a dozen or so rooms. I know I could do it like this: thePorch = Rooms(...) theKitchen = Rooms(...) theAttic = Rooms(...) ...etc... but this seems awfully tedious. It seems like creating an array of rooms would be much easier. I know that Python doesn't support arrays, and using a list would be the way to go. However, I'm not sure how to create a list of objects. Could anyone point me in the right direction? Britt ===== "The ocean, she is strange and wondrous, filled with animals that disturb even a Frenchman." __________________________________________________ Do You Yahoo!? Great stuff seeking new owners in Yahoo! Auctions! http://auctions.yahoo.com From pythontutor@venix.com Thu Jan 31 21:37:22 2002 From: pythontutor@venix.com (Lloyd Kvam) Date: Thu, 31 Jan 2002 16:37:22 -0500 Subject: [Tutor] List of Objects? References: <20020131211525.40906.qmail@web14101.mail.yahoo.com> Message-ID: <3C59B912.6060300@venix.com> class Rooms: def __init__(self, name, desc, exits): self.name = name self.desc = desc self.exits = exits make_rooms = ( ( 'theKitchen', 'kitchen with dishwasher', 2), ( 'thePorch', 'porch needs new screens', 3), ( 'theAtic', 'attic with pull down steps',1), ) avail_rooms = {} for room in make_rooms: # create room instances and store them in avail_rooms dictionary # using the name of the room as the key avail_rooms[room[0]] = Rooms( room[0], room[1], room[2]) This will create Rooms using the list (really tuples) of values in make_rooms and store them in the dictionary avail_rooms using the name as the key. If you'd rather, you could make avail_rooms a list, but then you would need to access rooms by index number. I hope this helps. Britt Green wrote: > Say I have a class called Rooms that looks something like this: > > class Rooms: > def __init__(self, name, desc, exits): > self.name = name > self.desc = desc > self.exits = exits > > Now, what I'm trying to do is to create a dozen or so rooms. I know I > could do it like this: > > thePorch = Rooms(...) > theKitchen = Rooms(...) > theAttic = Rooms(...) > ...etc... > > but this seems awfully tedious. It seems like creating an array of > rooms would be much easier. I know that Python doesn't support arrays, > and using a list would be the way to go. However, I'm not sure how to > create a list of objects. Could anyone point me in the right direction? > > Britt > > ===== > "The ocean, she is strange and wondrous, filled with animals that disturb even a Frenchman." > > __________________________________________________ > Do You Yahoo!? > Great stuff seeking new owners in Yahoo! Auctions! > http://auctions.yahoo.com > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From karthikg@aztec.soft.net Thu Jan 31 21:57:51 2002 From: karthikg@aztec.soft.net (Karthik Gurumurthy) Date: Fri, 1 Feb 2002 03:27:51 +0530 Subject: [Tutor] List of Objects? In-Reply-To: <20020131211525.40906.qmail@web14101.mail.yahoo.com> Message-ID: > class Rooms: def __init__(self, name, desc, exits): self.name = name self.desc = desc self.exits = exits > but this seems awfully tedious. It seems like creating an array of > rooms would be much easier. I know that Python doesn't support arrays, > and using a list would be the way to go. However, I'm not sure how to > create a list of objects. Could anyone point me in the right direction? params = [ [name1,desc1,exits1],[name2,desc2,exits2],[name3,desc3,exits3]] listofRooms = map(lambda params:apply(Rooms,params),params) is this ok? karthik. From Daniel.Kinnaer@Advalvas.be Thu Jan 31 21:59:44 2002 From: Daniel.Kinnaer@Advalvas.be (Daniel Kinnaer) Date: Thu, 31 Jan 2002 22:59:44 +0100 Subject: [Tutor] Re: Setting the system time In-Reply-To: Message-ID: Thanks for your replies. Meanwhile, I'm only halfway on how to set the systemtime. That is, I've found how to do this on a Windows-box (We use W2k at work). if sys.platform == 'win32': import win32api win32api.SetSystemTime() #by Mark Hammond I don't know how to go about when setting the systemtime in a Linux environment. Perhaps with the date-command? Is this command the same for all major Linux releases? I need this function in my NTP-client, as to synchronize our Server with the main Server (abroad). I use a socket for this purpose, get the ServerTime via port 37 and transform the given time into a tuple and use that tuple in the win32api.SetSystemTime(). This seems to work out very nicely, as we're about <= 500ms off, which is acceptable... Best regards, Daniel From dyoo@hkn.eecs.berkeley.edu Thu Jan 31 22:04:08 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 31 Jan 2002 14:04:08 -0800 (PST) Subject: [Tutor] my pet project (long) In-Reply-To: Message-ID: On Tue, 29 Jan 2002, Andrzej Kolinski wrote: > I am a total newbie surrounded by Python books and tutorials. Before I > became the one (this was not difficult :-)) I tried to learn a bit of > C (I am glad I did not). I found Python and this mailing are the best > things for what I dream to do. I'm glad to hear you're enjoying things. > This is my pet project. I would like to write a python program that > allows me to maintain players' ranking for our bridge club. This sounds good. Let's see some of the things that you're planning: > - how to get the data from the results file, i.e. how to create a > table/file with each player's name associated with the pair's Pct > (what type of file/string operation applies)? You'll want to get familiar with opening files and reading whole strings from them. A secondary thing is to pull out individual chunks of string. Most tutorials talk about the input and output (IO) that's involved in reading files. Alan's tutorial talks about opening files here: http://www.freenetpages.co.uk/hp/alan.gauld/tutfiles.htm To pull out individual columns from a line of text, we can using a function called string.split(). An example might help show what it does: ### >>> sentence = "the digital information that underlies biochemistry, cell biology, and development can be represented by a simple string of G's, A's, T's and C's." >>> >>> string.split(sentence) ['the', 'digital', 'information', 'that', 'underlies', 'biochemistry,', 'cell', 'biology,', 'and', 'development', 'can', 'be', 'represented', 'by', 'a', 'simple', 'string', 'of', "G's,", "A's,", "T's", 'and', "C's."] >>> >>> string.split(sentence, ',') ['the digital information that underlies biochemistry', ' cell biology', " and development can be represented by a simple string of G's", " A's", " T's and C's."] ### This example shows that we can break up a string into a list of smaller strings, and we have some control over which delimiters Python decides to split on. By default, string.split() will split things up, treating spaces as column boundaries. Play around with string.split() a bit, and you'll get the hang of it quickly. It sounds like you also want to fiddle around with lists. > I want to include the last 8 games in these calculations and produce a For this case, we can say "last 8 elements of a list of games" with something like this: games[-8:] This is called an array slice, and it's very nice because it does allow us to use negative indices, which count backwards from the end of our list. > I want to include the last 8 games in these calculations and produce a > current club ranking list for players that participated at least in 4 > out of the last 8 games. This is very doable. One way we can make this easier to write is to make a function that tells us how many games a person has played in a list of games: ### def countPlayerParticipation(player, games): """Returns the number of times a player has participated in games.""" # ... dunno what this looks like yet... ### If we had such a function, then we can just march down a list of all the players, and pick out the ones in which countPlayerParticipation() is greater than 4. This sounds like a great project! Keep us informed of your progress, and please feel free to ask questions as you're writing it. From pythontutor@venix.com Thu Jan 31 22:15:01 2002 From: pythontutor@venix.com (Lloyd Kvam) Date: Thu, 31 Jan 2002 17:15:01 -0500 Subject: [Tutor] KeyboardInterrupt handler Message-ID: <3C59C1E5.7060805@venix.com> Would it be practical to write a KeyboardInterrupt handler that "resumed" execution? Since the debugger seems to do this kind of thing, I assume the traceback object and its frame list could be used to accomplish a resume. (This is more idle curiosity than any real need.) Searching Google, my books, and the manual failed to come up with anything useful. -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From shalehperry@attbi.com Thu Jan 31 22:37:02 2002 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Thu, 31 Jan 2002 14:37:02 -0800 (PST) Subject: [Tutor] List of Objects? In-Reply-To: Message-ID: On 31-Jan-2002 Karthik Gurumurthy wrote: > >> class Rooms: > def __init__(self, name, desc, exits): > self.name = name > self.desc = desc > self.exits = exits > >> but this seems awfully tedious. It seems like creating an array of >> rooms would be much easier. I know that Python doesn't support arrays, >> and using a list would be the way to go. However, I'm not sure how to >> create a list of objects. Could anyone point me in the right direction? > > params = [ [name1,desc1,exits1],[name2,desc2,exits2],[name3,desc3,exits3]] > > listofRooms = map(lambda params:apply(Rooms,params),params) > > is this ok? > For an obfuscated python contest, sure. For newbie help I would say no. From kalle@gnupung.net Thu Jan 31 22:59:40 2002 From: kalle@gnupung.net (Kalle Svensson) Date: Thu, 31 Jan 2002 23:59:40 +0100 Subject: [Tutor] read file and match string In-Reply-To: <009201c1aa8b$1d48f060$8cd91282@echo6> References: <009201c1aa8b$1d48f060$8cd91282@echo6> Message-ID: <20020131225940.GA28719@sandra.lysator.liu.se> [Jim Ragsdale] > import mmap, re > def search(filename, rx): > f = open(filename, 'r+') > mem = mmap.mmap(f.fileno(), 0) > for match in rx.finditer(mem): > print match.group(0) > mem.close() > f.close() [...] > Can someone explain the top snippet to me? looks like a function > that takes a filename argument and what is the rx? A regular expression object, like re.compile("foo"). > Is this what is needed for what i am doing or is it slightly > different? I believe it's slightly different. The regular expression in the new function should match to the end of the line. If you had p = re.compile("foo") you want rx = re.compile(".*foo.*") now (I think). Also, it prints the results to standard output, instad of writing them to a result file. > The mem line looks like it opens the file like xreadlines. The mem line maps the file into memry, thereby making access to it faster. It might be a bad idea if your file is very large, say as large as your RAM. > Any help would be appreciated. Thanks! If the string you're searching for is simple, it might be faster to use the string find method instead of regular expressions. Also, if you're using an old version of python (1.5.2 or 2.0), try upgrading to 2.1.2 or 2.2, I think the file reading stuff (with xreadlines, like you used first) has been optimized a bit in those newer versions. Also, a warning: I don't use mmap or re very much, and might be totally wrong. I hope somebody will correct me in that case. Peace, Kalle -- Kalle Svensson (kalle@gnupung.net) - Laziness, impatience, hubris: Pick two! English: http://www.gnupung.net/ Svenska: http://www.lysator.liu.se/~kalle/ Stuff: ["http://www.%s.org/" % x for x in "gnu debian python emacs".split()] From overlord@netdoor.com Thu Jan 31 23:41:05 2002 From: overlord@netdoor.com (Jim Ragsdale) Date: Thu, 31 Jan 2002 17:41:05 -0600 Subject: [Tutor] read file and match string References: <009201c1aa8b$1d48f060$8cd91282@echo6> <20020131225940.GA28719@sandra.lysator.liu.se> Message-ID: <00f101c1aab0$c066e7a0$8cd91282@echo6> [Kalle Svensson ] Ok, im searching a log file from an Unreal Tournament server. it generates some output, but im really intested in 1 line: ScriptLog: [PLAYER_JOIN] {RS}]V{AD_l)OG_3 ip.address.omitted:1040 2600 Each line will have ScriptLog: [PLAYER_JOIN] a name and ip:port and another number. The other lines are just different server events and other things of interest. i just want the ip address. The logs can get big. right now it is at 1.5meg and has been running for almost 2 days. The log resets when the server does so i want to save the ip's to a different file so i can keep them thru server restarts and crashes and such. I did the regular expression because that is what i found on the net. Messed w/ it until i got it to match :) And I just upgraded to Python2.2. Using xreadline on a 1.56meg file on my 400celeron laptop takes about .4 sec.( Ran start = time.clock() before and finish = time.clock() after and took the difference) Also used the localtime function to write a date/time stamp in the logfile name(iplog.1.31.2002.5.35.log). Right now im trying to clean it up, use functions and stuff. do it right :) I would like to add some functionality as i go along. Say maybe determine if the log file has been reset and if it hasnt, start from where it left off last time. If it has been restarted, start fresh and maybe start a new output file. Thanks for your input! Ill have to say that python is my favorite language. easy to understand (or at least relativly :) ) and powerful. If i ever figure out oop im sure it will be even better! Hope everyone is able to follow the email. I tried to give it some semblance of order but dont know if I succeeded :) ----- Original Message ----- From: "Kalle Svensson" To: "Python Tutor Mailing List" Sent: Thursday, January 31, 2002 4:59 PM Subject: Re: [Tutor] read file and match string > [Jim Ragsdale] > > import mmap, re > > def search(filename, rx): > > f = open(filename, 'r+') > > mem = mmap.mmap(f.fileno(), 0) > > for match in rx.finditer(mem): > > print match.group(0) > > mem.close() > > f.close() > [...] > > Can someone explain the top snippet to me? looks like a function > > that takes a filename argument and what is the rx? > > A regular expression object, like re.compile("foo"). > > > Is this what is needed for what i am doing or is it slightly > > different? > > I believe it's slightly different. The regular expression in the new > function should match to the end of the line. If you had > p = re.compile("foo") > you want > rx = re.compile(".*foo.*") > now (I think). > Also, it prints the results to standard output, instad of writing them > to a result file. > > > The mem line looks like it opens the file like xreadlines. > > The mem line maps the file into memry, thereby making access to it > faster. It might be a bad idea if your file is very large, say as > large as your RAM. > > > Any help would be appreciated. Thanks! > > If the string you're searching for is simple, it might be faster to > use the string find method instead of regular expressions. Also, if > you're using an old version of python (1.5.2 or 2.0), try upgrading to > 2.1.2 or 2.2, I think the file reading stuff (with xreadlines, like > you used first) has been optimized a bit in those newer versions. > > Also, a warning: I don't use mmap or re very much, and might be > totally wrong. I hope somebody will correct me in that case. > > Peace, > Kalle > -- > Kalle Svensson (kalle@gnupung.net) - Laziness, impatience, hubris: Pick two! > English: http://www.gnupung.net/ Svenska: http://www.lysator.liu.se/~kalle/ > Stuff: ["http://www.%s.org/" % x for x in "gnu debian python emacs".split()] > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From lkvam@venix.com Wed Jan 30 13:27:57 2002 From: lkvam@venix.com (Lloyd Kvam) Date: Wed, 30 Jan 2002 08:27:57 -0500 Subject: [Tutor] Request Timeout References: <20020130020524.97741.qmail@web14704.mail.yahoo.com> <20020130051537.GA13432@dman.ddts.net> Message-ID: <3C57F4DD.40100@venix.com> I have been to sites that do sometimes take a long time to return results. http://www.traceroute.org/#USA traceroute.org http://www.net.cmu.edu/cgi-bin/netops.cgi Network Group Services I believe there is a way for the web server to return a "keep-alive" so the browser does not time out. Unfortunately, I do not know where to send you to get documentation on this. I presume it is part of HTTP 1.1. dman wrote: > On Tue, Jan 29, 2002 at 06:05:24PM -0800, Titu Kim wrote: > | I am writing a cgi script in python which posts a > | query to Oracle db. WHen the query takes long time, my > | browser get timeout message. How can i fix this > | problem to avoid timeout? I am not sure which side > | issue timeout(either browser, apache, or python cgi > | script). How can i fix this problem to make browser > | waits as long as it takes for oracle to return result? > | Thanks. > > It's the browser that times out -- it figures the web server ain't > there if it's not saying anything. The best solution is to use some > sort of persistant handler with a pool of db connections. When a > request arrives it is given to a running process (persistant cgi, zope > object, whatever middleware you choose) that already has a connection > to Oracle. Thus the time to create a connection is eliminated. > > (a not-really-a-solution solution is to increase the timeout values in > your browser, but then every visitor of your site has to do that too) > > HTH, > -D > > -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From webmindforever@organicmeat.net Wed Jan 30 14:06:05 2002 From: webmindforever@organicmeat.net (charlie derr) Date: Wed, 30 Jan 2002 09:06:05 -0500 Subject: [Tutor] Please read this and respond to me. [what to do with "hacker" requests?] In-Reply-To: <20020130085428.66d7a31b.rufmetal@rogers.com> Message-ID: For what it's worth, i thought i'd add my own thoughts to those who've already weighed in. (apologies in advance for contributing to a slightly off-topic thread) My position is that there is more value in being friendly in almost all circumstances. Let's take a hypothetical post by someone who is obviously on the *other* side. Even if the person is obviously requesting "hacking knowledge" and doesn't seem particularly interested in python, i believe there is more to be gained by "bringing this person into the fold" than by abusing her/him. One thing i believe that can safely be assumed is that someone making this type of post here probably doesn't already have a lot of knowledge. This means that it's probably going to take a while for this person to gain knowledge. If they are here asking questions during that period of time, they have a much better chance of absorbing things morally from the people here (who i think provide as good an example of a friendly community as i've seen anywhere on the internet). The "hacker ethic" and similar concepts/references should definitely be shared when appropriate, but i just think that a much greater chance for "success" exists when we are polite. just my $.01999999... ~c From james2dope@yahoo.com Thu Jan 31 17:37:22 2002 From: james2dope@yahoo.com (james middendorff) Date: Thu, 31 Jan 2002 09:37:22 -0800 (PST) Subject: [Tutor] help Message-ID: <20020131173722.55333.qmail@web13908.mail.yahoo.com> I have made a program that will prints out some options 1. to view the list 2. to add to the list 3. to delete from the list 4. to quit and after you select what you want to do, and do it then the program brings the menu up again and asks you what you want to do, but the prompt soon gets cluttered with all of the stuff inside it, is there a way to clear it before it displays the menu again? ===== "I would kill everyone in this room for a drop of sweet beer." ----Homer Simpson---- __________________________________________________ Do You Yahoo!? Great stuff seeking new owners in Yahoo! Auctions! http://auctions.yahoo.com From karthikg@aztec.soft.net Tue Jan 15 18:55:25 2002 From: karthikg@aztec.soft.net (Karthik Gurumurthy) Date: Wed, 16 Jan 2002 00:25:25 +0530 Subject: [Tutor] omit some keys from dict In-Reply-To: <4.2.0.58.20020206223333.019e2ba0@pop3.norton.antivirus> Message-ID: I have a dict and i don't want to look for certain keys. "omit" lists the keys i want to omit. To get the remaining keys i can probably do this.. j= {1:'hello',2:'fine',3:'python',4:'dicts',5:'lists',6:'tuples'} #actual dict omit = [1,3,5] checkkeys = [key for key in j.keys() if key not in omit] Now how can i write this using *only* filter and lambda? I thought i w'd'nt use list comprehensions, but now for this problem i had to use LCs. thanks, karthik. From thomi@thomi.imail.net.nz Tue Jan 1 12:09:01 2002 From: thomi@thomi.imail.net.nz (Thomi Richards) Date: Wed, 2 Jan 2002 01:09:01 +1300 Subject: [Tutor] extramural papers in python?? In-Reply-To: References: <20020101003555.57c5e2f8.thomi@thomi.imail.net.nz> Message-ID: <20020102010901.7b33b0a1.thomi@thomi.imail.net.nz> > Runs a paper using python? I'm not sure I understand the > question. If you're looking for papers ABOUT python, or > FEATURING python, I know there's a Master's Thesis at > Texas A&M that compares Python, Java and C++. If that > will help, send me an email and I'll get the citation for > you later this evening. I'm looking for a single paper which teaches programming (first year), which uses python as its reference language. My local college uses pascal (yuck yuck), and then delphi. I would like to use something which i feel i will actually *use* later in life :-) -- This message was brought to you by one bored guy, with nothing better to do, And the letter Q. Thomi Richards, thomi@imail.net.nz