From gdstack at gmail.com Tue Sep 1 03:04:44 2009 From: gdstack at gmail.com (guan dao) Date: Tue, 1 Sep 2009 09:04:44 +0800 Subject: [Tutor] Please delete my mail address from that mail list. Thanks! Message-ID: <9588e3fc0908311804s33cd982tc36bf78799881709@mail.gmail.com> -------------- next part -------------- An HTML attachment was scrubbed... URL: From ballerz4ishi at sbcglobal.net Tue Sep 1 03:43:29 2009 From: ballerz4ishi at sbcglobal.net (Ishan Puri) Date: Mon, 31 Aug 2009 18:43:29 -0700 (PDT) Subject: [Tutor] Easy Problem Message-ID: <985018.26123.qm@web83301.mail.sp1.yahoo.com> Hello, I have 2 plain text documents that have uneven spacing. I need to make these single spaced between lines and between words. Basically I need to get them to be equal character length after I abridge the uneven spacing. In Python there is probably one simple command for this for a text file? How do I do this? E.G.: Hi how are you? Fixed: Hi how are you? Thanks, Ishan -------------- next part -------------- An HTML attachment was scrubbed... URL: From rabidpoobear at gmail.com Tue Sep 1 04:22:42 2009 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Tue, 1 Sep 2009 04:22:42 +0200 Subject: [Tutor] Easy Problem In-Reply-To: <985018.26123.qm@web83301.mail.sp1.yahoo.com> References: <985018.26123.qm@web83301.mail.sp1.yahoo.com> Message-ID: >>> txt = "Hi how are you?" >>> " ".join(txt.strip().split()) 'Hi how are you?' On Tue, Sep 1, 2009 at 3:43 AM, Ishan Puri wrote: > Hello, > I have 2 plain text documents that have uneven spacing. I need to make > these single spaced between lines and between words. Basically I need to get > them to be equal character length after I abridge the uneven spacing. In > Python there is probably one simple command for this for a text file? How do > I do this? > E.G.: Hi how are you? > Fixed: Hi how are you? > Thanks, > Ishan > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From rabidpoobear at gmail.com Tue Sep 1 04:27:15 2009 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Tue, 1 Sep 2009 04:27:15 +0200 Subject: [Tutor] Please delete my mail address from that mail list. Thanks! In-Reply-To: <9588e3fc0908311804s33cd982tc36bf78799881709@mail.gmail.com> References: <9588e3fc0908311804s33cd982tc36bf78799881709@mail.gmail.com> Message-ID: there are directions on how to remove yourself from the list at the bottom of every message that the list sends out. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > click. -------------- next part -------------- An HTML attachment was scrubbed... URL: From stefan_ml at behnel.de Tue Sep 1 08:38:34 2009 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 01 Sep 2009 08:38:34 +0200 Subject: [Tutor] update html pages using python In-Reply-To: References: Message-ID: Alan Gauld wrote: > "Stefan Behnel" wrote >>> "pedro" wrote >>>> Hi, I was wondering if anyone could point me in the right direction as >>>> far as the best way to use python to update html. >>> >>> There are a number of modules in the standard library that can help but >>> the best known module for this is BeautifulSoup >> >> I would call that statement highly exaggerated. >> >> http://blog.ianbicking.org/2008/03/30/python-html-parser-performance/ > > There may be a language thing at work here but by "best known module" > I do not mean Beautiful Soup is the best of all known modules, rather it > is the module which is most widely known of the non standard HTML > packages. I think "non standard HTML package" pretty much hits the nail on the head. > It is also, arguably, one of the easiest to use > and well behaved with non compliant html That, again, is questionable. The task at hand was to "update HTML pages", in which case it is quite useful to have them fixed up into standard compliant HTML before working on them. BeautifulSoup will not do that for you. Instead, it will leave you with whatever tag soup you had at the beginning, so that you will end up sending out broken HTML again. I wouldn't call that "well behaved" at all. Stefan From quasipedia at gmail.com Tue Sep 1 10:30:18 2009 From: quasipedia at gmail.com (Mac Ryan) Date: Tue, 01 Sep 2009 10:30:18 +0200 Subject: [Tutor] Please delete my mail address from that mail list. Thanks! In-Reply-To: References: <9588e3fc0908311804s33cd982tc36bf78799881709@mail.gmail.com> Message-ID: <1251793818.7281.5.camel@jabbar> On Tue, 2009-09-01 at 04:27 +0200, Luke Paireepinart wrote: > there are directions on how to remove yourself from the list at the > bottom of every message that the list sends out. > _______________________________________________ > click. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor May I suggest, to slightly tweak the signature of the ML with something like: --- Tutor mailing list - tutor at python.org Configuration options (including unsubscribing): http://mail.python.org/mailman/listinfo/tutor --- so that the less tech-savvy among the subscribers get a better hint on how to manage by themselves? Mac. From kent37 at tds.net Tue Sep 1 15:25:35 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 1 Sep 2009 09:25:35 -0400 Subject: [Tutor] Please delete my mail address from that mail list. Thanks! In-Reply-To: <1251793818.7281.5.camel@jabbar> References: <9588e3fc0908311804s33cd982tc36bf78799881709@mail.gmail.com> <1251793818.7281.5.camel@jabbar> Message-ID: <1c2a2c590909010625i238ece2fy94606a42af6ae9dd@mail.gmail.com> On Tue, Sep 1, 2009 at 4:30 AM, Mac Ryan wrote: > May I suggest, > > to slightly tweak the signature of the ML with something like: > > --- > Tutor mailing list ?- ?tutor at python.org > Configuration options (including unsubscribing): > http://mail.python.org/mailman/listinfo/tutor > --- Good idea, see below (I hope) Kent From sander.sweers at gmail.com Tue Sep 1 14:46:33 2009 From: sander.sweers at gmail.com (Sander Sweers) Date: Tue, 1 Sep 2009 14:46:33 +0200 Subject: [Tutor] Easy Problem In-Reply-To: References: <985018.26123.qm@web83301.mail.sp1.yahoo.com> Message-ID: 2009/9/1 Luke Paireepinart : >>>> txt = "Hi ? ? ? ? ?how are you?" >>>> " ".join(txt.strip().split()) > 'Hi how are you?' txt.strip() only remove leading and trailing white space so does nothing in your example. However it works because txt.split() removes the excessive white space between the text. >>> txt 'Hi how are you?' >>> ' '.join(txt.split()) 'Hi how are you?' Greets Sander From kent37 at tds.net Tue Sep 1 16:24:24 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 1 Sep 2009 10:24:24 -0400 Subject: [Tutor] Easy Problem In-Reply-To: <985018.26123.qm@web83301.mail.sp1.yahoo.com> References: <985018.26123.qm@web83301.mail.sp1.yahoo.com> Message-ID: <1c2a2c590909010724t30fde8bavefc727245031d99f@mail.gmail.com> On Mon, Aug 31, 2009 at 9:43 PM, Ishan Puri wrote: > Hello, > ??? I have 2 plain text documents that have uneven spacing. I need to make > these single spaced between lines and between words. Basically I need to get > them to be equal character length after I abridge the uneven spacing. I don't know what you mean by "equal character length" here. > In > Python there is probably one simple command for this for a text file? How do > I do this? > E.G.: Hi????????? how are you? > Fixed: Hi how are you? Another way to do this is with regular expressions, for example In [1]: import re In [2]: txt = "Hi how are you?" In [4]: txt = re.sub(r' +', ' ', txt) In [5]: txt Out[5]: 'Hi how are you?' You can also replace multiple newlines with single newlines. The details of that will depend on the line endings in your text; assuming \n for newline then you could use txt = re.sub(r'\n\n+', '\n', txt) to remove extra newlines. The split() method won't distinguish between spaces and newlines so you have to apply it one line at a time. The re.sub() method can work on the entire text at once. Kent From krissy.ambert at gmail.com Tue Sep 1 21:51:34 2009 From: krissy.ambert at gmail.com (Kristina Ambert) Date: Tue, 1 Sep 2009 15:51:34 -0400 Subject: [Tutor] Tracking variable changes in a different application Message-ID: Hi again, The question might be a tad confusing, but what I want to ask is, if it's possible to track if and when a variable in an application has changed, and then grab the new content of that variable? I have my product inventory database application which is attached to another bigger application. Some of the data I need comes from that bigger application, like for instance Consumer information (not handled by the application that I'm working on). So, if the address of a consumer is changed, how my application track the changes without having to do something like: class Consumer(objectOfSomething): ----- ----- def updateConsumerInfo(newAddress): newAddress = newAddress inventory.updateConsumerInfo(newAddress) #<< From emile at fenx.com Tue Sep 1 22:23:29 2009 From: emile at fenx.com (Emile van Sebille) Date: Tue, 01 Sep 2009 13:23:29 -0700 Subject: [Tutor] Tracking variable changes in a different application In-Reply-To: References: Message-ID: On 9/1/2009 12:51 PM Kristina Ambert said... > Hi again, > > The question might be a tad confusing, but what I want to ask is, if > it's possible to track if and when a variable in an application has > changed, and then grab the new content of that variable? So, you want to be notified when a field in an external database changes. Databases commonly do this with triggers. Generally, I've not had access to the external databases, and so have had to detect changes in other ways. Depending on what I have access to I'll do one of several different things ranging from date and time stamp checking (to know when it changed), through ODBC connections for database access (so data is always current), to overnight data export and syncing (because it's good enough). If you describe your environment and requirements further specific solutions may be offered. Emile From dkuhlman at rexx.com Wed Sep 2 01:01:13 2009 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Tue, 1 Sep 2009 16:01:13 -0700 Subject: [Tutor] Easy Problem In-Reply-To: <985018.26123.qm@web83301.mail.sp1.yahoo.com> References: <985018.26123.qm@web83301.mail.sp1.yahoo.com> Message-ID: <20090901230113.GA62232@cutter.rexx.com> On Mon, Aug 31, 2009 at 06:43:29PM -0700, Ishan Puri wrote: > > Hello, > I have 2 plain text documents that have uneven spacing. I need to > make these single spaced between lines and between words. Basically I > need to get them to be equal character length after I abridge the > uneven spacing. In Python there is probably one simple command for > this for a text file? How do I do this? > E.G.: Hi how are you? > Fixed: Hi how are you? Not quite what you are asking for, but, if you are working with this kind of problem, you might want to know about the textwrap module in the standard library: http://docs.python.org/library/textwrap.html#module-textwrap - Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman From rabidpoobear at gmail.com Wed Sep 2 01:44:36 2009 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Tue, 1 Sep 2009 18:44:36 -0500 Subject: [Tutor] Easy Problem In-Reply-To: References: <985018.26123.qm@web83301.mail.sp1.yahoo.com> Message-ID: On Tue, Sep 1, 2009 at 7:46 AM, Sander Sweers wrote: > 2009/9/1 Luke Paireepinart : > >>>> txt = "Hi how are you?" > >>>> " ".join(txt.strip().split()) > > 'Hi how are you?' > > txt.strip() only remove leading and trailing white space so does > nothing in your example. It removes newlines as well. I couldn't remember if split() would leave the trailing newline on the last item. -------------- next part -------------- An HTML attachment was scrubbed... URL: From wagnerr at umich.edu Wed Sep 2 03:44:00 2009 From: wagnerr at umich.edu (Richard Wagner) Date: Tue, 1 Sep 2009 21:44:00 -0400 Subject: [Tutor] Rounding to n significant digits Message-ID: <5B992FF5-BDD6-4D89-A5BD-511DCB82785E@umich.edu> I'm fairly new to Python and am trying to find a simple way to round floats to a specific number of significant digits. I found an old post on this list with exactly the same problem: > Is there something (a function?) in Python 2.3.4 that will round a > result to n significant digits, or do I need to roll my own? I don't > see one in the math module. > > I mean something like rounding(float, n) that would do this: > float = 123.456789, n = 4, returns 123.5 > float = .000000123456789, n = 2, returns .00000012 > float = 123456789, n = 5, returns 123460000 > > Thanks, > > Dick Moores And another post gave this solution: > I expect the easiest way to do this in Python is to convert to > string using an %e format, then convert that back to float again. > Like this: > > def round_to_n(x, n): > if n < 1: > raise ValueError("number of significant digits must be >= 1") > # Use %e format to get the n most significant digits, as a string. > format = "%." + str(n-1) + "e" > as_string = format % x > return float(as_string) Converting to a string seemed like an awkward hack to me, so I came up with a mathematical solution: > import math > > def round_figures(x, n): > """Returns x rounded to n significant figures.""" > return round(x, int(n - math.ceil(math.log10(abs(x))))) > > print round_figures(123.456789,4) > print round_figures(.000000123456789,2) > print round_figures(123456789,5) > print round_figures(0.987,3) > print round_figures(0.987,2) > print round_figures(0.987,1) > print round_figures(-0.002468,2) > > 123.5 > 1.2e-07 > 123460000.0 > 0.987 > 0.99 > 1.0 > -0.0025 Since the built-in round(x,n) can do rounding in the 10's and 100's places just as easy as 0.1's and 0.01's, my function just counts how many digits are in use and rounds off n digits away. I thought others might find this solution useful. Or somebody else might share a nicer way. Richard Wagner From jsseabold at gmail.com Wed Sep 2 04:00:06 2009 From: jsseabold at gmail.com (Skipper Seabold) Date: Tue, 1 Sep 2009 22:00:06 -0400 Subject: [Tutor] Rounding to n significant digits In-Reply-To: <5B992FF5-BDD6-4D89-A5BD-511DCB82785E@umich.edu> References: <5B992FF5-BDD6-4D89-A5BD-511DCB82785E@umich.edu> Message-ID: On Tue, Sep 1, 2009 at 9:44 PM, Richard Wagner wrote: > I'm fairly new to Python and am trying to find a simple way to round floats > to a specific number of significant digits. ?I found an old post on this > list with exactly the same problem: > Python 2.5.4 (r254:67916, Apr 4 2009, 17:56:17) [GCC 4.3.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> print round(2.555555, 2) 2.56 http://docs.python.org/library/functions.html#round Skipper From jsseabold at gmail.com Wed Sep 2 04:06:04 2009 From: jsseabold at gmail.com (Skipper Seabold) Date: Tue, 1 Sep 2009 22:06:04 -0400 Subject: [Tutor] Rounding to n significant digits In-Reply-To: References: <5B992FF5-BDD6-4D89-A5BD-511DCB82785E@umich.edu> Message-ID: On Tue, Sep 1, 2009 at 10:00 PM, Skipper Seabold wrote: > On Tue, Sep 1, 2009 at 9:44 PM, Richard Wagner wrote: >> I'm fairly new to Python and am trying to find a simple way to round floats >> to a specific number of significant digits. ?I found an old post on this >> list with exactly the same problem: >> > > Python 2.5.4 (r254:67916, Apr ?4 2009, 17:56:17) > [GCC 4.3.3] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> print round(2.555555, 2) > 2.56 > > http://docs.python.org/library/functions.html#round > > Skipper > Sorry didn't read carefully enough. From alan.gauld at btinternet.com Wed Sep 2 09:54:35 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 2 Sep 2009 08:54:35 +0100 Subject: [Tutor] Tracking variable changes in a different application References: Message-ID: "Kristina Ambert" wrote > The question might be a tad confusing, but what I want to ask is, if it's > possible to track if and when a variable in an application has changed, > and > then grab the new content of that variable? Not in general. Variables change too quickly for that to be viable - think about a loop counter in a while loop, it could change millions of times per second! > I have my product inventory database application which is attached to > another bigger application. Some of the data I need comes from that > bigger > application, like for instance Consumer information (not handled by the > application that I'm working on). So, if the address of a consumer is > changed, how my application track the changes But this is different. I assume the other app is storing its data in a database? If so that database may suppport triggers which can call a stored procedure when an item (table, row,column) changes. That stored procedure can notify your app of the change. Of course that relies on you having access to the same database as the other app, but that sounds very likely in this scenario. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Wed Sep 2 10:05:02 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 2 Sep 2009 09:05:02 +0100 Subject: [Tutor] Rounding to n significant digits References: <5B992FF5-BDD6-4D89-A5BD-511DCB82785E@umich.edu> Message-ID: "Richard Wagner" wrote > I'm fairly new to Python and am trying to find a simple way to round > floats to a specific number of significant digits. I found an old post > on this list with exactly the same problem: The usual question is why would you want to lose precision in your data? Significant digits is usually only an issue for presentation not internal storage. That's why there is no built in way of losing precision (rounding) in the data. That having been said the two approaches, string or math, are equally valid. I suspect the math version will be much slower since it calls several functions but I haven't timed it. >> def round_to_n(x, n): >> fmt = "%%.%de" % (n) >> return float( fmt % x) > >> import math >> >> def round_figures(x, n): >> return round(x, int(n - math.ceil(math.log10(abs(x))))) HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From sander.sweers at gmail.com Wed Sep 2 13:19:33 2009 From: sander.sweers at gmail.com (Sander Sweers) Date: Wed, 2 Sep 2009 13:19:33 +0200 Subject: [Tutor] Rounding to n significant digits In-Reply-To: References: <5B992FF5-BDD6-4D89-A5BD-511DCB82785E@umich.edu> Message-ID: 2009/9/2 Alan Gauld : > That having been said the two approaches, string or math, are equally > valid. I suspect the math version will be much slower since it calls > several functions but I haven't timed ?it. > >>> def round_to_n(x, n): >>> ? ? ? ? fmt = "%%.%de" % (n) >>> ? ? ? ? return float( fmt % x) >> >>> import math >>> >>> def round_figures(x, n): >>> ? ? ? ?return round(x, int(n - math.ceil(math.log10(abs(x))))) Maybe the decimal module can help out. It can limit precision to n digits globally and per instance. I might be way of here so please do not hesitate to correct me :-) >>> i = float(1.333333) >>> i 1.3333330000000001 >>> c = decimal.getcontext().copy() >>> c.prec = 2 >>> d = c.create_decimal(str(i)) >>> d Decimal('1.3') >>> x = 2 >>> x < d False >>> x > d True Greets Sander From AMCasey at xtra.co.nz Wed Sep 2 12:30:35 2009 From: AMCasey at xtra.co.nz (Anthony Casey) Date: Wed, 2 Sep 2009 22:30:35 +1200 Subject: [Tutor] Boolean operations In-Reply-To: References: Message-ID: <010e01ca2bb8$68956b00$39c04100$@co.nz> Hello, tutors. I'm someone who used to programme as a hobby and who is trying to get back into it via Python. I'm reading Programming in Python 3 by Summerfield (excellent book). I read something unusual about Boolean operations in Python: >>> five = 5 >>> two = 2 >>> zero = 0 >>> five and two 2 I understand what it's doing here: returning the operand. But what is the practical application of that? How might I use that function? (Short-sighted imagination, I realise.) (I know how binary Booleans work etc., so this is a bit of a change of outlook.) Please pardon me if this is a silly or inane question. Regards, Anthony From vinces1979 at gmail.com Wed Sep 2 16:09:37 2009 From: vinces1979 at gmail.com (vince spicer) Date: Wed, 2 Sep 2009 08:09:37 -0600 Subject: [Tutor] Boolean operations In-Reply-To: <010e01ca2bb8$68956b00$39c04100$@co.nz> References: <010e01ca2bb8$68956b00$39c04100$@co.nz> Message-ID: <1e53c510909020709o37166e10tbf696e469b469148@mail.gmail.com> On Wed, Sep 2, 2009 at 4:30 AM, Anthony Casey wrote: > Hello, tutors. > > I'm someone who used to programme as a hobby and who is trying to get back > into it via Python. I'm reading Programming in Python 3 by Summerfield > (excellent book). > > I read something unusual about Boolean operations in Python: > > >>> five = 5 > >>> two = 2 > >>> zero = 0 > >>> five and two > 2 > > I understand what it's doing here: returning the operand. But what is the > practical application of that? How might I use that function? > (Short-sighted > imagination, I realise.) > > (I know how binary Booleans work etc., so this is a bit of a change of > outlook.) > > Please pardon me if this is a silly or inane question. > > Regards, > Anthony > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > this might make the "and" operator a little clearer http://pyref.infogami.com/and Vince -------------- next part -------------- An HTML attachment was scrubbed... URL: From krissy.ambert at gmail.com Wed Sep 2 15:55:36 2009 From: krissy.ambert at gmail.com (Kristina Ambert) Date: Wed, 2 Sep 2009 09:55:36 -0400 Subject: [Tutor] I always get this message as a reply Message-ID: Hi, I just wanted to ask if everyone else gets this message as a first reply everytime you send out a message to tutor. It feels like I'm getting spam or something. Genevi?ve DIAGORN to me show details 3:59 PM (17 hours ago) Bonjour, Je suis absente jusqu'au 02/09 inclus. En cas d'urgence Soprane, contacter notre adresse g?n?rique projet.soprane at teamlog.com. Cordialement. Genevi?ve -- Krissy ----------------------------------------------------------------------- Testing the waters is always fun... -------------- next part -------------- An HTML attachment was scrubbed... URL: From vinces1979 at gmail.com Wed Sep 2 16:36:18 2009 From: vinces1979 at gmail.com (vince spicer) Date: Wed, 2 Sep 2009 08:36:18 -0600 Subject: [Tutor] I always get this message as a reply In-Reply-To: References: Message-ID: <1e53c510909020736n36d08c89s2badcd05f43c5cc3@mail.gmail.com> On Wed, Sep 2, 2009 at 7:55 AM, Kristina Ambert wrote: > Hi, > > I just wanted to ask if everyone else gets this message as a first reply > everytime you send out a message to tutor. > It feels like I'm getting spam or something. > Genevi?ve DIAGORN to me > show details 3:59 PM (17 hours ago) > > Bonjour, > Je suis absente jusqu'au 02/09 inclus. > En cas d'urgence Soprane, contacter notre adresse g?n?rique > projet.soprane at teamlog.com. > Cordialement. > > Genevi?ve > > > > > -- > Krissy > ----------------------------------------------------------------------- > Testing the waters is always fun... > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > Someone on the list has gone on vacation and has an auto responder to tell clients that they are away. Vince -------------- next part -------------- An HTML attachment was scrubbed... URL: From cwitts at compuscan.co.za Wed Sep 2 16:56:42 2009 From: cwitts at compuscan.co.za (Christian Witts) Date: Wed, 02 Sep 2009 16:56:42 +0200 Subject: [Tutor] I always get this message as a reply In-Reply-To: References: Message-ID: <4A9E87AA.6010406@compuscan.co.za> Kristina Ambert wrote: > Hi, > > I just wanted to ask if everyone else gets this message as a first > reply everytime you send out a message to tutor. > It feels like I'm getting spam or something. > > > Genevi?ve DIAGORN > > to me > > > show details 3:59 PM (17 hours ago) > > > Bonjour, > Je suis absente jusqu'au 02/09 inclus. > En cas d'urgence Soprane, contacter notre adresse g?n?rique > projet.soprane at teamlog.com . > Cordialement. > > Genevi?ve > > > > > -- > Krissy > ----------------------------------------------------------------------- > Testing the waters is always fun... > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > I get that as well, been getting them for ages. -- Kind Regards, Christian Witts From krissy.ambert at gmail.com Wed Sep 2 17:10:37 2009 From: krissy.ambert at gmail.com (Kristina Ambert) Date: Wed, 2 Sep 2009 11:10:37 -0400 Subject: [Tutor] Tracking variable changes in a different application In-Reply-To: References: Message-ID: Hi, Thanks for the responses guys. I'll clear up my question a bit more maybe, the application which data I'm accessing doesn't store it's information in a database, it only stores it in the application at runtime. I did think to ask to have a module send the data to my application like what you guys suggested, but then that doesn't make my application standalone, or does it? In the sense that, a module from the bigger application has to be created to send whatever data I need, so really my .py application has to be imported into the bigger application, hence not making it standalone. Or am I trying to make things a bit too complication for myself? I guess I was just thinking of a way for my application to be more versatile and can be used with other similar main applications, sort of as a service application. On Wed, Sep 2, 2009 at 3:54 AM, Alan Gauld wrote: > > "Kristina Ambert" wrote > > The question might be a tad confusing, but what I want to ask is, if it's >> possible to track if and when a variable in an application has changed, >> and >> then grab the new content of that variable? >> > > Not in general. Variables change too quickly for that to be viable - think > about a loop counter in a while loop, it could change millions of times > per second! > > I have my product inventory database application which is attached to >> another bigger application. Some of the data I need comes from that bigger >> application, like for instance Consumer information (not handled by the >> application that I'm working on). So, if the address of a consumer is >> changed, how my application track the changes >> > > But this is different. I assume the other app is storing its data in a > database? > If so that database may suppport triggers which can call a stored procedure > when an item (table, row,column) changes. That stored procedure can notify > your app of the change. Of course that relies on you having access to the > same database as the other app, but that sounds very likely in this > scenario. > > HTH, > > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Cheers, Krissy ----------------------------------------------------------------------- Testing the waters is always fun... -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Wed Sep 2 17:21:51 2009 From: bgailer at gmail.com (bob gailer) Date: Wed, 02 Sep 2009 11:21:51 -0400 Subject: [Tutor] Tracking variable changes in a different application In-Reply-To: References: Message-ID: <4A9E8D8E.3010804@gmail.com> Kristina Ambert wrote: > Hi, > > Thanks for the responses guys. > I'll clear up my question a bit more maybe, the application which data > I'm accessing doesn't store it's information in a database, it only > stores it in the application at runtime. I did think to ask to have a > module send the data to my application like what you guys suggested, > but then that doesn't make my application standalone, or does it? In > the sense that, a module from the bigger application has to be created > to send whatever data I need, so really my .py application has to be > imported into the bigger application, hence not making it standalone. > Or am I trying to make things a bit too complication for myself? I > guess I was just thinking of a way for my application to be more > versatile and can be used with other similar main applications, sort > of as a service application. It sounds like you (or someone) can modify the "application which data I'm accessing" to meet your needs. True? If so consider these alternatives: 1) have it periodically write a file with the updated values. Your application will periodically read that file. 2) have it set up a socket connection that listens, and have your application periodically connect to the socket, at which point the "application which data I'm accessing" will return the changes. 3) using pywin32 make it a COM server. Your application will establish a COM connection to it and request updates. -- Bob Gailer Chapel Hill NC 919-636-4239 From kent37 at tds.net Wed Sep 2 18:45:17 2009 From: kent37 at tds.net (Kent Johnson) Date: Wed, 2 Sep 2009 12:45:17 -0400 Subject: [Tutor] Boolean operations In-Reply-To: <010e01ca2bb8$68956b00$39c04100$@co.nz> References: <010e01ca2bb8$68956b00$39c04100$@co.nz> Message-ID: <1c2a2c590909020945q52c92603j7f48fa63b6c36157@mail.gmail.com> On Wed, Sep 2, 2009 at 6:30 AM, Anthony Casey wrote: > Hello, tutors. > > I'm someone who used to programme as a hobby and who is trying to get back > into it via Python. I'm reading Programming in Python 3 by Summerfield > (excellent book). > > I read something unusual about Boolean operations in Python: > >>>> five = 5 >>>> two = 2 >>>> zero = 0 >>>> five and two > 2 > > I understand what it's doing here: returning the operand. But what is the > practical application of that? How might I use that function? (Short-sighted > imagination, I realise.) The equivalent behaviour for 'or' can be used to provide a default, for example: value = may_be_empty or 3 The obsolete (and problematic) hack for a ternary expression uses this: x = (cond and true_value) or false_value If cond evaluates to True, x will have true_value, otherwise it will have false_value. Kent From alan.gauld at btinternet.com Wed Sep 2 22:07:34 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 2 Sep 2009 21:07:34 +0100 Subject: [Tutor] Boolean operations References: <010e01ca2bb8$68956b00$39c04100$@co.nz> Message-ID: "Anthony Casey" wrote >>>> five and two > 2 > > I understand what it's doing here: returning the operand. But what is the > practical application of that? How might I use that function? Try >>> bool(2) True >>> bool(0) False So you can use the retuirn from the and as a boolean value in a test condition: if 5 and 2: print 'its true') if 5 and 0: print 'its not' > (I know how binary Booleans work etc., so this is a bit of a change of > outlook.) Hopefully that clears it up. There are some klunky hacks that you can do based on this side-effect but there are usually cleaner solutions especially since Pyton 2.5 introduced a ternary operator -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Wed Sep 2 22:10:13 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 2 Sep 2009 21:10:13 +0100 Subject: [Tutor] I always get this message as a reply References: Message-ID: "Kristina Ambert" wrote > It feels like I'm getting spam or something. > Genevi?ve DIAGORN to me Genevieve sets her vacation reminder when she is out of the office. Unfortunately she doesn't turn off her tutor subscription! And equally unfortunately her autoresponder doesn't recognise addresses to which it has already sent a reply! Maybe we should draw this to her attention next time she comes back! :-/ Alan G. From alan.gauld at btinternet.com Thu Sep 3 01:15:59 2009 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Wed, 2 Sep 2009 23:15:59 +0000 (GMT) Subject: [Tutor] Tracking variable changes in a different application In-Reply-To: <2ac5d4850909020914t76e96847l89d98ea3543ce444@mail.gmail.com> References: <2ac5d4850909020914t76e96847l89d98ea3543ce444@mail.gmail.com> Message-ID: <772801.89441.qm@web86706.mail.ird.yahoo.com> Not in general. Variables change too quickly for that to be viable - think >>about a loop counter in a while loop, it could change millions of times >>>>per second! >> >> >Could you not use an observer pattern here to do that? > >http://en.wikipedia.org/wiki/Observer_pattern > You could but the danger romains that if someone puts the change inside a loop: > for n in range(10,000): ChangeMyVariable() > You could wind up getting 10,000 change notifications within a second and very few applications will respond nicely to that! Which makes it a risky option and using a persistent queue such as a database table or middleware queuing mechanism is far safer. > HTH, > Alan G. -------------- next part -------------- An HTML attachment was scrubbed... URL: From mikeyang2 at gmail.com Thu Sep 3 03:58:37 2009 From: mikeyang2 at gmail.com (Michael Yang) Date: Wed, 2 Sep 2009 21:58:37 -0400 Subject: [Tutor] running python program on Linux Virtual Server - Plesk? Message-ID: Hi Everyone, I'm new to programming and to python. I have a program I want to run on my Media Temple Virtual Server (dv) - Linux. which has the latest Plesk 9 virtuozzo installed. Ultimately I want it to run the program (main.py) on a scheduled basis. How do I do this? Thanks! -Mike -------------- next part -------------- An HTML attachment was scrubbed... URL: From cwitts at compuscan.co.za Thu Sep 3 08:45:40 2009 From: cwitts at compuscan.co.za (Christian Witts) Date: Thu, 03 Sep 2009 08:45:40 +0200 Subject: [Tutor] running python program on Linux Virtual Server - Plesk? In-Reply-To: References: Message-ID: <4A9F6614.9020004@compuscan.co.za> Michael Yang wrote: > Hi Everyone, > > I'm new to programming and to python. > > I have a program I want to run on my Media Temple Virtual Server (dv) > - Linux. which has the latest Plesk 9 virtuozzo installed. > > Ultimately I want it to run the program (main.py) on a scheduled > basis. How do I do this? > > > > Thanks! > > -Mike > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Are you able to run it as a cron job ? That would be by far the easiest solution. crontab -e syntax when editing is "minute hour dayOfMonth month dayofWeek command" so you would do 0 0-23 * * * python main.py which would run your python script every hour every day. Personally, if you do schedule it like this you would better off calling a shell script with the cron job and in the shell script listing certain environment variables you might need and then calling the script. The job won't be running under your normal user account so you might need to add them. -- Kind Regards, Christian Witts From cwitts at compuscan.co.za Thu Sep 3 10:29:10 2009 From: cwitts at compuscan.co.za (Christian Witts) Date: Thu, 03 Sep 2009 10:29:10 +0200 Subject: [Tutor] running python program on Linux Virtual Server - Plesk? In-Reply-To: References: <4A9F6614.9020004@compuscan.co.za> Message-ID: <4A9F7E56.5020708@compuscan.co.za> Michael Yang wrote: > thanks. so this would run my script on a schedule i specify. And its > a "set it and forget it" deal. > > but if i want to view the output of the program (ie. the program has > various print statements to show program's status), how would I do > this while its running the job? > > MIke > > On Thu, Sep 3, 2009 at 2:45 AM, Christian Witts > > wrote: > > Michael Yang wrote: > > Hi Everyone, > > I'm new to programming and to python. > I have a program I want to run on my Media Temple Virtual > Server (dv) - Linux. which has the latest Plesk 9 virtuozzo > installed. > > Ultimately I want it to run the program (main.py) on a > scheduled basis. How do I do this? > > > > Thanks! > > -Mike > ------------------------------------------------------------------------ > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > > Are you able to run it as a cron job ? That would be by far the > easiest solution. > > crontab -e > syntax when editing is "minute hour dayOfMonth month dayofWeek > command" so you would do > 0 0-23 * * * python main.py > which would run your python script every hour every day. > Personally, if you do schedule it like this you would better off > calling a shell script with the cron job and in the shell script > listing certain environment variables you might need and then > calling the script. The job won't be running under your normal > user account so you might need to add them. > > -- > Kind Regards, > Christian Witts > > > > > > -- > Thanks, > Michael Yang > > 917-699-4655 phone > 212-500-0553 fax It is indeed "set and forget". Once your cron job is setup it was always execute the command for you at your scheduled intervals. Another creative way of running it would be to call 'at' at the end of the script to execute it again, for example 'at -f name_of_shell_script.sh now + 30 minutes' which would run it again in 30 minutes for you. If you change your print statements to write it to a log file instead, or in your shell script use the redirection characters > or >> to push the output to a file you want then you can use "tail -f filename" to watch the log file as output comes through. -- Kind Regards, Christian Witts From jojo.mwebaze at gmail.com Thu Sep 3 15:05:16 2009 From: jojo.mwebaze at gmail.com (Jojo Mwebaze) Date: Thu, 3 Sep 2009 15:05:16 +0200 Subject: [Tutor] how to read and transmit/send only section of the image (sub-image) Message-ID: <3124be320909030605p23803349mf4d5e042fb5cf5f6@mail.gmail.com> Hello Tutor I am writing Class to provide data transfer between the server and client processes based on simple HTTP GET/POST operations. However my interest is a sub-image (section of a full image). i am requesting help on how to read and transmit/send only section of the image (sub-image). i also prefer read the bytes (of the subimage) off the disk, without opening the file into memory! The images i work with are of type FITS. Kind Regards Jojo -------------- next part -------------- An HTML attachment was scrubbed... URL: From srilyk at gmail.com Thu Sep 3 15:50:53 2009 From: srilyk at gmail.com (Wayne) Date: Thu, 3 Sep 2009 08:50:53 -0500 Subject: [Tutor] how to read and transmit/send only section of the image (sub-image) In-Reply-To: <3124be320909030605p23803349mf4d5e042fb5cf5f6@mail.gmail.com> References: <3124be320909030605p23803349mf4d5e042fb5cf5f6@mail.gmail.com> Message-ID: <333efb450909030650r5aeb23bbqa3bc4f225bb8e28@mail.gmail.com> On Thu, Sep 3, 2009 at 8:05 AM, Jojo Mwebaze wrote: > Hello Tutor > > I am writing Class to provide data transfer between the server and client > processes based on simple HTTP GET/POST operations. However my interest is a > sub-image (section of a full image). i am requesting help on how to read and > transmit/send only section of the image (sub-image). i also prefer read the > bytes (of the subimage) off the disk, without opening the file into memory! > > The images i work with are of type FITS. > The biggest problem is that image files usually have header information in the file that tell what the file type is, how big it is, and that sort of thing. I've never used FITS images though, so I don't know that much about them. I'm not sure how the python open works, if it loads the file into memory or if it just creates a file pointer to the location on disk. AFAIK it's the latter, in which case opening the file and seeking to the correct place, reading a specific size, and saving that data would be all you need to do. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Thu Sep 3 17:06:17 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 3 Sep 2009 11:06:17 -0400 Subject: [Tutor] how to read and transmit/send only section of the image (sub-image) In-Reply-To: <3124be320909030605p23803349mf4d5e042fb5cf5f6@mail.gmail.com> References: <3124be320909030605p23803349mf4d5e042fb5cf5f6@mail.gmail.com> Message-ID: <1c2a2c590909030806h79268022y8a7c60ab4afcc8d9@mail.gmail.com> On Thu, Sep 3, 2009 at 9:05 AM, Jojo Mwebaze wrote: > Hello Tutor > > I am writing Class to provide data transfer between the server and client > processes based on simple HTTP GET/POST operations. However my interest is a > sub-image (section of a full image). i am requesting help on how to read and > transmit/send only section of the image (sub-image). i also prefer read the > bytes (of the subimage) off the disk, without opening the file into memory! > > The images i work with are of type FITS. I don't know much about FITS but my guess is you will have to read the image into memory, create a new image with the sub-image you want, then send the sub-image to the server. PyFITS looks like a good place to start... http://www.stsci.edu/resources/software_hardware/pyfits/ Kent From allen.fowler at yahoo.com Thu Sep 3 17:22:36 2009 From: allen.fowler at yahoo.com (Allen Fowler) Date: Thu, 3 Sep 2009 08:22:36 -0700 (PDT) Subject: [Tutor] multiprocessing: Correct usage of pool & queue? Message-ID: <696504.51597.qm@web45607.mail.sp1.yahoo.com> Hello, I have a list of tasks/items that I want handed off to threads/processes to complete. (I would like to stick with process if I could, since there is some CPU work here. ) Each task involves some calculations and a call to a remote server over urllib2/HTTP. The time to complete each task varies from 1 to 20 seconds depending on a number of factors including variable delay on the remote server. I would like to: 1) Have a maximum of 20 "in-flight" tasks. (thus worker processes?) 2) Not overload the external server that each task is calling. No more than "3 new tasks" per second. More "waiting" tasks may be OK, i need to test it. 3) Certain tasks in my list must be processed in the correct order. (I guess the asignment logic must somehow tag those to by done by the same worker?) Do any of you have suggestions? Can someone point me in the direction of sample code for this? Thank you, :) From krissy.ambert at gmail.com Thu Sep 3 19:10:49 2009 From: krissy.ambert at gmail.com (Kristina Ambert) Date: Thu, 3 Sep 2009 13:10:49 -0400 Subject: [Tutor] Tracking variable changes in a different application In-Reply-To: <772801.89441.qm@web86706.mail.ird.yahoo.com> References: <2ac5d4850909020914t76e96847l89d98ea3543ce444@mail.gmail.com> <772801.89441.qm@web86706.mail.ird.yahoo.com> Message-ID: Hey guys, Yes, I figure that there are changes that need to be done in the main application to fit the needs of my application. Like what some of you guys suggested, I have looked into having the main application use a database to feed the information that I'll need. Right now that I guess is the most likely option to use. Thanks for all the responses! -- Cheers, Krissy ----------------------------------------------------------------------- Testing the waters is always fun... -------------- next part -------------- An HTML attachment was scrubbed... URL: From fomcl at yahoo.com Thu Sep 3 19:31:00 2009 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Thu, 3 Sep 2009 10:31:00 -0700 (PDT) Subject: [Tutor] Input validation Message-ID: <64384.19764.qm@web110710.mail.gq1.yahoo.com> Hi, I'm wondering what is the most common method of input validation. See the example below. -Is the code below the most common/recognizable way something like this is done? -Which of the options #1 and #2 is the preferred method? Option #2 looks less esoteric, but #1 seems better when you have to check for several data types simultaneously. Thanks! Albert-Jan import os.path, textwrap def main(param): if validate_input(param) == "LT": return param[-1] elif validate_input(param) == "FILE": f = open(param, "rb").readlines() return " ".join(f) elif validate_input(param) == "STR": return textwrap.wrap(param) else: print "Invalid input!" return None def validate_input (param): if param.__class__ in (list, tuple): #option 1 return "LT" elif isinstance(param, str): # option 2 if os.path.isfile(param): return "FILE" else: return "STR" else: return None print main(param=[1,2,3]) print main(param="d:/temp/txt.txt") print main(param="yeah but yeah, but no") print main(param=1.0) From yam at nerd.cx Thu Sep 3 20:01:11 2009 From: yam at nerd.cx (William Witteman) Date: Thu, 3 Sep 2009 14:01:11 -0400 Subject: [Tutor] Having trouble with a dictionary of lists Message-ID: <20090903180111.GA28199@yam.witteman.ca> I am trying to create a CSV file of sorted similar lists, arranged so that differences are easily compared in a spreadsheet. I am encountering the following error, however: IndexError: list assignment index out of range On the indicated line below. I understand the error, but I don't understand why I am getting it. Can anyone shed some light on this? Thanks. #!/usr/bin/python """ Take a collection of lists, combine them into one list, deleting duplicates. Sort the list and use it as the leftmost column of a table. Then put each lists contents into the table, one per column, with the elements aligned with the leftmost (index) column. """ import os, sys, csv def cmpss(filename,*sslists): """Write a CSV file from the collection of lists.""" if os.path.exists(filename): print("%s exists: please choose another filename." % filename) sys.exit(1) else: try: fn = csv.writer(open(filename, "w")) except IOError: print("There is a problem opening the requested file. Sorry.") sys.exit(1) termdict = {} for sslist in sslists: for term in sslist: termdict[term] = "" termlist = termdict.keys() termlist.sort() sortedtermdict = {} number_of_commas = 1 - len(sslists) for term in termlist: sortedtermdict[term] = ["" for x in range(number_of_commas)] for sslist in sslists: counter = 0 for term in sslist: # The line below is where my program barfs. sortedtermdict[term][counter] = term counter = counter + 1 for row in sortedtermdict: fn.writerow(row) -- yours, William From emile at fenx.com Thu Sep 3 20:26:35 2009 From: emile at fenx.com (Emile van Sebille) Date: Thu, 03 Sep 2009 11:26:35 -0700 Subject: [Tutor] Having trouble with a dictionary of lists In-Reply-To: <20090903180111.GA28199@yam.witteman.ca> References: <20090903180111.GA28199@yam.witteman.ca> Message-ID: On 9/3/2009 11:01 AM William Witteman said... > I am trying to create a CSV file of sorted similar lists, arranged so > that differences are easily compared in a spreadsheet. I am > encountering the following error, however: > > IndexError: list assignment index out of range > > On the indicated line below. I understand the error, but I don't > understand why I am getting it. Can anyone shed some light on this? > Thanks. > > #!/usr/bin/python > > """ > Take a collection of lists, combine them into one list, deleting duplicates. > Sort the list and use it as the leftmost column of a table. Then put each > lists contents into the table, one per column, with the elements aligned > with the leftmost (index) column. > > """ > > import os, sys, csv > > def cmpss(filename,*sslists): > """Write a CSV file from the collection of lists.""" > > if os.path.exists(filename): > print("%s exists: please choose another filename." % filename) > sys.exit(1) > else: > try: > fn = csv.writer(open(filename, "w")) > except IOError: > print("There is a problem opening the requested file. Sorry.") > sys.exit(1) > > termdict = {} > > for sslist in sslists: > for term in sslist: > termdict[term] = "" > > termlist = termdict.keys() > termlist.sort() > > sortedtermdict = {} > number_of_commas = 1 - len(sslists) > > for term in termlist: > sortedtermdict[term] = ["" for x in range(number_of_commas)] > > for sslist in sslists: > counter = 0 > for term in sslist: > # The line below is where my program barfs. > sortedtermdict[term][counter] = term > counter = counter + 1 This increases counter once for each term in sslist, but sortedtermdict[term]'s length is a function of the number_of_commas, so when termlist if longer then number_of_commas, you'd get the error. HTH, Emile > > for row in sortedtermdict: > fn.writerow(row) > From goodpotatoes at yahoo.com Thu Sep 3 20:29:43 2009 From: goodpotatoes at yahoo.com (GoodPotatoes) Date: Thu, 3 Sep 2009 11:29:43 -0700 (PDT) Subject: [Tutor] Best Practice: Subroutines and Loop logic Message-ID: <586503.9469.qm@web51811.mail.re2.yahoo.com> Hello, I am trying to find the best way to do this. My goal is to only call this subroutine only ONCE, and the logic is contingent upon two outputs. lWords=[...] # List of many, many words lData=[...] #list of some words that need to be validated against lWords #subroutine to search for words, ignore case def sub1(foo): pFoo=re.compile(foo,re.I) for word in lWords: if re.search(pFoo,word): return[1,word] #logic loop for word in lData: if word in lWords: continue elif sub1(word)[0]=1: word=sub1(word)[1] # <--- Here is my question. else: print word " not found.\n" The subroutine is being run once at the elif statement. I don't want to run it again just to get the [1] value. *Is there any way to capture all of the values returned when it is run during the elif statement? *Is this actually running twice? -------------- next part -------------- An HTML attachment was scrubbed... URL: From dperlman at wisc.edu Thu Sep 3 21:17:11 2009 From: dperlman at wisc.edu (David Perlman) Date: Thu, 3 Sep 2009 14:17:11 -0500 Subject: [Tutor] Processing a string of bytes Message-ID: <5474EB65-0590-4CD9-B50D-95AF67FA7712@wisc.edu> I have successfully used the builtin "wave" module to read an audio file in as a string of bytes: >>> x=wave.open('DaCWL.wav','rb') >>> x.getparams() (1, 2, 44100, 15440, 'NONE', 'not compressed') >>> samp=x.readframes(15440) >>> type(samp) The x.getparams() indicates that there is one audio channel, 2 bytes per sample, 44100 sampling rate, and 15440 samples in the file. What I would like to know is, what is the most elegant and (dare I say it) pythonic way to do some processing on the resulting string of bytes, which represents a sequence of two-byte signed integers? The goal is to normalize the file, by taking the root-mean-square and then scaling every sample accordingly. So I only need to do simple arithmetic on the sample values. The obvious thing to do is to use a loop to get two bytes at a time, convert them to int, and work on the resulting list of ints. However this seems kind of inelegant, and wasteful of space, since python ints are way more than two bytes. Also I'm not sure if there's a convenient built-in way to do that conversion. So, in summary, I would be interested in either of two things: 1. advice on how to do arithmetic on the string of bytes without converting it to a list of ints first, or 2. advice on how to convert it to a list of ints, and then back to a string of bytes. Thanks very much! -- -dave---------------------------------------------------------------- "Pseudo-colored pictures of a person's brain lighting up are undoubtedly more persuasive than a pattern of squiggles produced by a polygraph. That could be a big problem if the goal is to get to the truth." -Dr. Steven Hyman, Harvard From jojo.mwebaze at gmail.com Fri Sep 4 00:01:52 2009 From: jojo.mwebaze at gmail.com (Jojo Mwebaze) Date: Fri, 4 Sep 2009 00:01:52 +0200 Subject: [Tutor] how to read and transmit/send only section of the image (sub-image) In-Reply-To: <1c2a2c590909030806h79268022y8a7c60ab4afcc8d9@mail.gmail.com> References: <3124be320909030605p23803349mf4d5e042fb5cf5f6@mail.gmail.com> <1c2a2c590909030806h79268022y8a7c60ab4afcc8d9@mail.gmail.com> Message-ID: <3124be320909031501v4f4dcdedt8919b891a90b0bbf@mail.gmail.com> thanks guys, Currently i am using pyfits, a bit slow cause loads the file in memory, creates a subimage and then saves the file then transmits the file over the network! My idea is, if there is a way of creating a file pointer to the location on disk, where the subimage lies, reading a specific size, and sending only the data read (like wayne had suggested) Do you think this possible? Johnson On Thu, Sep 3, 2009 at 5:06 PM, Kent Johnson wrote: > On Thu, Sep 3, 2009 at 9:05 AM, Jojo Mwebaze > wrote: > > Hello Tutor > > > > I am writing Class to provide data transfer between the server and client > > processes based on simple HTTP GET/POST operations. However my interest > is a > > sub-image (section of a full image). i am requesting help on how to read > and > > transmit/send only section of the image (sub-image). i also prefer read > the > > bytes (of the subimage) off the disk, without opening the file into > memory! > > > > The images i work with are of type FITS. > > I don't know much about FITS but my guess is you will have to read the > image into memory, create a new image with the sub-image you want, > then send the sub-image to the server. > > PyFITS looks like a good place to start... > http://www.stsci.edu/resources/software_hardware/pyfits/ > > Kent > -------------- next part -------------- An HTML attachment was scrubbed... URL: From transmogribenno at gmail.com Fri Sep 4 01:23:43 2009 From: transmogribenno at gmail.com (Benno Lang) Date: Fri, 4 Sep 2009 08:23:43 +0900 Subject: [Tutor] Best Practice: Subroutines and Loop logic In-Reply-To: <586503.9469.qm@web51811.mail.re2.yahoo.com> References: <586503.9469.qm@web51811.mail.re2.yahoo.com> Message-ID: <9b00d1a90909031623o798b6d29h2d29c1d58dcb583c@mail.gmail.com> On Fri, Sep 4, 2009 at 3:29 AM, GoodPotatoes wrote: > Hello, > > I am trying to find the best way to do this.? My goal is to only call this > subroutine only ONCE, and the logic is contingent upon two outputs. > > lWords=[...] # List of many, many words > lData=[...] #list of some words that need to be validated against lWords > > #subroutine to search for words, ignore case > def sub1(foo): > ??? pFoo=re.compile(foo,re.I) > ??? for word in lWords: > ??? ??? if re.search(pFoo,word): > ??? ??? ??? return[1,word] > > #logic loop > for word in lData: > ??? if word in lWords: > ??? ??? continue > ??? elif sub1(word)[0]=1: > ??? ??? word=sub1(word)[1]? # <--- Here is my question. > ??? else: > ??? ??? print word " not found.\n" > > The subroutine is being run once at the elif statement.? I don't want to run > it again just to get the [1] value. > ??? *Is there any way to capture all of the values returned when it is run > during the elif statement? Yes. BTW, since you have a continue, I don't think you need the elif. > ??? *Is this actually running twice? Yes, but it needn't. I think you would do something like this instead: if word in lWords: continue result = sub1(word): if result[0] == 1: word = result[1] else: print word " not found.\n" My apologies if this doesn't make any sense. I'm very much a beginner in Python. HTH, benno. From quasipedia at gmail.com Fri Sep 4 01:45:10 2009 From: quasipedia at gmail.com (Mac Ryan) Date: Fri, 04 Sep 2009 01:45:10 +0200 Subject: [Tutor] how to read and transmit/send only section of the image (sub-image) In-Reply-To: <3124be320909031501v4f4dcdedt8919b891a90b0bbf@mail.gmail.com> References: <3124be320909030605p23803349mf4d5e042fb5cf5f6@mail.gmail.com> <1c2a2c590909030806h79268022y8a7c60ab4afcc8d9@mail.gmail.com> <3124be320909031501v4f4dcdedt8919b891a90b0bbf@mail.gmail.com> Message-ID: <1252021510.20507.30.camel@jabbar> On Fri, 2009-09-04 at 00:01 +0200, Jojo Mwebaze wrote: > thanks guys, > > > Currently i am using pyfits, a bit slow cause loads the file in > memory, creates a subimage and then saves the file then transmits > the file over the network! My idea is, if there is a way of creating > a file pointer to the location on disk, where the subimage lies, > reading a specific size, and sending only the data read (like wayne > had suggested) > > > Do you think this possible? > > > Johnson I had no chance to look at the specific format of your image files, but unless it is an uncompressed raster I would guess what you want to do is rather difficult. Chances are indeed that the data in the image files are compressed, and this means that part of the information needed to properly render your sub-image lies in another part of the image that you are not interested in. Just think of compressed videos, a lot of codecs use the idea of "key frames": if for any reason you lose a key-frame, for a few seconds after that missing frame you won't see a proper video, but most probably a greenish moving blob, as what the video player is actually trying to do is modifying parts of the key-frame that is not there. Another problem is that the ratio raw data / compressed data is not constant throughout the entire file: I would guess that a portion of an image that is simply black deep space will be compressed in a few bytes, while a portion of the image of equal extension but with a galaxy in it will be compressed into a larger chunk of bytes, so - unless you have an index - it will be *very* hard for you to guess where your "sub-image" lies in your master file. Again: as I did not check out your file format specifically, you should check out by yourself if what above applies to you or not. It might well be that the format you are using was specifically designed to allow operations like the one you describe, and that the metainformation needed for you to access you sub-image are in the header of the master image. I just wanted to give you some input on you question "do you think this is possible?". :) Mac. From alan.gauld at btinternet.com Fri Sep 4 02:00:20 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 4 Sep 2009 01:00:20 +0100 Subject: [Tutor] Input validation References: <64384.19764.qm@web110710.mail.gq1.yahoo.com> Message-ID: "Albert-Jan Roskam" wrote > I'm wondering what is the most common method of input validation. Any and all of the methods will work in different situations but its generally best to use duck typing and try to write code that works for any type as far as possible. Then use exceptions to catch the ,erm, exceptions... So you could do try: param.readlines() except AttributeError: # not a file like object try param.uppercase() except AttributeError: # not a string And so on. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Fri Sep 4 02:09:31 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 4 Sep 2009 01:09:31 +0100 Subject: [Tutor] Best Practice: Subroutines and Loop logic References: <586503.9469.qm@web51811.mail.re2.yahoo.com> Message-ID: "GoodPotatoes" wrote > #logic loop > for word in lData: > if word in lWords: > continue > elif sub1(word)[0]=1: > word=sub1(word)[1] # <--- Here is my question. > else: > print word " not found.\n" > > The subroutine is being run once at the elif statement. > I don't want to run it again just to get the [1] value. > *Is there any way to capture all of the values returned when it is run > during the elif statement? Yes but you need to call it before the if. > #logic loop > for word in lData: test, wrd = sub1(word) > if word in lWords: > continue > elif test ==1: > word=wrd # <--- Here is my question. > else: > print word " not found.\n" > *Is this actually running twice? Yes, your code called sub1 twice. But my code has the disadvantage of now calling sub1 once for every word in IData. We can avoid that by inverting the if test: > for word in lData: > if word not in lWords: > test, wrd = sub1(word) > if test ==1: > word=wrd > else: > print word " not found.\n" That only calls sub1 when needed and only does it once even then HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From acallen99 at gmail.com Fri Sep 4 14:20:55 2009 From: acallen99 at gmail.com (zhang allen) Date: Fri, 4 Sep 2009 20:20:55 +0800 Subject: [Tutor] How to iterate through unicode string. Message-ID: Hi All, Say i have unicode string * B?ro*. i want to iterate this string . i write this python code which doesn't work. s ='B?ro' for ch in s: print ch it seems *B?ro* has 5 chars. *? *consists of 2 bytes. so does someone has any ideas? how to iterate this string, so i can hava 4 chars, like "B, ?, r, o ".? Thanks in advance. -- Best Regards, Allen -------------- next part -------------- An HTML attachment was scrubbed... URL: From andreengels at gmail.com Fri Sep 4 14:27:25 2009 From: andreengels at gmail.com (Andre Engels) Date: Fri, 4 Sep 2009 14:27:25 +0200 Subject: [Tutor] How to iterate through unicode string. In-Reply-To: References: Message-ID: <6faf39c90909040527h4412797ahd4ffc7a9db48b841@mail.gmail.com> On Fri, Sep 4, 2009 at 2:20 PM, zhang allen wrote: > Hi All, > > Say i have unicode string? B?ro. > i want to iterate this string . > > i write this python code which doesn't work. > > s ='B?ro' > for ch in s: > ??? print ch > > it seems B?ro has 5 chars. ? consists of 2 bytes. > > so does someone has any ideas? > > how to iterate this string, so i can hava 4 chars, like "B, ?, r, o ".? > > Thanks in advance. Try replacing s ='B?ro' by s = u'B?ro' The 'u' denotes that the string is to be interpretred as unicode. -- Andr? Engels, andreengels at gmail.com From cwitts at compuscan.co.za Fri Sep 4 14:50:52 2009 From: cwitts at compuscan.co.za (Christian Witts) Date: Fri, 04 Sep 2009 14:50:52 +0200 Subject: [Tutor] How to iterate through unicode string. In-Reply-To: References: Message-ID: <4AA10D2C.2050606@compuscan.co.za> zhang allen wrote: > Hi All, > > Say i have unicode string * B?ro*. > i want to iterate this string . > > i write this python code which doesn't work. > > s ='B?ro' > for ch in s: > print ch > > it seems *B?ro* has 5 chars. *? *consists of 2 bytes. > > so does someone has any ideas? > > how to iterate this string, so i can hava 4 chars, like "B, ?, r, o ".? > > Thanks in advance. > > > -- > Best Regards, > Allen > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > >>> s = 'B?ro' >>> for ch in s: ... print ch ... B ? r o You need to make it a unicode string. s = u'B?ro' >>> for ch in s: ... print ch ... B ? r o -- Kind Regards, Christian Witts From acallen99 at gmail.com Fri Sep 4 14:33:49 2009 From: acallen99 at gmail.com (zhang allen) Date: Fri, 4 Sep 2009 20:33:49 +0800 Subject: [Tutor] How to iterate through unicode string. In-Reply-To: <6faf39c90909040527h4412797ahd4ffc7a9db48b841@mail.gmail.com> References: <6faf39c90909040527h4412797ahd4ffc7a9db48b841@mail.gmail.com> Message-ID: Hi Andre, i tried this. s = u'B?ro' print len(s) prints 5. it seems not working : ) 2009/9/4 Andre Engels > On Fri, Sep 4, 2009 at 2:20 PM, zhang allen wrote: > > Hi All, > > > > Say i have unicode string B?ro. > > i want to iterate this string . > > > > i write this python code which doesn't work. > > > > s ='B?ro' > > for ch in s: > > print ch > > > > it seems B?ro has 5 chars. ? consists of 2 bytes. > > > > so does someone has any ideas? > > > > how to iterate this string, so i can hava 4 chars, like "B, ?, r, o ".? > > > > Thanks in advance. > > Try replacing > s ='B?ro' > by > s = u'B?ro' > > The 'u' denotes that the string is to be interpretred as unicode. > > > > -- > Andr? Engels, andreengels at gmail.com > -- Best Regards, Allen -------------- next part -------------- An HTML attachment was scrubbed... URL: From acallen99 at gmail.com Fri Sep 4 14:43:18 2009 From: acallen99 at gmail.com (zhang allen) Date: Fri, 4 Sep 2009 20:43:18 +0800 Subject: [Tutor] How to iterate through unicode string. In-Reply-To: <4AA10D2C.2050606@compuscan.co.za> References: <4AA10D2C.2050606@compuscan.co.za> Message-ID: Hi Christian, Thanks for your tip. But it seems to me still not working again. i wirte this python code k = [] s = u'B?ro' for c in s: k.append(c) print k k=[u'B', u'\xa8', u'\xb9', u'r', u'o'] i still have 5 different chars. 2009/9/4 Christian Witts > zhang allen wrote: > >> Hi All, >> >> Say i have unicode string * B?ro*. >> i want to iterate this string . >> >> i write this python code which doesn't work. >> >> s ='B?ro' >> for ch in s: >> print ch >> >> it seems *B?ro* has 5 chars. *? *consists of 2 bytes. >> >> so does someone has any ideas? >> >> how to iterate this string, so i can hava 4 chars, like "B, ?, r, o ".? >> >> Thanks in advance. >> >> >> -- >> Best Regards, >> Allen >> ------------------------------------------------------------------------ >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> >> > >>> s = 'B?ro' > >>> for ch in s: > ... print ch > ... > B > > ? > r > o > > You need to make it a unicode string. > > s = u'B?ro' > >>> for ch in s: > ... print ch > ... > B > ? > r > o > > -- > Kind Regards, > Christian Witts > > > -- Best Regards, Allen -------------- next part -------------- An HTML attachment was scrubbed... URL: From dstanek at dstanek.com Fri Sep 4 15:04:22 2009 From: dstanek at dstanek.com (David Stanek) Date: Fri, 4 Sep 2009 09:04:22 -0400 Subject: [Tutor] How to iterate through unicode string. In-Reply-To: References: <4AA10D2C.2050606@compuscan.co.za> Message-ID: Is the encoding of your file set? On 9/4/09, zhang allen wrote: > Hi Christian, > > Thanks for your tip. > > But it seems to me still not working again. > > i wirte this python code > > k = [] > s = u'B?ro' > for c in s: > k.append(c) > print k > > k=[u'B', u'\xa8', u'\xb9', u'r', u'o'] > > i still have 5 different chars. > > > > > > 2009/9/4 Christian Witts > >> zhang allen wrote: >> >>> Hi All, >>> >>> Say i have unicode string * B?ro*. >>> i want to iterate this string . >>> >>> i write this python code which doesn't work. >>> >>> s ='B?ro' >>> for ch in s: >>> print ch >>> >>> it seems *B?ro* has 5 chars. *? *consists of 2 bytes. >>> >>> so does someone has any ideas? >>> >>> how to iterate this string, so i can hava 4 chars, like "B, ?, r, o ".? >>> >>> Thanks in advance. >>> >>> >>> -- >>> Best Regards, >>> Allen >>> ------------------------------------------------------------------------ >>> >>> _______________________________________________ >>> Tutor maillist - Tutor at python.org >>> To unsubscribe or change subscription options: >>> http://mail.python.org/mailman/listinfo/tutor >>> >>> >> >>> s = 'B?ro' >> >>> for ch in s: >> ... print ch >> ... >> B >> >> ? >> r >> o >> >> You need to make it a unicode string. >> >> s = u'B?ro' >> >>> for ch in s: >> ... print ch >> ... >> B >> ? >> r >> o >> >> -- >> Kind Regards, >> Christian Witts >> >> >> > > > -- > Best Regards, > Allen > -- Sent from my mobile device David blog: http://www.traceback.org twitter: http://twitter.com/dstanek From cwitts at compuscan.co.za Fri Sep 4 15:27:18 2009 From: cwitts at compuscan.co.za (Christian Witts) Date: Fri, 04 Sep 2009 15:27:18 +0200 Subject: [Tutor] How to iterate through unicode string. In-Reply-To: References: <4AA10D2C.2050606@compuscan.co.za> Message-ID: <4AA115B6.7090209@compuscan.co.za> If it's not you can put an encoding line @ the top of your script like # -*- encoding: utf-8 -*- David Stanek wrote: > Is the encoding of your file set? > > On 9/4/09, zhang allen wrote: > >> Hi Christian, >> >> Thanks for your tip. >> >> But it seems to me still not working again. >> >> i wirte this python code >> >> k = [] >> s = u'B?ro' >> for c in s: >> k.append(c) >> print k >> >> k=[u'B', u'\xa8', u'\xb9', u'r', u'o'] >> >> i still have 5 different chars. >> >> >> >> >> >> 2009/9/4 Christian Witts >> >> >>> zhang allen wrote: >>> >>> >>>> Hi All, >>>> >>>> Say i have unicode string * B?ro*. >>>> i want to iterate this string . >>>> >>>> i write this python code which doesn't work. >>>> >>>> s ='B?ro' >>>> for ch in s: >>>> print ch >>>> >>>> it seems *B?ro* has 5 chars. *? *consists of 2 bytes. >>>> >>>> so does someone has any ideas? >>>> >>>> how to iterate this string, so i can hava 4 chars, like "B, ?, r, o ".? >>>> >>>> Thanks in advance. >>>> >>>> >>>> -- >>>> Best Regards, >>>> Allen >>>> ------------------------------------------------------------------------ >>>> >>>> _______________________________________________ >>>> Tutor maillist - Tutor at python.org >>>> To unsubscribe or change subscription options: >>>> http://mail.python.org/mailman/listinfo/tutor >>>> >>>> >>>> >>>>>> s = 'B?ro' >>>>>> for ch in s: >>>>>> >>> ... print ch >>> ... >>> B >>> >>> ? >>> r >>> o >>> >>> You need to make it a unicode string. >>> >>> s = u'B?ro' >>> >>>>>> for ch in s: >>>>>> >>> ... print ch >>> ... >>> B >>> ? >>> r >>> o >>> >>> -- >>> Kind Regards, >>> Christian Witts >>> >>> >>> >>> >> -- >> Best Regards, >> Allen >> >> > > -- Kind Regards, Christian Witts From acallen99 at gmail.com Fri Sep 4 15:14:12 2009 From: acallen99 at gmail.com (zhang allen) Date: Fri, 4 Sep 2009 21:14:12 +0800 Subject: [Tutor] How to iterate through unicode string. In-Reply-To: <4AA115B6.7090209@compuscan.co.za> References: <4AA10D2C.2050606@compuscan.co.za> <4AA115B6.7090209@compuscan.co.za> Message-ID: Thank you very much. :) it works now. 2009/9/4 Christian Witts > If it's not you can put an encoding line @ the top of your script like > # -*- encoding: utf-8 -*- > > David Stanek wrote: > >> Is the encoding of your file set? >> >> >> On 9/4/09, zhang allen wrote: >> >> >>> Hi Christian, >>> >>> Thanks for your tip. >>> >>> But it seems to me still not working again. >>> >>> i wirte this python code >>> >>> k = [] >>> s = u'B?ro' >>> for c in s: >>> k.append(c) >>> print k >>> >>> k=[u'B', u'\xa8', u'\xb9', u'r', u'o'] >>> >>> i still have 5 different chars. >>> >>> >>> >>> >>> >>> 2009/9/4 Christian Witts >>> >>> >>> >>>> zhang allen wrote: >>>> >>>> >>>> >>>>> Hi All, >>>>> >>>>> Say i have unicode string * B?ro*. >>>>> i want to iterate this string . >>>>> >>>>> i write this python code which doesn't work. >>>>> >>>>> s ='B?ro' >>>>> for ch in s: >>>>> print ch >>>>> >>>>> it seems *B?ro* has 5 chars. *? *consists of 2 bytes. >>>>> >>>>> so does someone has any ideas? >>>>> >>>>> how to iterate this string, so i can hava 4 chars, like "B, ?, r, o ".? >>>>> >>>>> Thanks in advance. >>>>> >>>>> >>>>> -- >>>>> Best Regards, >>>>> Allen >>>>> >>>>> ------------------------------------------------------------------------ >>>>> >>>>> _______________________________________________ >>>>> Tutor maillist - Tutor at python.org >>>>> To unsubscribe or change subscription options: >>>>> http://mail.python.org/mailman/listinfo/tutor >>>>> >>>>> >>>>> >>>>> >>>>>> s = 'B?ro' >>>>>>> for ch in s: >>>>>>> >>>>>>> >>>>>> ... print ch >>>> ... >>>> B >>>> >>>> ? >>>> r >>>> o >>>> >>>> You need to make it a unicode string. >>>> >>>> s = u'B?ro' >>>> >>>> >>>>> for ch in s: >>>>>>> >>>>>>> >>>>>> ... print ch >>>> ... >>>> B >>>> ? >>>> r >>>> o >>>> >>>> -- >>>> Kind Regards, >>>> Christian Witts >>>> >>>> >>>> >>>> >>>> >>> -- >>> Best Regards, >>> Allen >>> >>> >>> >> >> >> > > -- > Kind Regards, > Christian Witts > > > -- Best Regards, Allen -------------- next part -------------- An HTML attachment was scrubbed... URL: From dirk at pensiun.com Fri Sep 4 15:14:51 2009 From: dirk at pensiun.com (Dirk Wangsadirdja) Date: Fri, 04 Sep 2009 15:14:51 +0200 Subject: [Tutor] How to iterate through unicode string. In-Reply-To: References: <4AA10D2C.2050606@compuscan.co.za> Message-ID: <4AA112CB.70303@pensiun.com> Hi allen (and perhaps this goes also for others), just a suggestion, maybe when we post a problem, we should also mention the python version that we use. Sometimes, different version of python would give different results. I tried it with Python 3.1 (python 3.x uses unicode for string) and Python 2.6.2 (applying the s = u'B?ro') and both give me 4 characters. Sorry, I only have those 2 version installed. Regards, Dirk zhang allen wrote: > Hi Christian, > > Thanks for your tip. > > But it seems to me still not working again. > > i wirte this python code > > k = [] > s = u'B?ro' > for c in s: > k.append(c) > print k > > k=[u'B', u'\xa8', u'\xb9', u'r', u'o'] > > i still have 5 different chars. > > From kent37 at tds.net Fri Sep 4 15:56:35 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 4 Sep 2009 09:56:35 -0400 Subject: [Tutor] how to read and transmit/send only section of the image (sub-image) In-Reply-To: <3124be320909031501v4f4dcdedt8919b891a90b0bbf@mail.gmail.com> References: <3124be320909030605p23803349mf4d5e042fb5cf5f6@mail.gmail.com> <1c2a2c590909030806h79268022y8a7c60ab4afcc8d9@mail.gmail.com> <3124be320909031501v4f4dcdedt8919b891a90b0bbf@mail.gmail.com> Message-ID: <1c2a2c590909040656s3f65e77al32b1331fbd97402b@mail.gmail.com> On Thu, Sep 3, 2009 at 6:01 PM, Jojo Mwebaze wrote: > thanks guys, > Currently i am using pyfits, a bit slow cause loads the file in memory, > creates a subimage and then saves the file then transmits > the?file?over?the?network! My idea is, ?if?there?is?a?way?of?creating a file > pointer to the location on disk, where the subimage lies, reading a specific > size, and ?sending only the data read (like wayne had suggested) > Do you think this possible? Not by just reading a single portion of the file; even for an uncompressed bare raster image this would only work if the sub-image is the same width as the original. For a FITS file you also need to create a new header. It is technically possible to construct a subimage in memory without reading the original into memory but you would have to understand the details of the FITS format. You may be able to transmit the image without saving it first. Or perhaps one of the other FITS libs is faster. Kent From kent37 at tds.net Fri Sep 4 16:01:05 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 4 Sep 2009 10:01:05 -0400 Subject: [Tutor] Processing a string of bytes In-Reply-To: <5474EB65-0590-4CD9-B50D-95AF67FA7712@wisc.edu> References: <5474EB65-0590-4CD9-B50D-95AF67FA7712@wisc.edu> Message-ID: <1c2a2c590909040701r75a7a126nc792f20ddc9e3217@mail.gmail.com> On Thu, Sep 3, 2009 at 3:17 PM, David Perlman wrote: > So, in summary, I would be interested in either of two things: > 1. advice on how to do arithmetic on the string of bytes without converting > it to a list of ints first, or > 2. advice on how to convert it to a list of ints, and then back to a string > of bytes. Use the struct module to do the conversion. Don't worry about the memory; 15000 integers is not much. You have to convert to a numeric form to do you calculations, anyway. Kent From dan.king106 at yahoo.com Fri Sep 4 15:18:40 2009 From: dan.king106 at yahoo.com (dan06) Date: Fri, 4 Sep 2009 06:18:40 -0700 (PDT) Subject: [Tutor] Help deciding between python and ruby Message-ID: <25294195.post@talk.nabble.com> I'd like to learn a programming language - and I need help deciding between python and ruby. I'm interesting in learning what are the difference, both objective and subjective, between the two languages. I know this is a python mailing list, so knowledge/experience with ruby may be limited - in which case I'd still be interested in learning why members of this mailing list chose python over (or in addition to) any other programming language. I look forward to the feedback/insight. -- View this message in context: http://www.nabble.com/Help-deciding-between-python-and-ruby-tp25294195p25294195.html Sent from the Python - tutor mailing list archive at Nabble.com. From roadierich at googlemail.com Fri Sep 4 16:38:41 2009 From: roadierich at googlemail.com (Rich Lovely) Date: Fri, 4 Sep 2009 15:38:41 +0100 Subject: [Tutor] Input validation In-Reply-To: <64384.19764.qm@web110710.mail.gq1.yahoo.com> References: <64384.19764.qm@web110710.mail.gq1.yahoo.com> Message-ID: 2009/9/3 Albert-Jan Roskam : > Hi, > > I'm wondering what is the most common method of input validation. See the example below. > -Is the code below the most common/recognizable way something like this is done? > -Which of the options #1 and #2 is the preferred method? Option #2 looks less esoteric, but #1 seems better when you have to check for several data types simultaneously. > > Thanks! > Albert-Jan > > import os.path, textwrap > > def main(param): > ? ?if validate_input(param) == "LT": > ? ? ? ?return param[-1] > ? ?elif validate_input(param) == "FILE": > ? ? ? ?f = open(param, "rb").readlines() > ? ? ? ?return " ".join(f) > ? ?elif validate_input(param) == "STR": > ? ? ? ?return textwrap.wrap(param) > ? ?else: > ? ? ? ?print "Invalid input!" > ? ? ? ?return None > > def validate_input (param): > ? ?if param.__class__ in (list, tuple): #option 1 > ? ? ? ?return "LT" > ? ?elif isinstance(param, str): ? ? ? ?# option 2 > ? ? ? ?if os.path.isfile(param): > ? ? ? ? ? ?return "FILE" > ? ? ? ?else: > ? ? ? ? ? ?return "STR" > ? ?else: > ? ? ? ?return None > > print main(param=[1,2,3]) > print main(param="d:/temp/txt.txt") > print main(param="yeah but yeah, but no") > print main(param=1.0) > > > > > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > isinstance can take a tuple of types: def validate_input (param): if isinstance(param, (list, tuple)): #option 1 return "LT" elif isinstance(param, str): # option 2 if os.path.isfile(param): return "FILE" else: return "STR" else: return None Also, file-type objects aren't instances of str... -- Rich "Roadie Rich" Lovely There are 10 types of people in the world: those who know binary, those who do not, and those who are off by one. From rabidpoobear at gmail.com Fri Sep 4 17:01:14 2009 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Fri, 4 Sep 2009 17:01:14 +0200 Subject: [Tutor] Help deciding between python and ruby In-Reply-To: <25294195.post@talk.nabble.com> References: <25294195.post@talk.nabble.com> Message-ID: A primary draw of Ruby has always been Ruby on Rails, a web framework. Python has a lot of really good web frameworks now, though, so this is less of a concern.When I tried to learn Ruby, the docs were terrible. The primary developers are Japanese, and the translations were very poor and incomplete. I hear it's much better now but I haven't bothered checking. Also, language syntax is very important to me, and (here's the subjective bit) I thought Ruby's syntax was awful compared to Python's, though better than a lot of other languages. IF you're concerned about the power of Python, consider this: I'm a Computer Science grad student, and I've worked in the industry as well (internships and such), so I've used a myriad of languages (C, C++, C#, Java, Python, PHP, JSP, Perl, all the web stuff, etc, etc.) both academically and professionally, but I use Python for ALL of my personal projects. If something's not fast enough, I just drop that part down to C. Easy peasy lemon squeezy. Okay, C stuff is a little involved. But Python is so fast I hardly ever have to do that, even when I do game programming. I just like languages to be as transparent as possible. Python fits with the way I solve problems. When I read over a Python program I've written, all the syntax just drops away and I see the algorithms I had in my head when I wrote the code. I document, but I don't really need to most of the time. I really like Python. Also if you haven't noticed, a lot of the code examples on Wikipedia are Python, not pseudocode. Python's actually easier to read than pseudocode, because it has a more well-defined syntax (pseudocode is pretty much made up as you go along.) Python's standard library and community are also outstanding. Come join us! You'll like it here. http://xkcd.com/353/ It might be a good idea to try what Randall did, write 20 short programs (calculate fibonacci, prefix sums, merge sort, auto-organize a folder that's been bothering you, something like that) in both Python and Ruby and see which one you like more. Let us know what you decide, especially if you choose Ruby! I'd like to know your reasoning. If you have any problems with Python we'll be happy to help! Just make sure you read the rules for posting, and that you make a concerted effort to figure it out yourself. That's really the best way to learn a language; we try to give you just enough help to get you on your way, without just solving everything for you. Good luck! -Luke On Fri, Sep 4, 2009 at 3:18 PM, dan06 wrote: > > I'd like to learn a programming language - and I need help deciding between > python and ruby. I'm interesting in learning what are the difference, both > objective and subjective, between the two languages. I know this is a > python > mailing list, so knowledge/experience with ruby may be limited - in which > case I'd still be interested in learning why members of this mailing list > chose python over (or in addition to) any other programming language. I > look > forward to the feedback/insight. > -- > View this message in context: > http://www.nabble.com/Help-deciding-between-python-and-ruby-tp25294195p25294195.html > Sent from the Python - tutor mailing list archive at Nabble.com. > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From yam at nerd.cx Fri Sep 4 18:09:19 2009 From: yam at nerd.cx (William Witteman) Date: Fri, 4 Sep 2009 12:09:19 -0400 Subject: [Tutor] Having trouble with a dictionary of lists In-Reply-To: References: <20090903180111.GA28199@yam.witteman.ca> Message-ID: <20090904160919.GA30430@yam.witteman.ca> On Thu, Sep 03, 2009 at 11:26:35AM -0700, Emile van Sebille wrote: Thanks to Emile for pointing out the error. There were several other errors - initiating the counter in the loop (d'oh!), premature sorting of the dictionary by keys, not providing an index row for the output file, not returning anything from my function, and probably others. Here is how it looks now - any pointers, stylistic or otherwise, are welcome. It does, however, work. #!/usr/bin/python """ Take a collection of lists, combine them into one list, deleting duplicates. Sort the list and use it as the leftmost column of a table. Then put each lists contents into the table, one per column, with the elements aligned with the leftmost (index) column. """ import os, sys, csv def cmpss(filename,*sslists): """Write a CSV file from the collection of lists.""" if os.path.exists(filename): print("%s exists: please choose another filename." % filename) sys.exit(1) else: try: fn = csv.writer(open(filename, "w")) except IOError: print("There is a problem opening the requested file. Sorry.") sys.exit(1) toprow = [x for x in range(len(sslists))] toprow.insert(0, "index") fn.writerow(toprow) termdict = {} number_of_columns = len(sslists) for sslist in sslists: for term in sslist: termdict[term] = ["" for x in range(number_of_columns)] sortedtermlist = termdict.keys() sortedtermlist.sort() counter = 0 for sslist in sslists: for term in sslist: #debug print(counter) #debug print(term) termdict[term][counter] = term counter = counter + 1 for term in sortedtermlist: row = [term] row.extend(termdict[term]) fn.writerow(row) return termdict -- yours, William From quasipedia at gmail.com Fri Sep 4 18:30:34 2009 From: quasipedia at gmail.com (Mac Ryan) Date: Fri, 04 Sep 2009 18:30:34 +0200 Subject: [Tutor] Help deciding between python and ruby In-Reply-To: <25294195.post@talk.nabble.com> References: <25294195.post@talk.nabble.com> Message-ID: <1252081834.23990.60.camel@jabbar> On Fri, 2009-09-04 at 06:18 -0700, dan06 wrote: > I'd like to learn a programming language - and I need help deciding between > python and ruby. I'm interesting in learning what are the difference, both > objective and subjective, between the two languages. I know this is a python > mailing list, so knowledge/experience with ruby may be limited - in which > case I'd still be interested in learning why members of this mailing list > chose python over (or in addition to) any other programming language. I look > forward to the feedback/insight. IMO "python vs. ruby", "vi vs. emacs", "gtk vs qt" and company are all kind of comparisons where the ultimate "right" outcome is invariably a matter of taste. Both languages are powerful, mature and flexible enough to be used as an "all round" programming language. The only "objective" factor that IMO is truly important in the choice is if you are planning to develop for a specific platform that is biased towards one of the two. For example, I am using a linux distro (ubuntu) which is strongly python-oriented, and picking python instead of ruby makes my development cycle easier/smoother (all most commonly needed libs are in the repos, packages are up-to-date, most of the documentation has been ported to the standard developer's help application, etc...). As for "subjective" reasons, I can only share those that played a role *for me*: 1. Python community is fun-oriented: having fun while programming and while learning is part of the established python-culture. I tend to be an happy person, and I simply enjoy reading a book or following a tutorial that cracks a joke here and there and that does not take itself too seriously. 2. Whitespace is significant: this in turns makes code look very much alike on a page regardless of whom wrote it. Code is clean... I tend to be a clean person too! ;) 3. Python is heavily adopted by companies with a long-standing tradition of openness (in the sense of free-as-in-freedom-software). I could name here at least two: Canonical ltd. (mother of ubuntu) and Google inc. (you might have heard of it already ;). 4. I love the "monthy python". 5. Support in python communities is awesome, again I believe this has something to do with the "python-culture". Take this list as an example: it seems that people here made an oath to go the extra mile in helping others, and supporting them in their own learning. 6. Python comes with "batteries included" (i.e. the core distribution has a lot of functionalities that in other languages would require you to import external resources). While this makes it slightly bigger than more essential languages, I still feel the trade-off in terms of productivity and fun are worth the extra weight). That's why *I* chose python over ruby. As Luke already said, I would be happy too to know your reasoning if you would finally choose to go for ruby! Best luck, Mac. From emile at fenx.com Fri Sep 4 18:54:20 2009 From: emile at fenx.com (Emile van Sebille) Date: Fri, 04 Sep 2009 09:54:20 -0700 Subject: [Tutor] Having trouble with a dictionary of lists In-Reply-To: <20090904160919.GA30430@yam.witteman.ca> References: <20090903180111.GA28199@yam.witteman.ca> <20090904160919.GA30430@yam.witteman.ca> Message-ID: On 9/4/2009 9:09 AM William Witteman said... > On Thu, Sep 03, 2009 at 11:26:35AM -0700, Emile van Sebille wrote: > > Thanks to Emile for pointing out the error. There were several other > errors - initiating the counter in the loop (d'oh!), premature sorting > of the dictionary by keys, not providing an index row for the output > file, not returning anything from my function, and probably others. > > Here is how it looks now - any pointers, stylistic or otherwise, are > welcome. It does, however, work. That's normally when I stop looking at it. If I'm lucky, I'll never need to work on it again. If and when I do, that's when I clean it up in the area that needs attention. It's way to easy IMHO to turn one-off projects into time-sinks. Anyway, some notes interspersed below... Emile > > #!/usr/bin/python > > """ > Take a collection of lists, combine them into one list, deleting duplicates. > Sort the list and use it as the leftmost column of a table. Then put each > lists contents into the table, one per column, with the elements aligned > with the leftmost (index) column. > > """ > > import os, sys, csv > > def cmpss(filename,*sslists): > """Write a CSV file from the collection of lists.""" > > if os.path.exists(filename): > print("%s exists: please choose another filename." % filename) > sys.exit(1) > else: > try: > fn = csv.writer(open(filename, "w")) > except IOError: > print("There is a problem opening the requested file. Sorry.") > sys.exit(1) > toprow = [x for x in range(len(sslists))] This looks like toprow is simply range(len(sslists))... > toprow.insert(0, "index") > fn.writerow(toprow) > > termdict = {} > number_of_columns = len(sslists) > > for sslist in sslists: > for term in sslist: > termdict[term] = ["" for x in range(number_of_columns)] this might also be said [""]*number_of_columns > > sortedtermlist = termdict.keys() > sortedtermlist.sort() > > counter = 0 > > for sslist in sslists: > for term in sslist: > #debug print(counter) > #debug print(term) > termdict[term][counter] = term > counter = counter + 1 > > for term in sortedtermlist: > row = [term] > row.extend(termdict[term]) > fn.writerow(row) > > return termdict > > From bermanrl at cfl.rr.com Fri Sep 4 16:10:12 2009 From: bermanrl at cfl.rr.com (Robert Berman) Date: Fri, 04 Sep 2009 10:10:12 -0400 Subject: [Tutor] Help deciding between python and ruby In-Reply-To: <25294195.post@talk.nabble.com> References: <25294195.post@talk.nabble.com> Message-ID: <1252073412.6295.150.camel@bermanrl-desktop> I think you will get at the least a slight bias toward Python. However, I think you should do your own research and reach your own conclusions. Simply to get you started I put the following into Google: 'Python or Ruby: Which to learn' and got more than 1M hits. Best of luck. Robert On Fri, 2009-09-04 at 06:18 -0700, dan06 wrote: > I'd like to learn a programming language - and I need help deciding between > python and ruby. I'm interesting in learning what are the difference, both > objective and subjective, between the two languages. I know this is a python > mailing list, so knowledge/experience with ruby may be limited - in which > case I'd still be interested in learning why members of this mailing list > chose python over (or in addition to) any other programming language. I look > forward to the feedback/insight. From goodpotatoes at yahoo.com Fri Sep 4 19:34:51 2009 From: goodpotatoes at yahoo.com (GoodPotatoes) Date: Fri, 4 Sep 2009 10:34:51 -0700 (PDT) Subject: [Tutor] Simple regex replacement match (converting from Perl) In-Reply-To: References: <20090903180111.GA28199@yam.witteman.ca> <20090904160919.GA30430@yam.witteman.ca> Message-ID: <576727.44620.qm@web51803.mail.re2.yahoo.com> I simply want to remark out all non-word characters read from a line. Line: Q*bert says "#@!$% " in Perl #match each non-word character, add "\" before it, globally. $_=s/(\W)/\\$1/g; output: Q\*bert\ says\ \"\#\@\!\$\%\ \ \" #perfect! Is there something simple like this in python? I would imagine: foo='Q*bert says "#@!$% "' pNw=re.compile('(\W)') re.sub(pNw,'\\'+(match of each non-word character),foo) How do I get the match into this function? Is there a different way to do this? -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Fri Sep 4 19:54:11 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 4 Sep 2009 18:54:11 +0100 Subject: [Tutor] Help deciding between python and ruby References: <25294195.post@talk.nabble.com> Message-ID: "dan06" wrote > I'd like to learn a programming language - and I need help deciding > between > python and ruby. I'm interesting in learning what are the difference, There is lots of info on their web sites. asking a question like this is troll baiting in a big way, any debate about languages will allways be subjective. It is almost impossible to compare languages objectively, even the academic researchers who have tried have usually only succeeded in revealing what they think is important in language design... I chose Python for 2 main reasons 1) At the time I chose Ruby was in its infancy and almost all docs were in Japanese! 2) Ruby uses $ signs etc to indicate variable types etc which I hate. Python has started down that road using @ to indicate a decorator but it didn't have any of that crud at the time I chose it. (around 1998) But I almost moved to Ruby after the Hunt/Thomas book came out. Because.... Things I like about Ruby that I wish Python had: 1) anonymous code blocks. Thats it. But they are so insanely well implemented that I weep everytime I look at Python's lambdas nowadays... However I do prefer the way Python doesn't try to insist that everything has to be done using OOP, and that pure functional styles are catered for too. (Ruby supports FP well but only within an OOP context!) Otherwise there is very little to choose between them as languages and I'd consider things like quality of support in terms of community, web documents/tutors, 3rd party libraries etc. And finally your own tastes and programming requirements. What kind of programming will you be doing? Either way its not a one way street, learn either one and you will pick up the other very quickly. They are very similar both in style and even syntax.. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From yam at nerd.cx Fri Sep 4 20:17:16 2009 From: yam at nerd.cx (William Witteman) Date: Fri, 4 Sep 2009 14:17:16 -0400 Subject: [Tutor] Having trouble with a dictionary of lists In-Reply-To: References: <20090903180111.GA28199@yam.witteman.ca> <20090904160919.GA30430@yam.witteman.ca> Message-ID: <20090904181716.GA31610@yam.witteman.ca> On Fri, Sep 04, 2009 at 09:54:20AM -0700, Emile van Sebille wrote: >On 9/4/2009 9:09 AM William Witteman said... >>On Thu, Sep 03, 2009 at 11:26:35AM -0700, Emile van Sebille wrote: >> >>Thanks to Emile for pointing out the error. There were several other >>errors - initiating the counter in the loop (d'oh!), premature sorting >>of the dictionary by keys, not providing an index row for the output >>file, not returning anything from my function, and probably others. >> >>Here is how it looks now - any pointers, stylistic or otherwise, are >>welcome. It does, however, work. > >That's normally when I stop looking at it. If I'm lucky, I'll never >need to work on it again. If and when I do, that's when I clean it >up in the area that needs attention. It's way to easy IMHO to turn >one-off projects into time-sinks. > >Anyway, some notes interspersed below... Thanks! >> toprow = [x for x in range(len(sslists))] > >This looks like toprow is simply range(len(sslists))... Yes, until this next row... >> toprow.insert(0, "index") >> termdict[term] = ["" for x in range(number_of_columns)] > >this might also be said [""]*number_of_columns I was concerned that this would give me this: [""],[""],[""] rather than this: ["","",""] I see now that it doesn't but the list comprehension seems really fast compared to the multiplication. Is that true? -- yours, William From malaclypse2 at gmail.com Fri Sep 4 21:00:43 2009 From: malaclypse2 at gmail.com (Jerry Hill) Date: Fri, 4 Sep 2009 15:00:43 -0400 Subject: [Tutor] Simple regex replacement match (converting from Perl) In-Reply-To: <576727.44620.qm@web51803.mail.re2.yahoo.com> References: <20090903180111.GA28199@yam.witteman.ca> <20090904160919.GA30430@yam.witteman.ca> <576727.44620.qm@web51803.mail.re2.yahoo.com> Message-ID: <16651e80909041200u61348eb8qd70d81f877cd63a5@mail.gmail.com> On Fri, Sep 4, 2009 at 1:34 PM, GoodPotatoes wrote: > I simply want to remark out all non-word characters read from a line. > > Line: > Q*bert says "#@!$%? " > > in Perl > #match each non-word character, add "\" before it, globally. > > $_=s/(\W)/\\$1/g; > > output: > Q\*bert\ says\ \"\#\@\!\$\%\ \ \"? #perfect! > > Is there something simple like this in python? > > I would imagine: > foo='Q*bert says "#@!$%? "' > pNw=re.compile('(\W)') > re.sub(pNw,'\\'+(match of each non-word character),foo) > > How do I get the match into this function?? Is there a different way to do > this? Like this: >>> import re >>> line = 'Q*bert says "#@!$% "' >>> pattern = re.compile(r"(\W)") >>> re.sub(pattern, r"\\\1", line) 'Q\\*bert\\ says\\ \\"\\#\\@\\!\\$\\%\\ \\ \\"' Note that line is showing the single backslashes doubled up, because it's the repr of the string. If you print the string instead, you'll see what you expect: >>> print re.sub(pattern, r"\\\1", line) Q\*bert\ says\ \"\#\@\!\$\%\ \ \" >>> When you're using re.sub, \1 is the value of the first match. It's also helpful to use raw strings when you're using the python re library, since both python and the regular expression library use '\' as an escape character. (See the top of http://docs.python.org/library/re.html for more details). -- Jerry From kb1pkl at aim.com Fri Sep 4 21:07:39 2009 From: kb1pkl at aim.com (kb1pkl at aim.com) Date: Fri, 04 Sep 2009 15:07:39 -0400 Subject: [Tutor] (no subject) Message-ID: <8CBFBAA1AF96463-35D0-6044@webmail-d074.sysops.aol.com> On Fri, 2009-09-04 at 06:18 -0700, dan06 wrote: > I'd like to learn a programming language - and I need help deciding between > python and ruby. I'm interesting in learning what are the difference, both > objective and subjective, between the two languages. I know this is a python > mailing list, so knowledge/experience with ruby may be limited - in which > case I'd still be interested in learning why members of this mailing list > chose python over (or in addition to) any other programming language. I look > forward to the feedback/insight. I first learned about Python when I downloaded Blender, and It is required for all the things to work. I decided that while I had it, I might as well just learn how to use it. I googled a tutorial, found out how easy it was, and then it had me. I have some experience with Actionscript, Adobes code for Flash. After doing a really simple python tutorial, I found everything else falling into place. Thats why I chose it, and I plan on sticking with it, to help me when I (hopefully) learn other languages. ~Corey -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Sat Sep 5 00:48:12 2009 From: bgailer at gmail.com (bob gailer) Date: Fri, 04 Sep 2009 18:48:12 -0400 Subject: [Tutor] Help deciding between python and ruby In-Reply-To: <25294195.post@talk.nabble.com> References: <25294195.post@talk.nabble.com> Message-ID: <4AA1992C.8040009@gmail.com> dan06 wrote: > I'd like to learn a programming language - and I need help deciding between > python and ruby. I'm interesting in learning what are the difference, both > objective and subjective, between the two languages. I know this is a python > mailing list, so knowledge/experience with ruby may be limited - in which > case I'd still be interested in learning why members of this mailing list > chose python over (or in addition to) any other programming language. I look > forward to the feedback/insight. > I've used and taught many many languages. My favorites are APL and Python. I just went through some Ruby tutorials. I see some neat things, but in general it seems that Ruby requires more keyboard activity (typing) to get the same result. I will stick with Python. But then there are those who stick with COBOL, so who knows the truth? -- Bob Gailer Chapel Hill NC 919-636-4239 From upasara.wulung.1980 at gmail.com Sat Sep 5 01:31:00 2009 From: upasara.wulung.1980 at gmail.com (upasara wulung) Date: Sat, 5 Sep 2009 01:31:00 +0200 Subject: [Tutor] run command Message-ID: hello, Wish you would not mind a really beginner question. I am trying to use 'run' command, but didnot success yet. How I did it: (1) In a certain working folder, I produced simple python file, for an example, hello.py, which is free of error. (2) I called python from the same working folder using command 'python' (3) In the python shell, I executed: >>> run hello.py But I got only an error message: SyntaxError: invalid syntax. Please tell me a clue? I did those stuffs in Linux Debian. Thx a lot Upa. From dirk at pensiun.com Sat Sep 5 02:00:49 2009 From: dirk at pensiun.com (Dirk Wangsadirdja) Date: Sat, 05 Sep 2009 02:00:49 +0200 Subject: [Tutor] Help deciding between python and ruby In-Reply-To: <1252081834.23990.60.camel@jabbar> References: <25294195.post@talk.nabble.com> <1252081834.23990.60.camel@jabbar> Message-ID: <4AA1AA31.9020501@pensiun.com> Hi, I've never learned ruby, but from what I read, ruby is a pure OOP language, and if you are going to do a lot of web creation, then ruby on rails is a good one. What I can advice is, if you choose to stick with python, perhaps you shouldn't use python 3.x, but use python 2.5 (from what I heard, its supposed to be the best version?). Why? many python packages that later on I'm sure you would like to use are still based on python 2.x. I didnt know it before, and I start by learning python 3.1. Since I start with that (and because I'm too stubborn), I don't want to start learning python 2.x. But thats my choice, and if there are packages that I cant use yet, I just have to live with that. Besides that, I think that most of the python tutorials are still based on python 2.x. In case you're not aware of it, python 3.x is not backward compatible. And since there are several changes in python 3.x, it wouldnt be able to run python 2.x script. And if you're planning to make executeable files from your script, as far that I know, until now there are no tools to convert python 3.x script to executeable yet. > On Fri, 2009-09-04 at 06:18 -0700, dan06 wrote: >> I'd like to learn a programming language - and I need help deciding between >> python and ruby. I'm interesting in learning what are the difference, both >> objective and subjective, between the two languages. I know this is a python >> mailing list, so knowledge/experience with ruby may be limited - in which >> case I'd still be interested in learning why members of this mailing list >> chose python over (or in addition to) any other programming language. I look >> forward to the feedback/insight. From dkdropbox at gmail.com Sat Sep 5 02:18:15 2009 From: dkdropbox at gmail.com (David Kim) Date: Fri, 4 Sep 2009 20:18:15 -0400 Subject: [Tutor] Help deciding between python and ruby Message-ID: On Fri, 2009-09-04 at 06:18 -0700, dan06 wrote: > I'd like to learn a programming language - and I need help deciding between > python and ruby. I'm interesting in learning what are the difference, both > objective and subjective, between the two languages. I know this is a python > mailing list, so knowledge/experience with ruby may be limited - in which > case I'd still be interested in learning why members of this mailing list > chose python over (or in addition to) any other programming language. I look > forward to the feedback/insight. I'm a non-programmer that went through this process not too long ago (leaving a broken trail of google searches and books in my wake). I looked at a number of languages, Ruby included. I chose to focus on Python first because of it's relatively clear syntax and what seems like more mature scientific modules/distributions (Scipy, Numpy, EPD, Sage, and related packages). Much of the secondary material I found for Ruby focused on Rails and web-related endeavors (tho people obviously use Ruby for many things). Of course, Python offers its own web frameworks (e.g., Django, web2py) and probably plenty of other packages I haven't even encountered yet. I have no pet peeves when it comes to syntax (e.g., some people don't like significant whitespace, etc.). I was just looking for 1) a language that isn't too hard to learn and 2) a language that is flexible enough that future exploration/growth wouldn't be a huge pain in the ass. So, for example, pulling and storing data is relatively straightforward, but can I analyze it? If I do that, can I visualize the analysis? And can I automatically generate a presentation using these visualizations if I want to? If I then want to convert this presentation into a data-driven website, can I do that? Etc., etc., etc...One can do all of this in any language, but Python offered the best productivity-to-PITA ratio (to me, at least). So it all obviously depends on what you want to do, but those were my reasons. Both Ruby and Python were attractive, I just decided that Python's scientific ecosystem was the deciding factor. I am now looking at R to plug some holes, since no language is perfect ;) I'm interested to see how the MacRuby project develops as they are moving to an LLVM-based architecture that is expected to improve Ruby's performance a lot (mirrored by similar efforts by the JRuby team and others). I'm getting a bit out over my skis now, so I'll stop there. Hope it helps, dk -- morenotestoself.wordpress.com financialpython.wordpress.com From kb1pkl at aim.com Sat Sep 5 02:31:04 2009 From: kb1pkl at aim.com (kb1pkl at aim.com) Date: Fri, 04 Sep 2009 20:31:04 -0400 Subject: [Tutor] (no subject) Message-ID: <8CBFBD7498906CF-394C-8A00@webmail-m058.sysops.aol.com> I know, I'm a total noob (started yester day) But when I enter this code: x = 1 if x>0: ??? a = raw_input ("Type something in...I will echo it:") ??? print a ??? x=x+1 it does not loop..am I missing something here? -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Sat Sep 5 04:50:22 2009 From: bgailer at gmail.com (bob gailer) Date: Fri, 04 Sep 2009 22:50:22 -0400 Subject: [Tutor] (no subject) In-Reply-To: <8CBFBD7498906CF-394C-8A00@webmail-m058.sysops.aol.com> References: <8CBFBD7498906CF-394C-8A00@webmail-m058.sysops.aol.com> Message-ID: <4AA1D1EE.4080504@gmail.com> kb1pkl at aim.com wrote: > I know, I'm a total noob (started yester day) > But when I enter this code: > x = 1 > if x>0: > a = raw_input ("Type something in...I will echo it:") > print a > x=x+1 > it does not loop..am I missing something here? You are missing a looping statement. In Python they are for or while, not if. Also realize the above, when converted to a while loop will never terminate, since i keeps growing. -- Bob Gailer Chapel Hill NC 919-636-4239 From felixsan at gmail.com Sat Sep 5 03:49:10 2009 From: felixsan at gmail.com (Felix Santiago) Date: Fri, 4 Sep 2009 21:49:10 -0400 Subject: [Tutor] (no subject) In-Reply-To: <8CBFBD7498906CF-394C-8A00@webmail-m058.sysops.aol.com> References: <8CBFBD7498906CF-394C-8A00@webmail-m058.sysops.aol.com> Message-ID: On Sep 4, 2009, at 8:31 PM, kb1pkl at aim.com wrote: > I know, I'm a total noob (started yester day) > But when I enter this code: > x = 1 > if x>0: > a = raw_input ("Type something in...I will echo it:") > print a > x=x+1 > it does not loop..am I missing something here? In your example the if statement is only evaluated once, for when x = 1. If you want to create a loop replace the if with a while. --Felix -------------- next part -------------- An HTML attachment was scrubbed... URL: From dorseye at gmail.com Sat Sep 5 05:32:44 2009 From: dorseye at gmail.com (Eric Dorsey) Date: Fri, 4 Sep 2009 21:32:44 -0600 Subject: [Tutor] run command In-Reply-To: References: Message-ID: Make sure you are in the same directory as your hello.py, then run the interpreter/shell Try this: >>>import hello then you can do things like: >>>dir(hello) and >>>help(hello) I'm not sure if that's what you were asking, but "import" is how you .. import. HTH. On Fri, Sep 4, 2009 at 5:31 PM, upasara wulung < upasara.wulung.1980 at gmail.com> wrote: > hello, > > Wish you would not mind a really beginner question. I am trying to use > 'run' command, but didnot success yet. How I did it: > > (1) In a certain working folder, I produced simple python file, for an > example, hello.py, which is free of error. > (2) I called python from the same working folder using command 'python' > (3) In the python shell, I executed: >>> run hello.py > > But I got only an error message: SyntaxError: invalid syntax. > > Please tell me a clue? I did those stuffs in Linux Debian. > > Thx a lot > > Upa. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From michael at shamirlens.co.uk Sat Sep 5 09:54:06 2009 From: michael at shamirlens.co.uk (Michael M Mason) Date: Sat, 5 Sep 2009 08:54:06 +0100 Subject: [Tutor] run command In-Reply-To: References: Message-ID: "upasara wulung" wrote: > (1) In a certain working folder, I produced simple python file, for an > example, hello.py, which is free of error. > (2) I called python from the same working folder using command 'python' > (3) In the python shell, I executed: >>> run hello.py > > But I got only an error message: SyntaxError: invalid syntax. The "SyntaxError: invalid syntax" message occurs because there is no "run" command in python. Run the python file from the command prompt like this: python hello.py Alternatively, start python and then enter this at the python prompt (>>>): import hello The import command loads the python file and executes the code in the file. Note that you use "hello" and not "hello.py". -- Michael From alan.gauld at btinternet.com Sat Sep 5 10:15:08 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 5 Sep 2009 09:15:08 +0100 Subject: [Tutor] Looping quesion [WAS: Re: (no subject)] References: <8CBFBD7498906CF-394C-8A00@webmail-m058.sysops.aol.com> Message-ID: Please always put a meaningful subject line in when you post. wrote in message >I know, I'm a total noob (started yester day) > But when I enter this code: > x = 1 > if x>0: > ??? a = raw_input ("Type something in...I will echo it:") > ??? print a > ??? x=x+1 > it does not loop..am I missing something here? Yes, a loop. Python has two loop constructs: for and while. If you replace the if test with a while test it will do what you want I think. while x>0: Except that it will never stop looping! You might want to consider putting a mechanism for stopping in there :-) But any reasonable tutorial for beginners should cover loops. Try mine for example... :-) -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Sat Sep 5 10:21:16 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 5 Sep 2009 09:21:16 +0100 Subject: [Tutor] run command References: Message-ID: "upasara wulung" wrote > Wish you would not mind a really beginner question. Thats what we are here for! :-) > I am trying to use 'run' command, but didnot success yet. Thats because it does not exist in Python. > How I did it: > > (1) In a certain working folder, I produced simple python file, for an > example, hello.py, which is free of error. > (2) I called python from the same working folder using command 'python' Instead of just python type python hello.py -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From gslindstrom at gmail.com Sat Sep 5 14:29:56 2009 From: gslindstrom at gmail.com (Greg Lindstrom) Date: Sat, 5 Sep 2009 07:29:56 -0500 Subject: [Tutor] PyCon 2010 - Call for Tutorials Message-ID: The Tutorial Committee for PyCon 2010 in Atlanta is now accepting proposals for classes. This year will feature 2 days of classes prior to the "official" conference. These classes are 3-hour long sessions concentrating on specific Python packages or techniques and are taught by some of the smartest cookies in the Python Universe. Anything Python may be submitted for consideration but there are a limited number of sessions to be filled. Topics taught or requested over the past two years include: * Python 101 - An introduction to programming Python, either for complete beginners or programmers experienced in other languages. * Python 201 - There has been repeated requests for classes covering "intermediate" topics; data structures, database techniques, classes/objects, standard library, eggs, etc. * Python 401 - Classes covering "advanced" topics; multi-processing/concurrency, iterators/generators, OOP, etc. * Web Topics - Frameworks, web testing, design, security, scraping. * Scientific Python - MatLab, SciPy * Testing - Frameworks, methods * GUI - Dabo, wxPython, TkInter, etc. * More: XML, GIS, SQLAlchemy, Jython, System Administration More information, including a sample proposal and blank template, are at http://us.pycon.org/2010/tutorials/proposals/. Questions? Email us at pycon-tutorials at python.org. Greg Lindstrom -------------- next part -------------- An HTML attachment was scrubbed... URL: From dan.king106 at yahoo.com Fri Sep 4 16:46:14 2009 From: dan.king106 at yahoo.com (Dan King) Date: Fri, 4 Sep 2009 07:46:14 -0700 (PDT) Subject: [Tutor] Help deciding between python and ruby In-Reply-To: <1252073412.6295.150.camel@bermanrl-desktop> References: <25294195.post@talk.nabble.com> <1252073412.6295.150.camel@bermanrl-desktop> Message-ID: <234294.80315.qm@web112211.mail.gq1.yahoo.com> > I think you will get at the least a slight bias toward Python. However, > I think you should do your own research and reach your own conclusions. > Simply to get you started I put the following into Google: 'Python or > Ruby: Which to learn' and got more than 1M hits. > Best of luck. > Robert Well, the slight (at the very least) bias toward Python is expected as this is a python mailing list. I have already done research on python and ruby via Google. I've found that python is described as more 'explicit,' used in multiple situations, has better libraries, and has unique 'spacing & underscore' syntax requirements; and ruby on the other is more 'implicit,' used more in web-apps (via ROR), emphasizes code-readability/beauty, and is more flexible (i.e. has more than one way of doing something). While the preceding information is nice, the information hasn't helped me decide which one to learn - that's the reason for my post. I want to sift through the hype for each language. I want to understand the perspectives of people who use python - why they like/dislike it, if/why the would recommend learning it, and what experiences they've had with python in professional contexts. To put my programming knowledge in context, I have experience with php and java; I enjoy php's ease and the syntax of java (everything is apparent from the code, although it can be a bit verbose). Look forward to the responses. Thanks. -Dan From kp8 at mac.com Fri Sep 4 19:31:02 2009 From: kp8 at mac.com (kevin parks) Date: Sat, 05 Sep 2009 02:31:02 +0900 Subject: [Tutor] mapping/filtering a sequence Message-ID: <189A4F7F-08A8-40F0-BD37-A515BAC19857@mac.com> I am doing some data massage, minor mapping and filtering really and i find that i have a lot of this kind of kludgy code: # -- ------------------------- def filt_seq(inseq): out_list = [] for item in inseq: # 38 needs to be mapped on to 34 as we don't have a 38 in our grid if item == 38: item = item - 4 out_list.append(item) # We also don't have a 40, but we do have a 39. Map that sucka elif item == 40: item = item - 1 out_list.append(item) # if we get values that fall in good places, just pass them on to the out seq else: out_list.append(item) return out_list # -- ------------------------- To do some basic jiggering of some out of range off grid data. There has to be a better, more elegant, more flexible less brute force more pythonic way to do this kind of mapping no? cheers, -kp-- From kp8 at mac.com Sat Sep 5 10:18:01 2009 From: kp8 at mac.com (kevin parks) Date: Sat, 05 Sep 2009 17:18:01 +0900 Subject: [Tutor] working with multiple sets In-Reply-To: References: Message-ID: <229E0944-B50A-4214-8881-E9017C71BE8E@mac.com> I am doing some simple things with sets and so far have had a lot of success with python's built-in sets, which is such a great new(ish) "batteries included" type python data type. -------- [snip] -------- [snip] -------------- [snip] -------- [snip] ------ #!/usr/bin/env python def test(): x = range(10) y = range(5, 15) z = range(8, 22) setx = set(x) sety = set(y) setz = set(z) print "\n", "x = ", x, "\n", "y = ", y, "\n", "z = ", z, "\n" * 2 overlap1 = setx.intersection(sety) overlap1 = sorted(list(overlap1)) print "overlap of x and y:", overlap1 # overlap2 = sety.intersection(setz) overlap2 = sorted(list(overlap2)) print "overlap of y and z:", overlap2 # overlap3 = setx.intersection(setz) overlap3 = sorted(list(overlap3)) print "overlap of x and z:", overlap3 if __name__ == "__main__": test() -------- [snip] -------- [snip] -------------- [snip] -------- [snip] -------------- so silly stuff like that works fine. But i want to do a little more than that. I want to be able to look at a number/item and see which lists it is in so that i could maybe have a master list of all the data, a superset, and then an indication of which lists that data was in, as some items will only be in one list, some will appear in two lists (x & y, or x & z or y & z) and a small handful will be in all three lists. 0 - x 1 - x 2 - x 3 - x 4 - x 5 - x, y 6 - x, y 7 - x, y 8 - x, y, z 9 - x, y, z 10 - y, x etc. Of course the whole point of this is that the sets will be more complicated than 0-9, 5-14, and 8-21 and additionally, the sets may not be a list of numbers but eventually a list of strings. So the steps would be to create the superset then test for membership for each list? I kinda get it, the thing that warps my brain is the idea that there are more than 2 lists now to test against.... eventually my script needs to accommodate 4, 5, 6 sets.. but i would just like to see if i can get 3 sets to work first. From eike.welk at gmx.net Sat Sep 5 16:41:53 2009 From: eike.welk at gmx.net (Eike Welk) Date: Sat, 05 Sep 2009 16:41:53 +0200 Subject: [Tutor] run command In-Reply-To: References: Message-ID: <200909051641.53412.eike.welk@gmx.net> Hello Upasara! On Saturday 05 September 2009, upasara wulung wrote: > (1) In a certain working folder, I produced simple python file, for > an example, hello.py, which is free of error. > (2) I called python from the same working folder using command > 'python' (3) In the python shell, I executed: >>> run hello.py > > But I got only an error message: SyntaxError: invalid syntax. > > Please tell me a clue? I did those stuffs in Linux Debian. You have maybe confused Python and Ipython. Ipython is an alternative Python interpreter, with additional commands for interactive work. It has a 'run' command. To run it type 'ipython' in the shell window. If the 'ipython' program is not present on your computer go to the system administrator and ask him to install it. There is certainly an Ipython package for Debian. Kind regards, Eike. From srilyk at gmail.com Sat Sep 5 16:47:37 2009 From: srilyk at gmail.com (Wayne) Date: Sat, 5 Sep 2009 09:47:37 -0500 Subject: [Tutor] mapping/filtering a sequence In-Reply-To: <189A4F7F-08A8-40F0-BD37-A515BAC19857@mac.com> References: <189A4F7F-08A8-40F0-BD37-A515BAC19857@mac.com> Message-ID: <333efb450909050747sd78ae59r6c9220b6e98e4531@mail.gmail.com> On Fri, Sep 4, 2009 at 12:31 PM, kevin parks wrote: > I am doing some data massage, minor mapping and filtering really and i find > that i have a lot of this kind of kludgy code: > > To do some basic jiggering of some out of range off grid data. > > There has to be a better, more elegant, more flexible less brute force more > pythonic way to do this kind of mapping no? Why is data being generated outside your grid? That's the first question you should ask, and probably the better way to address the problem. What are the available values for the grid? Are they flexible or permanent? A bit more info would be helpful in finding a solution. -Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From upasara.wulung.1980 at gmail.com Sat Sep 5 16:48:02 2009 From: upasara.wulung.1980 at gmail.com (upasara wulung) Date: Sat, 5 Sep 2009 16:48:02 +0200 Subject: [Tutor] run command In-Reply-To: <200909051641.53412.eike.welk@gmx.net> References: <200909051641.53412.eike.welk@gmx.net> Message-ID: To all good friends, Wonderful, within just a short time, I have received many new things about python from this list. Thank you so much for all responses; they are really useful, shorten my learning time. --- Best regards, Upa From jojo.mwebaze at gmail.com Sat Sep 5 16:52:51 2009 From: jojo.mwebaze at gmail.com (Jojo Mwebaze) Date: Sat, 5 Sep 2009 16:52:51 +0200 Subject: [Tutor] how to read and transmit/send only section of the image (sub-image) In-Reply-To: <1c2a2c590909040656s3f65e77al32b1331fbd97402b@mail.gmail.com> References: <3124be320909030605p23803349mf4d5e042fb5cf5f6@mail.gmail.com> <1c2a2c590909030806h79268022y8a7c60ab4afcc8d9@mail.gmail.com> <3124be320909031501v4f4dcdedt8919b891a90b0bbf@mail.gmail.com> <1c2a2c590909040656s3f65e77al32b1331fbd97402b@mail.gmail.com> Message-ID: <3124be320909050752tc771f08n7f7be439e2cb380c@mail.gmail.com> oooh that will be helpful, kindly point me to how i can begin with getting a sub-image that has the same width as the original. That will be my starting point. Regards Johnson On Fri, Sep 4, 2009 at 3:56 PM, Kent Johnson wrote: > On Thu, Sep 3, 2009 at 6:01 PM, Jojo Mwebaze > wrote: > > thanks guys, > > Currently i am using pyfits, a bit slow cause loads the file in memory, > > creates a subimage and then saves the file then transmits > > the file over the network! My idea is, if there is a way of creating a > file > > pointer to the location on disk, where the subimage lies, reading a > specific > > size, and sending only the data read (like wayne had suggested) > > Do you think this possible? > > Not by just reading a single portion of the file; even for an > uncompressed bare raster image this would only work if the sub-image > is the same width as the original. For a FITS file you also need to > create a new header. > > It is technically possible to construct a subimage in memory without > reading the original into memory but you would have to understand the > details of the FITS format. > > You may be able to transmit the image without saving it first. Or > perhaps one of the other FITS libs is faster. > > Kent > -------------- next part -------------- An HTML attachment was scrubbed... URL: From martin at linux-ip.net Sat Sep 5 16:45:29 2009 From: martin at linux-ip.net (Martin A. Brown) Date: Sat, 5 Sep 2009 09:45:29 -0500 Subject: [Tutor] mapping/filtering a sequence In-Reply-To: <189A4F7F-08A8-40F0-BD37-A515BAC19857@mac.com> References: <189A4F7F-08A8-40F0-BD37-A515BAC19857@mac.com> Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 : I am doing some data massage, minor mapping and filtering really : and i find that i have a lot of this kind of kludgy code: : : # -- ------------------------- : def filt_seq(inseq): : out_list = [] : for item in inseq: : # 38 needs to be mapped on to 34 as we don't have a 38 in our : grid : if item == 38: : item = item - 4 : out_list.append(item) : # We also don't have a 40, but we do have a 39. Map that : sucka : elif item == 40: : item = item - 1 : out_list.append(item) : # if we get values that fall in good places, just pass them : on to the out seq : else: : out_list.append(item) : return out_list : : # -- ------------------------- : : To do some basic jiggering of some out of range off grid data. : : There has to be a better, more elegant, more flexible less brute : force more pythonic way to do this kind of mapping no? Have you discovered the map() builtin yet? I would imagine that others on this list will have some even more elegant and efficient solutions for you, but here's a possibility: def filt_seq( thing ): if thing == 38: thing = thing - 4 elif thing == 40: thing = thing - 1 return thing l = [ 1, 17, 12, 38, 4, 40, 17, 19 ] l = map( filt_seq, l ) Good luck, - -Martin - -- Martin A. Brown http://linux-ip.net/ -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.2 (GNU/Linux) Comment: pgf-0.72 (http://linux-ip.net/sw/pine-gpg-filter/) iD8DBQFKonmNHEoZD1iZ+YcRAme7AKDqThvHP6+3xbzBg1p48rxmY21ztgCdFYnA Z2YGRnW7HLm/1oroaCTmkgg= =G9w5 -----END PGP SIGNATURE----- From dgou at mac.com Sat Sep 5 17:26:08 2009 From: dgou at mac.com (Douglas Philips) Date: Sat, 05 Sep 2009 11:26:08 -0400 Subject: [Tutor] mapping/filtering a sequence In-Reply-To: References: <189A4F7F-08A8-40F0-BD37-A515BAC19857@mac.com> Message-ID: <6A3250C7-31B6-4958-8E0A-F538989ED4F9@mac.com> On or about 2009 Sep 5, at 10:45 AM, Martin A. Brown indited: > Have you discovered the map() builtin yet? > > I would imagine that others on this list will have some even more > elegant and efficient solutions for you, but here's a possibility: > > def filt_seq( thing ): > if thing == 38: > thing = thing - 4 > elif thing == 40: > thing = thing - 1 > return thing > > l = [ 1, 17, 12, 38, 4, 40, 17, 19 ] > l = map( filt_seq, l ) > > Good luck, I must have missed a message or two, because I don't understand why math is being done on constants like that. Given my misunderstanding, I'd go with: my_map = { 38: 34, 40: 39 } def filter_item(item): return my_map.get(item, item) l = [ ... ] l = map(filter_item, l) -Doug From metolone+gmane at gmail.com Sat Sep 5 18:22:33 2009 From: metolone+gmane at gmail.com (Mark Tolonen) Date: Sat, 5 Sep 2009 09:22:33 -0700 Subject: [Tutor] mapping/filtering a sequence References: <189A4F7F-08A8-40F0-BD37-A515BAC19857@mac.com> <6A3250C7-31B6-4958-8E0A-F538989ED4F9@mac.com> Message-ID: "Douglas Philips" wrote in message news:6A3250C7-31B6-4958-8E0A-F538989ED4F9 at mac.com... > On or about 2009 Sep 5, at 10:45 AM, Martin A. Brown indited: >> Have you discovered the map() builtin yet? >> >> I would imagine that others on this list will have some even more >> elegant and efficient solutions for you, but here's a possibility: >> >> def filt_seq( thing ): >> if thing == 38: >> thing = thing - 4 >> elif thing == 40: >> thing = thing - 1 >> return thing >> >> l = [ 1, 17, 12, 38, 4, 40, 17, 19 ] >> l = map( filt_seq, l ) >> >> Good luck, > > > I must have missed a message or two, because I don't understand why math > is being done on constants like that. > Given my misunderstanding, I'd go with: > > my_map = { 38: 34, 40: 39 } > > def filter_item(item): > return my_map.get(item, item) > > l = [ ... ] > l = map(filter_item, l) As a list comp: >>> L=range(30,41) >>> [{38:34,40:39}.get(n,n) for n in L] [30, 31, 32, 33, 34, 35, 36, 37, 34, 39, 39] -Mark From dgou at mac.com Sat Sep 5 18:54:54 2009 From: dgou at mac.com (Douglas Philips) Date: Sat, 05 Sep 2009 12:54:54 -0400 Subject: [Tutor] mapping/filtering a sequence In-Reply-To: References: <189A4F7F-08A8-40F0-BD37-A515BAC19857@mac.com> <6A3250C7-31B6-4958-8E0A-F538989ED4F9@mac.com> Message-ID: <9EE00578-6AF7-4C6C-9968-AF5F25A00E03@mac.com> On 2009 Sep 5, at 12:22 PM, Mark Tolonen wrote: > As a list comp: > >>>> L=range(30,41) >>>> [{38:34,40:39}.get(n,n) for n in L] > [30, 31, 32, 33, 34, 35, 36, 37, 34, 39, 39] True, that is terse, but IMHO has maintainability issues. The mapping data structure and the method of transformation (.get()) are tangled in with the transformation itself. Again, IMHO, unless this is a very short script, the maintenance should outweigh raw terseness. -Doug From davea at ieee.org Sat Sep 5 19:09:59 2009 From: davea at ieee.org (Dave Angel) Date: Sat, 05 Sep 2009 13:09:59 -0400 Subject: [Tutor] working with multiple sets In-Reply-To: <229E0944-B50A-4214-8881-E9017C71BE8E@mac.com> References: <229E0944-B50A-4214-8881-E9017C71BE8E@mac.com> Message-ID: <4AA29B67.3090601@ieee.org> kevin parks wrote: >
I am > doing some simple things with sets and so far have had a lot of > success with python's built-in sets, which is such a great new(ish) > "batteries included" type python data type. > > -------- [snip] -------- [snip] -------------- [snip] -------- [snip] > ------ > #!/usr/bin/env python > > def test(): > x = range(10) > y = range(5, 15) > z = range(8, 22) > setx = set(x) > sety = set(y) > setz = set(z) > print "\n", "x = ", x, "\n", "y = ", y, "\n", "z = ", z, "\n" * 2 > overlap1 = setx.intersection(sety) > overlap1 = sorted(list(overlap1)) > print "overlap of x and y:", overlap1 > # > overlap2 = sety.intersection(setz) > overlap2 = sorted(list(overlap2)) > print "overlap of y and z:", overlap2 > # > overlap3 = setx.intersection(setz) > overlap3 = sorted(list(overlap3)) > print "overlap of x and z:", overlap3 > > if __name__ == "__main__": > test() > > -------- [snip] -------- [snip] -------------- [snip] -------- [snip] > -------------- > > > so silly stuff like that works fine. But i want to do a little more > than that. I want to be able to look at a number/item and see which > lists it is in so that i could maybe have a master list of all the > data, a superset, and then an indication of which lists that data was > in, as some items will only be in one list, some will appear in two > lists (x & y, or x & z or y & z) and a small handful will be in all > three lists. > > 0 - x > 1 - x > 2 - x > 3 - x > 4 - x > 5 - x, y > 6 - x, y > 7 - x, y > 8 - x, y, z > 9 - x, y, z > 10 - y, x > > etc. > > Of course the whole point of this is that the sets will be more > complicated than 0-9, 5-14, and 8-21 and additionally, the sets may > not be a list of numbers but eventually a list of strings. > > So the steps would be to create the superset > then test for membership for each list? > > I kinda get it, the thing that warps my brain is the idea that there > are more than 2 lists now to test against.... eventually my script > needs to accommodate 4, 5, 6 sets.. but i would just like to see if i > can get 3 sets to work first. > > >
> The real question is why bother to make up a new data structure. If you're not careful you'll end up with multiple copies of the same data, and it'll be a pain to keep them in synch. Perhaps all you need is a list of sets, and one or more functions to query that list. You'll find that checking an item for membership in a set is very quick, so making a separate set of lists (that tells you which ones a given item is in) is probably not productive. x = range(10) y = range(5, 15) z = range(8, 22) mysets = [(x,"set x"), (y, "set y"), (z, "set z")] #any number of them def find_item(item, mysets): members = [] for myset, mysetname in mysets: if item in myset: members.append(mysetname) return members print find_item(4, mysets), find_item(5, mysets), find_item(9, mysets), find_item(12, mysets), find_item(21, mysets) DaveA From bgailer at gmail.com Sat Sep 5 20:06:05 2009 From: bgailer at gmail.com (bob gailer) Date: Sat, 05 Sep 2009 14:06:05 -0400 Subject: [Tutor] working with multiple sets Message-ID: <4AA2A88D.9060504@gmail.com> 1) Please don't hijack a post then change the subject. That screws things up for email clients that track threads. I have started a new thread with this reply. 2) Be sure to reply-all so a copy goes to the list. [SNIP] I want to be able to look at a number/item and see which lists it is in so that i could maybe have a master list of all the data, a superset, and then an indication of which lists that data was in, as some items will only be in one list, some will appear in two lists (x & y, or x & z or y & z) and a small handful will be in all three lists. I think you mean "set" rather than "list" To enable processing of an arbitrary number of sets, put them in a collection (list or dictionary). Use a list if it is sufficient to identify sets by number, else use a dictionary. Use a dictionary to relate items to their set(s). import collections lookup = collections.defaultdict(list) sets = {'x': set((1,2,3)), 'y': set((2,3))} for key, value in sets.items(): for element in value: lookup[element].append(key) print lookup 0 - x 1 - x 2 - x 3 - x 4 - x 5 - x, y 6 - x, y 7 - x, y 8 - x, y, z 9 - x, y, z 10 - y, x etc. Of course the whole point of this is that the sets will be more complicated than 0-9, 5-14, and 8-21 and additionally, the sets may not be a list of numbers but eventually a list of strings. So the steps would be to create the superset then test for membership for each list? I kinda get it, the thing that warps my brain is the idea that there are more than 2 lists now to test against.... eventually my script needs to accommodate 4, 5, 6 sets.. but i would just like to see if i can get 3 sets to work first. -- Bob Gailer Chapel Hill NC 919-636-4239 From kp8 at mac.com Sat Sep 5 15:25:18 2009 From: kp8 at mac.com (kevin parks) Date: Sat, 05 Sep 2009 22:25:18 +0900 Subject: [Tutor] Help deciding between python and ruby In-Reply-To: <234294.80315.qm@web112211.mail.gq1.yahoo.com> References: <25294195.post@talk.nabble.com> <1252073412.6295.150.camel@bermanrl-desktop> <234294.80315.qm@web112211.mail.gq1.yahoo.com> Message-ID: 1. go to the book store 2. pull a copy of learning ruby by Michael Fitzgerald (ora.com) 3. pull a copy of learning python by Mark Lutz (ora.com) 4. read chapter 1 of each 5. make a decision 6. get to work Alternately check comp.lang.python where this question comes up over and over and over and over and worry your head some more. And while i am all for python advocacy. I: 1. Could not do better than the first 20 pages of the Lutz. 2. I am (and i am sure i will be over-ruled and shouted down for this), not entirely sure the tutor list is the appropriate place for this query. Places like comp.lang.python better serve this purpose. The tutor list is primarily a list (cribbing from http://mail.python.org/mailman/listinfo/tutor) for folks who want to ask questions regarding how to learn computer programming with the Python language. I am not entirely sure i want to hear a long drawn out thought experiment on what one person thinks upon adopting a new programming language. I joined this list to learn the specifics of programming in python and to get help and learn from the questions and answers posted by others. If this place too gets clogged with python -v- perl, python-v-ruby, phython -v- php navelgazing it is going to ruin the tutor list which has a pretty clear mission and has served that purpose very very well over the years i have been on it. I think we should redirect this query and avoid "mission creep" All IMO, YMMV, etc. & co. If you think i am just being a jerk, at least take my initial advice. The ora books BOTH have great overviews of each language. A cup of coffee and reading the first 20 pages of each will tell you great overviews of Python v Ruby. -kevin On Sep 4, 2009, at 11:46 PM, Dan King wrote: >> I think you will get at the least a slight bias toward Python. >> However, >> I think you should do your own research and reach your own >> conclusions. >> Simply to get you started I put the following into Google: 'Python or >> Ruby: Which to learn' and got more than 1M hits. > >> Best of luck. > >> Robert > > Well, the slight (at the very least) bias toward Python is expected > as this is a python mailing list. I have already done research on > python and ruby via Google. I've found that python is described as > more 'explicit,' used in multiple situations, has better libraries, > and has unique 'spacing & underscore' syntax requirements; and ruby > on the other is more 'implicit,' used more in web-apps (via ROR), > emphasizes code-readability/beauty, and is more flexible (i.e. has > more than one way of doing something). > > While the preceding information is nice, the information hasn't > helped me decide which one to learn - that's the reason for my post. > I want to sift through the hype for each language. I want to > understand the perspectives of people who use python - why they like/ > dislike it, if/why the would recommend learning it, and what > experiences they've had with python in professional contexts. > > To put my programming knowledge in context, I have experience with > php and java; I enjoy php's ease and the syntax of java (everything > is apparent from the code, although it can be a bit verbose). Look > forward to the responses. Thanks. > > -Dan > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From kp8 at mac.com Sat Sep 5 17:21:18 2009 From: kp8 at mac.com (kevin parks) Date: Sun, 06 Sep 2009 00:21:18 +0900 Subject: [Tutor] mapping/filtering a sequence In-Reply-To: <333efb450909050747sd78ae59r6c9220b6e98e4531@mail.gmail.com> References: <189A4F7F-08A8-40F0-BD37-A515BAC19857@mac.com> <333efb450909050747sd78ae59r6c9220b6e98e4531@mail.gmail.com> Message-ID: <56D2FBB7-E2E0-4B9D-89E0-6922971DEC88@mac.com> I can think of about 80 billion reasons why you would encounter data outside your grid, esp. if you aren't the original producer of the data. Imagine you are mapping something to color (RGB values) or you are doing a signification of volcanic activity or the big bang or the earth's magnetic field and you are getting data from an external data. Mapping of external data happens all the time. Like the xSonify project, a Java application to display numerical data as sound by NASA, etc. Sometimes (to stay with this example) the data you have doesn't fit exactly to your grid (in this case a tuning system of musical pitches within the 12-tone ET system or any other form of tuning which will have discreet steps or a mix of RGB colors) Then what you would want to do is map the data to the nearest value no? >>Why is data being generated outside your grid? Because it is data given to me by an outside source for example, not necessarily data i generated myself, or it is the result of some algorithm or natural number series or a fractal, sensor data, younameit. >>What are the available values for the grid? Are they flexible or permanent? A bit more info would be helpful in finding a solution. At this moment, i have input that represents 7-bits of sensor data resolution (128) so a fixed grid of integers 0-127 is how i am getting this data in but i don't have all 0-127 to map it to. For this particular hack, I am mostly getting useful values in the range 30-85, so I am filtering out anything below 34 and above 83, but i don't have 34-83 contiguous. I have a gap toothed integer grid of: [34, 39, 41, 42, 43, 44, 46, 48, 49, 50, 51, 53, 54, 55, 56, 58, 60, 61, 62, 63, 65, 66, 67, 68, 70, 72, 73, 75, 77, 79, 80, 82] I want to map each incoming integer to the closest one available. I know, it is idiosyncratic. I also need to be able to do this with other idiosyncratic gap toothed sets. It's a weird, idiosyncratic, real world messy question. If there is no easy way, it would prolly be just as easy to hack it all up with conditionals by hand at this point. cheers, k PS. Os there some reason why it suddenly takes a day to see your posts to the tutor list appear? I thought this query didn't make it through and gave up as i sent it yesterday and it only popped up on list just now. On Sep 5, 2009, at 11:47 PM, Wayne wrote: > On Fri, Sep 4, 2009 at 12:31 PM, kevin parks wrote: > I am doing some data massage, minor mapping and filtering really and > i find that i have a lot of this kind of kludgy code: > > To do some basic jiggering of some out of range off grid data. > > There has to be a better, more elegant, more flexible less brute > force more pythonic way to do this kind of mapping no? > > Why is data being generated outside your grid? That's the first > question you should ask, and probably the better way to address the > problem. > > What are the available values for the grid? Are they flexible or > permanent? A bit more info would be helpful in finding a solution. > > -Wayne From kp8 at mac.com Sat Sep 5 17:49:14 2009 From: kp8 at mac.com (kevin parks) Date: Sun, 06 Sep 2009 00:49:14 +0900 Subject: [Tutor] mapping/filtering a sequence In-Reply-To: <6A3250C7-31B6-4958-8E0A-F538989ED4F9@mac.com> References: <189A4F7F-08A8-40F0-BD37-A515BAC19857@mac.com> <6A3250C7-31B6-4958-8E0A-F538989ED4F9@mac.com> Message-ID: <691483D8-D916-473C-8998-53C0A5E11D35@mac.com> Yeah the list seems flaky at the moment. Additionally, my query is an incredibly stupid one. But what you have works and represents an improvement over the unreadable kludge I was doing. Thanks to all who responded. cheers, k On Sep 6, 2009, at 12:26 AM, Douglas Philips wrote: > On or about 2009 Sep 5, at 10:45 AM, Martin A. Brown indited: > > I must have missed a message or two, because I don't understand why > math is being done on constants like that. > Given my misunderstanding, I'd go with: > > my_map = { 38: 34, 40: 39 } > > def filter_item(item): > return my_map.get(item, item) > > l = [ ... ] > l = map(filter_item, l) > > > -Doug -------------- next part -------------- An HTML attachment was scrubbed... URL: From metolone+gmane at gmail.com Sat Sep 5 22:29:57 2009 From: metolone+gmane at gmail.com (Mark Tolonen) Date: Sat, 5 Sep 2009 13:29:57 -0700 Subject: [Tutor] mapping/filtering a sequence References: <189A4F7F-08A8-40F0-BD37-A515BAC19857@mac.com><6A3250C7-31B6-4958-8E0A-F538989ED4F9@mac.com> <9EE00578-6AF7-4C6C-9968-AF5F25A00E03@mac.com> Message-ID: "Douglas Philips" wrote in message news:9EE00578-6AF7-4C6C-9968-AF5F25A00E03 at mac.com... > On 2009 Sep 5, at 12:22 PM, Mark Tolonen wrote: >> As a list comp: >> >>>>> L=range(30,41) >>>>> [{38:34,40:39}.get(n,n) for n in L] >> [30, 31, 32, 33, 34, 35, 36, 37, 34, 39, 39] > > > True, that is terse, but IMHO has maintainability issues. The mapping > data structure and the method of transformation (.get()) are tangled in > with the transformation itself. > Again, IMHO, unless this is a very short script, the maintenance should > outweigh raw terseness. This *was* a very short script. My point was using a list comp. If you want to nitpick, don't use lower-case L for variables either :^) my_map = { 38: 34, 40: 39 } def filter_item(item): return my_map.get(item, item) L = [filteritem(n) for n in L] Happy? -Mark From rabidpoobear at gmail.com Sat Sep 5 22:45:00 2009 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sat, 5 Sep 2009 22:45:00 +0200 Subject: [Tutor] Help deciding between python and ruby In-Reply-To: <234294.80315.qm@web112211.mail.gq1.yahoo.com> References: <25294195.post@talk.nabble.com> <1252073412.6295.150.camel@bermanrl-desktop> <234294.80315.qm@web112211.mail.gq1.yahoo.com> Message-ID: > ruby on the other is more 'implicit,' used more in web-apps (via ROR), > emphasizes code-readability/beauty, and is more flexible (i.e. has more than > one way of doing something). You mean people actually like ruby's syntax? I think Python's the prettiest language I've worked with syntactically. I wouldn't call having multiple ways to do something "flexible". I agree more with Python's philosophy, there should be one (and preferably only one) obvious way to do something. @kevin parks: > I am (and i am sure i will be over-ruled and shouted down for this), not entirely sure the tutor list > is the appropriate place for this query. Places like comp.lang.python better serve this purpose. This is a good point, you probably should have stopped there. Yes, this is probably not the best place for this discussion. I would like to see how it pans out, though, now that we're already 15 posts in. It's not very difficult to ignore a thread in your favorite e-mail client, perhaps you could just do that? If these debates become commonplace I will probably help you yell at everyone to stop flooding the list, but the amount of such questions has always been quite low and never bothersome, and I've been on Tutor since 2005. -------------- next part -------------- An HTML attachment was scrubbed... URL: From lie.1296 at gmail.com Sun Sep 6 02:42:47 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Sun, 06 Sep 2009 10:42:47 +1000 Subject: [Tutor] How to iterate through unicode string. In-Reply-To: <4AA112CB.70303@pensiun.com> References: <4AA10D2C.2050606@compuscan.co.za> <4AA112CB.70303@pensiun.com> Message-ID: Dirk Wangsadirdja wrote: > Hi allen (and perhaps this goes also for others), > > just a suggestion, maybe when we post a problem, we should also mention > the python version that we use. Every new subscribers to the tutor mailing list are sent an email that contains this: """ Finally, when you do send email to the Tutor list, be as clear as you can about the problem, including, when relevant, details like: - Precise error messages, including complete tracebacks - The hardware platform (available in the Python sys module as sys.platform) - The python version (sys.version) - The python search path (sys.path) """ but unfortunately only very few people actually read them. From srilyk at gmail.com Sun Sep 6 05:32:56 2009 From: srilyk at gmail.com (Wayne) Date: Sat, 5 Sep 2009 22:32:56 -0500 Subject: [Tutor] mapping/filtering a sequence In-Reply-To: <56D2FBB7-E2E0-4B9D-89E0-6922971DEC88@mac.com> References: <189A4F7F-08A8-40F0-BD37-A515BAC19857@mac.com> <333efb450909050747sd78ae59r6c9220b6e98e4531@mail.gmail.com> <56D2FBB7-E2E0-4B9D-89E0-6922971DEC88@mac.com> Message-ID: <333efb450909052032n42dc0bf7gfef108a09b75dd77@mail.gmail.com> On Sat, Sep 5, 2009 at 10:21 AM, kevin parks wrote: > > Then what you would want to do is map the data to the nearest value no? I guess it all depends on your desired level of precision! > For this particular hack, I am mostly getting useful values in the range > 30-85, so I am filtering out anything below 34 and above 83, but i don't > have 34-83 contiguous. I have a gap toothed integer grid of: > > [34, 39, 41, 42, 43, 44, 46, 48, 49, 50, 51, 53, 54, 55, 56, 58, 60, 61, > 62, 63, 65, 66, 67, 68, 70, 72, 73, 75, 77, 79, 80, 82] > > I want to map each incoming integer to the closest one available. I know, > it is idiosyncratic. I also need to be able to do this with other > idiosyncratic gap toothed sets. I think the simplest way is to use a dictionary. You could, of course, use a sort to find out where to insert your data. -Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From m.kossner at tu-bs.de Sun Sep 6 12:20:19 2009 From: m.kossner at tu-bs.de (markus kossner) Date: Sun, 06 Sep 2009 12:20:19 +0200 Subject: [Tutor] Problem with complex strings as key for a shelve-Dictionary Message-ID: <1252232419.6447.26.camel@akb-6> Dear all, I have a Problem with complex strings as keys in a shelve Object: #!/usr/bin/python import shelve test=shelve.open('testshelve') test={ 'CCN1c2ccccc2/C(=C2/S/C(=N\c3ccc(Cl)cc3)N(C)C2=O)C1=O':int(0), 'CN1/C(=N\c2ccc(Cl)cc2)S/C(=C2\C(=O)Nc3ccccc32)C1=O':int(20), 'c1cc2c(cc1)N(CCCl)C(=O)/C2=C1\S/C(=N/c2ccc(F)cc2)NC1=O':float(1), 'Cc1cccc(/N=C2/NC(=O)/C(=C3\c4c(cccc4)N(C)C3=O)S2)c1C':0.5, } print test['CCN1c2ccccc2/C(=C2/S/C(=N\c3ccc(Cl)cc3)N(C)C2=O)C1=O'] ==> script works without problems This works fine as long as I keep the shelve opened. However, when I then want to open the shelve with another python script I get key errors, as the different keys are not found: #!/usr/bin/python import shelve test=shelve.open('testshelve') print test['CCN1c2ccccc2/C(=C2/S/C(=N\c3ccc(Cl)cc3)N(C)C2=O)C1=O'] ==> leads to key error I tried raw strings and so on, but did not manage. Any Ideas? Cheers Markus From kp8 at mac.com Sun Sep 6 10:21:10 2009 From: kp8 at mac.com (kevin parks) Date: Sun, 06 Sep 2009 17:21:10 +0900 Subject: [Tutor] Help deciding between python and ruby In-Reply-To: References: <25294195.post@talk.nabble.com> <1252073412.6295.150.camel@bermanrl-desktop> <234294.80315.qm@web112211.mail.gq1.yahoo.com> Message-ID: Well, the only thing more annoying than off topic discussion is "meta" discussion on lists and folks passing judgement on other people's posts (ie. you should have x, your should not have Y... I shouldn't have this second doughnut, but you know what, i am gonna eat that *and* have a second cup of coffee). So i'll resist the temptation to reply to Luke in detail, who i did not realize was a moderator here. In any case, I happen to have right in front of me, a brandy new spendy (in Korea anyway) copy of the Lutz book Learning Python 3rd Edition O'Reilly and if you look at "Part I Getting Started," the book begins with a very compelling section called "Why People Use Python" and it outlines: Software quality Development productivity Program Portability Support libraries Component integration Enjoyment and the end of this chapter, pp. 18-19 has a section called: "How does python stack up to language x" which gives a bunch of comparisons to Ruby and others. Here he says: [Python] is more mature and has a more readable syntax than Ruby. Unlike Ruby and Java, OOP is an option in Python ? Python does not impose OOP on users or projects which might not apply. Most of this has already been touched on in this thread ... But I would add that that very past point is a HUGE reason why i use python. For little pea-shooter scripts I don't want to have to know and apply advanced OOP concepts. Yet if you do know them and your project requires it... it is there. One of the criticism of Python by Ruby users is that it isn't as "purely OO" as Ruby is. It is up to you whether that is a bug or a feature. But you can go quite far in Python without being an OOP guru but i am not sure that is entirely true of Ruby. Check with Ruby users. Personally i don't want to have to know how to do Schenkerian analysis and set theory just to have my first piano lesson and play Mary had a little Lamb, and i don't want to learn Norwegian just to hear a Norwegian folk tale. I like to dig right in and Python is good for that for sure. -k On Sep 6, 2009, at 5:45 AM, Luke Paireepinart wrote: > > ruby on the other is more 'implicit,' used more in web-apps (via > ROR), emphasizes code-readability/beauty, and is more flexible (i.e. > has more than one way of doing something). > You mean people actually like ruby's syntax? I think Python's the > prettiest language I've worked with syntactically. > I wouldn't call having multiple ways to do something "flexible". I > agree more with Python's philosophy, there should be one (and > preferably only one) obvious way to do something. > > @kevin parks: > > I am (and i am sure i will be over-ruled and shouted down for > this), not entirely sure the tutor list > > is the appropriate place for this query. Places like > comp.lang.python better serve this purpose. > This is a good point, you probably should have stopped there. > > Yes, this is probably not the best place for this discussion. I > would like to see how it pans out, though, now that we're already 15 > posts in. It's not very difficult to ignore a thread in your > favorite e-mail client, perhaps you could just do that? If these > debates become commonplace I will probably help you yell at everyone > to stop flooding the list, but the amount of such questions has > always been quite low and never bothersome, and I've been on Tutor > since 2005. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From kp8 at mac.com Sun Sep 6 10:29:44 2009 From: kp8 at mac.com (kevin parks) Date: Sun, 06 Sep 2009 17:29:44 +0900 Subject: [Tutor] mapping/filtering a sequence In-Reply-To: References: <189A4F7F-08A8-40F0-BD37-A515BAC19857@mac.com> <6A3250C7-31B6-4958-8E0A-F538989ED4F9@mac.com> <9EE00578-6AF7-4C6C-9968-AF5F25A00E03@mac.com> Message-ID: I actually find the map biz easier to get my head around than the list comp. I guess this makes it another good reason for me to be happy that map is apparently staying in after nearly being depreciated. I generally prefer list comp in every instance, but the idea of an if else construct within the conditional of a list comp really hurts my brain, but it is nice to see that, had map(), filter() and reduce() all gotten the boot, there is a way to do it with a list comp, opaque as it is. Thanks to all who responded this. -kp-- On Sep 6, 2009, at 5:29 AM, Mark Tolonen wrote: > > "Douglas Philips" wrote in message news:9EE00578-6AF7-4C6C-9968-AF5F25A00E03 at mac.com > ... >> On 2009 Sep 5, at 12:22 PM, Mark Tolonen wrote: >>> As a list comp: >>> >>>>>> L=range(30,41) >>>>>> [{38:34,40:39}.get(n,n) for n in L] >>> [30, 31, 32, 33, 34, 35, 36, 37, 34, 39, 39] >> >> >> True, that is terse, but IMHO has maintainability issues. The >> mapping data structure and the method of transformation (.get()) >> are tangled in with the transformation itself. >> Again, IMHO, unless this is a very short script, the maintenance >> should outweigh raw terseness. > > This *was* a very short script. My point was using a list comp. If > you want to nitpick, don't use lower-case L for variables either :^) > > my_map = { 38: 34, 40: 39 } > > def filter_item(item): > return my_map.get(item, item) > > L = [filteritem(n) for n in L] > > Happy? > > -Mark > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From kent37 at tds.net Sun Sep 6 16:23:53 2009 From: kent37 at tds.net (Kent Johnson) Date: Sun, 6 Sep 2009 10:23:53 -0400 Subject: [Tutor] how to read and transmit/send only section of the image (sub-image) In-Reply-To: <3124be320909050752tc771f08n7f7be439e2cb380c@mail.gmail.com> References: <3124be320909030605p23803349mf4d5e042fb5cf5f6@mail.gmail.com> <1c2a2c590909030806h79268022y8a7c60ab4afcc8d9@mail.gmail.com> <3124be320909031501v4f4dcdedt8919b891a90b0bbf@mail.gmail.com> <1c2a2c590909040656s3f65e77al32b1331fbd97402b@mail.gmail.com> <3124be320909050752tc771f08n7f7be439e2cb380c@mail.gmail.com> Message-ID: <1c2a2c590909060723r54885434n3db2f7c12a8d9532@mail.gmail.com> On Sat, Sep 5, 2009 at 10:52 AM, Jojo Mwebaze wrote: > oooh that will be helpful, ?kindly point me to how i can begin with getting > a sub-image that has the same width as the > original.?That?will?be?my?starting?point. I don't know the details of FITS format, but I imagine it would be something like this: - read enough of the FITS header to figure out where the image data is in the file - seek to the start of the sub-image and read the image data - construct a new header for the sub-image - write the new header and data to a new file This will require some understanding of FITS format, or a library that supports the operations you need. You might find code in PyFITS that will help. Kent From kent37 at tds.net Sun Sep 6 16:32:10 2009 From: kent37 at tds.net (Kent Johnson) Date: Sun, 6 Sep 2009 10:32:10 -0400 Subject: [Tutor] Problem with complex strings as key for a shelve-Dictionary In-Reply-To: <1252232419.6447.26.camel@akb-6> References: <1252232419.6447.26.camel@akb-6> Message-ID: <1c2a2c590909060732v2cf952dcu9b408eb7482a4137@mail.gmail.com> On Sun, Sep 6, 2009 at 6:20 AM, markus kossner wrote: > Dear all, > I have a Problem with complex strings as keys in a shelve Object: > > #!/usr/bin/python > import shelve > test=shelve.open('testshelve') > test={ > 'CCN1c2ccccc2/C(=C2/S/C(=N\c3ccc(Cl)cc3)N(C)C2=O)C1=O':int(0), > 'CN1/C(=N\c2ccc(Cl)cc2)S/C(=C2\C(=O)Nc3ccccc32)C1=O':int(20), > 'c1cc2c(cc1)N(CCCl)C(=O)/C2=C1\S/C(=N/c2ccc(F)cc2)NC1=O':float(1), > 'Cc1cccc(/N=C2/NC(=O)/C(=C3\c4c(cccc4)N(C)C3=O)S2)c1C':0.5, > } You just re-assigned test to be a plain dict, the result of shelve.open() is lost. You want test=shelve.open('testshelve') test['CCN1c2ccccc2/C(=C2/S/C(=N\c3ccc(Cl)cc3)N(C)C2=O)C1=O'] = int(0) etc. > This works fine as long as I keep the shelve opened. > However, when I then want to open the shelve with another python script > I get key errors, as the different keys are not found: Because you are not actually using the shelve, you are throwing away immediately. Kent From kb1pkl at aim.com Sun Sep 6 18:09:30 2009 From: kb1pkl at aim.com (Corey Richardson) Date: Sun, 06 Sep 2009 12:09:30 -0400 Subject: [Tutor] Simple Game Message-ID: <4AA3DEBA.6010704@aim.com> So far, I can use tuples/lists/dictionary's, and define some functions, and a bit of other things. Would it be hard for me to make a simple text rpg game? Or is there something else I should know before I try that. From dorseye at gmail.com Sun Sep 6 19:21:15 2009 From: dorseye at gmail.com (Eric Dorsey) Date: Sun, 6 Sep 2009 11:21:15 -0600 Subject: [Tutor] Simple Game In-Reply-To: <4AA3DEBA.6010704@aim.com> References: <4AA3DEBA.6010704@aim.com> Message-ID: Hi Corey, If this is going to be a command line program, two things that immediately come to mind for me are: validating user input and persistence. If you put something like "(1) to attack, (2) to run" what if the user types "yes", or "Y", or "9"? You'll want to make sure your program doesn't crash on wrong user input. And as far as "saving" the game, will the user be able to pick up where they left off(tracking user stats, progress in the game, posessions, etc)? If so, you'll need some kind of persistence, Pickle-ing or a SQLite database, etc. On Sun, Sep 6, 2009 at 10:09 AM, Corey Richardson wrote: > So far, I can use tuples/lists/dictionary's, and define some functions, and > a bit of other things. > Would it be hard for me to make a simple text rpg game? Or is there > something else I should know before I try that. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From oberoc at gmail.com Sun Sep 6 20:20:01 2009 From: oberoc at gmail.com (Tino Dai) Date: Sun, 6 Sep 2009 14:20:01 -0400 Subject: [Tutor] Pack/Unpack hacking Message-ID: <2ac5d4850909061120l27d605b4qe2b8e912c13a1d53@mail.gmail.com> Hi All, Hope the people in the US are having a nice Labor Day! I am looking for the source code for the pack/unpack functions found in the struct package. As of this email, I have tried a strings on the struct.pyc file. The inspection of the pyc file was hoping that I could find a stub to the source. I also looked directly at struct.py, with no success. Finally, I also tried downloading the source and grepping through the files, which didn't prove all that useful. Does anybody have any ideas on how I can find the source without having to go through the entire source tree file by file? Thanks in advance, Tino -------------- next part -------------- An HTML attachment was scrubbed... URL: From lukepadawan at gmail.com Sun Sep 6 20:31:16 2009 From: lukepadawan at gmail.com (Lucas Prado Melo) Date: Sun, 6 Sep 2009 15:31:16 -0300 Subject: [Tutor] Pack/Unpack hacking In-Reply-To: <2ac5d4850909061120l27d605b4qe2b8e912c13a1d53@mail.gmail.com> References: <2ac5d4850909061120l27d605b4qe2b8e912c13a1d53@mail.gmail.com> Message-ID: <9f4be2240909061131n44266bafq1e3dfbe9c860b541@mail.gmail.com> On Sun, Sep 6, 2009 at 3:20 PM, Tino Dai wrote: > Hi All, > > Hope the people in the US are having a nice Labor Day! I am looking for > the source code > for the pack/unpack functions found in the struct package. As of this > email, I have tried a > strings on the struct.pyc file. The inspection of the pyc file was hoping > that I could find a > stub to the source. I also looked directly at struct.py, with no success. > Finally, I also tried > downloading the source and grepping through the files, which didn't prove > all that useful. > Does anybody have any ideas on how I can find the source without having to > go through > the entire source tree file by file? > IIUC, there's a program called Cscope that might help. :-) -------------- next part -------------- An HTML attachment was scrubbed... URL: From dillyg23 at gmail.com Sun Sep 6 21:33:55 2009 From: dillyg23 at gmail.com (sharon) Date: Sun, 06 Sep 2009 19:33:55 -0000 Subject: [Tutor] A basic question Message-ID: <4A7B2CF9.8050100@gmail.com> I have been trying how to get a any python program to run by clicking on the icon. I keep reading on the internet make it executable: chmod a+x try_python.py Where do I actually put the above expression so that it will work everytime. If I then sent this try_python.py to someone else with Ubuntu would it run on their system? Sorry if this is too basic but it is an assumption that seems to be made and I really am a complete beginner. Thanks for any help Sharon From tjgolden at gmail.com Sun Sep 6 20:41:57 2009 From: tjgolden at gmail.com (Tim Golden) Date: Sun, 06 Sep 2009 19:41:57 +0100 Subject: [Tutor] Pack/Unpack hacking In-Reply-To: <9f4be2240909061131n44266bafq1e3dfbe9c860b541@mail.gmail.com> References: <2ac5d4850909061120l27d605b4qe2b8e912c13a1d53@mail.gmail.com> <9f4be2240909061131n44266bafq1e3dfbe9c860b541@mail.gmail.com> Message-ID: <4AA40275.4070900@gmail.com> >> Hope the people in the US are having a nice Labor Day! I am looking for >> the source code >> for the pack/unpack functions found in the struct package. As of this >> email, I have tried a >> strings on the struct.pyc file. The inspection of the pyc file was hoping >> that I could find a >> stub to the source. I also looked directly at struct.py, with no success. >> Finally, I also tried >> downloading the source and grepping through the files, which didn't prove >> all that useful. >> Does anybody have any ideas on how I can find the source without having to >> go through >> the entire source tree file by file? http://svn.python.org/view/python/trunk/Modules/_struct.c?view=markup TJG From kent37 at tds.net Sun Sep 6 21:44:37 2009 From: kent37 at tds.net (Kent Johnson) Date: Sun, 6 Sep 2009 15:44:37 -0400 Subject: [Tutor] Pack/Unpack hacking In-Reply-To: <2ac5d4850909061120l27d605b4qe2b8e912c13a1d53@mail.gmail.com> References: <2ac5d4850909061120l27d605b4qe2b8e912c13a1d53@mail.gmail.com> Message-ID: <1c2a2c590909061244w379caa89g5d0a88172fe18689@mail.gmail.com> On Sun, Sep 6, 2009 at 2:20 PM, Tino Dai wrote: > Hi All, > > ??? Hope the people in the US are having a nice Labor Day! I am looking for > the source code > for the pack/unpack functions found in the struct package. As of this email, > I have tried a > strings on the struct.pyc file. The inspection of the pyc file was hoping > that I could find a > stub to the source. I also looked directly at struct.py, with no success. > Finally, I also tried > downloading the source and grepping through the files, which didn't prove > all that useful. > Does anybody have any ideas on how I can find the source without having to > go through > the entire source tree file by file? In general, xxx.pyc is the compiled Python bytecode for xxx.py, so struct.py is the source for struct.pyc. Looking at struct.py, it's entire contents is from _struct import * from _struct import _clearcache This is a pretty common idiom in the std lib for modules that are implemented partially or completely as C extensions - there is a Python wrapper, called xxx.py, which imports functions from a C extension called _xxx. Often there are some functions in the Python module; in this case, the implementation is entirely in _struct and struct.py is just a shell. The source for C extension modules in the std lib is in the Modules folder. Look for _struct.c. BTW another common convention is for modules that are implemented entirely in C; they will have source in Modules/xxxmodule.c, for example datetimemodule.c. Kent From lukepadawan at gmail.com Sun Sep 6 21:48:35 2009 From: lukepadawan at gmail.com (Lucas Prado Melo) Date: Sun, 6 Sep 2009 16:48:35 -0300 Subject: [Tutor] A basic question In-Reply-To: <4A7B2CF9.8050100@gmail.com> References: <4A7B2CF9.8050100@gmail.com> Message-ID: <9f4be2240909061248r34073b6dxd9401de366b2611e@mail.gmail.com> On Thu, Aug 6, 2009 at 4:20 PM, sharon wrote: > I have been trying how to get a any python program to run by clicking on > the icon. I keep reading on the internet make it executable: > > chmod a+x try_python.py > Did you write: #!/usr/bin/env python at the first line of the file too? > Where do I actually put the above expression so that it will work > everytime. If I then sent this try_python.py to someone else with Ubuntu > would it run on their system? Sorry if this is too basic but it is an > assumption that seems to be made and I really am a complete beginner. > Don't worry about it. :-) -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sun Sep 6 19:51:58 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 6 Sep 2009 18:51:58 +0100 Subject: [Tutor] Simple Game References: <4AA3DEBA.6010704@aim.com> Message-ID: "Corey Richardson" wrote > So far, I can use tuples/lists/dictionary's, and define some functions, > and a bit of other things. > Would it be hard for me to make a simple text rpg game? Or is there > something else I should know before I try that. No idea about rpg because I've never played one far less written one. But you certainly have enough to write a simple game like mastermind, oxo or hangman... Assuming you also mean that you know about loops and branches then you can program anything since sequences, loops and branches are all that are necessary to program anything! So go for it, and if you get stuick as here. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Sun Sep 6 22:46:03 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 6 Sep 2009 21:46:03 +0100 Subject: [Tutor] A basic question References: <4A7B2CF9.8050100@gmail.com> Message-ID: "sharon" wrote >I have been trying how to get a any python program to run by clicking on > the icon. I keep reading on the internet make it executable: > > chmod a+x try_python.py You do this in a console window, at a bash prompt. You also need to add the "shebang" line at the top of the file. That's a standard format comment line that Unix knows to look at to determine which interpreter to use to execute the script. It's a Unix thing, not Python, which is why the tutorials don't say much about it, they assume you know Unix if you are using it. > everytime. If I then sent this try_python.py to someone else with > Ubuntu would it run on their system? Yes provided they use chmod on it too. You can find more about the chmod and shebang stuff in the Style topic off my tutorial inside the Note for Unix Users near the bottom. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From rabidpoobear at gmail.com Sun Sep 6 23:23:12 2009 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sun, 6 Sep 2009 23:23:12 +0200 Subject: [Tutor] Help deciding between python and ruby In-Reply-To: References: <25294195.post@talk.nabble.com> <1252073412.6295.150.camel@bermanrl-desktop> <234294.80315.qm@web112211.mail.gq1.yahoo.com> Message-ID: On Sun, Sep 6, 2009 at 10:21 AM, kevin parks wrote: > Well, the only thing more annoying than off topic discussion is "meta" > discussion on lists and folks passing judgement on other people's posts (ie. > you should have x, your should not have Y... I shouldn't have this second > doughnut, but you know what, i am gonna eat that *and* have a second cup of > coffee). So i'll resist the temptation to reply to Luke in detail, who i did > not realize was a moderator here. > For the record, I'm not a moderator. I'm sorry if it seemed like I was flaming you, I just don't think this discussion is a bad thing so far. Most of this has already been touched on in this thread ... But I would add > that that very past point is a HUGE reason why i use python. For little > pea-shooter scripts I don't want to have to know and apply advanced OOP > concepts. Yet if you do know them and your project requires it... it is > there. [snip] I like to dig right in and Python is good for that for sure. > > I agree, but I can see how some people don't like it. It's similar to the Java vs. C++ debate I guess, Java is forced OO and C++ is optional. -------------- next part -------------- An HTML attachment was scrubbed... URL: From jojo.mwebaze at gmail.com Mon Sep 7 00:12:51 2009 From: jojo.mwebaze at gmail.com (Jojo Mwebaze) Date: Mon, 7 Sep 2009 00:12:51 +0200 Subject: [Tutor] how to read and transmit/send only section of the image (sub-image) In-Reply-To: <1c2a2c590909060723r54885434n3db2f7c12a8d9532@mail.gmail.com> References: <3124be320909030605p23803349mf4d5e042fb5cf5f6@mail.gmail.com> <1c2a2c590909030806h79268022y8a7c60ab4afcc8d9@mail.gmail.com> <3124be320909031501v4f4dcdedt8919b891a90b0bbf@mail.gmail.com> <1c2a2c590909040656s3f65e77al32b1331fbd97402b@mail.gmail.com> <3124be320909050752tc771f08n7f7be439e2cb380c@mail.gmail.com> <1c2a2c590909060723r54885434n3db2f7c12a8d9532@mail.gmail.com> Message-ID: <3124be320909061512y10d4222j7cc7a6f78fc43ae9@mail.gmail.com> thanks a lot . cheers Johnson On Sun, Sep 6, 2009 at 4:23 PM, Kent Johnson wrote: > On Sat, Sep 5, 2009 at 10:52 AM, Jojo Mwebaze > wrote: > > oooh that will be helpful, kindly point me to how i can begin with > getting > > a sub-image that has the same width as the > > original. That will be my starting point. > > I don't know the details of FITS format, but I imagine it would be > something like this: > - read enough of the FITS header to figure out where the image data is > in the file > - seek to the start of the sub-image and read the image data > - construct a new header for the sub-image > - write the new header and data to a new file > > This will require some understanding of FITS format, or a library that > supports the operations you need. You might find code in PyFITS that > will help. > > Kent > -------------- next part -------------- An HTML attachment was scrubbed... URL: From kb1pkl at aim.com Mon Sep 7 00:24:59 2009 From: kb1pkl at aim.com (Corey Richardson) Date: Sun, 06 Sep 2009 18:24:59 -0400 Subject: [Tutor] Tutor Digest, Vol 67, Issue 22 In-Reply-To: References: Message-ID: <4AA436BB.30307@aim.com> > > > "Corey Richardson" wrote > > >> So far, I can use tuples/lists/dictionary's, and define some functions, >> and a bit of other things. >> Would it be hard for me to make a simple text rpg game? Or is there >> something else I should know before I try that. >> > > No idea about rpg because I've never played one far less written one. > > But you certainly have enough to write a simple game like mastermind, > oxo or hangman... > > Assuming you also mean that you know about loops and branches > then you can program anything since sequences, loops and > branches are all that are necessary to program anything! > > So go for it, and if you get stuick as here. > > > > Ummm, whats a branch? Haha, I know loops, but not branches. From rabidpoobear at gmail.com Mon Sep 7 00:35:52 2009 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Mon, 7 Sep 2009 00:35:52 +0200 Subject: [Tutor] Tutor Digest, Vol 67, Issue 22 In-Reply-To: <4AA436BB.30307@aim.com> References: <4AA436BB.30307@aim.com> Message-ID: > > >> Ummm, whats a branch? Haha, I know loops, but not branches. > A branch changes the program flow based on a condition. Example: x = int(raw_input("Please enter a number!")) if x > 10: print "Your number was greater than 10!" else: print "Your number was less than or equal to 10!" -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Sep 7 02:15:41 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 7 Sep 2009 01:15:41 +0100 Subject: [Tutor] Help deciding between python and ruby References: <25294195.post@talk.nabble.com><1252073412.6295.150.camel@bermanrl-desktop><234294.80315.qm@web112211.mail.gq1.yahoo.com> Message-ID: "Luke Paireepinart" wrote >> I agree, but I can see how some people don't like it. It's similar to >> the > Java vs. C++ debate I guess, Java is forced OO and C++ is optional. While this is a genuine complaint for Java I have to be fair and say that Ruby does a good job of hiding its OOP purity when you don't need it. Any function defined outside of a class automatically gets created as a static method of a "secret" hidden toplevel class that is never explicitly instantiated. So for the programmer you can 99% of the time forget that Ruby always requires OOP and use it just as you would non OOP Python. And of course so many of Python's types are now objects that it's virtually impossible to write a truly non OOP program in Python! So that point is rather moot for the Python/Ruby debate. - IMHO of course :-) -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Mon Sep 7 02:18:42 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 7 Sep 2009 01:18:42 +0100 Subject: [Tutor] Tutor Digest, Vol 67, Issue 22 References: <4AA436BB.30307@aim.com> Message-ID: "Corey Richardson" wrote >> then you can program anything since sequences, loops and >> branches are all that are necessary to program anything! > Ummm, whats a branch? Haha, I know loops, but not branches. Branches are if/else statements and case statements and jump or goto statements. In Python they are restricted to if/elif/else Sometimes known as conditionals. See the branching topic in my tutor for more detail. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From m.kossner at tu-bs.de Sun Sep 6 12:20:19 2009 From: m.kossner at tu-bs.de (markus kossner) Date: Sun, 06 Sep 2009 12:20:19 +0200 Subject: [Tutor] Problem with complex strings as key for a shelve-Dictionary Message-ID: <1252232419.6447.26.camel@akb-6> Dear all, I have a Problem with complex strings as keys in a shelve Object: #!/usr/bin/python import shelve test=shelve.open('testshelve') test={ 'CCN1c2ccccc2/C(=C2/S/C(=N\c3ccc(Cl)cc3)N(C)C2=O)C1=O':int(0), 'CN1/C(=N\c2ccc(Cl)cc2)S/C(=C2\C(=O)Nc3ccccc32)C1=O':int(20), 'c1cc2c(cc1)N(CCCl)C(=O)/C2=C1\S/C(=N/c2ccc(F)cc2)NC1=O':float(1), 'Cc1cccc(/N=C2/NC(=O)/C(=C3\c4c(cccc4)N(C)C3=O)S2)c1C':0.5, } print test['CCN1c2ccccc2/C(=C2/S/C(=N\c3ccc(Cl)cc3)N(C)C2=O)C1=O'] ==> script works without problems This works fine as long as I keep the shelve opened. However, when I then want to open the shelve with another python script I get key errors, as the different keys are not found: #!/usr/bin/python import shelve test=shelve.open('testshelve') print test['CCN1c2ccccc2/C(=C2/S/C(=N\c3ccc(Cl)cc3)N(C)C2=O)C1=O'] ==> leads to key error I tried raw strings and so on, but did not manage. Any Ideas? Cheers Markus From oberoc at gmail.com Mon Sep 7 16:42:06 2009 From: oberoc at gmail.com (Tino Dai) Date: Mon, 7 Sep 2009 10:42:06 -0400 Subject: [Tutor] Pack/Unpack hacking In-Reply-To: <1c2a2c590909061244w379caa89g5d0a88172fe18689@mail.gmail.com> References: <2ac5d4850909061120l27d605b4qe2b8e912c13a1d53@mail.gmail.com> <1c2a2c590909061244w379caa89g5d0a88172fe18689@mail.gmail.com> Message-ID: <2ac5d4850909070742hb95b23cu62d5f8c1e859776a@mail.gmail.com> In general, xxx.pyc is the compiled Python bytecode for xxx.py, so > struct.py is the source for struct.pyc. > > Looking at struct.py, it's entire contents is > from _struct import * > from _struct import _clearcache > > This is a pretty common idiom in the std lib for modules that are > implemented partially or completely as C extensions - there is a > Python wrapper, called xxx.py, which imports functions from a C > extension called _xxx. Often there are some functions in the Python > module; in this case, the implementation is entirely in _struct and > struct.py is just a shell. > > The source for C extension modules in the std lib is in the Modules > folder. Look for _struct.c. > > BTW another common convention is for modules that are implemented > entirely in C; they will have source in Modules/xxxmodule.c, for > example datetimemodule.c. > > Kent > Thanks Kent and TJG! I will tell you want I find. -Tino -------------- next part -------------- An HTML attachment was scrubbed... URL: From joshharper27 at gmail.com Tue Sep 8 03:31:41 2009 From: joshharper27 at gmail.com (Joshua Harper) Date: Mon, 7 Sep 2009 21:31:41 -0400 Subject: [Tutor] Pyduino Message-ID: <7d15d3b40909071831x6a047138j186f1393e2cf24b5@mail.gmail.com> I just bought an arduino and id like to use python instead of the arduino language, any tips, tutorials, anything, i googled but there isnt much on it really... -- - JH -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Tue Sep 8 04:11:24 2009 From: bgailer at gmail.com (bob gailer) Date: Mon, 07 Sep 2009 22:11:24 -0400 Subject: [Tutor] Pyduino In-Reply-To: <7d15d3b40909071831x6a047138j186f1393e2cf24b5@mail.gmail.com> References: <7d15d3b40909071831x6a047138j186f1393e2cf24b5@mail.gmail.com> Message-ID: <4AA5BD4C.5030009@gmail.com> Joshua Harper wrote: > I just bought an arduino and id like to use python instead of the > arduino language, any tips, tutorials, anything, i googled but there > isnt much on it really.. about 3,000,000 results? -- Bob Gailer Chapel Hill NC 919-636-4239 From cfuller084 at thinkingplanet.net Tue Sep 8 04:00:33 2009 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Mon, 7 Sep 2009 21:00:33 -0500 Subject: [Tutor] Pyduino In-Reply-To: <7d15d3b40909071831x6a047138j186f1393e2cf24b5@mail.gmail.com> References: <7d15d3b40909071831x6a047138j186f1393e2cf24b5@mail.gmail.com> Message-ID: <200909072100.34080.cfuller084@thinkingplanet.net> There are a few projects attempting something like this, but it is not easy to get a language like Python running on the minimalist resources found in a microcontroller. Google "python microcontroller" (without the quotes).. you could also try the plural form to see if that brings up other hits. In the best case, you are going to have a limited subset of the language in some way, I'm sure. There is a fairly mature gcc toolchain for the Atmel AVR microcontrollers, so you can also use that. At least for straight C, I dunno about C++, Fortran, Objective C, Ada, or the others. Cheers On Monday 07 September 2009 20:31, Joshua Harper wrote: > I just bought an arduino and id like to use python instead of the arduino > language, any tips, tutorials, anything, i googled but there isnt much on > it really... From rabidpoobear at gmail.com Tue Sep 8 07:30:21 2009 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Tue, 8 Sep 2009 07:30:21 +0200 Subject: [Tutor] Pyduino In-Reply-To: References: <7d15d3b40909071831x6a047138j186f1393e2cf24b5@mail.gmail.com> Message-ID: man, here I am always complaining about people replying directly to me, and I go and do it to Joshua!meant to send this to the list. sorry! ---------- Forwarded message ---------- From: Luke Paireepinart Date: Tue, Sep 8, 2009 at 3:53 AM Subject: Re: [Tutor] Pyduino To: Joshua Harper You wouldn't want to run python on a 16 mhz processor, the interpreter would use up all your resources. The Arduino language is not too hard to learn. On 9/7/09, Joshua Harper wrote: > I just bought an arduino and id like to use python instead of the arduino > language, any tips, tutorials, anything, i googled but there isnt much on it > really... > > -- > - JH > -- Sent from my mobile device -------------- next part -------------- An HTML attachment was scrubbed... URL: From connorsml at gmail.com Tue Sep 8 09:13:11 2009 From: connorsml at gmail.com (Michael Connors) Date: Tue, 8 Sep 2009 09:13:11 +0200 Subject: [Tutor] Pyduino In-Reply-To: References: <7d15d3b40909071831x6a047138j186f1393e2cf24b5@mail.gmail.com> Message-ID: > > > > You wouldn't want to run python on a 16 mhz processor, the interpreter > would use up all your resources. The Arduino language is not too hard > to learn. > > > I have followed some tutorials in the Arduino playground, for talking to the arduino from Python. You can do things like tell your LED to turn on and off based on a key press on your computers keyboard, and from there you can probably figure out how to do plenty of other things. The coding for the Arduino is still done in the native language, but the client you use to speak to the connected arduino would be written in Python. -- Michael Connors Leiden The Netherlands -------------- next part -------------- An HTML attachment was scrubbed... URL: From rabidpoobear at gmail.com Tue Sep 8 11:22:50 2009 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Tue, 8 Sep 2009 11:22:50 +0200 Subject: [Tutor] Pyduino In-Reply-To: References: <7d15d3b40909071831x6a047138j186f1393e2cf24b5@mail.gmail.com> Message-ID: Yes, this is true, but he was asking to use Python *instead* of the Arduino language. I really don't think it's too hard to learn the language, it's really straightforward. On Tue, Sep 8, 2009 at 9:13 AM, Michael Connors wrote: > >> >> You wouldn't want to run python on a 16 mhz processor, the interpreter >> would use up all your resources. The Arduino language is not too hard >> to learn. >> >> >> > > I have followed some tutorials in the Arduino playground, for talking to > the arduino from Python. You can do things like tell your LED to turn on and > off based on a key press on your computers keyboard, and from there you can > probably figure out how to do plenty of other things. > > The coding for the Arduino is still done in the native language, but the > client you use to speak to the connected arduino would be written in Python. > > -- > Michael Connors > Leiden > The Netherlands > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From srilyk at gmail.com Tue Sep 8 13:11:43 2009 From: srilyk at gmail.com (Wayne) Date: Tue, 8 Sep 2009 06:11:43 -0500 Subject: [Tutor] Pyduino In-Reply-To: References: <7d15d3b40909071831x6a047138j186f1393e2cf24b5@mail.gmail.com> Message-ID: <333efb450909080411v7b033933h44d8ff550d1f116d@mail.gmail.com> On Tue, Sep 8, 2009 at 4:22 AM, Luke Paireepinart wrote: > Yes, this is true, but he was asking to use Python *instead* of the Arduino > language. I really don't think it's too hard to learn the language, it's > really straightforward. I'll echo that sentiment. Just following the tutorials you can pretty much figure out everything you need to know. It's basically a simplified version of C++. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From kp8 at me.com Tue Sep 8 14:48:18 2009 From: kp8 at me.com (kevin parks) Date: Tue, 08 Sep 2009 21:48:18 +0900 Subject: [Tutor] working with multiple sets In-Reply-To: <0E9249DF-48FF-4565-8A26-88DCFD8E4116@mac.com> References: <4AA2A88D.9060504@gmail.com> <0E9249DF-48FF-4565-8A26-88DCFD8E4116@mac.com> Message-ID: I am looking at this and wondering: Why does this use collections.defaultdict ? In fact i guess since collections.defaultdict is new to me i am not even sure why it exists and why someone would use this as opposed to using Python's built-in dictionary? and why was it used in this instance? cheers, -kp-- On Sep 6, 2009, at 3:06 AM, bob gailer wrote: > > > I want to be able to look at a number/item and see which lists it is > in so that i could maybe have a master list of all the data, a > superset, and then an indication of which lists that data was in, > as some items will only be in one list, some will appear in two > lists (x & y, or x & z or y & z) and a small handful will be in all > three lists. > > I think you mean "set" rather than "list" > > To enable processing of an arbitrary number of sets, put them in a > collection (list or dictionary). Use a list if it is sufficient to > identify sets by number, else use a dictionary. > > Use a dictionary to relate items to their set(s). > > import collections > lookup = collections.defaultdict(list) > sets = {'x': set((1,2,3)), 'y': set((2,3))} > for key, value in sets.items(): > for element in value: > lookup[element].append(key) > print lookup > > > 0 - x > 1 - x > 2 - x > 3 - x > 4 - x > 5 - x, y > 6 - x, y > 7 - x, y > 8 - x, y, z > 9 - x, y, z > 10 - y, x > > etc. > > Of course the whole point of this is that the sets will be more > complicated than 0-9, 5-14, and 8-21 and additionally, the sets may > not be a list of numbers but eventually a list of strings. > > So the steps would be to create the superset > then test for membership for each list? > > I kinda get it, the thing that warps my brain is the idea that there > are more than 2 lists now to test against.... eventually my script > needs to accommodate 4, 5, 6 sets.. but i would just like to see if > i can get 3 sets to work first. > -- > Bob Gailer > Chapel Hill NC > 919-636-4239 From dgou at mac.com Tue Sep 8 15:03:46 2009 From: dgou at mac.com (Douglas Philips) Date: Tue, 08 Sep 2009 09:03:46 -0400 Subject: [Tutor] Pyduino In-Reply-To: References: <7d15d3b40909071831x6a047138j186f1393e2cf24b5@mail.gmail.com> Message-ID: <615A7F69-6577-4033-A6CC-56020C1251FD@mac.com> Check out: http://us.pycon.org/2009/conference/schedule/event/73/ which has the video of the talk as well. That was one of the many talks I didn't see in person, and is on my queue to watch. Hmmm, just got bumped a lot higher on the queue since I've also recently been bitten by the Arduino bug. :) -Doug From bgailer at gmail.com Tue Sep 8 15:52:47 2009 From: bgailer at gmail.com (bob gailer) Date: Tue, 08 Sep 2009 09:52:47 -0400 Subject: [Tutor] working with multiple sets In-Reply-To: References: <4AA2A88D.9060504@gmail.com> <0E9249DF-48FF-4565-8A26-88DCFD8E4116@mac.com> Message-ID: <4AA661AF.6020807@gmail.com> kevin parks wrote: > > > I am looking at this and wondering: > > Why does this use collections.defaultdict ? > > In fact i guess since collections.defaultdict is new to me i am not > even sure why it exists > and why someone would use this as opposed to using Python's built-in > dictionary? and why was it > used in this instance? It simplifies coding, as it takes care of initializing each new entry to a list. > On Sep 6, 2009, at 3:06 AM, bob gailer wrote: > >> >> >> I want to be able to look at a number/item and see which lists it is >> in so that i could maybe have a master list of all the data, a >> superset, and then an indication of which lists that data was in, as >> some items will only be in one list, some will appear in two lists (x >> & y, or x & z or y & z) and a small handful will be in all three lists. >> >> I think you mean "set" rather than "list" >> >> To enable processing of an arbitrary number of sets, put them in a >> collection (list or dictionary). Use a list if it is sufficient to >> identify sets by number, else use a dictionary. >> >> Use a dictionary to relate items to their set(s). >> >> import collections >> lookup = collections.defaultdict(list) >> sets = {'x': set((1,2,3)), 'y': set((2,3))} >> for key, value in sets.items(): >> for element in value: >> lookup[element].append(key) >> print lookup >> >> -- Bob Gailer Chapel Hill NC 919-636-4239 From kp8 at me.com Tue Sep 8 16:07:02 2009 From: kp8 at me.com (kevin parks) Date: Tue, 08 Sep 2009 23:07:02 +0900 Subject: [Tutor] working with multiple sets In-Reply-To: <4AA661AF.6020807@gmail.com> References: <4AA2A88D.9060504@gmail.com> <0E9249DF-48FF-4565-8A26-88DCFD8E4116@mac.com> <4AA661AF.6020807@gmail.com> Message-ID: I also notice that if i do: def foo(): lookup = collections.defaultdict(list) x = range(10) y = range(5, 15) z = range(8, 22) sets = {'x': set(x), 'y': set(y), 'z': set(z)} for key, value in sets.items(): for element in value: lookup[element].append(key) for x in lookup: print x, lookup[x] print in oder to print more clearly what I want to see, the sets (as usual for a mapping type) are not always in order. Note that from 5 to 7 for example 'y' is listed in front of 'x' and 8 & 9 have 'y', 'x', 'z' and not 'x', 'y', 'z' ... I am not clear on how to sort that as the dictionary method lookup.sort() either doesn't work or i have tried it in all the wrong places. 0 ['x'] 1 ['x'] 2 ['x'] 3 ['x'] 4 ['x'] 5 ['y', 'x'] 6 ['y', 'x'] 7 ['y', 'x'] 8 ['y', 'x', 'z'] 9 ['y', 'x', 'z'] 10 ['y', 'z'] 11 ['y', 'z'] 12 ['y', 'z'] 13 ['y', 'z'] 14 ['y', 'z'] 15 ['z'] 16 ['z'] 17 ['z'] 18 ['z'] 19 ['z'] 20 ['z'] 21 ['z'] On Sep 8, 2009, at 10:52 PM, bob gailer wrote: > kevin parks wrote: >> >> >> I am looking at this and wondering: >> >> Why does this use collections.defaultdict ? >> >> In fact i guess since collections.defaultdict is new to me i am not >> even sure why it exists >> and why someone would use this as opposed to using Python's built- >> in dictionary? and why was it >> used in this instance? > > It simplifies coding, as it takes care of initializing each new > entry to a list. > >> On Sep 6, 2009, at 3:06 AM, bob gailer wrote: >> >>> >>> >>> I want to be able to look at a number/item and see which lists it >>> is in so that i could maybe have a master list of all the data, a >>> superset, and then an indication of which lists that data was in, >>> as some items will only be in one list, some will appear in two >>> lists (x & y, or x & z or y & z) and a small handful will be in >>> all three lists. >>> >>> I think you mean "set" rather than "list" >>> >>> To enable processing of an arbitrary number of sets, put them in a >>> collection (list or dictionary). Use a list if it is sufficient to >>> identify sets by number, else use a dictionary. >>> >>> Use a dictionary to relate items to their set(s). >>> >>> import collections >>> lookup = collections.defaultdict(list) >>> sets = {'x': set((1,2,3)), 'y': set((2,3))} >>> for key, value in sets.items(): >>> for element in value: >>> lookup[element].append(key) >>> print lookup >>> >>> > -- > Bob Gailer > Chapel Hill NC > 919-636-4239 From dgou at mac.com Tue Sep 8 16:11:14 2009 From: dgou at mac.com (Douglas Philips) Date: Tue, 08 Sep 2009 10:11:14 -0400 Subject: [Tutor] Pyduino In-Reply-To: <615A7F69-6577-4033-A6CC-56020C1251FD@mac.com> References: <7d15d3b40909071831x6a047138j186f1393e2cf24b5@mail.gmail.com> <615A7F69-6577-4033-A6CC-56020C1251FD@mac.com> Message-ID: > Check out: > http://us.pycon.org/2009/conference/schedule/event/73/ > which has the video of the talk as well. > That was one of the many talks I didn't see in person, and is on my > queue to watch. Hmmm, just got bumped a lot higher on the queue > since I've also recently been bitten by the Arduino bug. :) For another microcontroller python, there is PyMite: http://us.pycon.org/2009/openspace/ForEmbeddedSystems/ http://code.google.com/p/python-on-a-chip/ --Doug From shellcom3 at juno.com Tue Sep 8 15:48:05 2009 From: shellcom3 at juno.com (shellcom3 at juno.com) Date: Tue, 8 Sep 2009 13:48:05 GMT Subject: [Tutor] (no subject) Message-ID: <20090908.094805.11025.1@webmail07.dca.untd.com> I want to write a code that allows me to input a phrase and calculate the number of vowels twice. once with the for loop and second with the while loop.I can get the for loop to work but, not the while loop. this is my code and response. #demo for loop, and while loop phrase = raw_input("enter your phrase:") VOWELS = "aeiou" number = 0 for letter in phrase: if letter.lower() in VOWELS: number = number +1 else: pass print "Number of vowels =",number raw_input("Press the enter key to continue.") index = 0 while index < len(phrase): if phrase[index] in VOWELS: index = index +1 print "number of vowels" ,index enter your phrase:tell me your name Number of vowels = 0 Number of vowels = 1 Number of vowels = 1 Number of vowels = 1 Number of vowels = 1 Number of vowels = 1 Number of vowels = 2 Number of vowels = 2 Number of vowels = 2 Number of vowels = 3 Number of vowels = 4 Number of vowels = 4 Number of vowels = 4 Number of vowels = 4 Number of vowels = 5 Number of vowels = 5 Number of vowels = 6 Press the enter key to continue. ____________________________________________________________ Best Weight Loss Program - Click Here! http://thirdpartyoffers.juno.com/TGL2141/fc/BLSrjpTFoYcWEqYCcbHEaFPTq8jdS8V2cC4YnTjQIbcZlB9fvaKI0BwmgT2/ From lukepadawan at gmail.com Tue Sep 8 16:25:48 2009 From: lukepadawan at gmail.com (Lucas Prado Melo) Date: Tue, 8 Sep 2009 11:25:48 -0300 Subject: [Tutor] (no subject) In-Reply-To: <20090908.094805.11025.1@webmail07.dca.untd.com> References: <20090908.094805.11025.1@webmail07.dca.untd.com> Message-ID: <9f4be2240909080725l24171a8albfad0688a70c6545@mail.gmail.com> On Tue, Sep 8, 2009 at 10:48 AM, shellcom3 at juno.com wrote: > > I want to write a code that allows me to input a phrase and calculate the > number of vowels twice. once with the for loop and second with the while > loop.I can get the for loop to work but, not the while loop. this is my code > and response. > [snip] > index = 0 > while index < len(phrase): > if phrase[index] in VOWELS: > > index = index +1 > print "number of vowels" ,index > This is an infinite loop. When phrase[index] is not in VOWELS, nothing changes and the test "index < len(phrase)" is still true. -------------- next part -------------- An HTML attachment was scrubbed... URL: From cwitts at compuscan.co.za Tue Sep 8 16:51:05 2009 From: cwitts at compuscan.co.za (Christian Witts) Date: Tue, 08 Sep 2009 16:51:05 +0200 Subject: [Tutor] (no subject) In-Reply-To: <20090908.094805.11025.1@webmail07.dca.untd.com> References: <20090908.094805.11025.1@webmail07.dca.untd.com> Message-ID: <4AA66F59.2020206@compuscan.co.za> shellcom3 at juno.com wrote: > I want to write a code that allows me to input a phrase and calculate the number of vowels twice. once with the for loop and second with the while loop.I can get the for loop to work but, not the while loop. this is my code and response. > > > #demo for loop, and while loop > > > > > phrase = raw_input("enter your phrase:") > > VOWELS = "aeiou" > > number = 0 > > > > > for letter in phrase: > if letter.lower() in VOWELS: > number = number +1 > else: > pass > print "Number of vowels =",number > > raw_input("Press the enter key to continue.") > > index = 0 > while index < len(phrase): > if phrase[index] in VOWELS: > > index = index +1 > print "number of vowels" ,index > > > > enter your phrase:tell me your name > Number of vowels = 0 > Number of vowels = 1 > Number of vowels = 1 > Number of vowels = 1 > Number of vowels = 1 > Number of vowels = 1 > Number of vowels = 2 > Number of vowels = 2 > Number of vowels = 2 > Number of vowels = 3 > Number of vowels = 4 > Number of vowels = 4 > Number of vowels = 4 > Number of vowels = 4 > Number of vowels = 5 > Number of vowels = 5 > Number of vowels = 6 > Press the enter key to continue. > > > > ____________________________________________________________ > Best Weight Loss Program - Click Here! > http://thirdpartyoffers.juno.com/TGL2141/fc/BLSrjpTFoYcWEqYCcbHEaFPTq8jdS8V2cC4YnTjQIbcZlB9fvaKI0BwmgT2/ > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > Your while loop will continue indefinitely if the phrase is not completely vowels. What you should do is remember to increment the value of index regardless of if the letter is a vowel of not: VOWELS = 'aeiouAEIOU' cnt = 0 index = 0 while index < len(phrase): if phrase[index] in VOWELS: cnt += 1 print 'Number of Vowels = %s' %cnt index += 1 -- Kind Regards, Christian Witts From kent37 at tds.net Tue Sep 8 17:44:31 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 8 Sep 2009 11:44:31 -0400 Subject: [Tutor] working with multiple sets In-Reply-To: References: <4AA2A88D.9060504@gmail.com> <0E9249DF-48FF-4565-8A26-88DCFD8E4116@mac.com> <4AA661AF.6020807@gmail.com> Message-ID: <1c2a2c590909080844q62ab34b3ve6607001f2182350@mail.gmail.com> On Tue, Sep 8, 2009 at 10:07 AM, kevin parks wrote: > I also notice that if i do: > > > def foo(): > ? ? ? ?lookup = collections.defaultdict(list) > ? ? ? ?x = range(10) > ? ? ? ?y = range(5, 15) > ? ? ? ?z = range(8, 22) > ? ? ? ?sets = {'x': set(x), 'y': set(y), 'z': set(z)} > ? ? ? ?for key, value in sets.items(): > ? ? ? ? ? ? ? ?for element in value: > ? ? ? ? ? ? ? ? ? ? ? ?lookup[element].append(key) > ? ? ? ?for x in lookup: > ? ? ? ? ? ? ? ?print x, lookup[x] > ? ? ? ?print > > in oder to print more clearly what I want to see, the sets (as usual for a > mapping type) are not always in order. Note that from 5 to 7 for example 'y' > is listed in front of 'x' and 8 & 9 have 'y', 'x', 'z' and not 'x', 'y', 'z' Dictionaries and sets are not ordered. The order of items in sets.items() is an implementation detail, not something you can depend on. > ... I am not clear on how to sort that as the dictionary ? ? ?method > lookup.sort() either doesn't work or i have tried it in all the wrong > places. lookup can't be sorted directly as it is a (default)dict. Anyway it is lookup[x] that you want to sort. Try print x, sorted(lookup[x]) or for x in lookup: lookup[x].sort() # list.sort() sorts the list in place and does not return a value. print x, lookup[x] Another alternative would be to use a list of tuples instead of a dict for sets, then the lookup values would be created in the desired order, e.g. sets = [ (x', set(x)), ('y', set(y)), ('z', set(z)) ] for key, value in sets: # etc Kent From kent37 at tds.net Tue Sep 8 17:51:16 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 8 Sep 2009 11:51:16 -0400 Subject: [Tutor] Pyduino In-Reply-To: References: <7d15d3b40909071831x6a047138j186f1393e2cf24b5@mail.gmail.com> <615A7F69-6577-4033-A6CC-56020C1251FD@mac.com> Message-ID: <1c2a2c590909080851k4d02104en152079c9b4dd8f@mail.gmail.com> On Tue, Sep 8, 2009 at 10:11 AM, Douglas Philips wrote: >> Check out: >> http://us.pycon.org/2009/conference/schedule/event/73/ >> which has the video of the talk as well. >> That was one of the many talks I didn't see in person, and is on my queue >> to watch. Hmmm, just got bumped a lot higher on the queue since I've also >> recently been bitten by the Arduino bug. :) > > For another microcontroller python, there is PyMite: > http://us.pycon.org/2009/openspace/ForEmbeddedSystems/ > http://code.google.com/p/python-on-a-chip/ Which seems to be running on Arduino Mega: http://groups.google.com/group/python-on-a-chip/web/step-by-step-on-running-pymite-on-arduino-mega Kent From kp8 at me.com Tue Sep 8 17:51:12 2009 From: kp8 at me.com (kevin parks) Date: Wed, 09 Sep 2009 00:51:12 +0900 Subject: [Tutor] working with multiple sets In-Reply-To: <1c2a2c590909080844q62ab34b3ve6607001f2182350@mail.gmail.com> References: <4AA2A88D.9060504@gmail.com> <0E9249DF-48FF-4565-8A26-88DCFD8E4116@mac.com> <4AA661AF.6020807@gmail.com> <1c2a2c590909080844q62ab34b3ve6607001f2182350@mail.gmail.com> Message-ID: <7221BB0F-6280-44A3-89DD-59F3CF092F7B@me.com> Actually, This seems like it works: lookup[x].sort() in like so: def foo(): lookup = collections.defaultdict(list) x = range(10) y = range(5, 15) z = range(8, 22) sets = {'x': set(x), 'y': set(y), 'z': set(z)} for key, value in sets.items(): for element in value: lookup[element].append(key) print print lookup, "\n\n" for x in lookup: lookup[x].sort() print x, lookup[x] #print type(lookup) print #print sets I realized that i was trying to apply the standard: k = lookup.keys() k.sort() in the wrong way and in the wrong place (i accidentally cut it out in my message when i removed the scaffolding) I might try the tuple things to for educational purposes. I am somewhat nervous about using something other than a built in type as i am not familiar with collections and it isn't well covered in beginner books or the docs. On Sep 9, 2009, at 12:44 AM, Kent Johnson wrote: > On Tue, Sep 8, 2009 at 10:07 AM, kevin parks wrote: >> I also notice that if i do: >> >> >> def foo(): >> lookup = collections.defaultdict(list) >> x = range(10) >> y = range(5, 15) >> z = range(8, 22) >> sets = {'x': set(x), 'y': set(y), 'z': set(z)} >> for key, value in sets.items(): >> for element in value: >> lookup[element].append(key) >> for x in lookup: >> print x, lookup[x] >> print >> >> in oder to print more clearly what I want to see, the sets (as >> usual for a >> mapping type) are not always in order. Note that from 5 to 7 for >> example 'y' >> is listed in front of 'x' and 8 & 9 have 'y', 'x', 'z' and not 'x', >> 'y', 'z' > > Dictionaries and sets are not ordered. The order of items in > sets.items() is an implementation detail, not something you can depend > on. > >> ... I am not clear on how to sort that as the dictionary method >> lookup.sort() either doesn't work or i have tried it in all the wrong >> places. > > lookup can't be sorted directly as it is a (default)dict. Anyway it is > lookup[x] that you want to sort. Try > print x, sorted(lookup[x]) > > or > for x in lookup: > lookup[x].sort() # list.sort() sorts the list in place and does not > return a value. > print x, lookup[x] > > Another alternative would be to use a list of tuples instead of a dict > for sets, then the lookup values would be created in the desired > order, e.g. > sets = [ (x', set(x)), ('y', set(y)), ('z', set(z)) ] > for key, value in sets: > # etc > > Kent From kp8 at me.com Tue Sep 8 18:40:31 2009 From: kp8 at me.com (kevin parks) Date: Wed, 09 Sep 2009 01:40:31 +0900 Subject: [Tutor] working with multiple sets In-Reply-To: <3587032D-143A-406B-9EE2-864F6B68B45F@mac.com> References: <4AA2A88D.9060504@gmail.com> <0E9249DF-48FF-4565-8A26-88DCFD8E4116@mac.com> <4AA661AF.6020807@gmail.com> <1c2a2c590909080844q62ab34b3ve6607001f2182350@mail.gmail.com> <7221BB0F-6280-44A3-89DD-59F3CF092F7B@me.com> <3587032D-143A-406B-9EE2-864F6B68B45F@mac.com> Message-ID: <5F16B20C-06C2-45EC-B660-A9F0C3A7FA65@me.com> I guess what i honestly want to asks, but am hesitant to since it makes me look like a dork is: What would this look like if i want to use a straight up built-in dictionary type and not the collections.defaultdict. import collections def foo(): lookup = collections.defaultdict(list) x = range(10) y = range(5, 15) z = range(8, 22) sets = {'x': set(x), 'y': set(y), 'z': set(z)} for key, value in sets.items(): for element in value: lookup[element].append(key) print "\n", lookup, "\n\n" for x in lookup: lookup[x].sort() print x, lookup[x] print "\n" From shellcom3 at juno.com Tue Sep 8 19:09:57 2009 From: shellcom3 at juno.com (shellcom3 at juno.com) Date: Tue, 8 Sep 2009 17:09:57 GMT Subject: [Tutor] (no subject) Message-ID: <20090908.130957.4086.0@webmail06.dca.untd.com> I,m trying to get a phrase from a user and print it backwards using the for statement along with the range function, but all I get with range function is integers not alpha. example range(-1) does not work. message = raw_input("enter a message: ") # will produce a back ward message by elements 1 @ time print message[::-1] raw_input("\n\nPress the enter key to exit.\n") enter a message: what time is it ti si emit tahw Press the enter key to exit. ____________________________________________________________ Get Medical Insurance quotes and compare plans. Click now. http://thirdpartyoffers.juno.com/TGL2141/fc/BLSrjpTInCRVJAUElsmT5bwVZjc6LtIZ7jXy33NsWVplFqavu7wZrW7Uk9a/ From lukepadawan at gmail.com Tue Sep 8 19:16:46 2009 From: lukepadawan at gmail.com (Lucas Prado Melo) Date: Tue, 8 Sep 2009 14:16:46 -0300 Subject: [Tutor] (no subject) In-Reply-To: <20090908.130957.4086.0@webmail06.dca.untd.com> References: <20090908.130957.4086.0@webmail06.dca.untd.com> Message-ID: <9f4be2240909081016q2748e206tdf75d4ed6bb45b51@mail.gmail.com> On Tue, Sep 8, 2009 at 2:09 PM, shellcom3 at juno.com wrote: > I,m trying to get a phrase from a user and print it backwards using the for > statement along with the range function, but all I get with range function > is integers not alpha. example range(-1) does not work. > > What about range(0, -n, -1) ? -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue Sep 8 19:45:32 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 8 Sep 2009 18:45:32 +0100 Subject: [Tutor] (no subject) References: <20090908.094805.11025.1@webmail07.dca.untd.com> Message-ID: wrote in message Please specify a meaningful subject line, it makes reading messages in a threaded mailtool or newsreader much easier. > #demo for loop, and while loop > > phrase = raw_input("enter your phrase:") > VOWELS = "aeiou" > number = 0 > > for letter in phrase: > if letter.lower() in VOWELS: > number = number +1 > else: > pass You don't need the else if its only a pass statement. > print "Number of vowels =",number > > raw_input("Press the enter key to continue.") > index = 0 > while index < len(phrase): > if phrase[index] in VOWELS: > index = index +1 > print "number of vowels" ,index The index is the position in the string not the count of vowels. But you are trying to use the same variable for both. Thats a bad idea. Because you only increment the position if thre is a vowel you get stuck if any letter is not a vowel. You need a new count variable and keep index just for iterating in the loop.. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Tue Sep 8 19:51:40 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 8 Sep 2009 18:51:40 +0100 Subject: [Tutor] working with multiple sets References: <4AA2A88D.9060504@gmail.com><0E9249DF-48FF-4565-8A26-88DCFD8E4116@mac.com><4AA661AF.6020807@gmail.com><1c2a2c590909080844q62ab34b3ve6607001f2182350@mail.gmail.com><7221BB0F-6280-44A3-89DD-59F3CF092F7B@me.com><3587032D-143A-406B-9EE2-864F6B68B45F@mac.com> <5F16B20C-06C2-45EC-B660-A9F0C3A7FA65@me.com> Message-ID: "kevin parks" wrote > What would this look like if i want to use a straight up built-in > dictionary type and not the collections.defaultdict. > Not too different: > import collections > > def foo(): > lookup = collections.defaultdict(list) > x = range(10) > y = range(5, 15) > z = range(8, 22) > sets = {'x': set(x), 'y': set(y), 'z': set(z)} > for key, value in sets.items(): > for element in value: lookup[element] = lookup.get(element, []).append(key) > print "\n", lookup, "\n\n" > for x in lookup: > lookup[x].sort() > print x, lookup[x] > print "\n" At least I think thats all you need here. Alan G. From alan.gauld at btinternet.com Tue Sep 8 19:57:11 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 8 Sep 2009 18:57:11 +0100 Subject: [Tutor] Pyduino References: <7d15d3b40909071831x6a047138j186f1393e2cf24b5@mail.gmail.com> <333efb450909080411v7b033933h44d8ff550d1f116d@mail.gmail.com> Message-ID: "Wayne" wrote >> Yes, this is true, but he was asking to use Python *instead* of the >> Arduino >> language. I really don't think it's too hard to learn the language, >> it's >> really straightforward. > > I'll echo that sentiment. Just following the tutorials you can pretty > much > figure out everything you need to know. It's basically a simplified > version > of C++. caveat, if you don't know C or C++ there is a huge mountain of things to learn in migrating from Python. If you already know any C-like langfuage then the Arduino language is straightforward but from Python alone you suddenly have braces and semi colons and type definitions and a welter of other details to learn and understand. I've only browsed the docs so am no expert but it looks like a pretty close clone of C with some C++ bits added. But thats a big jump from Python. But arguably to get the most out of a tool like Arduino you probably do need a language like C vthat is conceptuially closer to the machine than to the user.... -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From dgou at mac.com Tue Sep 8 19:58:12 2009 From: dgou at mac.com (Douglas Philips) Date: Tue, 08 Sep 2009 13:58:12 -0400 Subject: [Tutor] working with multiple sets In-Reply-To: References: <4AA2A88D.9060504@gmail.com> <0E9249DF-48FF-4565-8A26-88DCFD8E4116@mac.com> <4AA661AF.6020807@gmail.com> <1c2a2c590909080844q62ab34b3ve6607001f2182350@mail.gmail.com> <7221BB0F-6280-44A3-89DD-59F3CF092F7B@me.com> <3587032D-143A-406B-9EE2-864F6B68B45F@mac.com> <5F16B20C-06C2-45EC-B660-A9F0C3A7FA65@me.com> Message-ID: <5B930EC8-398E-4B24-BD20-DA255F202B25@mac.com> On or about 2009 Sep 8, at 1:51 PM, Alan Gauld indited: > "kevin parks" wrote >> What would this look like if i want to use a straight up built-in >> dictionary type and not the collections.defaultdict. > > Not too different: > >> import collections >> def foo(): >> lookup = collections.defaultdict(list) # Doug: lookup = dict() >> x = range(10) >> y = range(5, 15) >> z = range(8, 22) >> sets = {'x': set(x), 'y': set(y), 'z': set(z)} >> for key, value in sets.items(): >> for element in value: > lookup[element] = lookup.get(element, []).append(key) # Doug: That doesn't do what you think it does, it won't insert the new list into the dictionary. # Doug: I think what you want is lookup.setdefault(element, []).append(key) >> print "\n", lookup, "\n\n" >> for x in lookup: >> lookup[x].sort() >> print x, lookup[x] >> print "\n" > > At least I think thats all you need here. >>> help(dict.setdefault) setdefault(...) D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D -Doug -Doug From qbits143 at gmail.com Tue Sep 8 20:08:18 2009 From: qbits143 at gmail.com (Ajith Gopinath) Date: Tue, 8 Sep 2009 23:38:18 +0530 Subject: [Tutor] pygtk Message-ID: I will appreciate , if somebody guides me to a proper doc. on pygtk for 2.5/2.6. I am currently unable to find a good doc for the same :o( Thanks and regards ~|| a j i t || -------------- next part -------------- An HTML attachment was scrubbed... URL: From zstumgoren at gmail.com Tue Sep 8 21:53:27 2009 From: zstumgoren at gmail.com (Serdar Tumgoren) Date: Tue, 8 Sep 2009 15:53:27 -0400 Subject: [Tutor] use case for graphs and generators? Message-ID: Hi everyone, I was hoping someone could advise on whether I'm tackling a specific problem in the correct manner. Specifically, I'm trying to use a "clean" set of historical data to fix omissions/errors among a stream of newer data. To do so, I've devised a series of backend SQL statements which need to be triggered in various orders depending on the state of my object's attributes. If my Person object, for example, only has a name and a state, then I need to execute a SQL statement relying on those attributes to pull additional information about the Persion. And if that search yields a unique id for my Person object, then I can fire another SQL statement that uses the unique ID to pull more attributes from my historical data. Or, if my Person object happened to be instantiated with a unique ID, then I can just skip the name/state search (and various others) and go straight to the ID search. After each query, I clearly need to inspect the status of the attributes: once they've all been corrected, I can stop executing corrective queries and move on to the next Person object. To implement the above, I was starting to research generators and graph data structures (e.g. http://www.python.org/doc/essays/graphs.html). So my question -- is that indeed the correct approach for what I've described as the use case? I've never tackled graphs or generators before, and I figure I have plenty of reading to do before I could devise a solution relying on both. I'd be grateful if anyone could weigh in on my approach, or perhaps advise on alternatives. Regards, Serdar From patrick.just4fun at gmail.com Tue Sep 8 21:57:41 2009 From: patrick.just4fun at gmail.com (Patrick Sabin) Date: Tue, 08 Sep 2009 21:57:41 +0200 Subject: [Tutor] pygtk In-Reply-To: References: Message-ID: <4AA6B735.5090100@gmail.com> The official docs http://www.pygtk.org/pygtk2tutorial/index.html http://library.gnome.org/devel/pygtk/stable/ worked for me. - Patrick Ajith Gopinath schrieb: > I will appreciate , if somebody guides me to a proper doc. on pygtk > for 2.5/2.6. I am currently unable to find a good doc for the same :o( > > Thanks and regards > ~|| a j i t || > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld at btinternet.com Tue Sep 8 23:26:14 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 8 Sep 2009 22:26:14 +0100 Subject: [Tutor] working with multiple sets References: <4AA2A88D.9060504@gmail.com><0E9249DF-48FF-4565-8A26-88DCFD8E4116@mac.com><4AA661AF.6020807@gmail.com><1c2a2c590909080844q62ab34b3ve6607001f2182350@mail.gmail.com><7221BB0F-6280-44A3-89DD-59F3CF092F7B@me.com><3587032D-143A-406B-9EE2-864F6B68B45F@mac.com><5F16B20C-06C2-45EC-B660-A9F0C3A7FA65@me.com> <5B930EC8-398E-4B24-BD20-DA255F202B25@mac.com> Message-ID: "Douglas Philips" wrote >>> for element in value: >> lookup[element] = lookup.get(element, []).append(key) > # Doug: That doesn't do what you think it does, it won't insert the > new list into the dictionary. Ah, yes I forgot append was one of those annoying python methods that doesn't return self... You need to do it in three lines... One to get the list, one to append and one to assign the value... > # Doug: I think what you want is lookup.setdefault(element, > []).append(key) or use setdfault (which I forgot all about! :-) Thanks for picking that one up Doug. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From lie.1296 at gmail.com Wed Sep 9 05:22:29 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Wed, 09 Sep 2009 13:22:29 +1000 Subject: [Tutor] working with multiple sets In-Reply-To: References: <4AA2A88D.9060504@gmail.com><0E9249DF-48FF-4565-8A26-88DCFD8E4116@mac.com><4AA661AF.6020807@gmail.com><1c2a2c590909080844q62ab34b3ve6607001f2182350@mail.gmail.com><7221BB0F-6280-44A3-89DD-59F3CF092F7B@me.com><3587032D-143A-406B-9EE2-864F6B68B45F@mac.com> <5F16B20C-06C2-45EC-B660-A9F0C3A7FA65@me.com> Message-ID: Alan Gauld wrote: > > "kevin parks" wrote >> What would this look like if i want to use a straight up built-in >> dictionary type and not the collections.defaultdict. >> > > Not too different: Alternatively: >> import collections >> >> def foo(): >> lookup = collections.defaultdict(list) >> x = range(10) >> y = range(5, 15) >> z = range(8, 22) >> sets = {'x': set(x), 'y': set(y), 'z': set(z)} >> for key, value in sets.items(): >> for element in value: try: lookup[element] = lookup[element].append(key) except KeyError: lookup[element] = [key] >> print "\n", lookup, "\n\n" >> for x in lookup: >> lookup[x].sort() >> print x, lookup[x] >> print "\n" which I /personally/ found easier to follow than using dict.get()'s or defaultdict (YMMV) From qbits143 at gmail.com Wed Sep 9 06:33:18 2009 From: qbits143 at gmail.com (Ajith Gopinath) Date: Wed, 9 Sep 2009 10:03:18 +0530 Subject: [Tutor] pygtk In-Reply-To: <4AA6B735.5090100@gmail.com> References: <4AA6B735.5090100@gmail.com> Message-ID: Thanks Patrik, this is what i am searching for. || a j i t || On Wed, Sep 9, 2009 at 1:27 AM, Patrick Sabin wrote: > The official docs > > http://www.pygtk.org/pygtk2tutorial/index.html > http://library.gnome.org/devel/pygtk/stable/ > > worked for me. > > - Patrick > > Ajith Gopinath schrieb: > >> I will appreciate , if somebody guides me to a proper doc. on pygtk for >> 2.5/2.6. I am currently unable to find a good doc for the same :o( >> >> Thanks and regards >> ~|| a j i t || >> ------------------------------------------------------------------------ >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> >> > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From cwitts at compuscan.co.za Wed Sep 9 08:30:17 2009 From: cwitts at compuscan.co.za (Christian Witts) Date: Wed, 09 Sep 2009 08:30:17 +0200 Subject: [Tutor] (no subject) In-Reply-To: <9f4be2240909081016q2748e206tdf75d4ed6bb45b51@mail.gmail.com> References: <20090908.130957.4086.0@webmail06.dca.untd.com> <9f4be2240909081016q2748e206tdf75d4ed6bb45b51@mail.gmail.com> Message-ID: <4AA74B79.9090301@compuscan.co.za> Lucas Prado Melo wrote: > On Tue, Sep 8, 2009 at 2:09 PM, shellcom3 at juno.com > > wrote: > > I,m trying to get a phrase from a user and print it backwards > using the for statement along with the range function, but all I > get with range function is integers not alpha. example range(-1) > does not work. > > What about range(0, -n, -1) ? > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > That would need to have a starting value of -1 and an end value of -(len(phrase)+1). Of else you can start at length - 1, end at zero and a step value of -1. -- Kind Regards, Christian Witts From alan.gauld at btinternet.com Wed Sep 9 08:34:19 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 9 Sep 2009 07:34:19 +0100 Subject: [Tutor] (no subject) References: <20090908.130957.4086.0@webmail06.dca.untd.com><9f4be2240909081016q2748e206tdf75d4ed6bb45b51@mail.gmail.com> <4AA74B79.9090301@compuscan.co.za> Message-ID: "Christian Witts" wrote >> >> What about range(0, -n, -1) ? >> > That would need to have a starting value of -1 and an end value of > -(len(phrase)+1). Of else you can start at length - 1, end at zero and > a step value of -1. Another option, using "normal" range values but negative indexing is for i in range(1,len(word)+1): print word[-i], Alan G From alan.gauld at btinternet.com Wed Sep 9 08:36:42 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 9 Sep 2009 07:36:42 +0100 Subject: [Tutor] working with multiple sets References: <4AA2A88D.9060504@gmail.com><0E9249DF-48FF-4565-8A26-88DCFD8E4116@mac.com><4AA661AF.6020807@gmail.com><1c2a2c590909080844q62ab34b3ve6607001f2182350@mail.gmail.com><7221BB0F-6280-44A3-89DD-59F3CF092F7B@me.com><3587032D-143A-406B-9EE2-864F6B68B45F@mac.com> <5F16B20C-06C2-45EC-B660-A9F0C3A7FA65@me.com> Message-ID: "Lie Ryan" wrote >>> for key, value in sets.items(): >>> for element in value: > try: > lookup[element] = lookup[element].append(key) This has the same flaw as mine. it nneeds to be lookup[element].append(key) ie no assignment, othewise you just get None stored... HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From cheesman at titan.physx.u-szeged.hu Wed Sep 9 08:52:54 2009 From: cheesman at titan.physx.u-szeged.hu (andy) Date: Wed, 9 Sep 2009 08:52:54 +0200 Subject: [Tutor] Python and google sites Message-ID: <20090909065254.GB28849@titan.physx.u-szeged.hu> Hi people After searching pypy and google, I was wondering if anyone has any experience/knowledge of a python module which would enable the interaction with Google sites? I'm looking for a method of scripted addition of pictyres to a page on a google site page and wondered if someone has been clever before me Thanks for any help Andy From stefan at lsd.co.za Wed Sep 9 09:31:14 2009 From: stefan at lsd.co.za (Stefan Lesicnik) Date: Wed, 9 Sep 2009 09:31:14 +0200 Subject: [Tutor] web2py vs django Message-ID: <5cb309e70909090031h733507b7y6a25832b04119938@mail.gmail.com> Hi guys. I am writing this because i am little confused and wanted a more 'expert' opinion on the two frameworks. I am still quite a python newbie, and not really familiar with all the intricacies of it and the frameworks. I discovered Django as a framework first. I thought it was really great. The tutorials makes sense, i really like the generic views (looks clean, added a filter, sorting works etc). The importing of various modules did confuse me a bit, but I think its something you can learn and work through. A friend asked me if I had tried web2py, and started looking at it. I haven't looked as much as Django, but I also think its due to the fact that Django seemed to have more resources available to learn. The Django book is great. There are many video tutorials showing you how to start and get going. With web2py, i run it, and I actually dont have a clue what to do next... Admittedly I have put more effort so far into learning Django. I have purchased the web2py book, but havent gone through it yet in detail. I plan on using either framework for a project i want to do that will contain a database of computer resources available, have a workflow where a user can request a service, administrator approve it, and the system will automate and build a machine, virtual machine and notify people. If that makes any difference to framework selection... I guess im trying to choose the correct framework before I put alot of effort into a dead horse :) Maybe to summarise what ive found so far (i know there are more, im coming from a newbie perspective here!) Django - Great generic views (sortable, filters etc) - Nice admin interface - Looks professional and clean - May be slightly more complex than web2py - Template specific language. - Feels like more addons and 3rd party support, not sure about this? web2py - Simpler syntax for doing things (This may be a nice factor, but then it does do more 'magic') - Unable to find generic views? - Not sure how to begin - Works with google app engine (not an issue for me, but thats pretty cool) - Template stuff is pure python with no indentation (this is good!) - Interface feels old. LIke pre 2003 way of doing stuff. feels like static html pages. - No importing of modules, all handled for you (this may not be a great thing. I am undecided still...) Thanks everyone, i would really appreciate hearing your views. Stefan -------------- next part -------------- An HTML attachment was scrubbed... URL: From dextrous85 at gmail.com Wed Sep 9 09:36:10 2009 From: dextrous85 at gmail.com (vishwajeet singh) Date: Wed, 9 Sep 2009 13:06:10 +0530 Subject: [Tutor] web2py vs django In-Reply-To: <5cb309e70909090031h733507b7y6a25832b04119938@mail.gmail.com> References: <5cb309e70909090031h733507b7y6a25832b04119938@mail.gmail.com> Message-ID: <5487b3060909090036y564bd2g18704aae305b9475@mail.gmail.com> I had asked this question earlier is django users google group you can find the responses here http://groups.google.co.in/group/django-users/browse_thread/thread/4c8bfa995c93b07b/f12442dd0d7f4fcd?q=#f12442dd0d7f4fcd On Wed, Sep 9, 2009 at 1:01 PM, Stefan Lesicnik wrote: > Hi guys. > > I am writing this because i am little confused and wanted a more 'expert' > opinion on the two frameworks. I am still quite a python newbie, and not > really familiar with all the intricacies of it and the frameworks. > > I discovered Django as a framework first. I thought it was really great. > The tutorials makes sense, i really like the generic views (looks clean, > added a filter, sorting works etc). The importing of various modules did > confuse me a bit, but I think its something you can learn and work through. > > A friend asked me if I had tried web2py, and started looking at it. I > haven't looked as much as Django, but I also think its due to the fact that > Django seemed to have more resources available to learn. The Django book is > great. There are many video tutorials showing you how to start and get > going. With web2py, i run it, and I actually dont have a clue what to do > next... Admittedly I have put more effort so far into learning Django. > > I have purchased the web2py book, but havent gone through it yet in detail. > > I plan on using either framework for a project i want to do that will > contain a database of computer resources available, have a workflow where a > user can request a service, administrator approve it, and the system will > automate and build a machine, virtual machine and notify people. If that > makes any difference to framework selection... I guess im trying to choose > the correct framework before I put alot of effort into a dead horse :) > > Maybe to summarise what ive found so far (i know there are more, im coming > from a newbie perspective here!) > > Django > - Great generic views (sortable, filters etc) > - Nice admin interface > - Looks professional and clean > - May be slightly more complex than web2py > - Template specific language. > - Feels like more addons and 3rd party support, not sure about this? > > web2py > - Simpler syntax for doing things (This may be a nice factor, but then it > does do more 'magic') > - Unable to find generic views? > - Not sure how to begin > - Works with google app engine (not an issue for me, but thats pretty cool) > - Template stuff is pure python with no indentation (this is good!) > - Interface feels old. LIke pre 2003 way of doing stuff. feels like static > html pages. > - No importing of modules, all handled for you (this may not be a great > thing. I am undecided still...) > > Thanks everyone, i would really appreciate hearing your views. > > Stefan > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- Cheers, Vishwajeet http://www.singhvishwajeet.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From oltarasenko at gmail.com Wed Sep 9 11:06:11 2009 From: oltarasenko at gmail.com (Oleg Oltar) Date: Wed, 9 Sep 2009 12:06:11 +0300 Subject: [Tutor] Encoding question Message-ID: Hi! One of my tests returned following text () The test: from django.test.client import Client c = Client() resp = c.get("/") resp.content In [25]: resp.content Out[25]: '\r\n\r\n\r\n\r\n\r\n\r\n \r\n \r\n \r\n \nJapanese innovation | \xd0\xaf\xd0\xbf\xd0\xbe\xd0\xbd\xd0\xb8\xd1\x8f \xd0\xb8\xd0\xbd\xd0\xbd\xd0\xbe\xd0\xb2\xd0\xb0\xd1\x86\xd0\xb8\xd0\xb8\n\r\n \n\n\n\r\n\r\n Is there a way I can convert it to normal readable text? (I need for example to find a string of text in this response to check if my test case Pass or failed) -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Wed Sep 9 12:59:41 2009 From: kent37 at tds.net (Kent Johnson) Date: Wed, 9 Sep 2009 06:59:41 -0400 Subject: [Tutor] Encoding question In-Reply-To: References: Message-ID: <1c2a2c590909090359h84527dcj37dee3848ef7eb81@mail.gmail.com> On Wed, Sep 9, 2009 at 5:06 AM, Oleg Oltar wrote: > Hi! > > One of my tests returned following text () > > The test: > from django.test.client import Client > ?c = Client() > resp = c.get("/") > resp.content > > In [25]: resp.content > Out[25]: '\r\n\r\n\r\n Strict//EN" > "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">\r\n\r\n xmlns="http://www.w3.org/1999/xhtml">\r\n? \r\n??? http-equiv="content-type" content="text/html; charset=utf-8" />\r\n > \r\n??? \nJapanese innovation | > \xd0\xaf\xd0\xbf\xd0\xbe\xd0\xbd\xd0\xb8\xd1\x8f > \xd0\xb8\xd0\xbd\xd0\xbd\xd0\xbe\xd0\xb2\xd0\xb0\xd1\x86\xd0\xb8\xd0\xb8\n\r\n > Is there a way I can convert it to normal readable text? (I need for example > to find a string of text in this response to check if my test case Pass or > failed) resp.content.decode('string_escape') will convert it to encoded bytes. Then another decode() with the correct encoding will get you Unicode. I'm not sure what the correct encoding is for the second decode(), most likely one of 'utf-8', 'utf_16_le' or 'utf_16_be'. Kent From sierra_mtnview at sbcglobal.net Wed Sep 9 13:04:57 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Wed, 09 Sep 2009 04:04:57 -0700 Subject: [Tutor] Web Site for Temporarily Posting Pictures for Images of Dialogs? Message-ID: <4AA78BD9.3070409@sbcglobal.net> Some months ago when I was active in modifying a Python program I needed to show members of the group pix of dialogs, and someone or two offered choices for web sites that allow temporary posts. Could someone send me links to some of these? -- Wayne Watson (Watson Adventures, Prop., Nevada City, CA) (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet "I feel that if a person has problems communicating the very least he can do is to shut up." -- Tom Lehrer Web Page: From kp8 at mac.com Wed Sep 9 13:48:20 2009 From: kp8 at mac.com (kevin parks) Date: Wed, 09 Sep 2009 20:48:20 +0900 Subject: [Tutor] working with multiple sets In-Reply-To: References: <4AA2A88D.9060504@gmail.com> <0E9249DF-48FF-4565-8A26-88DCFD8E4116@mac.com> <4AA661AF.6020807@gmail.com> <1c2a2c590909080844q62ab34b3ve6607001f2182350@mail.gmail.com> <7221BB0F-6280-44A3-89DD-59F3CF092F7B@me.com> <3587032D-143A-406B-9EE2-864F6B68B45F@mac.com> <5F16B20C-06C2-45EC-B660-A9F0C3A7FA65@me.com> Message-ID: <9CCF2739-CC48-4F53-887E-565750643AE8@mac.com> This discussion is making my brain melt. It is also showing how clever Bob was to do it the way he did... I found a solution that i think works, and think has not yet been suggested. I quarantined Bob's code into a black box ... and then cast the output as a plain old fashioned python built in dictionary on output. So now instead of printing the code Bob gave the collection is returned by the func. Then i can cast it as a dict and pick over that dictionary as i wish. Here (as a bonus) I can transverse a range of keys that is inclusive of all my keys and also use python's get() dict method to also indicate index points (keys) that are empty.. which by default returns 'None', which is also useful in this case to show me what is missing. But I also have to do some type testing tomfoolery since missing keys return None, which is a special type (and not a list like the others)... I wanted the value list sorted so... i did if type(item) == type(foo): .... not sure if there is a betterererer way. Anyway, this woiks. -- #!/usr/bin/env python import collections def pscape(): lookup = collections.defaultdict(list) k1 = [34, 39, 41, 42, 43, 44, 46, 48, 49, 50, 51, 54, 55, 56, 58, 60, 61, 62, 63, 65, 66, 67, 68] k2 = [51, 56, 58, 63, 65, 68, 70, 72, 75, 77, 80, 82] y1 = [51, 53, 54, 56, 58, 60, 61, 63, 65, 66, 68, 70, 72, 73, 70, 72, 73, 75, 77, 79, 80] sets = {'k1': set(k1), 'k2': set(k2), 'y1': set(y1)} for key, value in sets.items(): for element in value: lookup[element].append(key) return lookup def test(): gamut = dict(pscape()) # -- scaffolding #print "\n\n", type(gamut), "\n\n", gamut, "\n\n", gamut.keys() print "\n\n" foo = [1, 2, 3] for x in range(30, 85): item = gamut.get(x) if type(item) == type(foo): item.sort() print x, item print "\n\n" if __name__ == "__main__": test() From kp8 at mac.com Wed Sep 9 13:54:58 2009 From: kp8 at mac.com (kevin parks) Date: Wed, 09 Sep 2009 20:54:58 +0900 Subject: [Tutor] mapping/filtering a sequence In-Reply-To: <333efb450909052032n42dc0bf7gfef108a09b75dd77@mail.gmail.com> References: <189A4F7F-08A8-40F0-BD37-A515BAC19857@mac.com> <333efb450909050747sd78ae59r6c9220b6e98e4531@mail.gmail.com> <56D2FBB7-E2E0-4B9D-89E0-6922971DEC88@mac.com> <333efb450909052032n42dc0bf7gfef108a09b75dd77@mail.gmail.com> Message-ID: <69D2D2CE-9ECC-4F52-9804-ED4B4FC1C668@mac.com> Prolly good to post final solutions for future goog'lerz (like when i forget) or anyone who was following along. Here's where i ended up with this... shows both ways. ---------- #!/usr/bin/env python my_map = { 38:34, 40:39, 45:44, 47:46, 52:51, 59:58, 55:56 } def filter_item(item): return my_map.get(item, item) # you can do it old skool with map() def filter_test1(): foo = range(60) mappedfoo = map(filter_item, foo) for item in foo: print foo[item], mappedfoo[item] # you can also do it with a list comp def filter_test2(): foo = range(60) mappedfoo = [filter_item(n) for n in foo] for item in foo: print foo[item], mappedfoo[item] if __name__ == "__main__": filter_test1() print "\n","------" * 8, "\n" filter_test2() #--EOF-- From lie.1296 at gmail.com Wed Sep 9 15:12:07 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Wed, 09 Sep 2009 23:12:07 +1000 Subject: [Tutor] working with multiple sets In-Reply-To: <9CCF2739-CC48-4F53-887E-565750643AE8@mac.com> References: <4AA2A88D.9060504@gmail.com> <0E9249DF-48FF-4565-8A26-88DCFD8E4116@mac.com> <4AA661AF.6020807@gmail.com> <1c2a2c590909080844q62ab34b3ve6607001f2182350@mail.gmail.com> <7221BB0F-6280-44A3-89DD-59F3CF092F7B@me.com> <3587032D-143A-406B-9EE2-864F6B68B45F@mac.com> <5F16B20C-06C2-45EC-B660-A9F0C3A7FA65@me.com> <9CCF2739-CC48-4F53-887E-565750643AE8@mac.com> Message-ID: kevin parks wrote: > This discussion is making my brain melt. > > It is also showing how clever Bob was to do it the way he did... I found > a solution that i think works, and think has not yet been suggested. I > quarantined Bob's code into a black box ... and then cast the output as > a plain old fashioned python built in dictionary on output. So now > instead of printing the code Bob gave the collection is returned by the > func. > > Then i can cast it as a dict and pick over that dictionary as i wish. > Here (as a bonus) I can transverse a range of keys that is inclusive of > all my keys and also use python's get() dict method to also indicate > index points (keys) that are empty.. which by default returns 'None', > which is also useful in this case to show me what is missing. But I also > have to do some type testing tomfoolery since missing keys return None, > which is a special type (and not a list like the others)... I wanted the > value list sorted so... i did if type(item) == type(foo): .... not sure > if there is a betterererer way. > You can use: alist = [1, 2, 3] if isinstance(alist, list): ... or alternatively check for the None case: if alist is not None: ... From roadierich at googlemail.com Wed Sep 9 16:04:32 2009 From: roadierich at googlemail.com (Rich Lovely) Date: Wed, 9 Sep 2009 15:04:32 +0100 Subject: [Tutor] Fwd: Python and google sites In-Reply-To: References: <20090909065254.GB28849@titan.physx.u-szeged.hu> Message-ID: Forgot to reply-all... ---------- Forwarded message ---------- From: Rich Lovely Date: 2009/9/9 Subject: Re: [Tutor] Python and google sites To: andy 2009/9/9 andy : > Hi people > > After searching pypy and google, I was wondering if anyone has any > experience/knowledge of a python module which would enable the > interaction with Google sites? > I'm looking for a method of scripted addition of pictyres to a page on a > google site page and wondered if someone has been clever before me > > Thanks for any help > > Andy > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Mechanize is a module built around urllib, BeautifulSoup and a web forms handler. ?I really like it, and it could probably do what you're looking at. http://wwwsearch.sourceforge.net/mechanize/ You would have to do most of the work yourself, but it save messing with headers and content-types to get logging in and forms to function correctly. -- Rich "Roadie Rich" Lovely There are 10 types of people in the world: those who know binary, those who do not, and those who are off by one. -- Rich "Roadie Rich" Lovely There are 10 types of people in the world: those who know binary, those who do not, and those who are off by one. From mdipierro at cs.depaul.edu Wed Sep 9 16:13:21 2009 From: mdipierro at cs.depaul.edu (mdipierro) Date: Wed, 9 Sep 2009 07:13:21 -0700 (PDT) Subject: [Tutor] web2py vs django In-Reply-To: <5cb309e70909090031h733507b7y6a25832b04119938@mail.gmail.com> References: <5cb309e70909090031h733507b7y6a25832b04119938@mail.gmail.com> Message-ID: <25365869.post@talk.nabble.com> If you know Django you basically know web2py. Let me address some of you concerns below and then I will give you some examples: > web2py > Simpler syntax for doing things (This may be a nice factor, but then it > does do more 'magic') The only "magic" is that your code is executed in a context, not imported. this makes sure there are no memory leaks, your app is dynamically updated without need to restart. > Unable to find generic views? We have them but they are different than Django's. They are in yourapp/views/generic.* The main difference from Django is that you do not have to declare generic views in url.py. I an action returns a dictionary, web2py will find a generic view for you, depending on whether you requested the page in .html or .xml or .json, etc. > - Not sure how to begin 1) start the web server 2) open http://127.0.0.1/admin and login 3) use the form on the right to create a new app then edit the model/controllers/views as you would in Django. You can use the shell and emacs or use the web based IDE that comes with it (and we call admin). > - Works with google app engine (not an issue for me, but thats pretty > cool) yes > - Template stuff is pure python with no indentation (this is good!) yes > - Interface feels old. LIke pre 2003 way of doing stuff. feels like static > html pages. You are probably talking about the scaffolding application welcome, you have not tried admin yet. > - No importing of modules, all handled for you (this may not be a great > thing. I am undecided still...) Not quite correct. In web2py you import modules as in Django except that you do not import web2py keywords and you do not import your own models. That is done for you by web2py before controllers are executed. We follow the DRY. Join us on the web2py google group and we will be happy to answer more of your questions. We have video tutorials linked from the documentation page. Stefan Lesicnik-2 wrote: > > Hi guys. > > I am writing this because i am little confused and wanted a more 'expert' > opinion on the two frameworks. I am still quite a python newbie, and not > really familiar with all the intricacies of it and the frameworks. > > I discovered Django as a framework first. I thought it was really great. > The > tutorials makes sense, i really like the generic views (looks clean, added > a > filter, sorting works etc). The importing of various modules did confuse > me > a bit, but I think its something you can learn and work through. > > A friend asked me if I had tried web2py, and started looking at it. I > haven't looked as much as Django, but I also think its due to the fact > that > Django seemed to have more resources available to learn. The Django book > is > great. There are many video tutorials showing you how to start and get > going. With web2py, i run it, and I actually dont have a clue what to do > next... Admittedly I have put more effort so far into learning Django. > > I have purchased the web2py book, but havent gone through it yet in > detail. > > I plan on using either framework for a project i want to do that will > contain a database of computer resources available, have a workflow where > a > user can request a service, administrator approve it, and the system will > automate and build a machine, virtual machine and notify people. If that > makes any difference to framework selection... I guess im trying to > choose > the correct framework before I put alot of effort into a dead horse :) > > Maybe to summarise what ive found so far (i know there are more, im coming > from a newbie perspective here!) > > Django > - Great generic views (sortable, filters etc) > - Nice admin interface > - Looks professional and clean > - May be slightly more complex than web2py > - Template specific language. > - Feels like more addons and 3rd party support, not sure about this? > > web2py > - Simpler syntax for doing things (This may be a nice factor, but then it > does do more 'magic') > - Unable to find generic views? > - Not sure how to begin > - Works with google app engine (not an issue for me, but thats pretty > cool) > - Template stuff is pure python with no indentation (this is good!) > - Interface feels old. LIke pre 2003 way of doing stuff. feels like static > html pages. > - No importing of modules, all handled for you (this may not be a great > thing. I am undecided still...) > > Thanks everyone, i would really appreciate hearing your views. > > Stefan > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- View this message in context: http://www.nabble.com/web2py-vs-django-tp25360012p25365869.html Sent from the Python - tutor mailing list archive at Nabble.com. From kp8 at mac.com Wed Sep 9 16:23:44 2009 From: kp8 at mac.com (kevin parks) Date: Wed, 09 Sep 2009 23:23:44 +0900 Subject: [Tutor] working with multiple sets In-Reply-To: References: <4AA2A88D.9060504@gmail.com> <0E9249DF-48FF-4565-8A26-88DCFD8E4116@mac.com> <4AA661AF.6020807@gmail.com> <1c2a2c590909080844q62ab34b3ve6607001f2182350@mail.gmail.com> <7221BB0F-6280-44A3-89DD-59F3CF092F7B@me.com> <3587032D-143A-406B-9EE2-864F6B68B45F@mac.com> <5F16B20C-06C2-45EC-B660-A9F0C3A7FA65@me.com> <9CCF2739-CC48-4F53-887E-565750643AE8@mac.com> Message-ID: <2EFBCA9B-52A2-46AD-A06C-4A046D98F608@mac.com> Are any of these methods better than another for some reason? On Sep 9, 2009, at 10:12 PM, Lie Ryan wrote: > kevin parks wrote: >> This discussion is making my brain melt. >> It is also showing how clever Bob was to do it the way he did... I >> found a solution that i think works, and think has not yet been >> suggested. I quarantined Bob's code into a black box ... and then >> cast the output as a plain old fashioned python built in dictionary >> on output. So now instead of printing the code Bob gave the >> collection is returned by the func. >> Then i can cast it as a dict and pick over that dictionary as i >> wish. Here (as a bonus) I can transverse a range of keys that is >> inclusive of all my keys and also use python's get() dict method to >> also indicate index points (keys) that are empty.. which by default >> returns 'None', which is also useful in this case to show me what >> is missing. But I also have to do some type testing tomfoolery >> since missing keys return None, which is a special type (and not a >> list like the others)... I wanted the value list sorted so... 1 >> i did if type(item) == type(foo): .... not sure if there is a >> betterererer way. > 2 > You can use: > alist = [1, 2, 3] > if isinstance(alist, list): > ... > 3 > or alternatively check for the None case: > if alist is not None: > ... From kent37 at tds.net Wed Sep 9 19:08:19 2009 From: kent37 at tds.net (Kent Johnson) Date: Wed, 9 Sep 2009 13:08:19 -0400 Subject: [Tutor] web2py vs django In-Reply-To: <5487b3060909090036y564bd2g18704aae305b9475@mail.gmail.com> References: <5cb309e70909090031h733507b7y6a25832b04119938@mail.gmail.com> <5487b3060909090036y564bd2g18704aae305b9475@mail.gmail.com> Message-ID: <1c2a2c590909091008h6b4022c9g272e6cc105d61b8b@mail.gmail.com> On Wed, Sep 9, 2009 at 3:36 AM, vishwajeet singh wrote: > I had asked this question earlier is django users google group you can find > the responses here > http://groups.google.co.in/group/django-users/browse_thread/thread/4c8bfa995c93b07b/f12442dd0d7f4fcd?q=#f12442dd0d7f4fcd That thread is about web.py, not web2py, they are different frameworks. Kent From kent37 at tds.net Wed Sep 9 19:19:45 2009 From: kent37 at tds.net (Kent Johnson) Date: Wed, 9 Sep 2009 13:19:45 -0400 Subject: [Tutor] working with multiple sets In-Reply-To: <9CCF2739-CC48-4F53-887E-565750643AE8@mac.com> References: <4AA2A88D.9060504@gmail.com> <1c2a2c590909080844q62ab34b3ve6607001f2182350@mail.gmail.com> <7221BB0F-6280-44A3-89DD-59F3CF092F7B@me.com> <3587032D-143A-406B-9EE2-864F6B68B45F@mac.com> <5F16B20C-06C2-45EC-B660-A9F0C3A7FA65@me.com> <9CCF2739-CC48-4F53-887E-565750643AE8@mac.com> Message-ID: <1c2a2c590909091019g4ec82344o9473d6c4c9c7fae6@mail.gmail.com> On Wed, Sep 9, 2009 at 7:48 AM, kevin parks wrote: > Then i can cast it as a dict and pick over that dictionary as i wish. There is no need for that. defaultdict is a subclass of dict and supports all the methods of dict. > Here > (as a bonus) I can transverse a range of keys that is inclusive of all my > keys and also use python's get() dict method to also indicate index points > (keys) that are empty.. which by default returns 'None', which is also > useful in this case to show me what is missing. But I also have to do some > type testing tomfoolery since missing keys return None, which is a special > type (and not a list like the others)... I wanted the value list sorted > so... i did ?if type(item) == type(foo): .... not sure if there is a > betterererer way. Besides Lie's suggestions, you could use item = gamut.get(x, []) item.sort() print x, item Kent From alan.gauld at btinternet.com Wed Sep 9 21:29:56 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 9 Sep 2009 20:29:56 +0100 Subject: [Tutor] web2py vs django References: <5cb309e70909090031h733507b7y6a25832b04119938@mail.gmail.com><5487b3060909090036y564bd2g18704aae305b9475@mail.gmail.com> <1c2a2c590909091008h6b4022c9g272e6cc105d61b8b@mail.gmail.com> Message-ID: "Kent Johnson" wrote > That thread is about web.py, not web2py, they are different frameworks. I confess I too had missed that subtlety! Like editors and standards... The wonderful thing about Web Frameworks in Python - there are so many to choose from! But it is confusing, my advice is just pick one and stick with it! -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From krissy.ambert at gmail.com Wed Sep 9 21:52:53 2009 From: krissy.ambert at gmail.com (Kristina Ambert) Date: Wed, 9 Sep 2009 15:52:53 -0400 Subject: [Tutor] wxpython question Message-ID: Hi, I'm not sure if I could ask questions about wx in this list or not, hopefully it's okay? If not I guess disregard this question. But, does anyone have any idea of if it's possible to make a frame that will latch on to the parent frame (e.g. if you resize the parent, the child also resizes, if you move the parent, the child also moves), aside from using the MDI window that's wxpython provides? -- Cheers, Krissy ----------------------------------------------------------------------- Testing the waters is always fun... -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at alchemy.com Wed Sep 9 22:18:18 2009 From: steve at alchemy.com (Steve Willoughby) Date: Wed, 9 Sep 2009 13:18:18 -0700 Subject: [Tutor] web2py vs django In-Reply-To: References: <1c2a2c590909091008h6b4022c9g272e6cc105d61b8b@mail.gmail.com> Message-ID: <20090909201818.GB82586@dragon.alchemy.com> On Wed, Sep 09, 2009 at 08:29:56PM +0100, Alan Gauld wrote: > But it is confusing, my advice is just pick one and stick with it! Yeah, that's probably the best advice. Each framework has its particular area of applicability it's been optimized for, so depending on what you plan to do most of the time, you might want to look at that initially. Having learned one of the popular frameworks, though, you probably will just stick to it since the good ones are usable for lots of application types. Personally, I started out with TurboGears, and although I found the others interesting and cool in their own ways, at that point I had what I needed and it worked well. I suspect those who use Pylons or Django or whatever would say the same thing. -- Steve Willoughby | Using billion-dollar satellites steve at alchemy.com | to hunt for Tupperware. From mdipierro at cs.depaul.edu Wed Sep 9 22:45:41 2009 From: mdipierro at cs.depaul.edu (mdipierro) Date: Wed, 9 Sep 2009 13:45:41 -0700 (PDT) Subject: [Tutor] web2py vs django In-Reply-To: <5cb309e70909090031h733507b7y6a25832b04119938@mail.gmail.com> References: <5cb309e70909090031h733507b7y6a25832b04119938@mail.gmail.com> Message-ID: <25372849.post@talk.nabble.com> Since you said you know Django, perhaps this video will help jump start with web2py: http://www.vimeo.com/6504620 Massimo -- View this message in context: http://www.nabble.com/web2py-vs-django-tp25360012p25372849.html Sent from the Python - tutor mailing list archive at Nabble.com. From mdipierro at cs.depaul.edu Wed Sep 9 23:38:50 2009 From: mdipierro at cs.depaul.edu (mdipierro) Date: Wed, 9 Sep 2009 14:38:50 -0700 (PDT) Subject: [Tutor] web2py vs django In-Reply-To: <20090909201818.GB82586@dragon.alchemy.com> References: <5cb309e70909090031h733507b7y6a25832b04119938@mail.gmail.com> <5487b3060909090036y564bd2g18704aae305b9475@mail.gmail.com> <1c2a2c590909091008h6b4022c9g272e6cc105d61b8b@mail.gmail.com> <20090909201818.GB82586@dragon.alchemy.com> Message-ID: <25373518.post@talk.nabble.com> Let's say you buy a car (spend time and money to learn a framework). It is a good advice to stick with it and don't change your car (framework) too often until the maintenance costs (keep up with changes, backward incompatibilities, integration with third party libraries) exceed the cost of buying a new car (use a new framework) or the resale values of your current car (the value of your skills in the job market) falls too low Meanwhile it is a good idea to keep your eyes open, see what is out there and test drive some of the most recent options. You may like web2py so much that you decide to port some of its features to your other favorite framework. -- View this message in context: http://www.nabble.com/web2py-vs-django-tp25360012p25373518.html Sent from the Python - tutor mailing list archive at Nabble.com. From pine508 at hotmail.com Thu Sep 10 00:37:36 2009 From: pine508 at hotmail.com (Che M) Date: Wed, 9 Sep 2009 18:37:36 -0400 Subject: [Tutor] wxpython question In-Reply-To: References: Message-ID: Date: Wed, 9 Sep 2009 15:52:53 -0400 From: krissy.ambert at gmail.com To: tutor at python.org Subject: [Tutor] wxpython question Hi, I'm not sure if I could ask questions about wx in this list or not, hopefully it's okay? If not I guess disregard this question. But, does anyone have any idea of if it's possible to make a frame that will latch on to the parent frame (e.g. if you resize the parent, the child also resizes, if you move the parent, the child also moves), aside from using the MDI window that's wxpython provides? -- Cheers, Krissy ----------------------------------------------------------------------- Testing the waters is always fun... __________________________ Although people on this list would likely be happy to try to help, there is a wxPython users list that is really good: http://www.wxpython.org/maillist.php You can do what you are saying, although I don't think there is any built-in way to do it. You would have to use the two frames' methods of getting and setting position on the screen and then bind the Move event of the parent frame to an event handler function that then updates the position of the child (following) frame. The people on that list can help you if you have further questions. CM _________________________________________________________________ Get back to school stuff for them and cashback for you. http://www.bing.com/cashback?form=MSHYCB&publ=WLHMTAG&crea=TEXT_MSHYCB_BackToSchool_Cashback_BTSCashback_1x1 -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Thu Sep 10 01:14:46 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 10 Sep 2009 00:14:46 +0100 Subject: [Tutor] wxpython question References: Message-ID: "Kristina Ambert" wrote > I'm not sure if I could ask questions about wx in this list or not, > hopefully it's okay? If not I guess disregard this question. Yes its fine but you will get more complete answers in the wx mailing list. > But, does anyone have any idea of if it's possible to make a frame that > will > latch on to the parent frame (e.g. if you resize the parent, the child > also > resizes, if you move the parent, the child also moves), aside from using > the > MDI window that's wxpython provides? Yes, I think so - I'm not 100% sure I know what you mean. But the standard wxPython layout managers should control all that for you. Look into the docs for FlexGrid and Grid Bag sizers. They are probably the most powerful sizers but also take more effort to use of course. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From smiles at worksmail.net Thu Sep 10 02:30:06 2009 From: smiles at worksmail.net (C or L Smith) Date: Thu, 10 Sep 2009 06:15:06 +0545 Subject: [Tutor] (no subject) References: Message-ID: <6AA0976CCDDB4A5C8C0C97B6A6D364E0@kisc.edu.np> >>>> What about range(0, -n, -1) ? >>>> >>> That would need to have a starting value of -1 and an end value of >>> -(len(phrase)+1). Of else you can start at length - 1, end at zero >>> and a step value of -1. >> >> Another option, using "normal" range values but negative indexing is >> >> for i in range(1,len(word)+1): >> print word[-i], >> Or (and I'll duck after I pass on what I just happened across today on the web): ### for i in range(len(word)): print word[~i] ### /c From alan.gauld at btinternet.com Thu Sep 10 09:51:38 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 10 Sep 2009 08:51:38 +0100 Subject: [Tutor] (no subject) References: <6AA0976CCDDB4A5C8C0C97B6A6D364E0@kisc.edu.np> Message-ID: "C or L Smith" wrote > Or (and I'll duck after I pass on what I just happened across today on > the web): > > ### > for i in range(len(word)): > print word[~i] > ### Neat trick! Now what does ~ do?... the bitwise inverse. So it relies on the rules of complementing the binary value to effectively add one and negate. Sneaky, and a new one on me! Alan G. From oltarasenko at gmail.com Thu Sep 10 10:13:03 2009 From: oltarasenko at gmail.com (Oleg Oltar) Date: Thu, 10 Sep 2009 11:13:03 +0300 Subject: [Tutor] Threads very simple examle Message-ID: Hi! I have a question. I want to create simple load test for my web application. Consider the following script: while 1: urllib2.urlopen("www.example.com") How can I make it running in several threads? -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Thu Sep 10 11:43:42 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 10 Sep 2009 10:43:42 +0100 Subject: [Tutor] Threads very simple examle References: Message-ID: "Oleg Oltar" wrote > I want to create simple load test for my web application. > Consider the following script: > > while 1: > urllib2.urlopen("www.example.com") Just a small caveat. If you try a load test like this from a single PC you might get very surprising (and non representative) results. Remember that each request will be sharing a single network connection, so the performance bottleneck can very quickly become the network interface not the server. It depends of course on what you are measuring and how many threads you want to run. Just be aware of the full architecture that you are testing to make sure what you measure is what you mean to measure. Load testing is a very complex task, frought with potential for false results. I've seen far more erroneous load tests than I've seen valid ones!If you on;y want to test for 3 or 4 connections then it is probably OK but if you try running dozens of concurrent tests it will almost certainly fail to reflect reality. The same applies to the server of course, if it only has one network connection then it may bottleneck there too. But most servers (in a data center environment) have at least two network interfaces running so its usually less of an issue. > How can I make it running in several threads? I'll leave the threading part to someone else. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From dirk at pensiun.com Thu Sep 10 11:44:38 2009 From: dirk at pensiun.com (Dirk Wangsadirdja) Date: Thu, 10 Sep 2009 11:44:38 +0200 Subject: [Tutor] (no subject) In-Reply-To: References: <6AA0976CCDDB4A5C8C0C97B6A6D364E0@kisc.edu.np> Message-ID: <4AA8CA86.2030402@pensiun.com> I tested it and it works. But I dont understand why it works. Can someone please explain it further? Thanks. Alan Gauld wrote: > > "C or L Smith" wrote > >> Or (and I'll duck after I pass on what I just happened across today on >> the web): >> >> ### >> for i in range(len(word)): >> print word[~i] >> ### > > Neat trick! > Now what does ~ do?... the bitwise inverse. > So it relies on the rules of complementing the binary value > to effectively add one and negate. Sneaky, and a new one on me! > > Alan G. > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From lukepadawan at gmail.com Thu Sep 10 11:51:49 2009 From: lukepadawan at gmail.com (Lucas Prado Melo) Date: Thu, 10 Sep 2009 06:51:49 -0300 Subject: [Tutor] (no subject) In-Reply-To: <4AA8CA86.2030402@pensiun.com> References: <6AA0976CCDDB4A5C8C0C97B6A6D364E0@kisc.edu.np> <4AA8CA86.2030402@pensiun.com> Message-ID: <9f4be2240909100251s675b1a3flb5639a299e4c4bc3@mail.gmail.com> On Thu, Sep 10, 2009 at 6:44 AM, Dirk Wangsadirdja wrote: > I tested it and it works. But I dont understand why it works. Can someone > please explain it further? Thanks. ~i == -i - 1 http://en.wikipedia.org/wiki/Two%27s_complement -------------- next part -------------- An HTML attachment was scrubbed... URL: From oltarasenko at gmail.com Thu Sep 10 12:21:04 2009 From: oltarasenko at gmail.com (Oleg Oltar) Date: Thu, 10 Sep 2009 13:21:04 +0300 Subject: [Tutor] Threads very simple examle In-Reply-To: References: Message-ID: On Thu, Sep 10, 2009 at 12:43 PM, Alan Gauld wrote: > "Oleg Oltar" wrote > > I want to create simple load test for my web application. >> Consider the following script: >> >> while 1: >> urllib2.urlopen("www.example.com") >> > > Just a small caveat. > If you try a load test like this from a single PC you might get very > surprising (and non representative) results. Remember that each request will > be sharing a single network connection, so the performance bottleneck > can very quickly become the network interface not the server. It depends of > course on what you are measuring and how many threads you want to run. Just > be aware of the full architecture that you are testing to make sure what you > measure is what you mean to measure. > > Load testing is a very complex task, frought with potential > for false results. I've seen far more erroneous load tests than I've seen > valid ones!If you on;y want to test for 3 or 4 connections then it is > probably OK but if you try running dozens of concurrent tests it will almost > certainly fail to reflect reality. The same applies to the server of course, > if it only has one network connection then it may bottleneck there too. But > most servers (in a data center environment) have at least two network > interfaces running so its usually less of an issue. > > How can I make it running in several threads? >> > > I'll leave the threading part to someone else. > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Yes, I use tsung to make massive tests, but I just wanted to make some small test runner for approx 10-20 threads Here what I've done: import urllib2 from threading import Thread def btl_test(): while True: page = urllib2.urlopen("example.com") print page.code for i in range(120): t = Thread(target = btl_test) t.start() -------------- next part -------------- An HTML attachment was scrubbed... URL: From mdipierro at cs.depaul.edu Thu Sep 10 04:06:43 2009 From: mdipierro at cs.depaul.edu (mdipierro) Date: Wed, 9 Sep 2009 19:06:43 -0700 (PDT) Subject: [Tutor] web2py vs django In-Reply-To: <5cb309e70909090031h733507b7y6a25832b04119938@mail.gmail.com> References: <5cb309e70909090031h733507b7y6a25832b04119938@mail.gmail.com> Message-ID: <25376004.post@talk.nabble.com> This is an example of a Django tutorial "polls" being rewritten in web2py. Hope to help kickstart: http://vimeo.com/6507384 -- View this message in context: http://www.nabble.com/web2py-vs-django-tp25360012p25376004.html Sent from the Python - tutor mailing list archive at Nabble.com. From kent37 at tds.net Thu Sep 10 13:01:06 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 10 Sep 2009 07:01:06 -0400 Subject: [Tutor] Threads very simple examle In-Reply-To: References: Message-ID: <1c2a2c590909100401w3d1ec204yd3a440ec01bd56f1@mail.gmail.com> On Thu, Sep 10, 2009 at 4:13 AM, Oleg Oltar wrote: > Hi! > > I have a question. > I want to create simple load test for my web application. > > Consider the following script: > > while 1: > ??? urllib2.urlopen("www.example.com") > > How can I make it running in several threads? Have you read at all about threads? http://www.devshed.com/c/a/Python/Basic-Threading-in-Python/ http://www.wellho.net/solutions/python-python-threads-a-first-example.html You might consider using an existing load test application, there are many, some even written in Python: http://httpd.apache.org/docs/2.0/programs/ab.html http://www.opensourcetesting.org/performance.php http://www.softwareqatest.com/qatweb1.html#LOAD Kent From shellcom3 at juno.com Thu Sep 10 15:54:55 2009 From: shellcom3 at juno.com (shellcom3 at juno.com) Date: Thu, 10 Sep 2009 13:54:55 GMT Subject: [Tutor] (no subject) Message-ID: <20090910.095455.18831.0@webmail19.dca.untd.com> I want to display all the cards in a deck of playing cards using two tuples for all the possible suits. value = ("A","2","3","4","5","6","7","8","9","10","J","Q","K") suit = ("c","h","s","d") deck = value[0:1] + suit[0:1] for item in deck: print item This is the display >>> A c ____________________________________________________________ Woodhouse Day Spa Luxury Plano Day Spa with over 70 pampering services http://thirdpartyoffers.juno.com/TGL2141/c?cp=dsr8LBg9kip6hkIh3gzXYwAAJ1CmHaRKpeX3s0f3JfT8odq8AAUAAAAAAAAAACSXfz4cTkdAnjuWutIFlqhweIymAAAAAA== From krissy.ambert at gmail.com Thu Sep 10 16:29:59 2009 From: krissy.ambert at gmail.com (Kristina Ambert) Date: Thu, 10 Sep 2009 10:29:59 -0400 Subject: [Tutor] wxpython question In-Reply-To: References: Message-ID: Thank you guys for the replies! And thanks for the headsup about the wxpython mail list, I'll be sure to sign up there as well. On Wed, Sep 9, 2009 at 7:14 PM, Alan Gauld wrote: > "Kristina Ambert" wrote > > I'm not sure if I could ask questions about wx in this list or not, >> hopefully it's okay? If not I guess disregard this question. >> > > Yes its fine but you will get more complete answers in the wx mailing list. > > But, does anyone have any idea of if it's possible to make a frame that >> will >> latch on to the parent frame (e.g. if you resize the parent, the child >> also >> resizes, if you move the parent, the child also moves), aside from using >> the >> MDI window that's wxpython provides? >> > > Yes, I think so - I'm not 100% sure I know what you mean. But the > standard wxPython layout managers should control all that for you. > Look into the docs for FlexGrid and Grid Bag sizers. > > They are probably the most powerful sizers but also take more effort > to use of course. > > HTH, > > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Cheers, Krissy ----------------------------------------------------------------------- Testing the waters is always fun... -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Thu Sep 10 16:42:36 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 10 Sep 2009 10:42:36 -0400 Subject: [Tutor] (no subject) In-Reply-To: <20090910.095455.18831.0@webmail19.dca.untd.com> References: <20090910.095455.18831.0@webmail19.dca.untd.com> Message-ID: <1c2a2c590909100742p20608351hdc63d0545e4c1c5d@mail.gmail.com> On Thu, Sep 10, 2009 at 9:54 AM, shellcom3 at juno.com wrote: > I want to display all the cards in a deck of playing cards using two tuples for all the possible suits. > > > > value = ("A","2","3","4","5","6","7","8","9","10","J","Q","K") > > suit = ("c","h","s","d") > > deck = value[0:1] + suit[0:1] > for item in deck: > ? ?print item See itertools.product(), you can use it directly or use a nested list comprehension as shown in the docs: http://docs.python.org/library/itertools.html#itertools.product Kent From oltarasenko at gmail.com Thu Sep 10 16:51:53 2009 From: oltarasenko at gmail.com (Oleg Oltar) Date: Thu, 10 Sep 2009 17:51:53 +0300 Subject: [Tutor] Getting list of attributes from list of objects Message-ID: Hi! I have the following list l= [ a, b, c] Where a,b,c are objects created from one class, e.g. each has title attribute. What I want to have is a list of titles, e.g. [a.title, b.title, c.title] Is there a quick way to do it? Or I should use loops (looping through each element, and generating list) -------------- next part -------------- An HTML attachment was scrubbed... URL: From vinces1979 at gmail.com Thu Sep 10 17:31:11 2009 From: vinces1979 at gmail.com (vince spicer) Date: Thu, 10 Sep 2009 09:31:11 -0600 Subject: [Tutor] Getting list of attributes from list of objects In-Reply-To: References: Message-ID: <1e53c510909100831x4fa6c6cal3a5243cd0641149a@mail.gmail.com> On Thu, Sep 10, 2009 at 8:51 AM, Oleg Oltar wrote: > Hi! > > I have the following list > > l= [ a, b, c] > > Where a,b,c are objects created from one class, e.g. each has title > attribute. > What I want to have is a list of titles, e.g. [a.title, b.title, c.title] > > Is there a quick way to do it? Or I should use loops (looping through each > element, and generating list) > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > you can use list comprehension, which is a type of loop, but looks so pretty :) titles = [x.title for x in l] Vince -------------- next part -------------- An HTML attachment was scrubbed... URL: From zstumgoren at gmail.com Thu Sep 10 17:36:49 2009 From: zstumgoren at gmail.com (Serdar Tumgoren) Date: Thu, 10 Sep 2009 11:36:49 -0400 Subject: [Tutor] Getting list of attributes from list of objects In-Reply-To: References: Message-ID: > I have the following list > > l= [ a, b, c] > > Where a,b,c are objects created from one class, e.g. each has title > attribute. > What I want to have is a list of titles, e.g. [a.title, b.title, c.title] > > Is there a quick way to do it? Or I should use loops (looping through each > element, and generating list) I think a list comprehension might be the most compact way to accomplish what you're after: objcts = [a, b, c] titles = [obj.title for obj in objcts] From dgou at mac.com Thu Sep 10 18:20:50 2009 From: dgou at mac.com (Douglas Philips) Date: Thu, 10 Sep 2009 12:20:50 -0400 Subject: [Tutor] Getting list of attributes from list of objects In-Reply-To: References: Message-ID: <83C21834-B11C-449E-B513-54D5FE6E549F@mac.com> On or about 2009 Sep 10, at 11:36 AM, Serdar Tumgoren indited: > I think a list comprehension might be the most compact way to > accomplish what you're after: > > objcts = [a, b, c] > > titles = [obj.title for obj in objcts] That probably is the best form. For the sake of showing other options: from operator import attrgetter #... titles = map(attrgetter("title"), objcts) # I love placeholder for this kind of thing. from placeholder import __ #... titles = map(__.title, objcts) --Doug P.S. placeholder can be found at: http://pypi.python.org/pypi/placeholder P.P.S. I have a version that composes, so you can say: map((__ + 3) * 2, my_numbers) -- http://bitbucket.org/dgou/placeholder2/ From digitalxero at gmail.com Thu Sep 10 18:45:01 2009 From: digitalxero at gmail.com (Dj Gilcrease) Date: Thu, 10 Sep 2009 10:45:01 -0600 Subject: [Tutor] Vista UAC Message-ID: I have a python app that requires elevated privileges on Vista when installed in "Program Files" since it has an auto updater. I was wondering if there was a way with a standard install of python 2.6 that I can check if I have the correct privileges and if not relaunch the app required privileges. Dj Gilcrease OpenRPG Developer ~~http://www.openrpg.com From alan.gauld at btinternet.com Thu Sep 10 20:13:51 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 10 Sep 2009 19:13:51 +0100 Subject: [Tutor] (no subject) References: <6AA0976CCDDB4A5C8C0C97B6A6D364E0@kisc.edu.np> <4AA8CA86.2030402@pensiun.com> Message-ID: "Dirk Wangsadirdja" wrote >I tested it and it works. But I dont understand why it works. Can > someone please explain it further? Thanks. ~n means the bitwise complement (or inverse) of n. This simply means reversing every bit of n so that 1-> 0 and 0->1 This trick relies on the fact that negative numbers are stored on computers using a thing called twos-complement (or ones-complement sometimes) . This ensures tjhe leftmost bit is always 1 which the PC uses to indicate a negative number. Thus to represent -1 we take the bitwise inverse of 1 and add 1 1 = 0001 -> 1110 + 1 -> 1111 To get back we subtract 1 and then take the bitwise complement 1111-1 -> 1110 -> 0001 But with this trick we omit the initial add by 1 stage so range(n) yields 0...n But the inverse of 0000 is 1111 which is interpreted as -1 by Python as above, so 0 maps to -1 in decimal! and thus 1 (0001) becomes 1110 to which python does: 1110 subtracting 1 becomes 1101, and inverting gives 0010 = -2! and so on. So using ~ maps 0,1,2... to -1,-2,-3... Very, very sneaky and the first time I've sen it done! (because its so opaque I wouldn't actually recommend it, most programmers would struggle to figure out what was going on and probably think ~ was a typo for - I suspect) See wikipedia for more on twos-complement, and the related trick , which is also used sometimes, of ones-complement. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From dperlman at wisc.edu Thu Sep 10 22:13:23 2009 From: dperlman at wisc.edu (David Perlman) Date: Thu, 10 Sep 2009 15:13:23 -0500 Subject: [Tutor] Poorly understood error involving class inheritance Message-ID: <5D4B5145-7433-45C6-94D2-73FD649482AD@wisc.edu> I'm not sure why I'm getting an error at the end here: >>> class dummy: ... def __init__(self,dur=0): ... self.dur=dur ... >>> z=dummy(3) >>> z.dur 3 >>> z=dummy(dur=3) >>> z.dur 3 That worked fine, of course. >>> class dummy2(str): ... def __init__(self,dur=0): ... self.dur=dur ... >>> z=dummy2(3) >>> z.dur 3 So far so good. But: >>> z=dummy2(dur=3) Traceback (most recent call last): File "", line 1, in TypeError: 'dur' is an invalid keyword argument for this function >>> Why doesn't that last bit work? I'm not sure where to begin to look this up. Thanks! -- -dave---------------------------------------------------------------- "Pseudo-colored pictures of a person's brain lighting up are undoubtedly more persuasive than a pattern of squiggles produced by a polygraph. That could be a big problem if the goal is to get to the truth." -Dr. Steven Hyman, Harvard From zstumgoren at gmail.com Thu Sep 10 22:42:04 2009 From: zstumgoren at gmail.com (Serdar Tumgoren) Date: Thu, 10 Sep 2009 16:42:04 -0400 Subject: [Tutor] Poorly understood error involving class inheritance In-Reply-To: <5D4B5145-7433-45C6-94D2-73FD649482AD@wisc.edu> References: <5D4B5145-7433-45C6-94D2-73FD649482AD@wisc.edu> Message-ID: >>>> class dummy2(str): > ... ? ? def __init__(self,dur=0): > ... ? ? ? ? ? ? self.dur=dur > ... >>>> z=dummy2(3) >>>> z.dur > 3 > > So far so good. ?But: > >>>> z=dummy2(dur=3) > Traceback (most recent call last): > ?File "", line 1, in > TypeError: 'dur' is an invalid keyword argument for this function >>>> I think you're problem may stem from the fact that you subclassed the string type and then tried to pass in an integer. >>> class Dummy2(int): ... def __init__(self, dur=0): ... self.dur = dur ... >>> z = Dummy2(3) >>> z.dur 3 When you sub "int" for "str", it seems to work. Is there a reason you're not just subclassing "object"? I believe doing so would give you the best of both worlds. From dperlman at wisc.edu Thu Sep 10 22:51:02 2009 From: dperlman at wisc.edu (David Perlman) Date: Thu, 10 Sep 2009 15:51:02 -0500 Subject: [Tutor] Poorly understood error involving class inheritance In-Reply-To: References: <5D4B5145-7433-45C6-94D2-73FD649482AD@wisc.edu> Message-ID: <81121468-12AE-4284-A587-229532722698@wisc.edu> Well, here's what I am really doing: class oneStim(str): def __init__(self, time, mods=[], dur=None, format='%1.2f'): self.time=time self.mods=mods self.dur=dur self.format=format def __cmp__(self,other): return cmp(self.time,other.time) def __repr__(self): timestr=self.format % self.time if self.mods == []: modstr='' else: modstr = '*' + ','.join(self.format % i for i in self.mods) if self.dur == None: durstr = '' else: durstr = ':' + (self.format % self.dur) return timestr + modstr + durstr def __len__(self): return len(self.__repr__()) The purpose of this is to make an object that holds a collection of numbers and represents them as a specifically formatted string. I want to be able to do something like: >>> z=oneStim(22.5678) >>> z.dur=10 >>> z 22.57:10.00 >>> len(z) 11 >>> z.rjust(20) ' 22.5678' Note that that doesn't work either. It works fine like this, though: >>> z 22.57:10.00 >>> str(z).rjust(20) ' 22.57:10.00' I can work with that just fine, but I am curious to understand what's going on under the hood that makes it fail when subclassed from str... On Sep 10, 2009, at 3:42 PM, Serdar Tumgoren wrote: >>>>> class dummy2(str): >> ... def __init__(self,dur=0): >> ... self.dur=dur >> ... >>>>> z=dummy2(3) >>>>> z.dur >> 3 >> >> So far so good. But: >> >>>>> z=dummy2(dur=3) >> Traceback (most recent call last): >> File "", line 1, in >> TypeError: 'dur' is an invalid keyword argument for this function >>>>> > > I think you're problem may stem from the fact that you subclassed the > string type and then tried to pass in an integer. > >>>> class Dummy2(int): > ... def __init__(self, dur=0): > ... self.dur = dur > ... >>>> z = Dummy2(3) >>>> z.dur > 3 > > When you sub "int" for "str", it seems to work. Is there a reason > you're not just subclassing "object"? I believe doing so would give > you the best of both worlds. -- -dave---------------------------------------------------------------- "Pseudo-colored pictures of a person's brain lighting up are undoubtedly more persuasive than a pattern of squiggles produced by a polygraph. That could be a big problem if the goal is to get to the truth." -Dr. Steven Hyman, Harvard From zstumgoren at gmail.com Thu Sep 10 22:51:18 2009 From: zstumgoren at gmail.com (Serdar Tumgoren) Date: Thu, 10 Sep 2009 16:51:18 -0400 Subject: [Tutor] Poorly understood error involving class inheritance In-Reply-To: References: <5D4B5145-7433-45C6-94D2-73FD649482AD@wisc.edu> Message-ID: > When you sub "int" for "str", it seems to work. Is there a reason > you're not just subclassing "object"? I believe doing so would give > you the best of both worlds. > Of course, I should qualify the above -- the "str" subclass inherits very different methods than "int" or "object". http://docs.python.org/library/stdtypes.html#sequence-types-str-unicode-list-tuple-buffer-xrange If retaining the string methods is important for your use case, you might require a more nuanced solution... From christopher.henk at allisontransmission.com Thu Sep 10 22:59:36 2009 From: christopher.henk at allisontransmission.com (christopher.henk at allisontransmission.com) Date: Thu, 10 Sep 2009 16:59:36 -0400 Subject: [Tutor] Poorly understood error involving class inheritance In-Reply-To: <5D4B5145-7433-45C6-94D2-73FD649482AD@wisc.edu> Message-ID: tutor-bounces+christopher.henk=allisontransmission.com at python.org wrote on 09/10/2009 04:13:23 PM: > I'm not sure why I'm getting an error at the end here: > > >>> class dummy: > ... def __init__(self,dur=0): > ... self.dur=dur > ... > >>> z=dummy(3) > >>> z.dur > 3 > >>> z=dummy(dur=3) > >>> z.dur > 3 > > That worked fine, of course. > > >>> class dummy2(str): > ... def __init__(self,dur=0): > ... self.dur=dur > ... > >>> z=dummy2(3) > >>> z.dur > 3 > > So far so good. But: > > >>> z=dummy2(dur=3) > Traceback (most recent call last): > File "", line 1, in > TypeError: 'dur' is an invalid keyword argument for this function > >>> > > Why doesn't that last bit work? I'm not sure where to begin to look > this up. > Thanks! > > -- > -dave---------------------------------------------------------------- > "Pseudo-colored pictures of a person's brain lighting up are > undoubtedly more persuasive than a pattern of squiggles produced by a > polygraph. That could be a big problem if the goal is to get to the > truth." -Dr. Steven Hyman, Harvard > I believe it has to do with the fact that str is immutable and thus should use __new__ instead of __init__. >>> class bob(str): ... def __new__(self, fred=3): ... self.fred=fred ... return self ... >>> george=bob() >>> george.fred 3 >>> george=bob(fred=7) >>> george.fred 7 Don't have a chance to read it now but maybe pep 253 explains it. http://www.python.org/dev/peps/pep-0253/ Chris -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Thu Sep 10 23:17:05 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 10 Sep 2009 17:17:05 -0400 Subject: [Tutor] Poorly understood error involving class inheritance In-Reply-To: <81121468-12AE-4284-A587-229532722698@wisc.edu> References: <5D4B5145-7433-45C6-94D2-73FD649482AD@wisc.edu> <81121468-12AE-4284-A587-229532722698@wisc.edu> Message-ID: <1c2a2c590909101417sd57bea5r23b6002894ffce52@mail.gmail.com> On Thu, Sep 10, 2009 at 4:51 PM, David Perlman wrote: > Well, here's what I am really doing: > > class oneStim(str): > ? ?def __init__(self, time, mods=[], dur=None, format='%1.2f'): > ? ? ? ?self.time=time > ? ? ? ?self.mods=mods > ? ? ? ?self.dur=dur > ? ? ? ?self.format=format This is a bit odd because you don't call str.__init__() so you never initialize the "str" part of a oneStim. Actually when you subclass immutable, built-in classes you have to override __new__() rather than __init__(). Here is an example: http://mail.python.org/pipermail/python-list/2004-June/265368.html > The purpose of this is to make an object that holds a collection of numbers > and represents them as a specifically formatted string. ?I want to be able > to do something like: > >>>> z=oneStim(22.5678) >>>> z.dur=10 >>>> z > 22.57:10.00 >>>> len(z) > 11 >>>> z.rjust(20) > ' ? ? ? ? ? ? 22.5678' > > Note that that doesn't work either. You are expecting that str.rjust() accesses the string using __repr__() but it doesn't, it directly accesses the internal data. >?It works fine like this, though: >>>> z > 22.57:10.00 >>>> str(z).rjust(20) > ' ? ? ? ? 22.57:10.00' > > I can work with that just fine, but I am curious to understand what's going > on under the hood that makes it fail when subclassed from str... I would skip the cleverness of trying to subclass string. You can use str(z).rjust(20) as above, or use string formatting: '%20s' % z Kent From dperlman at wisc.edu Fri Sep 11 00:48:49 2009 From: dperlman at wisc.edu (David Perlman) Date: Thu, 10 Sep 2009 17:48:49 -0500 Subject: [Tutor] Poorly understood error involving class inheritance In-Reply-To: <1c2a2c590909101417sd57bea5r23b6002894ffce52@mail.gmail.com> References: <5D4B5145-7433-45C6-94D2-73FD649482AD@wisc.edu> <81121468-12AE-4284-A587-229532722698@wisc.edu> <1c2a2c590909101417sd57bea5r23b6002894ffce52@mail.gmail.com> Message-ID: <65DFA0CC-43A7-41E3-9B3F-E343FC952064@wisc.edu> Yeah, this seems to be the best answer in this situation. :) On Sep 10, 2009, at 4:17 PM, Kent Johnson wrote: > I would skip the cleverness of trying to subclass string. You can use > str(z).rjust(20) as above, or use string formatting: > '%20s' % z -- -dave---------------------------------------------------------------- Unfortunately, as soon as they graduate, our people return to a world driven by a tool that is the antithesis of thinking: PowerPoint. Make no mistake, PowerPoint is not a neutral tool ? it is actively hostile to thoughtful decision-making. It has fundamentally changed our culture by altering the expectations of who makes decisions, what decisions they make and how they make them. -Colonel T. X. Hammes, USMC From m.wanstall at gmail.com Fri Sep 11 01:39:40 2009 From: m.wanstall at gmail.com (Mal Wanstall) Date: Fri, 11 Sep 2009 09:39:40 +1000 Subject: [Tutor] web2py vs django In-Reply-To: References: <5cb309e70909090031h733507b7y6a25832b04119938@mail.gmail.com> <5487b3060909090036y564bd2g18704aae305b9475@mail.gmail.com> <1c2a2c590909091008h6b4022c9g272e6cc105d61b8b@mail.gmail.com> Message-ID: <4fb9d14e0909101639u7b63f71el78357916018b939a@mail.gmail.com> On Thu, Sep 10, 2009 at 5:29 AM, Alan Gauld wrote: > > "Kent Johnson" wrote >> >> That thread is about web.py, not web2py, they are different frameworks. > > I confess I too had missed that subtlety! > Like editors and standards... > The wonderful thing about Web Frameworks in Python - there are so many to > choose from! > > But it is confusing, my advice is just pick one and stick with it! > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > That is the advice that certainly worked for me. For a long time I was switching between web frameworks, as each have their nuances which make them seem better than the others, and what you end up with is a bit of knowledge on each...but not enough on any single one to get the full power out of it. There is always risk involved with backing a single horse, but I found it massively beneficial when I did. In the end I settled with Pylons because I like it's lack of glue between components but I'm positive I could have done all of my projects in any of the frameworks and each would have had their challenges and successes. Kudos to Massimo though; web2py is a spiffy idea and it's implemented well. From alan.gauld at btinternet.com Fri Sep 11 01:43:29 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 11 Sep 2009 00:43:29 +0100 Subject: [Tutor] Vista UAC References: Message-ID: "Dj Gilcrease" wrote > wondering if there was a way with a standard install of python 2.6 > that I can check if I have the correct privileges and if not relaunch > the app required privileges. I haven't checked what the standard os functions do on Windows but you can always use ctypes to access the Windows API directly. Not trivial but possible. Alan G. From jeff at dcsoftware.com Fri Sep 11 02:13:37 2009 From: jeff at dcsoftware.com (Jeff Johnson) Date: Thu, 10 Sep 2009 17:13:37 -0700 Subject: [Tutor] Vista UAC In-Reply-To: References: Message-ID: <4AA99631.5030906@dcsoftware.com> Dj Gilcrease wrote: > I have a python app that requires elevated privileges on Vista when > installed in "Program Files" since it has an auto updater. I was > wondering if there was a way with a standard install of python 2.6 > that I can check if I have the correct privileges and if not relaunch > the app required privileges. > > > Dj Gilcrease > OpenRPG Developer > ~~http://www.openrpg.com I have an application that uses something that auto updates but it may not be the same process as yours. I have a "stub" executable that checks a network location for a different copy of the "real" executable. If one exists, it copies the exe to the application folder and executes it. My solution for Vista - which works very well - is to put my application in a folder C:\users\public\applications\myapplication. This way there is no need for raised privileges. -- Jeff Jeff Johnson jeff at dcsoftware.com Phoenix Python User Group - sunpiggies at googlegroups.com From alex.feddor at gmail.com Fri Sep 11 12:31:26 2009 From: alex.feddor at gmail.com (Alex Feddor) Date: Fri, 11 Sep 2009 12:31:26 +0200 Subject: [Tutor] IBPY: How to use it - interactivebrokers API Message-ID: <5bf184e30909110331p61f1a78o64656259d9371f46@mail.gmail.com> Hi Year ago I have bulid simple logic with Python. Is out there anoyone who can explain me how IBPY interface can be used. I am looking for simple code sample that I need to insert into my Python code to be able to Buy and Sell stocks on Interactivebrokers demo account. Software was donwloaded from: http://code.google.com/p/ibpy/wiki/GettingStarted It looks very cools however I do not undestand have can I integrate Trade function witin my python code. I went through demo directory - api_coverafe file. I am looking for buy and sell stock order function. Appreciated .py example - what includes has to be used , how trade function is look like for example BUY Ticker: XSNX, OnLimit 0.30, Valid 90 days.. Plus is it IbPy-0.7.6-9.51.zip last software version? In case your software is not updated anymore please advise what else can be used instead! Thanks for your advise! Sorry for probably stupied question - have in mind that I am not proffesional programer .. Cheers, Alex -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Fri Sep 11 14:31:39 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 11 Sep 2009 08:31:39 -0400 Subject: [Tutor] IBPY: How to use it - interactivebrokers API In-Reply-To: <5bf184e30909110331p61f1a78o64656259d9371f46@mail.gmail.com> References: <5bf184e30909110331p61f1a78o64656259d9371f46@mail.gmail.com> Message-ID: <1c2a2c590909110531h5e2a0903l11aa3c0090b0b812@mail.gmail.com> On Fri, Sep 11, 2009 at 6:31 AM, Alex Feddor wrote: > Hi > > Year ago I have bulid simple logic with Python. Is out there anoyone who can > explain me how IBPY interface can be used. I am looking for simple code > sample that I need to insert into my Python code to be able to Buy and Sell > stocks on Interactivebrokers demo account. > > Software was donwloaded from: > http://code.google.com/p/ibpy/wiki/GettingStarted > > It looks very cools however I do not?undestand?have can I integrate?Trade > function witin my python code. I think you will have to refer to the TWS API docs to figure this out. ibpy has the same interface as the Java API. http://www.interactivebrokers.com/php/apiUsersGuide/apiguide.htm There is a mailing list that seems to be active, you will probably do better asking for help there: http://groups.google.com/group/ibpy-discuss?pli=1 > Plus is it IbPy-0.7.6-9.51.zip ?last software version? Seems to be. > In case your software is not updated anymore please advise what else can be > used instead! It's not our software. Ask this on the ibpy list. Kent From lie.1296 at gmail.com Fri Sep 11 19:01:28 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Sat, 12 Sep 2009 03:01:28 +1000 Subject: [Tutor] Vista UAC In-Reply-To: References: Message-ID: Dj Gilcrease wrote: > I have a python app that requires elevated privileges on Vista when > installed in "Program Files" since it has an auto updater. I was > wondering if there was a way with a standard install of python 2.6 > that I can check if I have the correct privileges and if not relaunch > the app required privileges. I never worked with UAC, but I think you can try writing to the Program Files/YourApp and if it fails and raises IOError (check the exception arguments as well) then you don't have the privilege. At least that what I *think* how Windows Explorer file copying routine works (based on day-to-day observation, not some special research, I'd love to be proven wrong). You can also try using runas, though I never figured out how to make it work to obtain administrator privilege (sudo is much easier to work with): C:\Users\Lie Ryan>runas /user:"MyUserName" "C:\Python26\python.exe \"K:\path\to\my\script.py\"" That will run the script as user "MyUserName" though only with the standard privilege. Alternatively, you may be able to dissect this script and include parts of it with your app: http://bink.nu/news/script-elevation-powertoys-for-windows-vista.aspx From lie.1296 at gmail.com Fri Sep 11 19:05:28 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Sat, 12 Sep 2009 03:05:28 +1000 Subject: [Tutor] Vista UAC In-Reply-To: <4AA99631.5030906@dcsoftware.com> References: <4AA99631.5030906@dcsoftware.com> Message-ID: Jeff Johnson wrote: > Dj Gilcrease wrote: >> I have a python app that requires elevated privileges on Vista when >> installed in "Program Files" since it has an auto updater. I was >> wondering if there was a way with a standard install of python 2.6 >> that I can check if I have the correct privileges and if not relaunch >> the app required privileges. >> >> >> Dj Gilcrease >> OpenRPG Developer >> ~~http://www.openrpg.com > I have an application that uses something that auto updates but it may > not be the same process as yours. I have a "stub" executable that > checks a network location for a different copy of the "real" executable. > If one exists, it copies the exe to the application folder and executes > it. My solution for Vista - which works very well - is to put my > application in a folder C:\users\public\applications\myapplication. > > This way there is no need for raised privileges. > The only problem with installing in public folder that is it allows non-privileged (read: any) user to modify the program; which might be unwanted for some apps. From jeff at dcsoftware.com Fri Sep 11 19:43:55 2009 From: jeff at dcsoftware.com (Jeff Johnson) Date: Fri, 11 Sep 2009 10:43:55 -0700 Subject: [Tutor] Vista UAC In-Reply-To: References: <4AA99631.5030906@dcsoftware.com> Message-ID: <4AAA8C5B.7030502@dcsoftware.com> Lie Ryan wrote: > Jeff Johnson wrote: >> I have an application that uses something that auto updates but it may >> not be the same process as yours. I have a "stub" executable that >> checks a network location for a different copy of the "real" >> executable. If one exists, it copies the exe to the application >> folder and executes it. My solution for Vista - which works very well >> - is to put my application in a folder >> C:\users\public\applications\myapplication. >> >> This way there is no need for raised privileges. >> > > The only problem with installing in public folder that is it allows > non-privileged (read: any) user to modify the program; which might be > unwanted for some apps. My programs are exe's and not editable. -- Jeff Jeff Johnson jeff at dcsoftware.com Phoenix Python User Group - sunpiggies at googlegroups.com From lie.1296 at gmail.com Fri Sep 11 22:19:01 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Sat, 12 Sep 2009 06:19:01 +1000 Subject: [Tutor] Vista UAC In-Reply-To: <4AAA8C5B.7030502@dcsoftware.com> References: <4AA99631.5030906@dcsoftware.com> <4AAA8C5B.7030502@dcsoftware.com> Message-ID: Jeff Johnson wrote: > Lie Ryan wrote: >> Jeff Johnson wrote: >>> I have an application that uses something that auto updates but it >>> may not be the same process as yours. I have a "stub" executable >>> that checks a network location for a different copy of the "real" >>> executable. If one exists, it copies the exe to the application >>> folder and executes it. My solution for Vista - which works very >>> well - is to put my application in a folder >>> C:\users\public\applications\myapplication. >>> >>> This way there is no need for raised privileges. >>> >> >> The only problem with installing in public folder that is it allows >> non-privileged (read: any) user to modify the program; which might be >> unwanted for some apps. > > My programs are exe's and not editable. > Even if it's an .exe, malicious users could overwrite your program with a malicious executable. In some environment this could be considered a security issue. From ranjand2005 at gmail.com Sat Sep 12 10:35:13 2009 From: ranjand2005 at gmail.com (ranjan das) Date: Sat, 12 Sep 2009 14:05:13 +0530 Subject: [Tutor] How to print the next line in python Message-ID: <8e8e6fc00909120135x85eb754n7ddaace1cc5b3a6d@mail.gmail.com> Hi, I am new to python and i wrote this piece of code which is ofcourse not serving my purpose: Aim of the code: To read a file and look for lines which contain the string 'CL'. When found, print the entry of the next line (positioned directly below the string 'CL') ....continue to do this till the end of the file (since there are more than one occurrences of 'CL' in the file) My piece of code (which just prints lines which contain the string 'CL') f=open('somefile.txt','r') for line in f.readlines(): if 'CL' in line: print line please suggest how do i print the entry right below the string 'CL' -- The inherent vice of capitalism is the unequal sharing of blessings; the inherent virtue of socialism is the equal sharing of miseries. ~ Winston Churchill -------------- next part -------------- An HTML attachment was scrubbed... URL: From andreengels at gmail.com Sat Sep 12 10:47:29 2009 From: andreengels at gmail.com (Andre Engels) Date: Sat, 12 Sep 2009 10:47:29 +0200 Subject: [Tutor] How to print the next line in python In-Reply-To: <8e8e6fc00909120135x85eb754n7ddaace1cc5b3a6d@mail.gmail.com> References: <8e8e6fc00909120135x85eb754n7ddaace1cc5b3a6d@mail.gmail.com> Message-ID: <6faf39c90909120147t41165f80td22a3140eb2bc34@mail.gmail.com> On Sat, Sep 12, 2009 at 10:35 AM, ranjan das wrote: > Hi, > > I am new to python and i wrote this piece of code which is ofcourse not > serving my purpose: > > Aim of the code: > > To read a file and look for lines which contain the string 'CL'. When found, > print the entry of the next line (positioned directly below the string 'CL') > ....continue to do this till the end of the file (since there are more than > one occurrences of 'CL' in the file) > > My piece of code (which just prints lines which contain the string 'CL') > > f=open('somefile.txt','r') > > for line in f.readlines(): > > ???? if 'CL' in line: > ????????????? print line > > > please suggest how do i print the entry right below the string 'CL' I would this using a boolean variable to denote whether the line should be printed: printline = false for line in f.readlines(): if printline: print line printline = 'CL' in line (I assume the last line does not contain 'CL', because otherwise we have a problem with the problem definition) -- Andr? Engels, andreengels at gmail.com From ranjand2005 at gmail.com Sat Sep 12 11:34:39 2009 From: ranjand2005 at gmail.com (ranjan das) Date: Sat, 12 Sep 2009 15:04:39 +0530 Subject: [Tutor] How to print the next line in python In-Reply-To: <6faf39c90909120147t41165f80td22a3140eb2bc34@mail.gmail.com> References: <8e8e6fc00909120135x85eb754n7ddaace1cc5b3a6d@mail.gmail.com> <6faf39c90909120147t41165f80td22a3140eb2bc34@mail.gmail.com> Message-ID: <8e8e6fc00909120234y56bb6871r685c12f694779cbb@mail.gmail.com> Thanks a lot Andre...it is working On Sat, Sep 12, 2009 at 2:17 PM, Andre Engels wrote: > On Sat, Sep 12, 2009 at 10:35 AM, ranjan das > wrote: > > Hi, > > > > I am new to python and i wrote this piece of code which is ofcourse not > > serving my purpose: > > > > Aim of the code: > > > > To read a file and look for lines which contain the string 'CL'. When > found, > > print the entry of the next line (positioned directly below the string > 'CL') > > ....continue to do this till the end of the file (since there are more > than > > one occurrences of 'CL' in the file) > > > > My piece of code (which just prints lines which contain the string 'CL') > > > > f=open('somefile.txt','r') > > > > for line in f.readlines(): > > > > if 'CL' in line: > > print line > > > > > > please suggest how do i print the entry right below the string 'CL' > > I would this using a boolean variable to denote whether the line > should be printed: > > printline = false > for line in f.readlines(): > if printline: > print line > printline = 'CL' in line > > (I assume the last line does not contain 'CL', because otherwise we > have a problem with the problem definition) > > -- > Andr? Engels, andreengels at gmail.com > -- The inherent vice of capitalism is the unequal sharing of blessings; the inherent virtue of socialism is the equal sharing of miseries. ~ Winston Churchill -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at ieee.org Sat Sep 12 11:45:03 2009 From: davea at ieee.org (Dave Angel) Date: Sat, 12 Sep 2009 05:45:03 -0400 Subject: [Tutor] How to print the next line in python In-Reply-To: <8e8e6fc00909120135x85eb754n7ddaace1cc5b3a6d@mail.gmail.com> References: <8e8e6fc00909120135x85eb754n7ddaace1cc5b3a6d@mail.gmail.com> Message-ID: <4AAB6D9F.8050606@ieee.org> ranjan das wrote: > Hi, > > I am new to python and i wrote this piece of code which is ofcourse not > serving my purpose: > > Aim of the code: > > To read a file and look for lines which contain the string 'CL'. When found, > print the entry of the next line (positioned directly below the string 'CL') > ....continue to do this till the end of the file (since there are more than > one occurrences of 'CL' in the file) > > My piece of code (which just prints lines which contain the string 'CL') > > f=open('somefile.txt','r') > > for line in f.readlines(): > > if 'CL' in line: > print line > > > please suggest how do i print the entry right below the string 'CL' > > > Easiest way is probably to introduce another local, "previous_line" containing the immediately previous line each time through the loop. Then if "CL" is in the previous_line, you print current_line. (untested) infile=open('somefile.txt','r') previous_line = "" for current_line in infile: if 'CL' in previous_line: print current_line previous_line = current_line infile.close() Notice also that your call to readlines() was unnecessary. You can iterate through a text file directly with a for loop. That won't matter for a small file, but if the file is huge, this saves memory, plus it could save a pause a the beginning while the whole file is read by readlines(). I also added a close(), for obvious reasons. DaveA From roadierich at googlemail.com Sat Sep 12 14:50:25 2009 From: roadierich at googlemail.com (Rich Lovely) Date: Sat, 12 Sep 2009 13:50:25 +0100 Subject: [Tutor] How to print the next line in python In-Reply-To: <4AAB6D9F.8050606@ieee.org> References: <8e8e6fc00909120135x85eb754n7ddaace1cc5b3a6d@mail.gmail.com> <4AAB6D9F.8050606@ieee.org> Message-ID: 2009/9/12 Dave Angel : > ranjan das wrote: >> >> Hi, >> >> I am new to python and i wrote this piece of code which is ofcourse not >> serving my purpose: >> >> Aim of the code: >> >> To read a file and look for lines which contain the string 'CL'. When >> found, >> print the entry of the next line (positioned directly below the string >> 'CL') >> ....continue to do this till the end of the file (since there are more >> than >> one occurrences of 'CL' in the file) >> >> My piece of code (which just prints lines which contain the string 'CL') >> >> f=open('somefile.txt','r') >> >> for line in f.readlines(): >> >> ? ? if 'CL' in line: >> ? ? ? ? ? ? ?print line >> >> >> please suggest how do i print the entry right below the string 'CL' >> >> >> > > Easiest way is probably to introduce another local, "previous_line" > containing the immediately previous line each time through the loop. ?Then > if "CL" is in the previous_line, you print current_line. > > > (untested) > > infile=open('somefile.txt','r') > > previous_line = "" > > for current_line in infile: > ? if 'CL' in previous_line: > ? ? ? print current_line > > ? ? ? ? previous_line = current_line > infile.close() > > Notice also that your call to readlines() was unnecessary. ?You can iterate > through a text file directly with a for loop. ?That won't matter for a small > file, but if the file is huge, this saves memory, plus it could save a pause > a the beginning while the whole file is read by readlines(). ?I also added a > close(), for obvious reasons. > > DaveA > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > If we want to be really modern: #Only works on python 2.5 or later. On 2.6 (or higher...), the following line is not needed. from __future__ import with_statement previous_line = "" with open('somefile.txt','r') as infile: for current_line in infile: if 'CL' in previous_line: print current_line previous_line = current_line -- Rich "Roadie Rich" Lovely There are 10 types of people in the world: those who know binary, those who do not, and those who are off by one. From optomatic at rogers.com Sat Sep 12 14:55:59 2009 From: optomatic at rogers.com (Patrick) Date: Sat, 12 Sep 2009 08:55:59 -0400 Subject: [Tutor] include remote module Message-ID: <4AAB9A5F.7040905@rogers.com> Strange question..... Is it possible to include a module that is on another computer? I have been day-dreaming about a project that would allow web code to drive a desktop App. Thanks in advance-Patrick From optomatic at rogers.com Sat Sep 12 16:19:50 2009 From: optomatic at rogers.com (Patrick) Date: Sat, 12 Sep 2009 10:19:50 -0400 Subject: [Tutor] include remote module In-Reply-To: <333efb450909120614h59650f42u1bafe3187178b8cf@mail.gmail.com> References: <4AAB9A5F.7040905@rogers.com> <333efb450909120614h59650f42u1bafe3187178b8cf@mail.gmail.com> Message-ID: <4AABAE06.8000904@rogers.com> Hi Wayne Thanks for your help. I was thinking of the latter but now that I think of it, once you import a module it won't help to modify that module on the fly later anyways, right? I would need to re-import it. Sounds like reading it via http would be simpler. Thanks again-Patrick Wayne wrote: > On Sat, Sep 12, 2009 at 7:55 AM, Patrick > wrote: > > Strange question..... > > Is it possible to include a module that is on another computer? > > I have been day-dreaming about a project that would allow web code to > drive a desktop App. > > > I know of one way, using sshfs, which allows you to mount an ssh > location as a directory on your computer. Then it would effectively be > a local filesystem. I don't know if there's something like that on > Windows. > > Of course, what do you mean when you say "web code to drive a desktop > app"? Do you mean you want to host some code that others can connect > to that will change? Or do you mean you want people to connect to your > server and it will run an app on your desktop? > > For the former it's not really necessary to include the mod on another > computer. Just use the http libraries and download the file when the > script runs. Then import it. > > HTH, > Wayne From patrick.just4fun at gmail.com Sat Sep 12 16:59:37 2009 From: patrick.just4fun at gmail.com (Patrick Sabin) Date: Sat, 12 Sep 2009 16:59:37 +0200 Subject: [Tutor] include remote module In-Reply-To: <4AABAE06.8000904@rogers.com> References: <4AAB9A5F.7040905@rogers.com> <333efb450909120614h59650f42u1bafe3187178b8cf@mail.gmail.com> <4AABAE06.8000904@rogers.com> Message-ID: <4AABB759.6090706@gmail.com> Maybe something like this helps you to solve your problem: # get code via http, etc. code = """ def blah(): print 'blah' print 'hello' blah() """ compiled_code = compile(code, 'filename', 'exec') exec(compiled_code) This way you could execute some code from a web client, but the client would be able to execute any code, he could even delete your hard drive. - Patrick Patrick schrieb: > Hi Wayne > > Thanks for your help. I was thinking of the latter but now that I think > of it, once you import a module it won't help to modify that module on > the fly later anyways, right? I would need to re-import it. Sounds like > reading it via http would be simpler. > > Thanks again-Patrick > > Wayne wrote: >> On Sat, Sep 12, 2009 at 7:55 AM, Patrick > > wrote: >> >> Strange question..... >> >> Is it possible to include a module that is on another computer? >> >> I have been day-dreaming about a project that would allow web code to >> drive a desktop App. >> >> >> I know of one way, using sshfs, which allows you to mount an ssh >> location as a directory on your computer. Then it would effectively be >> a local filesystem. I don't know if there's something like that on >> Windows. >> >> Of course, what do you mean when you say "web code to drive a desktop >> app"? Do you mean you want to host some code that others can connect >> to that will change? Or do you mean you want people to connect to your >> server and it will run an app on your desktop? >> >> For the former it's not really necessary to include the mod on another >> computer. Just use the http libraries and download the file when the >> script runs. Then import it. >> >> HTH, >> Wayne > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From alan.gauld at btinternet.com Sat Sep 12 18:52:42 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 12 Sep 2009 17:52:42 +0100 Subject: [Tutor] include remote module References: <4AAB9A5F.7040905@rogers.com> Message-ID: "Patrick" wrote > Is it possible to include a module that is on another computer? Possible provided you can specify the patgh in some way that can be added to sys.path. Or you can read and exec. But whatever you do its extremely dangerous unless the remote computer is under your complete control, otherwise you could be executing any old bit of random, possibly maliciouis code! So some basic security checks - a checksum at least or, better still, a digital signature embedded in a comment would be a good idea! HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From roadierich at googlemail.com Sat Sep 12 19:32:02 2009 From: roadierich at googlemail.com (Rich Lovely) Date: Sat, 12 Sep 2009 18:32:02 +0100 Subject: [Tutor] include remote module In-Reply-To: <4AAB9A5F.7040905@rogers.com> References: <4AAB9A5F.7040905@rogers.com> Message-ID: 2009/9/12 Patrick : > Strange question..... > > Is it possible to include a module that is on another computer? > > I have been day-dreaming about a project that would allow web code to > drive a desktop App. > > Thanks in advance-Patrick > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > You might like to look at some of the standard library modules that handle importing. You will find a list of them at http://docs.python.org/library/modules.html -- Rich "Roadie Rich" Lovely There are 10 types of people in the world: those who know binary, those who do not, and those who are off by one. From optomatic at rogers.com Sat Sep 12 19:35:28 2009 From: optomatic at rogers.com (Patrick) Date: Sat, 12 Sep 2009 13:35:28 -0400 Subject: [Tutor] include remote module In-Reply-To: <4AABB759.6090706@gmail.com> References: <4AAB9A5F.7040905@rogers.com> <333efb450909120614h59650f42u1bafe3187178b8cf@mail.gmail.com> <4AABAE06.8000904@rogers.com> <4AABB759.6090706@gmail.com> Message-ID: <4AABDBE0.7000000@rogers.com> Hey Patrick What I great idea. I did not even know about the compile function. Maybe this idea could really work. Imagine if I gave a client a live Linux CD that automatically called this sort of script right after boot up. They could have the absolute most current version of an application from my server launched on their box and if their data from that application was re-uploaded back to the server they would have a desktop application with persistence and assuming the hard drive was not mounted in the process(or it was but they could trust me), they would also have fairly secure environment to work in. It would not be perfect yet but it would be safer then using closed source applications. Thanks again and thanks to Rich, Allan and Wayne too-Pat Patrick Sabin wrote: > Maybe something like this helps you to solve your problem: > > # get code via http, etc. > code = """ > def blah(): > print 'blah' > > print 'hello' > blah() > """ > > compiled_code = compile(code, 'filename', 'exec') > exec(compiled_code) > > This way you could execute some code from a web client, but the client > would be able to execute any code, he could even delete your hard drive. > > - Patrick > > Patrick schrieb: >> Hi Wayne >> >> Thanks for your help. I was thinking of the latter but now that I think >> of it, once you import a module it won't help to modify that module on >> the fly later anyways, right? I would need to re-import it. Sounds like >> reading it via http would be simpler. >> >> Thanks again-Patrick >> >> Wayne wrote: >>> On Sat, Sep 12, 2009 at 7:55 AM, Patrick >> > wrote: >>> >>> Strange question..... >>> >>> Is it possible to include a module that is on another computer? >>> >>> I have been day-dreaming about a project that would allow web code to >>> drive a desktop App. >>> >>> >>> I know of one way, using sshfs, which allows you to mount an ssh >>> location as a directory on your computer. Then it would effectively be >>> a local filesystem. I don't know if there's something like that on >>> Windows. >>> >>> Of course, what do you mean when you say "web code to drive a desktop >>> app"? Do you mean you want to host some code that others can connect >>> to that will change? Or do you mean you want people to connect to your >>> server and it will run an app on your desktop? >>> >>> For the former it's not really necessary to include the mod on another >>> computer. Just use the http libraries and download the file when the >>> script runs. Then import it. >>> >>> HTH, >>> Wayne >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From srilyk at gmail.com Sun Sep 13 04:37:15 2009 From: srilyk at gmail.com (Wayne) Date: Sat, 12 Sep 2009 21:37:15 -0500 Subject: [Tutor] Sorting 2-d data Message-ID: <333efb450909121937p5a66ed8fo5b6a7e65231a7f6a@mail.gmail.com> Hi, I have a set of data that looks something like this: 3, 4, 3, 2, 1 2, 1, 1, 1, 1 4, 2, 2, 1, 2 1, 3, 1, 1, 1 I want to be able to sort it by the first column, keeping the rest of the values in the same position relative to the original: 1, 3, 1, 1, 1 2, 1, 1, 1, 1 3, 4, 3, 2, 1 4, 2, 2, 1, 2 and I'm wondering if there are any included ways to sort data like this. I've currently got a 2d list by columns, but I could easily convert that to rows if it would work better. I'm about to check if sorting a list of lists will work in that fashion. Thanks for any help/advice, Wayne -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn?t. - Primo Levi -------------- next part -------------- An HTML attachment was scrubbed... URL: From lie.1296 at gmail.com Sun Sep 13 06:53:04 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Sun, 13 Sep 2009 14:53:04 +1000 Subject: [Tutor] How to print the next line in python In-Reply-To: <8e8e6fc00909120135x85eb754n7ddaace1cc5b3a6d@mail.gmail.com> References: <8e8e6fc00909120135x85eb754n7ddaace1cc5b3a6d@mail.gmail.com> Message-ID: ranjan das wrote: > Hi, > > I am new to python and i wrote this piece of code which is ofcourse not > serving my purpose: > > Aim of the code: > > To read a file and look for lines which contain the string 'CL'. When > found, print the entry of the next line (positioned directly below the > string 'CL') ....continue to do this till the end of the file (since > there are more than one occurrences of 'CL' in the file) > > My piece of code (which just prints lines which contain the string 'CL') > > f=open('somefile.txt','r') > > for line in f.readlines(): > > if 'CL' in line: > print line > > > please suggest how do i print the entry right below the string 'CL' > > Will "the next line" ever contains "CL"? And if it does, should we print the next, next line. That is, in case of: abcCLdef ghiCLjkl mnopqrst should we print: ghiCLjkl mnopqrst or: ghiCLjkl if the latter is the case, then you can advance the file's cursor: with open('myfile.txt') as f: for line in f: if 'CL' in line: print next(f) From lie.1296 at gmail.com Sun Sep 13 07:17:45 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Sun, 13 Sep 2009 15:17:45 +1000 Subject: [Tutor] Sorting 2-d data In-Reply-To: <333efb450909121937p5a66ed8fo5b6a7e65231a7f6a@mail.gmail.com> References: <333efb450909121937p5a66ed8fo5b6a7e65231a7f6a@mail.gmail.com> Message-ID: Wayne wrote: > Hi, > > I have a set of data that looks something like this: > > 3, 4, 3, 2, 1 > 2, 1, 1, 1, 1 > 4, 2, 2, 1, 2 > 1, 3, 1, 1, 1 > > I want to be able to sort it by the first column, keeping the rest of > the values in the same position relative to the original: > > 1, 3, 1, 1, 1 > 2, 1, 1, 1, 1 > 3, 4, 3, 2, 1 > 4, 2, 2, 1, 2 > > and I'm wondering if there are any included ways to sort data like this. > I've currently got a 2d list by columns, but I could easily convert that > to rows if it would work better. > if you have data like this: mylist = [ [3, 4, 3, 2, 1], [2, 1, 1, 1, 1], [4, 2, 2, 1, 2], [1, 3, 1, 1, 1], ] you can use mylist.sort(key=lambda x: x[0]) sorted(mylist, key=lambda x: x[0]) works as well if you need a new list if your data is like this: mylist = [ [3, 2, 4, 1], [4, 1, 2, 3], [3, 1, 2, 1], [2, 1, 1, 1], [1, 1, 2, 1], ] you can use zip(*mylist) to transform your data to row-first list, sort using the above method, then zip(*mylist) again. Beware that zip(*mylist) returns a list of tuples even if the original data is list of lists. I think there should be an easier (and faster) way, that others can point out. From roadierich at googlemail.com Sun Sep 13 14:27:41 2009 From: roadierich at googlemail.com (Rich Lovely) Date: Sun, 13 Sep 2009 13:27:41 +0100 Subject: [Tutor] Sorting 2-d data In-Reply-To: <333efb450909121937p5a66ed8fo5b6a7e65231a7f6a@mail.gmail.com> References: <333efb450909121937p5a66ed8fo5b6a7e65231a7f6a@mail.gmail.com> Message-ID: 2009/9/13 Lie Ryan : > Wayne wrote: >> >> Hi, >> >> I have a set of data that looks something like this: >> >> 3, 4, 3, 2, 1 >> 2, 1, 1, 1, 1 >> 4, 2, 2, 1, 2 >> 1, 3, 1, 1, 1 >> >> I want to be able to sort it by the first column, keeping the rest of the >> values in the same position relative to the original: >> >> 1, 3, 1, 1, 1 >> 2, 1, 1, 1, 1 >> 3, 4, 3, 2, 1 >> 4, 2, 2, 1, 2 >> >> and I'm wondering if there are any included ways to sort data like this. >> I've currently got a 2d list by columns, but I could easily convert that to >> rows if it would work better. >> > > if you have data like this: > mylist = [ > [3, 4, 3, 2, 1], > [2, 1, 1, 1, 1], > [4, 2, 2, 1, 2], > [1, 3, 1, 1, 1], > ] > > you can use mylist.sort(key=lambda x: x[0]) > > sorted(mylist, key=lambda x: x[0]) works as well if you need a new list > > if your data is like this: > mylist = [ > [3, 2, 4, 1], > [4, 1, 2, 3], > [3, 1, 2, 1], > [2, 1, 1, 1], > [1, 1, 2, 1], > ] > > you can use zip(*mylist) to transform your data to row-first list, sort > using the above method, then zip(*mylist) again. Beware that zip(*mylist) > returns a list of tuples even if the original data is list of lists. I think > there should be an easier (and faster) way, that others can point out. > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > This is another way, but will probably be slower than re-zipping into row-major order. keys = mylist[0] myNewList = [] for L in mylist: decoratedList = zip(keys, L) decoratedList.sort(key=lambda x: x[0]) undecoratedList = map(lambda x: x[1], decoratedList) myNewList.append(undecoratedList) This is known as the decorate-sort-undecorate pattern. It is possible to turn it into a one line comprehension: myNewList = [[decorated[1] for decorated in sorted(zip(mylist[0], L), key=lambda t: t[0])] for L in mylist] I'm not suggesting you do it like this, but it's always useful to learn new patterns. -- Rich "Roadie Rich" Lovely There are 10 types of people in the world: those who know binary, those who do not, and those who are off by one. From srilyk at gmail.com Sun Sep 13 15:18:00 2009 From: srilyk at gmail.com (Wayne) Date: Sun, 13 Sep 2009 08:18:00 -0500 Subject: [Tutor] Sorting 2-d data In-Reply-To: References: <333efb450909121937p5a66ed8fo5b6a7e65231a7f6a@mail.gmail.com> Message-ID: <333efb450909130618g6b72b18md06f036b33888985@mail.gmail.com> On Sun, Sep 13, 2009 at 7:27 AM, Rich Lovely wrote: > 2009/9/13 Lie Ryan : > > Wayne wrote: > >> > > if your data is like this: > > mylist = [ > > [3, 2, 4, 1], > > [4, 1, 2, 3], > > [3, 1, 2, 1], > > [2, 1, 1, 1], > > [1, 1, 2, 1], > > ] > > > > you can use zip(*mylist) to transform your data to row-first list, sort > > using the above method, then zip(*mylist) again. Beware that zip(*mylist) > > returns a list of tuples even if the original data is list of lists. I > think > > there should be an easier (and faster) way, that others can point out. > That zip method is very useful because my original data set is in column format and this is how I was swapping directions previously: def swap_directions(list_): newlist = [] row = [] for x in xrange(len(list_[0])): for y in xrange(len(list_)): row.append(list_[y][x]) newlist.append(row) row = [] return newlist I'm not suggesting you do it like this, but it's always useful to > learn new patterns. > That's certainly true! Thanks for the help, Rich and Lie. I think I can get it now. -Wayne -- > Rich "Roadie Rich" Lovely > > There are 10 types of people in the world: those who know binary, > those who do not, and those who are off by one. > -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn?t. - Primo Levi -------------- next part -------------- An HTML attachment was scrubbed... URL: From admin at gg-lab.net Sun Sep 13 15:59:37 2009 From: admin at gg-lab.net (admin at gg-lab.net) Date: Sun, 13 Sep 2009 15:59:37 +0200 Subject: [Tutor] Still Trying to Understand GAE Message-ID: <48758b600909130659r48eb2771s2568eaae2d12e454@mail.gmail.com> Hi All, i've started earning python sone months ago (on Google App Engine unfortunately). I have some doubts reagrding "import", and have asked a similar question here months ago, but without finding a solution. So: with import i can import modules or single functions. And this is ok. Then: as i have understood from all the books i readm in each package directory i have the __init__.py file that decides what import with it. In other words if my package skel is like: /gg/ /gg/sub1/ /gg/sub1/file.py /gg/sub2/ /gg/sub2/file.py and i use "import gg", nothing is imported. To import sub1 and sub2, i can: - Put in /gg/ a __init__.py file that tells to import them - Use "from gg import sub1" Ok now the $1 Billion question: google app engine has the same schema than my "gg" package, an empty __init__.py file, but if i use "import google" it also imports all subdirectories. And i can't understand wi?hy it does so. Can you help me? Thankyou Giorgio From kent37 at tds.net Sun Sep 13 16:12:02 2009 From: kent37 at tds.net (Kent Johnson) Date: Sun, 13 Sep 2009 10:12:02 -0400 Subject: [Tutor] Sorting 2-d data In-Reply-To: References: <333efb450909121937p5a66ed8fo5b6a7e65231a7f6a@mail.gmail.com> Message-ID: <1c2a2c590909130712p51732528wbac4b03ae830a3b5@mail.gmail.com> On Sun, Sep 13, 2009 at 1:17 AM, Lie Ryan wrote: > if you have data like this: > mylist = [ > ? ?[3, 4, 3, 2, 1], > ? ?[2, 1, 1, 1, 1], > ? ?[4, 2, 2, 1, 2], > ? ?[1, 3, 1, 1, 1], > ] > > you can use mylist.sort(key=lambda x: x[0]) You can omit the key parameter completely in this case, unless you want to preserve the order of lines whose first element are the same. The default comparison of lists is lexicographic, meaning it will compare the first element, if they are the same then compare the second, etc. > if your data is like this: > mylist = [ > ? ?[3, 2, 4, 1], > ? ?[4, 1, 2, 3], > ? ?[3, 1, 2, 1], > ? ?[2, 1, 1, 1], > ? ?[1, 1, 2, 1], > ] > > you can use zip(*mylist) to transform your data to row-first list, sort > using the above method, then zip(*mylist) again. Beware that zip(*mylist) > returns a list of tuples even if the original data is list of lists. I think > there should be an easier (and faster) way, that others can point out. zip() is the best method I know to do this. Kent From dirk at pensiun.com Sun Sep 13 17:25:17 2009 From: dirk at pensiun.com (Dirk Wangsadirdja) Date: Sun, 13 Sep 2009 17:25:17 +0200 Subject: [Tutor] Sorting 2-d data In-Reply-To: References: <333efb450909121937p5a66ed8fo5b6a7e65231a7f6a@mail.gmail.com> Message-ID: <4AAD0EDD.3010303@pensiun.com> Lie Ryan wrote: > > if you have data like this: > mylist = [ > [3, 4, 3, 2, 1], > [2, 1, 1, 1, 1], > [4, 2, 2, 1, 2], > [1, 3, 1, 1, 1], > ] > > you can use mylist.sort(key=lambda x: x[0]) > > sorted(mylist, key=lambda x: x[0]) works as well if you need a new list > I have a further question. If I want to sort the list not based on first element, but the second, third and so on, then using the lambda works nicely. But for sorting the list with the first element as key, I tried it using just mylist.sort() without the lambda, and its working also. Then why use the lambda? Sorry, I'm using python3. so maybe it won't work on python2 with just mylist.sort()? From wescpy at gmail.com Sun Sep 13 20:49:41 2009 From: wescpy at gmail.com (wesley chun) Date: Sun, 13 Sep 2009 11:49:41 -0700 Subject: [Tutor] Still Trying to Understand GAE In-Reply-To: <48758b600909130659r48eb2771s2568eaae2d12e454@mail.gmail.com> References: <48758b600909130659r48eb2771s2568eaae2d12e454@mail.gmail.com> Message-ID: <78b3a9580909131149q5238f444h2c17da0851223bb8@mail.gmail.com> hi Giorgio, welcome to Python (whether directly or from GAE!) :-) my comments below. > with import i can import modules or single functions. And this is ok. not quite true. regardless of whether you use import or from-import, you're *always* importing (and loading) modules or packages in their entirety. now, whether you have *access* to "entire" modules/packages or individual attributes (functions, classes, or standard data), is another matter -- usually this is a result of using from-import. also, the difference between importing and loading is that loading only happens the first time you import a module/package. (if you do it more than once, e.g., module A imports B and C and module B also imports C, the import of C happens twice but the loading happens only once. > if i use "import > google" it also imports all subdirectories. And i can't understand > wi?hy it does so. it imports all sub*packages*. don't think directories because the import mechanism doesn't work this way. this is likely because there are __init__.py files in those subdirectories. another possibility is that there are non-empty __init__.py files that do the imports of things that you're not expecting. hope this helps! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 "Python Fundamentals", Prentice Hall, (c)2009 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From patrick.just4fun at gmail.com Sun Sep 13 21:19:24 2009 From: patrick.just4fun at gmail.com (Patrick Sabin) Date: Sun, 13 Sep 2009 21:19:24 +0200 Subject: [Tutor] Sorting 2-d data In-Reply-To: <4AAD0EDD.3010303@pensiun.com> References: <333efb450909121937p5a66ed8fo5b6a7e65231a7f6a@mail.gmail.com> <4AAD0EDD.3010303@pensiun.com> Message-ID: <4AAD45BC.1090408@gmail.com> > But for sorting the list with the first element as key, I tried it using > just mylist.sort() without the lambda, and its working also. Then why > use the lambda? > There is a little difference between those two variations. Example: >>> sorted([[1,2],[1,3],[1,1]]) [[1, 1], [1, 2], [1, 3]] >>> sorted([[1,2],[1,3],[1,1]], key=lambda x:x[0]) [[1, 2], [1, 3], [1, 1]] For sorting it is necessary to compare items. So for example [1,1] is compared to [1,2] As you see: >>> [1,1] < [1,2] True If you apply the lambda things change: >>> (lambda x: x[0])([1,1])<(lambda x:x[0])([1,2]) False >>> (lambda x: x[0])([1,1])==(lambda x:x[0])([1,2]) True This is because now only the first item of the list is compared. - Patrick > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From eike.welk at gmx.net Mon Sep 14 00:18:00 2009 From: eike.welk at gmx.net (Eike Welk) Date: Mon, 14 Sep 2009 00:18:00 +0200 Subject: [Tutor] include remote module In-Reply-To: <4AABDBE0.7000000@rogers.com> References: <4AAB9A5F.7040905@rogers.com> <4AABB759.6090706@gmail.com> <4AABDBE0.7000000@rogers.com> Message-ID: <200909140018.00635.eike.welk@gmx.net> On Saturday 12 September 2009, Patrick wrote: > Imagine if I gave a client a live Linux CD that automatically > called this sort of script right after boot up. They could have the > absolute most current version of an application from my server > launched on their box and if their data from that application was For this kind of application you could tansfer *.tar.gz or *.rmp files and unpack/install them. This would also be more general. Kind regards, Eike. From shellcom3 at juno.com Mon Sep 14 01:45:32 2009 From: shellcom3 at juno.com (shellcom3 at juno.com) Date: Sun, 13 Sep 2009 23:45:32 GMT Subject: [Tutor] (no subject) Message-ID: <20090913.194532.13399.0@webmail10.dca.untd.com> I want to take two tuples and and print out all the elements in both tuples ____________________________________________________________ Best Weight Loss Program - Click Here! http://thirdpartyoffers.juno.com/TGL2141/fc/BLSrjpTFoYayK1TMy2HLJuXWZVUVwGcRz3BvRi27bhNCVhUuOvezC0KPl88/ From bhaaluu at gmail.com Mon Sep 14 01:50:38 2009 From: bhaaluu at gmail.com (bhaaluu) Date: Sun, 13 Sep 2009 19:50:38 -0400 Subject: [Tutor] (no subject) In-Reply-To: <20090913.194532.13399.0@webmail10.dca.untd.com> References: <20090913.194532.13399.0@webmail10.dca.untd.com> Message-ID: Go for it! 8^D On Sun, Sep 13, 2009 at 7:45 PM, shellcom3 at juno.com wrote: > I want to take two tuples and and print out all the elements in both tuples > > ____________________________________________________________ > Best Weight Loss Program - Click Here! > http://thirdpartyoffers.juno.com/TGL2141/fc/BLSrjpTFoYayK1TMy2HLJuXWZVUVwGcRz3BvRi27bhNCVhUuOvezC0KPl88/ > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- b h a a l u u at g m a i l dot c o m Gnu/Linux IS user-friendly. It's NOT ignorant-friendly or idiot-friendly. From bgailer at gmail.com Mon Sep 14 02:42:42 2009 From: bgailer at gmail.com (bob gailer) Date: Sun, 13 Sep 2009 20:42:42 -0400 Subject: [Tutor] (no subject) In-Reply-To: <20090913.194532.13399.0@webmail10.dca.untd.com> References: <20090913.194532.13399.0@webmail10.dca.untd.com> Message-ID: <4AAD9182.3030300@gmail.com> Please provide a meaningful subject (other than no subject) shellcom3 at juno.com wrote: > I want to take two tuples and and print out all the elements in both tuples > > Please explain your goals more thoroughly. A trivial answer to your question is: tuple1 = (2.3) tuple2 = (3,4) print tuple1, tuple2 You probably want something different. So explain please. -- Bob Gailer Chapel Hill NC 919-636-4239 From alan.gauld at btinternet.com Mon Sep 14 11:09:03 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 14 Sep 2009 10:09:03 +0100 Subject: [Tutor] include remote module References: <4AAB9A5F.7040905@rogers.com> <4AABB759.6090706@gmail.com><4AABDBE0.7000000@rogers.com> <200909140018.00635.eike.welk@gmx.net> Message-ID: "Eike Welk" wrote >> called this sort of script right after boot up. They could have the >> absolute most current version of an application from my server >> launched on their box and if their data from that application was > > For this kind of application you could tansfer *.tar.gz or *.rmp files > and unpack/install them. This would also be more general. It would also save valuable bandwidth and session time. Alan G. From bgailer at gmail.com Mon Sep 14 14:03:37 2009 From: bgailer at gmail.com (bob gailer) Date: Mon, 14 Sep 2009 08:03:37 -0400 Subject: [Tutor] Displaying elements of twoTuples In-Reply-To: <20090913.230000.29882.2@webmail19.dca.untd.com> References: <20090913.230000.29882.2@webmail19.dca.untd.com> Message-ID: <4AAE3119.8050104@gmail.com> **** Please read and follow all advice you receive. **** Otherwise trying to help gets very frustrating. **** Be sure copies of your replies go to the Tutor List. **** (Yes I took the effort to find out which list you had written to). Best way is to reply-all. **** DO NOT USE the same name for the tuple of suits and an individual suit. **** That is what is screwing up your results. Did you walk thru the program step-by-step? shellcom3 at juno.com wrote: > This is my rewrite > > value = ("A","2","3","4","5","6","7","8","9","10","J","Q","K") > > suit = ("c","h","s","d") > > > > > for card in value: > for suit in suit: > print card + suit > > This is the output only shows part of the possible deck of cards or suits.Ac > Ah > As > Ad > 2d > 3d > 4d > 5d > 6d > 7d > 8d > 9d > 10d > Jd > Qd > Kd > > also note that you can use strings instead of tuples: (using T instead of 10) values = "A23456789TJQK" suits = "chsd" OR values = "A 2 3 4 5 6 7 8 9 10 J Q K".split() -- Bob Gailer Chapel Hill NC 919-636-4239 From eike.welk at gmx.net Mon Sep 14 14:42:11 2009 From: eike.welk at gmx.net (Eike Welk) Date: Mon, 14 Sep 2009 14:42:11 +0200 Subject: [Tutor] include remote module In-Reply-To: References: <4AAB9A5F.7040905@rogers.com> <200909140018.00635.eike.welk@gmx.net> Message-ID: <200909141442.12134.eike.welk@gmx.net> On Monday 14 September 2009, Alan Gauld wrote: > It would also save valuable bandwidth and session time. Thinking about it... One could send compressed differences to the version on the CD. Rpm has such a feature I think (Delta RPM, Patch RPM). Eike. From eduardo.susan at gmail.com Mon Sep 14 18:05:43 2009 From: eduardo.susan at gmail.com (Eduardo Vieira) Date: Mon, 14 Sep 2009 10:05:43 -0600 Subject: [Tutor] How to print the next line in python In-Reply-To: References: <8e8e6fc00909120135x85eb754n7ddaace1cc5b3a6d@mail.gmail.com> Message-ID: <9356b9f30909140905t7360ef5r23ddd983b1bd2385@mail.gmail.com> On Sat, Sep 12, 2009 at 10:53 PM, Lie Ryan wrote: > ranjan das wrote: >> >> Hi, >> >> I am new to python and i wrote this piece of code which is ofcourse not >> serving my purpose: >> >> Aim of the code: >> >> To read a file and look for lines which contain the string 'CL'. When >> found, print the entry of the next line (positioned directly below the >> string 'CL') ....continue to do this till the end of the file (since there >> are more than one occurrences of 'CL' in the file) >> >> My piece of code (which just prints lines which contain the string 'CL') >> >> f=open('somefile.txt','r') >> >> for line in f.readlines(): >> >> ? ? if 'CL' in line: >> ? ? ? ? ? ? ?print line >> >> >> please suggest how do i print the entry right below the string 'CL' >> >> > > Will "the next line" ever contains "CL"? And if it does, should we print the > next, next line. That is, in case of: > > abcCLdef > ghiCLjkl > mnopqrst > > should we print: > ghiCLjkl > mnopqrst > > or: > ghiCLjkl > > if the latter is the case, then you can advance the file's cursor: > > with open('myfile.txt') as f: > ? ?for line in f: > ? ? ? ?if 'CL' in line: > ? ? ? ? ? ?print next(f) > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > I like this solution, but it brings a StopIteration error in case the last line contains a 'CL' Regards, Eduardo From warren at wantonhubris.com Mon Sep 14 21:30:20 2009 From: warren at wantonhubris.com (Warren) Date: Mon, 14 Sep 2009 15:30:20 -0400 Subject: [Tutor] New guy question... Message-ID: <47020A04-6AF9-4D51-B1DA-E4F36F14125D@wantonhubris.com> Hey all, I'm just getting started with Python and I'm working my way through my first "Learn Python" book on my Mac. I ran into a weird issue though. Here's the example code I'm using: #!/usr/bin/env python3 print( "Type integers, each followed by ENTER; or just ENTER to finish" ) total = 0 count = 0 while True: line = input() if line: try: number = int(line) except ValueErr as err: print( "BLARGH : ", err ) continue total += number count += 1 else: break if count: print( "count =", count, "total =", total, "mean =", total / count ) Now, what happens is that this starts up and immediately dies, giving me this error: Type integers, each followed by ENTER; or just ENTER to finish Traceback (most recent call last): method in test.py at line 9 line = input() EOFError: EOF when reading a line Why is the "input" statement not waiting for input like it should be and instead killing the app? My google-fu is failing me on this one. - Warren (warren at wantonhubris.com) From bermanrl at cfl.rr.com Mon Sep 14 21:57:29 2009 From: bermanrl at cfl.rr.com (Robert Berman) Date: Mon, 14 Sep 2009 15:57:29 -0400 Subject: [Tutor] New guy question... In-Reply-To: <47020A04-6AF9-4D51-B1DA-E4F36F14125D@wantonhubris.com> References: <47020A04-6AF9-4D51-B1DA-E4F36F14125D@wantonhubris.com> Message-ID: <1252958249.4810.34.camel@bermanrl-desktop> Hi, I noticed this: #!/usr/bin/env python3.... which I think indicates you are using python version 3. I strongly suspect you are reading a text based on one of the version 2 issues of python. You might consider dropping back a version(such as 2.6.) since most learning texts are not updated to work with Version 3. Robert Berman On Mon, 2009-09-14 at 15:30 -0400, Warren wrote: > Hey all, > > I'm just getting started with Python and I'm working my way through my > first "Learn Python" book on my Mac. I ran into a weird issue > though. Here's the example code I'm using: > > #!/usr/bin/env python3 > > print( "Type integers, each followed by ENTER; or just ENTER to > finish" ) > > total = 0 > count = 0 > > while True: > line = input() > > if line: > try: > number = int(line) > except ValueErr as err: > print( "BLARGH : ", err ) > continue > > total += number > count += 1 > else: > break > > if count: > print( "count =", count, "total =", total, "mean =", total / count ) > > > Now, what happens is that this starts up and immediately dies, giving > me this error: > > Type integers, each followed by ENTER; or just ENTER to finish > Traceback (most recent call last): > method in test.py at line 9 > line = input() > EOFError: EOF when reading a line > > Why is the "input" statement not waiting for input like it should be > and instead killing the app? My google-fu is failing me on this one. > > - Warren > (warren at wantonhubris.com) > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Mon Sep 14 22:10:54 2009 From: bgailer at gmail.com (bob gailer) Date: Mon, 14 Sep 2009 16:10:54 -0400 Subject: [Tutor] New guy question... In-Reply-To: <47020A04-6AF9-4D51-B1DA-E4F36F14125D@wantonhubris.com> References: <47020A04-6AF9-4D51-B1DA-E4F36F14125D@wantonhubris.com> Message-ID: <4AAEA34E.3000700@gmail.com> Warren wrote: > > Hey all, > > I'm just getting started with Python and I'm working my way through my > first "Learn Python" book on my Mac. I ran into a weird issue > though. Here's the example code I'm using: > > #!/usr/bin/env python3 > > print( "Type integers, each followed by ENTER; or just ENTER to finish" ) > > total = 0 > count = 0 > > while True: > line = input() > > if line: > try: > number = int(line) > except ValueErr as err: > print( "BLARGH : ", err ) > continue > > total += number > count += 1 > else: > break > > if count: > print( "count =", count, "total =", total, "mean =", total / count ) > > > Now, what happens is that this starts up and immediately dies, giving > me this error: > > Type integers, each followed by ENTER; or just ENTER to finish > Traceback (most recent call last): > method in test.py at line 9 > line = input() > EOFError: EOF when reading a line > > Why is the "input" statement not waiting for input like it should be > and instead killing the app? My google-fu is failing me on this one. Sorry - I can't explain that. But consider a simplified program: total = 0 count = 0 line = input() while line: if line.isdigit(): number = int(line) total += number count += 1 else: print( "BLARGH : ", err ) line = input() if count: print( "count =", count, "total =", total, "mean =", total / count ) -- Bob Gailer Chapel Hill NC 919-636-4239 From warren at wantonhubris.com Mon Sep 14 22:06:25 2009 From: warren at wantonhubris.com (Warren) Date: Mon, 14 Sep 2009 16:06:25 -0400 Subject: [Tutor] New guy question... In-Reply-To: <1252958249.4810.34.camel@bermanrl-desktop> References: <47020A04-6AF9-4D51-B1DA-E4F36F14125D@wantonhubris.com> <1252958249.4810.34.camel@bermanrl-desktop> Message-ID: <76C1C31F-0BB2-463C-8D24-B6C6FF817A70@wantonhubris.com> Well, I thought that as well but I took it out which makes it run under 2.6.1 and I get similar, but not exactly the same, output: Type integers, each followed by ENTER; or just ENTER to finish EOFError: EOF when reading a line - Warren (warren at wantonhubris.com) On Sep 14, 2009, at 3:57 PM, Robert Berman wrote: > Hi, > > I noticed this: #!/usr/bin/env python3.... which I think indicates > you are using python version 3. I strongly suspect you are reading a > text based on one of the version 2 issues of python. > > You might consider dropping back a version(such as 2.6.) since most > learning texts are not updated to work with Version 3. > > Robert Berman > > > > > On Mon, 2009-09-14 at 15:30 -0400, Warren wrote: >> Hey all, >> >> I'm just getting started with Python and I'm working my way through >> my >> first "Learn Python" book on my Mac. I ran into a weird issue >> though. Here's the example code I'm using: >> >> #!/usr/bin/env python3 >> >> print( "Type integers, each followed by ENTER; or just ENTER to >> finish" ) >> >> total = 0 >> count = 0 >> >> while True: >> line = input() >> >> if line: >> try: >> number = int(line) >> except ValueErr as err: >> print( "BLARGH : ", err ) >> continue >> >> total += number >> count += 1 >> else: >> break >> >> if count: >> print( "count =", count, "total =", total, "mean =", total / count ) >> >> >> Now, what happens is that this starts up and immediately dies, giving >> me this error: >> >> Type integers, each followed by ENTER; or just ENTER to finish >> Traceback (most recent call last): >> method in test.py at line 9 >> line = input() >> EOFError: EOF when reading a line >> >> Why is the "input" statement not waiting for input like it should be >> and instead killing the app? My google-fu is failing me on this one. >> >> - Warren >> ( >> warren at wantonhubris.com >> ) >> >> >> >> >> _______________________________________________ >> Tutor maillist - >> Tutor at python.org >> >> To unsubscribe or change subscription options: >> >> http://mail.python.org/mailman/listinfo/tutor From marc.tompkins at gmail.com Mon Sep 14 22:31:43 2009 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Mon, 14 Sep 2009 13:31:43 -0700 Subject: [Tutor] New guy question... In-Reply-To: <47020A04-6AF9-4D51-B1DA-E4F36F14125D@wantonhubris.com> References: <47020A04-6AF9-4D51-B1DA-E4F36F14125D@wantonhubris.com> Message-ID: <40af687b0909141331g6c09b8e0y7f96c19678fc4605@mail.gmail.com> On Mon, Sep 14, 2009 at 12:30 PM, Warren wrote: > Type integers, each followed by ENTER; or just ENTER to finish > Traceback (most recent call last): > ?method in test.py at line 9 > ? ?line = input() > EOFError: EOF when reading a line > > Why is the "input" statement not waiting for input like it should be and > instead killing the app? ?My google-fu is failing me on this one. > Try changing it to raw_input() instead... >From the docs: input([prompt]) Equivalent to eval(raw_input(prompt)). In other words, Python is trying to evaluate your input as a valid Python statement at the moment you enter it. I don't quite see why eval(blank line) == EOF, but apparently it does... When I tried your code, if I pressed Enter it blew up with the same error you reported; if I entered integers instead, it accepted them happily until my first blank line, at which point it again complained of an EOF. (I'm running 2.62 on Windows, by the way.) Changing to raw_input() made things work, so I think it's the implicit eval(). -- www.fsrtechnologies.com From mark at timewasted.net Mon Sep 14 22:33:05 2009 From: mark at timewasted.net (Mark Freeman) Date: Mon, 14 Sep 2009 15:33:05 -0500 Subject: [Tutor] New guy question... Message-ID: <304394da0909141333t689398f3q6a4273f84f4e9ea3@mail.gmail.com> Have you tried running this line by line through the interactive shell? Given, I'm not doing this on a mac, but your input() call doesn't fail for me. I'm using Python 2.6. mark From eduardo.susan at gmail.com Mon Sep 14 22:37:52 2009 From: eduardo.susan at gmail.com (Eduardo Vieira) Date: Mon, 14 Sep 2009 14:37:52 -0600 Subject: [Tutor] (no subject) In-Reply-To: <4AAD9182.3030300@gmail.com> References: <20090913.194532.13399.0@webmail10.dca.untd.com> <4AAD9182.3030300@gmail.com> Message-ID: <9356b9f30909141337g23767260i30a564a99a597e92@mail.gmail.com> On Sun, Sep 13, 2009 at 6:42 PM, bob gailer wrote: > Please provide a meaningful subject (other than no subject) > > > shellcom3 at juno.com wrote: >> >> I want to take two tuples and and print out all the elements in both >> tuples >> >> > > You probably want something different. So explain please. > Maybe he wants you to click on the weight loss link ;-)) From srilyk at gmail.com Mon Sep 14 23:07:48 2009 From: srilyk at gmail.com (Wayne) Date: Mon, 14 Sep 2009 16:07:48 -0500 Subject: [Tutor] New guy question... In-Reply-To: <40af687b0909141331g6c09b8e0y7f96c19678fc4605@mail.gmail.com> References: <47020A04-6AF9-4D51-B1DA-E4F36F14125D@wantonhubris.com> <40af687b0909141331g6c09b8e0y7f96c19678fc4605@mail.gmail.com> Message-ID: <333efb450909141407x2c304e51u47562a2639cfd6cd@mail.gmail.com> On Mon, Sep 14, 2009 at 3:31 PM, Marc Tompkins wrote: > On Mon, Sep 14, 2009 at 12:30 PM, Warren wrote: > > Type integers, each followed by ENTER; or just ENTER to finish > > Traceback (most recent call last): > > method in test.py at line 9 > > line = input() > > EOFError: EOF when reading a line > > > > Why is the "input" statement not waiting for input like it should be and > > instead killing the app? My google-fu is failing me on this one. > > > > Try changing it to raw_input() instead... > >From the docs: > input([prompt]) > Equivalent to eval(raw_input(prompt)). > > In other words, Python is trying to evaluate your input as a valid > Python statement at the moment you enter it. > I don't quite see why eval(blank line) == EOF, but apparently it does... > > When I tried your code, if I pressed Enter it blew up with the same > error you reported; if I entered integers instead, it accepted them > happily until my first blank line, at which point it again complained > of an EOF. (I'm running 2.62 on Windows, by the way.) Changing to > raw_input() made things work, so I think it's the implicit eval(). On python3 they changed input to work like raw_input, or am I mistaken? But as I test, my 2.6 gives an identical error so I'm suspecting there's a problem with that shebang line. I also suspect if the OP puts import platform platform.python_version() he'll get something < 3.0 -Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at ieee.org Mon Sep 14 23:21:54 2009 From: davea at ieee.org (Dave Angel) Date: Mon, 14 Sep 2009 17:21:54 -0400 Subject: [Tutor] New guy question... In-Reply-To: <76C1C31F-0BB2-463C-8D24-B6C6FF817A70@wantonhubris.com> References: <47020A04-6AF9-4D51-B1DA-E4F36F14125D@wantonhubris.com> <1252958249.4810.34.camel@bermanrl-desktop> <76C1C31F-0BB2-463C-8D24-B6C6FF817A70@wantonhubris.com> Message-ID: <4AAEB3F2.4020108@ieee.org> (You're top-posting, which makes the message flow very confusing) Warren wrote: >
> Well, I thought that as well but I took it out which makes it run > under 2.6.1 and I get similar, but not exactly the same, output: > > > Type integers, each followed by ENTER; or just ENTER to finish > > EOFError: EOF when reading a line > > > > - Warren > (warren at wantonhubris.com) > > > > > On Sep 14, 2009, at 3:57 PM, Robert Berman wrote: > >> Hi, >> >> I noticed this: #!/usr/bin/env python3.... which I think indicates >> you are using python version 3. I strongly suspect you are reading a >> text based on one of the version 2 issues of python. >> >> You might consider dropping back a version(such as 2.6.) since most >> learning texts are not updated to work with Version 3. >> >> Robert Berman >> >> >> >> >> On Mon, 2009-09-14 at 15:30 -0400, Warren wrote: >>> Hey all, >>> >>> I'm just getting started with Python and I'm working my way through my >>> first "Learn Python" book on my Mac. I ran into a weird issue >>> though. Here's the example code I'm using: >>> >>> #!/usr/bin/env python3 >>> >>> print( "Type integers, each followed by ENTER; or just ENTER to >>> finish" ) >>> >>> total = 0 >>> count = 0 >>> >>> while True: >>> line = input() >>> >>> if line: >>> try: >>> number = int(line) >>> except ValueErr as err: >>> print( "BLARGH : ", err ) >>> continue >>> >>> total += number >>> count += 1 >>> else: >>> break >>> >>> if count: >>> print( "count =", count, "total =", total, "mean =", total / >>> count ) >>> >>> >>> Now, what happens is that this starts up and immediately dies, giving >>> me this error: >>> >>> Type integers, each followed by ENTER; or just ENTER to finish >>> Traceback (most recent call last): >>> method in test.py at line 9 >>> line = input() >>> EOFError: EOF when reading a line >>> >>> Why is the "input" statement not waiting for input like it should be >>> and instead killing the app? My google-fu is failing me on this one. >>> >>> - Warren >>> ( >>> warren at wantonhubris.com >>> ) >>> >>> >>> >>> >>> _______________________________________________ >>> Tutor maillist - >>> Tutor at python.org >>> >>> To unsubscribe or change subscription options: >>> >>> http://mail.python.org/mailman/listinfo/tutor > > >
> Seems to me you're running Python 2.x. The input() function is dangerous. In Python 2.x you should use raw_input(), and your program will behave as you expect. In Python 3, raw_input() has been dropped, and that functionality is called input(). The old input() function evaluates the input, and if there isn't anything to evaluate, it raises an exception, as you see. But to get a uninterpreted string, use raw_input(). DaveA From roadierich at googlemail.com Mon Sep 14 23:25:41 2009 From: roadierich at googlemail.com (Rich Lovely) Date: Mon, 14 Sep 2009 22:25:41 +0100 Subject: [Tutor] New guy question... In-Reply-To: <47020A04-6AF9-4D51-B1DA-E4F36F14125D@wantonhubris.com> References: <47020A04-6AF9-4D51-B1DA-E4F36F14125D@wantonhubris.com> Message-ID: 2009/9/14 Warren : > > Hey all, > > I'm just getting started with Python and I'm working my way through my first > "Learn Python" book on my Mac. ?I ran into a weird issue though. ?Here's the > example code I'm using: > > #!/usr/bin/env python3 > > print( "Type integers, each followed by ENTER; or just ENTER to finish" ) > > total = 0 > count = 0 > > while True: > ? ? ? ?line = input() > > ? ? ? ?if line: > ? ? ? ? ? ? ? ?try: > ? ? ? ? ? ? ? ? ? ? ? ?number = int(line) > ? ? ? ? ? ? ? ?except ValueErr as err: > ? ? ? ? ? ? ? ? ? ? ? ?print( "BLARGH : ", err ) > ? ? ? ? ? ? ? ? ? ? ? ?continue > > ? ? ? ? ? ? ? ?total += number > ? ? ? ? ? ? ? ?count += 1 > ? ? ? ?else: > ? ? ? ? ? ? ? ?break > > if count: > ? ? ? ?print( "count =", count, "total =", total, "mean =", total / count ) > > > Now, what happens is that this starts up and immediately dies, giving me > this error: > > Type integers, each followed by ENTER; or just ENTER to finish > Traceback (most recent call last): > ?method in test.py at line 9 > ? ?line = input() > EOFError: EOF when reading a line > > Why is the "input" statement not waiting for input like it should be and > instead killing the app? ?My google-fu is failing me on this one. > > - Warren > (warren at wantonhubris.com) > > > > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > I'm just a little irritated at all the "Don;t use input()"-alikes... > #!/usr/bin/env python3 The OP is in python3, so it isn't an issue. I agree with the don't use python 3 emails, but that's another matter. The way I read the OP, the problem appears to be that input() isn't blocking... so none of the other responses have actually replicated the problem described. (I can't even get the eof error by hitting enter on a newline) - I am on a mac, running from terminal. I can only replicate the error one way: $ cat test.py | python3 Traceback (most recent call last): File "", line 1, in EOFError: EOF when reading a line How exactly you running your script? -- Rich "Roadie Rich" Lovely There are 10 types of people in the world: those who know binary, those who do not, and those who are off by one. From alan.gauld at btinternet.com Tue Sep 15 01:38:48 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 15 Sep 2009 00:38:48 +0100 Subject: [Tutor] New guy question... References: <47020A04-6AF9-4D51-B1DA-E4F36F14125D@wantonhubris.com> Message-ID: "Warren" wrote > while True: > line = input() Beats me, it works OK on my XP box. > try: > number = int(line) > except ValueErr as err: Are you sure this shouldn't be ValueError rather than ValueErr? It won't be causing your current problem but it might cause your next one! :-) > Now, what happens is that this starts up and immediately dies, giving > me this error: > > Type integers, each followed by ENTER; or just ENTER to finish > Traceback (most recent call last): > method in test.py at line 9 > line = input() > EOFError: EOF when reading a line > Why is the "input" statement not waiting for input like it should be > and instead killing the app? My google-fu is failing me on this one. How are you running the code? Are you typing it into a file and then running the file? If so are you typing python foo.py or double clicking the file in Finder? Are you using an IDE? If so which? Finally which version of Python are you using? v3.0 or 3.1 or something else? Clutching at straws... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/l2p/ From david at pythontoo.com Tue Sep 15 01:47:45 2009 From: david at pythontoo.com (David) Date: Mon, 14 Sep 2009 19:47:45 -0400 Subject: [Tutor] New guy question... In-Reply-To: References: <47020A04-6AF9-4D51-B1DA-E4F36F14125D@wantonhubris.com> Message-ID: <4AAED621.9010707@pythontoo.com> Rich Lovely wrote: > 2009/9/14 Warren : >> Hey all, >> >> I'm just getting started with Python and I'm working my way through my first >> "Learn Python" book on my Mac. I ran into a weird issue though. Here's the >> example code I'm using: >> >> #!/usr/bin/env python3 >> >> print( "Type integers, each followed by ENTER; or just ENTER to finish" ) >> >> total = 0 >> count = 0 >> >> while True: >> line = input() >> >> if line: >> try: >> number = int(line) >> except ValueErr as err: >> print( "BLARGH : ", err ) >> continue >> >> total += number >> count += 1 >> else: >> break >> >> if count: >> print( "count =", count, "total =", total, "mean =", total / count ) >> >> >> Now, what happens is that this starts up and immediately dies, giving me >> this error: >> >> Type integers, each followed by ENTER; or just ENTER to finish >> Traceback (most recent call last): >> method in test.py at line 9 >> line = input() >> EOFError: EOF when reading a line >> >> Why is the "input" statement not waiting for input like it should be and >> instead killing the app? My google-fu is failing me on this one. >> >> - Warren >> (warren at wantonhubris.com) >> >> >> >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> > > I'm just a little irritated at all the "Don;t use input()"-alikes... > >> #!/usr/bin/env python3 > > The OP is in python3, so it isn't an issue. I agree with the don't > use python 3 emails, but that's another matter. > > The way I read the OP, the problem appears to be that input() isn't > blocking... so none of the other responses have actually replicated > the problem described. (I can't even get the eof error by hitting > enter on a newline) - I am on a mac, running from terminal. > > I can only replicate the error one way: > > $ cat test.py | python3 > Traceback (most recent call last): > File "", line 1, in > EOFError: EOF when reading a line > > How exactly you running your script? > This works with 2.6 #!/usr/bin/python print "Type integers, each followed by ENTER; or just ENTER to finish" total = 0 count = 0 while True: line = raw_input() if line: try: number = int(line) except ValueErr as err: print( "BLARGH : ", err ) continue total += number count += 1 else: break if count: print "count =", count, "total =", total, "mean =", total / count david [07:43 PM] opteron ~ $ ./tutor_input.py Type integers, each followed by ENTER; or just ENTER to finish 1 2 3 4 5 6 count = 6 total = 21 mean = 3 -- Powered by Gentoo GNU/Linux http://linuxcrazy.com From govindgoyal at gmail.com Tue Sep 15 12:50:38 2009 From: govindgoyal at gmail.com (Govind Agrawal) Date: Tue, 15 Sep 2009 03:50:38 -0700 (PDT) Subject: [Tutor] Invitation to connect on LinkedIn Message-ID: <1064957795.4081165.1253011838205.JavaMail.app@ech3-cdn07.prod> LinkedIn ------------ I'd like to add you to my professional network on LinkedIn. - Govind Accept Govind Agrawal's invite: https://www.linkedin.com/e/isd/738276939/KwugpKmr/ ------ (c) 2009, LinkedIn Corporation -------------- next part -------------- An HTML attachment was scrubbed... URL: From llvirta at gmail.com Tue Sep 15 11:34:51 2009 From: llvirta at gmail.com (Olli Virta) Date: Tue, 15 Sep 2009 12:34:51 +0300 Subject: [Tutor] collecting certain data from a textfile Message-ID: <17042c3d0909150234n4de45eebx668102f64d657f76@mail.gmail.com> Hi! I got this simple but effective piece of code. It picks certain wanted pieces of data from a textfile based on database records and puts all of them them in a new textfile in certain order. I was wondering, could it be possible to make it otherwise in case that there's much more rows in that textfile and/or there's much more bits of data to collect? data = open('data.txt','r') f1 = data.readlines() data.close() f2 = open('data.txt','r') i=0 f3 = [] while i < len(f1): a=f2.readline() b=f2.readline() c=f2.readline() data2 = ( a[1:38].strip()+';'+ a[54:88].strip()+';'+ b[77:96].strip()+';'+ b[1:16].strip()+';'+ c[23:33].strip()+';'+ c[123:133].strip()+';' ) wanted = (data2) f3.append(wanted + "\n") i += 3 f4 = open('wanted.txt', 'w') f4.write(''.join(f3)) f2.close() f4.close() Thanks! OV -------------- next part -------------- An HTML attachment was scrubbed... URL: From admin at gg-lab.net Tue Sep 15 14:21:14 2009 From: admin at gg-lab.net (admin at gg-lab.net) Date: Tue, 15 Sep 2009 14:21:14 +0200 Subject: [Tutor] Still Trying to Understand GAE In-Reply-To: <78b3a9580909131149q5238f444h2c17da0851223bb8@mail.gmail.com> References: <48758b600909130659r48eb2771s2568eaae2d12e454@mail.gmail.com> <78b3a9580909131149q5238f444h2c17da0851223bb8@mail.gmail.com> Message-ID: <48758b600909150521r39243fe4mfc51f421ea9f87ef@mail.gmail.com> Hi Wesley! Thankyou very much for your mail (and i'd like to thankyou in a special way for your corrections :) ). > it imports all sub*packages*. don't think directories because the > import mechanism doesn't work this way. this is likely because there > are __init__.py files in those subdirectories. another possibility is > that there are non-empty __init__.py files that do the imports of > things that you're not expecting. Ok, i've checked all those files, because in a standard python evinronment the __init__.py is the only file that can decide what to import. If you want to check directly, here you can find the SDK. Just open the "google" directory. http://googleappengine.googlecode.com/files/google_appengine_1.2.5.zip As i've said, this simple script: --- #!/usr/bin/python import google print "Content-Type: text/html" print "" print "" print "" print "" print "google",dir(google) print "
" print "
" print "" --- Gives this output: "google ['__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__', 'appengine', 'net', 'pyglib']" The "google" directoy has an empty __init__.py file (well, if we want to be completely correct it contains some commented -#- lines). Same for "appengine", "net" and "pyglib". As they all have an __init__.py file, they should be consiedered as modules from the python interpreter. So, if i run "import google" it imports all google's submodules. Well, now, the problem: if i create another directory (module) in the google dir, it doesn't get imported. Of course i've put in it some .py files and an empty __init__.py file. Thankyou again! Giorgio 2009/9/13 wesley chun : > hi Giorgio, > > welcome to Python (whether directly or from GAE!) :-) my comments below. > > >> with import i can import modules or single functions. And this is ok. > > not quite true. regardless of whether you use import or from-import, > you're *always* importing (and loading) modules or packages in their > entirety. > > now, whether you have *access* to "entire" modules/packages or > individual attributes (functions, classes, or standard data), is > another matter -- usually this is a result of using from-import. > > also, the difference between importing and loading is that loading > only happens the first time you import a module/package. (if you do it > more than once, e.g., module A imports B and C and module B also > imports C, the import of C happens twice but the loading happens only > once. > > >> if i use "import >> google" it also imports all subdirectories. And i can't understand >> wi?hy it does so. > > it imports all sub*packages*. don't think directories because the > import mechanism doesn't work this way. this is likely because there > are __init__.py files in those subdirectories. another possibility is > that there are non-empty __init__.py files that do the imports of > things that you're not expecting. > > hope this helps! > -- wesley > - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - > "Core Python Programming", Prentice Hall, (c)2007,2001 > "Python Fundamentals", Prentice Hall, (c)2009 > ? ?http://corepython.com > > wesley.j.chun :: wescpy-at-gmail.com > python training and technical consulting > cyberweb.consulting : silicon valley, ca > http://cyberwebconsulting.com > From kent37 at tds.net Tue Sep 15 14:40:27 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 15 Sep 2009 08:40:27 -0400 Subject: [Tutor] Invitation to connect on LinkedIn In-Reply-To: <1064957795.4081165.1253011838205.JavaMail.app@ech3-cdn07.prod> References: <1064957795.4081165.1253011838205.JavaMail.app@ech3-cdn07.prod> Message-ID: <1c2a2c590909150540s67334717v6a785538ec9d3e6a@mail.gmail.com> I'm going to be charitable and assume this is a mistake. This is completely inappropriate to post to the tutor list. Kent On Tue, Sep 15, 2009 at 6:50 AM, Govind Agrawal wrote: > LinkedIn > > I'd like to add you to my professional network on LinkedIn. > > - Govind > > Accept Govind Agrawal's invite: > https://www.linkedin.com/e/isd/738276939/KwugpKmr/ > > ? 2009, LinkedIn Corporation > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From connorsml at gmail.com Tue Sep 15 14:47:25 2009 From: connorsml at gmail.com (Michael Connors) Date: Tue, 15 Sep 2009 14:47:25 +0200 Subject: [Tutor] Invitation to connect on LinkedIn In-Reply-To: <1c2a2c590909150540s67334717v6a785538ec9d3e6a@mail.gmail.com> References: <1064957795.4081165.1253011838205.JavaMail.app@ech3-cdn07.prod> <1c2a2c590909150540s67334717v6a785538ec9d3e6a@mail.gmail.com> Message-ID: Gmail adds everyone you mail to your address book, and sites like LinkedIn ask for your email account credentials to search for contacts from your address book. I think this could happen to anyone who is unfamiliar with either service. Michael 2009/9/15 Kent Johnson > I'm going to be charitable and assume this is a mistake. This is completely > inappropriate to post to the tutor list. > > Kent > > On Tue, Sep 15, 2009 at 6:50 AM, Govind Agrawal wrote: > >> LinkedIn >> >> I'd like to add you to my professional network on LinkedIn. >> >> - Govind >> >> Accept Govind Agrawal's invite: >> https://www.linkedin.com/e/isd/738276939/KwugpKmr/ >> >> ? 2009, LinkedIn Corporation >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> >> > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- Michael Connors Burggravenlaan 148, Leiden 2313 HZ, The Netherlands 0031611520252 -------------- next part -------------- An HTML attachment was scrubbed... URL: From mail at timgolden.me.uk Tue Sep 15 14:54:16 2009 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 15 Sep 2009 13:54:16 +0100 Subject: [Tutor] Invitation to connect on LinkedIn In-Reply-To: <1c2a2c590909150540s67334717v6a785538ec9d3e6a@mail.gmail.com> References: <1064957795.4081165.1253011838205.JavaMail.app@ech3-cdn07.prod> <1c2a2c590909150540s67334717v6a785538ec9d3e6a@mail.gmail.com> Message-ID: <4AAF8E78.5030804@timgolden.me.uk> Kent Johnson wrote: > I'm going to be charitable and assume this is a mistake. This is completely > inappropriate to post to the tutor list. I assume -- having seen a few of these go past -- that such services say on joining: do you want me to email every one in your address book to ask them to link in with you (or be your friend, or whatever). Naive users will simply say: yes; here are the keys to my mailbox... and the result will be posts like these. TJG From lakshman.sah at wipro.com Tue Sep 15 14:41:31 2009 From: lakshman.sah at wipro.com (lakshman.sah at wipro.com) Date: Tue, 15 Sep 2009 18:11:31 +0530 Subject: [Tutor] PyInit__tkinter fails with UnicodeEncodeError Message-ID: Hi, I have a standalone python executable created using PyInstaller (modified to support Python 3) on Linux. This executable was running well with Python 3.0.1. But on Python 3.1.1 it is breaking with UnicodeEncodeError. Executable created with same code on Windows it is running without any error. After debugging the Python code I found that the PyInit__tkinter in file _tkinter.c is not able to encode the executable name or path when it finds characters other than 'a' ('A') through 'p' ('P') at position multiple of 4 (0 based). For example if my executable name is "setup" it finds 's' at the position 0 and breaks with UnicodeEncodeError. NOTE: If I change the name to "etup" (removed 's') it is executing well. And also if I replace 's' with any character 'a' through 'p' it is working. This is happening because here by default 'strict' error handler is being used. I tried to play a little with the Python code. And modified PyInit__tkinter() to used "surrogatepass" error handler while it is encoding the Unicode string with utf-8 encoding. i.e. I replaced cexe = PyUnicode_AsEncodeString(uexe,Py_FileSystemDefaultEncoding,NULL); with cexe = PyUnicode_AsEncodeString(uexe,Py_FileSystemDefaultEncoding, "surrogatepass"); My executable started running without changing its name. I have no idea whether this is a feature or bug in PyInit__tkinter(). Is there any way I can specify PyInit__tkinter to use "surrogatepass" instead of "strict" error handler. Please help me with your suggestions. Thanks, Lakshman Please do not print this email unless it is absolutely necessary. The information contained in this electronic message and any attachments to this message are intended for the exclusive use of the addressee(s) and may contain proprietary, confidential or privileged information. If you are not the intended recipient, you should not disseminate, distribute or copy this e-mail. Please notify the sender immediately and destroy all copies of this message and any attachments. WARNING: Computer viruses can be transmitted via email. The recipient should check this email and any attachments for the presence of viruses. The company accepts no liability for any damage caused by any virus transmitted by this email. www.wipro.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From warren at wantonhubris.com Tue Sep 15 15:07:17 2009 From: warren at wantonhubris.com (Warren) Date: Tue, 15 Sep 2009 09:07:17 -0400 Subject: [Tutor] New guy question... In-Reply-To: <4AAED621.9010707@pythontoo.com> References: <47020A04-6AF9-4D51-B1DA-E4F36F14125D@wantonhubris.com> <4AAED621.9010707@pythontoo.com> Message-ID: First, let me say thanks for all the responses! This definitely looks like a useful mailing list for complete noobs like me. Second, I think my machine is probably set up a little weird. I have Python 2.6.2 installed alongside 3.1.1 so maybe that makes a difference. I'm writing programs in TextMate and running them from there. Which seemed to be working fine until I ran into this "input" issue. At any rate, I've installed 2.6.2 over again from a fresh download and I think I can move ahead. The example works now as long as I change "input" to "raw_input". This should allow me to get through some more of this tutorial book anyway. Thanks again, all! I appreciate the help. - Warren (warren at wantonhubris.com) From kent37 at tds.net Tue Sep 15 16:15:21 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 15 Sep 2009 10:15:21 -0400 Subject: [Tutor] New guy question... In-Reply-To: References: <47020A04-6AF9-4D51-B1DA-E4F36F14125D@wantonhubris.com> <4AAED621.9010707@pythontoo.com> Message-ID: <1c2a2c590909150715o37d3e13ep7b1af5728c7e40a@mail.gmail.com> On Tue, Sep 15, 2009 at 9:07 AM, Warren wrote: > Second, I think my machine is probably set up a little weird. ?I have Python > 2.6.2 installed alongside 3.1.1 so maybe that makes a difference. That should be fine. > ?I'm > writing programs in TextMate and running them from there. ?Which seemed to > be working fine until I ran into this "input" issue. Does TextMate support input into a running Python program? I'm not sure if it supports standard input. You might have to run the program from Terminal to get this to work. Kent From warren at wantonhubris.com Tue Sep 15 16:46:11 2009 From: warren at wantonhubris.com (Warren) Date: Tue, 15 Sep 2009 10:46:11 -0400 Subject: [Tutor] New guy question... In-Reply-To: <1c2a2c590909150715o37d3e13ep7b1af5728c7e40a@mail.gmail.com> References: <47020A04-6AF9-4D51-B1DA-E4F36F14125D@wantonhubris.com> <4AAED621.9010707@pythontoo.com> <1c2a2c590909150715o37d3e13ep7b1af5728c7e40a@mail.gmail.com> Message-ID: <6D2428E9-7890-4D10-AE6C-37BE8E1C987E@wantonhubris.com> > > Does TextMate support input into a running Python program? I'm not > sure if it supports standard input. You might have to run the program > from Terminal to get this to work. Good question, Kent. That might be the root of all of this pain. I'll experiment when I get a chance... - Warren (warren at wantonhubris.com) From bgailer at gmail.com Tue Sep 15 16:53:23 2009 From: bgailer at gmail.com (bob gailer) Date: Tue, 15 Sep 2009 10:53:23 -0400 Subject: [Tutor] collecting certain data from a textfile In-Reply-To: <17042c3d0909150234n4de45eebx668102f64d657f76@mail.gmail.com> References: <17042c3d0909150234n4de45eebx668102f64d657f76@mail.gmail.com> Message-ID: <4AAFAA63.5030802@gmail.com> Olli Virta wrote: > Hi! > > I got this simple but effective piece of code. It picks certain wanted > pieces of data from a textfile based on database records and puts all > of them them in a new textfile in certain order. I was wondering, > could it be possible to make it otherwise in case that there's much > more rows in that textfile and/or there's much more bits of data to > collect? Otherwise is always possible! What is the problem? Why do you want it "otherwise"? > > data = open('data.txt','r') > f1 = data.readlines() > data.close() There is no need to do the above! You don't need a line count to control the loop. > f2 = open('data.txt','r') Drop next lline: > i=0 > f3 = [] Change next two lines: > while i < len(f1): > a=f2.readline() To: while True: a=f2.readline() if not a: break > b=f2.readline() > c=f2.readline() > data2 = ( > a[1:38].strip()+';'+ > a[54:88].strip()+';'+ > b[77:96].strip()+';'+ > b[1:16].strip()+';'+ > c[23:33].strip()+';'+ > c[123:133].strip()+';' > ) > wanted = (data2) If you are concerned about enough memory, write data2 to the file instead of collecting in a list. > f3.append(wanted + "\n") Drop next line: > i += 3 > f4 = open('wanted.txt', 'w') > f4.write(''.join(f3)) > f2.close() > f4.close() -- Bob Gailer Chapel Hill NC 919-636-4239 From dan.king106 at yahoo.com Tue Sep 15 18:03:25 2009 From: dan.king106 at yahoo.com (dan06) Date: Tue, 15 Sep 2009 09:03:25 -0700 (PDT) Subject: [Tutor] Image manipluation (On-the-fly thumbnail creation) Message-ID: <25456792.post@talk.nabble.com> I've recently delved into python, about a week or so ago; I'm trying to figure out how to create on-the-fly thumbnails. Are there python standard library modules I could/should use or should I use external libraries like: GD, Gimp, or ImageMagick? -- View this message in context: http://www.nabble.com/Image-manipluation-%28On-the-fly-thumbnail-creation%29-tp25456792p25456792.html Sent from the Python - tutor mailing list archive at Nabble.com. From vinces1979 at gmail.com Tue Sep 15 19:25:38 2009 From: vinces1979 at gmail.com (vince spicer) Date: Tue, 15 Sep 2009 11:25:38 -0600 Subject: [Tutor] Image manipluation (On-the-fly thumbnail creation) In-Reply-To: <25456792.post@talk.nabble.com> References: <25456792.post@talk.nabble.com> Message-ID: <1e53c510909151025m1e7fb3e8q26dacd7a7e7d8957@mail.gmail.com> On Tue, Sep 15, 2009 at 10:03 AM, dan06 wrote: > > I've recently delved into python, about a week or so ago; I'm trying to > figure out how to create on-the-fly thumbnails. Are there python standard > library modules I could/should use or should I use external libraries like: > GD, Gimp, or ImageMagick? > -- > View this message in context: > http://www.nabble.com/Image-manipluation-%28On-the-fly-thumbnail-creation%29-tp25456792p25456792.html > Sent from the Python - tutor mailing list archive at Nabble.com. > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > check out: http://www.pythonware.com/products/pil/ creating thumbnail example here http://www.pythonware.com/library/pil/handbook/image.htm Vince -------------- next part -------------- An HTML attachment was scrubbed... URL: From qbits143 at gmail.com Tue Sep 15 19:46:24 2009 From: qbits143 at gmail.com (Ajith Gopinath) Date: Tue, 15 Sep 2009 23:16:24 +0530 Subject: [Tutor] Image manipluation (On-the-fly thumbnail creation) In-Reply-To: <1e53c510909151025m1e7fb3e8q26dacd7a7e7d8957@mail.gmail.com> References: <25456792.post@talk.nabble.com> <1e53c510909151025m1e7fb3e8q26dacd7a7e7d8957@mail.gmail.com> Message-ID: import glob import Image for infile in glob.glob("*.jpg"): im = Image.open(infile) # converting to thumbnail image im.thumbnail((128, 128), Image.ANTIALIAS) im.save("thumb" + infile, "JPEG") Will this be of ur help Vince? On 15/09/2009, vince spicer wrote: > On Tue, Sep 15, 2009 at 10:03 AM, dan06 wrote: > >> >> I've recently delved into python, about a week or so ago; I'm trying to >> figure out how to create on-the-fly thumbnails. Are there python standard >> library modules I could/should use or should I use external libraries >> like: >> GD, Gimp, or ImageMagick? >> -- >> View this message in context: >> http://www.nabble.com/Image-manipluation-%28On-the-fly-thumbnail-creation%29-tp25456792p25456792.html >> Sent from the Python - tutor mailing list archive at Nabble.com. >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> > > > check out: > > http://www.pythonware.com/products/pil/ > > > creating thumbnail example here > > http://www.pythonware.com/library/pil/handbook/image.htm > > > Vince > -- || a j i t || From patrick.just4fun at gmail.com Tue Sep 15 20:51:05 2009 From: patrick.just4fun at gmail.com (Patrick Sabin) Date: Tue, 15 Sep 2009 20:51:05 +0200 Subject: [Tutor] Image manipluation (On-the-fly thumbnail creation) In-Reply-To: <25456792.post@talk.nabble.com> References: <25456792.post@talk.nabble.com> Message-ID: <4AAFE219.8000304@gmail.com> dan06 wrote: > I've recently delved into python, about a week or so ago; I'm trying to > figure out how to create on-the-fly thumbnails. Are there python standard > library modules I could/should use or should I use external libraries like: > GD, Gimp, or ImageMagick? When I needed thumbnails of my images, I created them using ImageMagick. ImageMagick is a very nice tool for editing images and since it is called from the command line it is easy to invoke it from a programming language. There are python-bindings for it, but I think they are not very actively maintained and so I wouldn't use them. Using PIL is another option and maybe more pythonic, but if you are familiar with ImageMagick it might be a good alternative. - Patrick From kreglet at gmail.com Tue Sep 15 21:06:39 2009 From: kreglet at gmail.com (kreglet) Date: Tue, 15 Sep 2009 14:06:39 -0500 Subject: [Tutor] Wordscramble.py Message-ID: <4AAFE5BF.30308@gmail.com> This is my first Python project. I am doing this to help me learn the language. I was wondering if someone could give me some advice as I have a lot of questions. 1. I would like to have someone look over the code and tell me how to improve it. I am sure that a lot of it can be done better than the way that I have it written. Is anyone that would be willing to do this? 2. Although it works as is I would like some advice on improving it. ie. Making it look better, play better, etc. 3. I switched from Windows to Linux about 2 months ago. I read that Python is a cross platform language. What would need to be done to make this program run in windows too? 4. Once it is finished, I would like to make it installable for people other than programmers. How? These are a few of the things that I would like to accomplish. The code can be found at pastebin.com: http://pastebin.com/m1ab9a734 Wordscramble.py http://pastebin.com/d2686ec4 scrmod.py http://pastebin.com/m4f611e0c wordlist.py From roadierich at googlemail.com Tue Sep 15 22:28:20 2009 From: roadierich at googlemail.com (Rich Lovely) Date: Tue, 15 Sep 2009 21:28:20 +0100 Subject: [Tutor] New guy question... In-Reply-To: <6D2428E9-7890-4D10-AE6C-37BE8E1C987E@wantonhubris.com> References: <47020A04-6AF9-4D51-B1DA-E4F36F14125D@wantonhubris.com> <4AAED621.9010707@pythontoo.com> <1c2a2c590909150715o37d3e13ep7b1af5728c7e40a@mail.gmail.com> <6D2428E9-7890-4D10-AE6C-37BE8E1C987E@wantonhubris.com> Message-ID: 2009/9/15 Warren : >> >> Does TextMate support input into a running Python program? I'm not >> sure if it supports standard input. You might have to run the program >> from Terminal to get this to work. > > > Good question, Kent. ?That might be the root of all of this pain. ?I'll > experiment when I get a chance... > > - Warren > (warren at wantonhubris.com) > > > > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > As I mentioned in my earlier response, the only way I could replicate the error was to pipe the file into python, disconnecting (I'm guessing) the stdin stream from the terminal: $ cat test.py input() $ cat test.py | python3 Traceback (most recent call last): File "", line 1, in EOFError: EOF when reading a line (I also tested the script in the OP, and got identical output to that mentioned). This supports Kent's suggestion in a way, although maybe for a slightly different reason. -- Rich "Roadie Rich" Lovely There are 10 types of people in the world: those who know binary, those who do not, and those who are off by one. From zstumgoren at gmail.com Tue Sep 15 23:02:09 2009 From: zstumgoren at gmail.com (Serdar Tumgoren) Date: Tue, 15 Sep 2009 17:02:09 -0400 Subject: [Tutor] breaking out of a function that takes too long Message-ID: Hey everyone, Is there a way to break out of a function if it exceeds a certain time limit for execution? There's a Website I'm scraping on a regular basis, and for some reason that I can't divine the site has radically varying response times. In some cases, I get a result vary quickly; at other times, my entire program hangs because of this one call to an external source. Even more strange, if I quit the scrape when it appears to hang and then try it again a few moments later, it will sometimes work just fine ("sometimes" being the key word). I'm not certain, but I'm guessing this inconsistent behavior has something to do with the site that I'm scraping. So again, is there a way to place a time limit on the execution of a function, after which you can break out of it and then retry it or move along with the rest of your program? TIA, Serdar From alan.gauld at btinternet.com Tue Sep 15 23:26:52 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 15 Sep 2009 22:26:52 +0100 Subject: [Tutor] breaking out of a function that takes too long References: Message-ID: "Serdar Tumgoren" wrote > Is there a way to break out of a function if it exceeds a certain time > limit for execution? Yes, you can put the call in a thread then in the main thread start a timer. If the timer expuires before the thread returns kill the thread.thread > There's a Website I'm scraping on a regular basis, and for some reason > that I can't divine the site has radically varying response times. Could be a lot of people have written scrapers and they all schedule them to run at reulat intervals... If the clocks all suddenly align you will get a massive demand on the server (its effectively like a denial of service attack on the server!). Or it could even be real users if it happens when some significant change occurs - like stock/share price web sites often get big peaks at market open and close times. > try it again a few moments later, it will sometimes work just fine > ("sometimes" being the key word). I'm not certain, but I'm guessing > this inconsistent behavior has something to do with the site that I'm > scraping. It could be anywhere in your network connection, including your ISP. If its a local operator there may be peak periods when people go online based on local patterns of usage, especially if its ot a big company - they might only have a couple of 2M pipes say to the core network. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From kent37 at tds.net Tue Sep 15 23:44:43 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 15 Sep 2009 17:44:43 -0400 Subject: [Tutor] breaking out of a function that takes too long In-Reply-To: References: Message-ID: <1c2a2c590909151444m3f740212ha9395229e413ab29@mail.gmail.com> On Tue, Sep 15, 2009 at 5:02 PM, Serdar Tumgoren wrote: > Hey everyone, > Is there a way to break out of a function if it exceeds a certain time > limit for execution? In general this is tricky. It usually involves setting up another thread to run or monitor the function, then somehow terminating the thread if it runs too long. In your case, it sounds like a better solution is to set a socket timeout. At the beginning of your program - before attempting any access to the website - put import socket socket.setdefaulttimeout() This will cause the web site fetch to fail by raising socket.timeout if the fetch blocks for longer than the timeout seconds. Kent From rabidpoobear at gmail.com Wed Sep 16 00:10:18 2009 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Tue, 15 Sep 2009 17:10:18 -0500 Subject: [Tutor] breaking out of a function that takes too long In-Reply-To: References: Message-ID: Most socket request libraries have timeouts on connection attempts, have you looked into that already? On Tue, Sep 15, 2009 at 4:02 PM, Serdar Tumgoren wrote: > Hey everyone, > Is there a way to break out of a function if it exceeds a certain time > limit for execution? > > There's a Website I'm scraping on a regular basis, and for some reason > that I can't divine the site has radically varying response times. In > some cases, I get a result vary quickly; at other times, my entire > program hangs because of this one call to an external source. Even > more strange, if I quit the scrape when it appears to hang and then > try it again a few moments later, it will sometimes work just fine > ("sometimes" being the key word). I'm not certain, but I'm guessing > this inconsistent behavior has something to do with the site that I'm > scraping. > > So again, is there a way to place a time limit on the execution of a > function, after which you can break out of it and then retry it or > move along with the rest of your program? > > TIA, > Serdar > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From zstumgoren at gmail.com Wed Sep 16 00:45:20 2009 From: zstumgoren at gmail.com (Serdar Tumgoren) Date: Tue, 15 Sep 2009 18:45:20 -0400 Subject: [Tutor] breaking out of a function that takes too long In-Reply-To: References: Message-ID: Thanks to all for the responses. I've never used threading, but from some initial googling it appears that it can indeed by tricky and there seem to be numerous recommendations against killing threads or processes. I'll explore the socket request libraries mentioned by several to see if that does the trick. Many thanks! From david at pythontoo.com Wed Sep 16 03:43:31 2009 From: david at pythontoo.com (David) Date: Tue, 15 Sep 2009 21:43:31 -0400 Subject: [Tutor] Wordscramble.py In-Reply-To: <4AAFE5BF.30308@gmail.com> References: <4AAFE5BF.30308@gmail.com> Message-ID: <4AB042C3.80502@pythontoo.com> kreglet wrote: > This is my first Python project. I am doing this to help me learn the > language. I was wondering if someone could give > me some advice as I have a lot of questions. > > 1. I would like to have someone look over the code and tell me how to > improve it. I am sure that a lot of it can be done better than the way > that I have it written. > Is anyone that would be willing to do this? > > 2. Although it works as is I would like some advice on improving it. > ie. Making it look better, play better, etc. > > 3. I switched from Windows to Linux about 2 months ago. I read that > Python is a cross platform language. What would need to be done > to make this program run in windows too? > > 4. Once it is finished, I would like to make it installable for > people other than programmers. How? > > These are a few of the things that I would like to accomplish. > > The code can be found at pastebin.com: > > http://pastebin.com/m1ab9a734 Wordscramble.py > http://pastebin.com/d2686ec4 scrmod.py > http://pastebin.com/m4f611e0c wordlist.py I got it to work on linux but first had to use dos2unix to remove the ^M. I am new to programing myself so can not be of much help but to make it a python program I have used distutils; http://wiki.python.org/moin/Distutils/Tutorial Now to get it cross platform I have no idea. -david -- Powered by Gentoo GNU/Linux http://linuxcrazy.com From davidkim05 at gmail.com Wed Sep 16 00:24:27 2009 From: davidkim05 at gmail.com (David Kim) Date: Tue, 15 Sep 2009 18:24:27 -0400 Subject: [Tutor] Parsing html tables and using numpy for subsequent processing Message-ID: Hello all, I've finally gotten around to my 'learn how to parse html' project. For those of you looking for examples (like me!), hopefully it will show you one potentially thickheaded way to do it. For those of you with powerful python-fu, I would appreciate any feedback regarding the direction I'm taking and obvious coding no-no's (I have no formal training in computer science). Please note the project is unfinished, so there isn't a nice, neat result quite yet. Rather than spam the list with a long description, please visit the following post where I outline my approach and provide necessary links -- http://financialpython.wordpress.com/2009/09/15/parsing-dtcc-part-1-pita/ The code can be found at pastebin: http://financialpython.pastebin.com/f4efd8930 The original html can be found at http://www.dtcc.com/products/derivserv/data/index.php (I am pulling and parsing tables from all three sections). Many thanks! -- DK -------------- next part -------------- An HTML attachment was scrubbed... URL: From ansuman.dash at gmail.com Wed Sep 16 08:03:03 2009 From: ansuman.dash at gmail.com (Ansuman Dash) Date: Wed, 16 Sep 2009 11:33:03 +0530 Subject: [Tutor] Fwd: Executing a command from a specific directory In-Reply-To: <8c0cfa60909150431u705ea8b2vbbaadefafb3ee9ac@mail.gmail.com> References: <8c0cfa60909150431u705ea8b2vbbaadefafb3ee9ac@mail.gmail.com> Message-ID: <8c0cfa60909152303w7b795ecci43db03bad7930ccd@mail.gmail.com> Hello Everybody, In Python scripting, how can I execute a command (which can be run from spcific directory) and then retrieve the result (after executing the command it give the command is executed successfull or not), so that I can validate it. Thanks, AD -------------- next part -------------- An HTML attachment was scrubbed... URL: From patrick.just4fun at gmail.com Wed Sep 16 09:25:49 2009 From: patrick.just4fun at gmail.com (Patrick Sabin) Date: Wed, 16 Sep 2009 09:25:49 +0200 Subject: [Tutor] Fwd: Executing a command from a specific directory In-Reply-To: <8c0cfa60909152303w7b795ecci43db03bad7930ccd@mail.gmail.com> References: <8c0cfa60909150431u705ea8b2vbbaadefafb3ee9ac@mail.gmail.com> <8c0cfa60909152303w7b795ecci43db03bad7930ccd@mail.gmail.com> Message-ID: <4AB092FD.8000604@gmail.com> Ansuman Dash schrieb: > > Hello Everybody, > > In Python scripting, how can I execute a command (which can be run from > spcific directory) and then retrieve the result (after executing the > command it give the command is executed successfull or not), so that I > can validate it. > > Thanks, > AD > > import os import subprocess os.chdir('/your/directory') p = subprocess.Popen("ls -l", shell=True, stdout=subprocess.PIPE) out = p.stdout.read() print out - Patrick From alan.gauld at btinternet.com Wed Sep 16 09:50:04 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 16 Sep 2009 08:50:04 +0100 Subject: [Tutor] Parsing html tables and using numpy for subsequentprocessing References: Message-ID: "David Kim" wrote > The code can be found at pastebin: > http://financialpython.pastebin.com/f4efd8930 Nothing to do with the parsing but I noticed: def get_files(path): ''' Get a list of all files in a given directory. Returns a list of filename strings. ''' files = os.listdir(path) return files Since you are just returning the result of listdir you could achieve the same effect by simply aliasing listdir: get_files = os.listdir Much less typing! HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Wed Sep 16 09:54:26 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 16 Sep 2009 08:54:26 +0100 Subject: [Tutor] Executing a command from a specific directory References: <8c0cfa60909150431u705ea8b2vbbaadefafb3ee9ac@mail.gmail.com> <8c0cfa60909152303w7b795ecci43db03bad7930ccd@mail.gmail.com> Message-ID: "Ansuman Dash" wrote > In Python scripting, how can I execute a command (which can be run from > spcific directory) and then retrieve the result (after executing the > command > it give the command is executed successfull or not), so that I can > validate > it. There are sweveral ways to do this but the preferred route is using the subprocess module. You can see examples of several of the options in the Using the OS topic in my tutorial, under the heading "Manipulating Processes". HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From smiles at worksmail.net Wed Sep 16 12:07:23 2009 From: smiles at worksmail.net (C or L Smith) Date: Wed, 16 Sep 2009 15:52:23 +0545 Subject: [Tutor] : breaking out of a function that takes too long References: Message-ID: <443DEE47EFB94310A65162917C1301AF@kisc.edu.np> >> Serdar wrote: ... >> So again, is there a way to place a time limit on the execution of a >> function, after which you can break out of it and then retry it or >> move along with the rest of your program? At http://tinyurl.com/rbre9n you can find a recipe that tells you how to decorate a function so it will return after a given amount of time. According to the comments, this will leave the process still running, but at least the whole program won't hang. I've used it successfully from time to time. /c From lie.1296 at gmail.com Wed Sep 16 12:55:54 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Wed, 16 Sep 2009 20:55:54 +1000 Subject: [Tutor] Wordscramble.py In-Reply-To: <4AB042C3.80502@pythontoo.com> References: <4AAFE5BF.30308@gmail.com> <4AB042C3.80502@pythontoo.com> Message-ID: David wrote: > > kreglet wrote: >> This is my first Python project. I am doing this to help me learn the >> language. I was wondering if someone could give >> me some advice as I have a lot of questions. >> >> 1. I would like to have someone look over the code and tell me how >> to improve it. I am sure that a lot of it can be done better than the >> way that I have it written. >> Is anyone that would be willing to do this? In no specific order: 1. A file is its own iterator, instead of this: for line in f.readlines(): line=line.strip("\r\n") wordlist.append(line) you can have: for line in f: line=line.strip("\r\n") wordlist.append(line) 2. You are mixing spaces and tabs! PEP 8 (Style guidelines) prefers the use of 4-spaces. Among other things, it also says to use TitleCase for class names. 3. The star-import is discouraged for a good reason. from scrmod import * import only what you needed from scrmod import this, that or import the module import scrmod 4. instead of x=random.randint(0, c-1), you can use x=random.randrange(0, c); btw, do you know about random.shuffle(), random.? >> 2. Although it works as is I would like some advice on improving >> it. ie. Making it look better, play better, etc. I happen to come accross words such as these: D?TENTE which, I guess, might cause problems with the gameplay? >> >> 3. I switched from Windows to Linux about 2 months ago. I read that >> Python is a cross platform language. What would need to be done >> to make this program run in windows too? Usually there is nothing special you need to do. If your program only interacts with the stdin/stdout/stderr and/or a cross-platform window manager (Tkinter, gtk, qt) and/or the standard library; then you can almost be sure that your program will run cross-platform without change. A certain care need to be taken for path handling; make sure to use os.path instead of trying to manipulate paths yourself. Naturally, if you used third-party modules, you must make sure that they support all your target platforms. Creating self-installer is a bit tricky. >> 4. Once it is finished, I would like to make it installable for >> people other than programmers. How? >> These are a few of the things that I would like to accomplish. >> >> The code can be found at pastebin.com: >> >> http://pastebin.com/m1ab9a734 Wordscramble.py >> http://pastebin.com/d2686ec4 scrmod.py >> http://pastebin.com/m4f611e0c wordlist.py > > I got it to work on linux but first had to use dos2unix to remove the > ^M. I am new to programing myself so can not be of much help but to make > it a python program I have used distutils; > http://wiki.python.org/moin/Distutils/Tutorial > Now to get it cross platform I have no idea. > -david > From grflanagan at gmail.com Wed Sep 16 12:57:33 2009 From: grflanagan at gmail.com (Gerard Flanagan) Date: Wed, 16 Sep 2009 11:57:33 +0100 Subject: [Tutor] Parsing html tables and using numpy for subsequent processing In-Reply-To: References: Message-ID: David Kim wrote: > Hello all, > > I've finally gotten around to my 'learn how to parse html' project. For > those of you looking for examples (like me!), hopefully it will show you > one potentially thickheaded way to do it. >[...] > > The code can be found at pastebin: > http://financialpython.pastebin.com/f4efd8930 > The original html can be found at > http://www.dtcc.com/products/derivserv/data/index.php (I am pulling and > parsing tables from all three sections). > Doing something similar at the minute if you want to compare: http://bitbucket.org/djerdo/tronslenk/src/tip/data/scrape_translink.py Not very pretty, but I imagine there are very few pretty examples of this kind of thing. I'll add more comments...honest. Nothing obviously wrong with your code to my eyes. Regards g. From grflanagan at gmail.com Wed Sep 16 13:47:51 2009 From: grflanagan at gmail.com (Gerard Flanagan) Date: Wed, 16 Sep 2009 12:47:51 +0100 Subject: [Tutor] Still Trying to Understand GAE In-Reply-To: <48758b600909150521r39243fe4mfc51f421ea9f87ef@mail.gmail.com> References: <48758b600909130659r48eb2771s2568eaae2d12e454@mail.gmail.com> <78b3a9580909131149q5238f444h2c17da0851223bb8@mail.gmail.com> <48758b600909150521r39243fe4mfc51f421ea9f87ef@mail.gmail.com> Message-ID: admin at gg-lab.net wrote: > The "google" directoy has an empty __init__.py file (well, if we want > to be completely correct it contains some commented -#- lines). Same > for "appengine", "net" and "pyglib". As they all have an __init__.py > file, they should be consiedered as modules from the python > interpreter. So, if i run "import google" it imports all google's > submodules. > > Well, now, the problem: if i create another directory (module) in the > google dir, it doesn't get imported. Of course i've put in it some .py > files and an empty __init__.py file. > > I would guess that additions have been made to the list of modules in sys.path. Where the code that is making these additions is located is another matter. Often, people manipulate sys.path from within __init__.py files but, as you have seen, this isn't the case for the google package - all the __init__.py are empty. To verify, navigate to the GAE directory, the one containing the 'google' package, and start a python interactive session. Then do --- import google --- dir(google) You don't get 'appengine', 'net' etc. in the output. So the google package *is* the same as your own package. The confusion is probably coming from the fact that you are doing your imports from 'within' an already running process - the appserver, and this process has had a chance to manipulate sys.path before your code runs. Look at dev_appserver.py in the sdk and google/appengine/tools/dev_appserver.py - don't ask me what that code is doing, but perhaps there is a clue there, let us know if you find it! Regards From kent37 at tds.net Wed Sep 16 14:01:42 2009 From: kent37 at tds.net (Kent Johnson) Date: Wed, 16 Sep 2009 08:01:42 -0400 Subject: [Tutor] : breaking out of a function that takes too long In-Reply-To: <443DEE47EFB94310A65162917C1301AF@kisc.edu.np> References: <443DEE47EFB94310A65162917C1301AF@kisc.edu.np> Message-ID: <1c2a2c590909160501l6ee16598mc413b7b89cad7eb6@mail.gmail.com> On Wed, Sep 16, 2009 at 6:07 AM, C or L Smith wrote: >>> Serdar wrote: > ... >>> So again, is there a way to place a time limit on the execution of a >>> function, after which you can break out of it and then retry it or >>> move along with the rest of your program? > > At http://tinyurl.com/rbre9n you can find a recipe that tells you how to decorate a function so it will return after a given amount of time. According to the comments, this will leave the process still running, but at least the whole program won't hang. I've used it successfully from time to time. All that recipe really does is to tell you that the function has taken too long. It doesn't stop it. Kent From kent37 at tds.net Wed Sep 16 14:16:35 2009 From: kent37 at tds.net (Kent Johnson) Date: Wed, 16 Sep 2009 08:16:35 -0400 Subject: [Tutor] Still Trying to Understand GAE In-Reply-To: <48758b600909130659r48eb2771s2568eaae2d12e454@mail.gmail.com> References: <48758b600909130659r48eb2771s2568eaae2d12e454@mail.gmail.com> Message-ID: <1c2a2c590909160516l45eb8da9v96490fbe1641c576@mail.gmail.com> On Sun, Sep 13, 2009 at 9:59 AM, admin at gg-lab.net wrote: > Hi All, > > i've started earning python sone months ago (on Google App Engine > unfortunately). > > I have some doubts reagrding "import", and have asked a similar > question here months ago, but without finding a solution. > > So: > > with import i can import modules or single functions. And this is ok. > Then: as i have understood from all the books i readm in each package > directory i have the __init__.py file that decides what import with > it. In other words if my package skel is like: > > /gg/ > /gg/sub1/ > /gg/sub1/file.py > /gg/sub2/ > /gg/sub2/file.py > > and i use "import gg", nothing is imported. To import sub1 and sub2, i can: > > - Put in /gg/ a __init__.py file that tells to import them > - Use "from gg import sub1" > > Ok now the $1 Billion question: google app engine has the same schema > than my "gg" package, an empty __init__.py file, but if i use "import > google" it also imports all subdirectories. And i can't understand > wi?hy it does so. In general, import foo does not import subpackages of foo unless they are specifically imported in foo/__init__.py, so dir(foo) will not show the subpackages. However if you import foo import foo.bar then dir(foo) will include 'bar'. Here is an example from the std lib: In [1]: import distutils In [2]: dir(distutils) Out[2]: ['__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__', '__revision__', '__version__'] In [3]: import distutils.cmd In [4]: dir(distutils) Out[4]: ['__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__', '__revision__', '__version__', 'archive_util', 'cmd', 'dep_util', 'dir_util', 'errors', 'file_util', 'log', 'spawn', 'util'] My guess is that the startup for GAE is importing the subpackages so they then appear as imported modules. To access your sub-package, just import it normally. Kent From ansuman.dash at gmail.com Wed Sep 16 14:33:21 2009 From: ansuman.dash at gmail.com (Ansuman Dash) Date: Wed, 16 Sep 2009 18:03:21 +0530 Subject: [Tutor] Fwd: Executing a command from a specific directory In-Reply-To: <4AB092FD.8000604@gmail.com> References: <8c0cfa60909150431u705ea8b2vbbaadefafb3ee9ac@mail.gmail.com> <8c0cfa60909152303w7b795ecci43db03bad7930ccd@mail.gmail.com> <4AB092FD.8000604@gmail.com> Message-ID: <8c0cfa60909160533y2456b160jdc39e4510f30d203@mail.gmail.com> Hi, Thank you very much for the quick response. Code is working fine. Now I am trying to validate that the command is executed successfully. I have written following script to validate the log file which is created after running the command. ======================================================== if os.access("C:/Python25/Own.log", os.F_OK): f = open("C:/Python25/Own.log") time.sleep(30) try: for line in f.readlines(): a=line if "Request timed out.." not in a: print("Ping is not successful.") pLogger.info("Ping is not successful.") else: print ("Ping is successful.") pLogger.info("Ping is successful.") finally: f.close() else: pLogger.info("File doesn't exist") ========================================================= But it is not working, even if ping is successfully it is printing "Ping is not successful.". Can you please point out where I am making mistake. Thanks, AD On Wed, Sep 16, 2009 at 12:55 PM, Patrick Sabin wrote: > Ansuman Dash schrieb: > > >> Hello Everybody, >> >> In Python scripting, how can I execute a command (which can be run from >> spcific directory) and then retrieve the result (after executing the command >> it give the command is executed successfull or not), so that I can validate >> it. >> >> Thanks, >> AD >> >> >> > import os > import subprocess > > os.chdir('/your/directory') > p = subprocess.Popen("ls -l", shell=True, stdout=subprocess.PIPE) > out = p.stdout.read() > print out > > - Patrick > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From sander.sweers at gmail.com Wed Sep 16 15:03:58 2009 From: sander.sweers at gmail.com (Sander Sweers) Date: Wed, 16 Sep 2009 15:03:58 +0200 Subject: [Tutor] Fwd: Executing a command from a specific directory In-Reply-To: <8c0cfa60909160533y2456b160jdc39e4510f30d203@mail.gmail.com> References: <8c0cfa60909150431u705ea8b2vbbaadefafb3ee9ac@mail.gmail.com> <8c0cfa60909152303w7b795ecci43db03bad7930ccd@mail.gmail.com> <4AB092FD.8000604@gmail.com> <8c0cfa60909160533y2456b160jdc39e4510f30d203@mail.gmail.com> Message-ID: <1253106238.5408.2.camel@infirit.homelinux.org> On Wed, 2009-09-16 at 18:03 +0530, Ansuman Dash wrote: > if "Request timed out.." not in a: > print("Ping is not successful.") > pLogger.info("Ping is not successful.") This will check for the string "Request timed out.." is NOT in a. Now when the ping is successfull the string will not be in a. I suspect you are looking for the logic being reversed so remove the not. Greets Sander From igor.mavrovic at irb.hr Wed Sep 16 15:51:02 2009 From: igor.mavrovic at irb.hr (=?iso-8859-2?Q?Igor_Mavrovi=E6_-_Maqui@IRB?=) Date: Wed, 16 Sep 2009 15:51:02 +0200 Subject: [Tutor] Fw: utf locale sorting Message-ID: <502C9A373AD94621ADF80C60150B53FE@MaquijevaKanta> Hi, I know about the use of locale module: >>> import locale >>> locale.setlocale(locale.LC_ALL, "hr_HR.UTF8") >>> print sorted(words, key=locale.strxfrm) but I have specific and complicated data structure (list of lists containing strings, tuples and dictionaries) due to LDAP search result data. So I use the 'key' option to get to the neaded attributes, and can't use it for the locale setting. How can I sort this monster list by attribute values inside it, and still get the correct sorting order? Anyone? Thanks in advance! From jojo.mwebaze at gmail.com Wed Sep 16 16:33:05 2009 From: jojo.mwebaze at gmail.com (Jojo Mwebaze) Date: Wed, 16 Sep 2009 16:33:05 +0200 Subject: [Tutor] strings and replace Message-ID: <3124be320909160733l6f4887f4yce46e3e232fe317f@mail.gmail.com> Hello There Again Might be a silly question but it has played me for the last two days! I have a string 'mystring' (pasted below), what i want to do is to change the values of of NAXIS1 (=1024) and NAXIS2 (=2048) to some other values! say NAXIS1 = 999 and NAXIS2 = 888. These old values that i want to change are not know forehand so i can not use >>> string.replace(1024, 999) # i also have tried >>> re.sub(r'(\d{4})', ' '+str(999), mystring) but this changes all occurrences of any 4 digit number in the string and also sets both NAXIS1 and NAXIS2 to the same value! i also tried >>> naxis = re.findall(r'(\d{4})',mystring[:360]) >>> mystring.replace(naxis[0], ' '+str(999)) >>> mystring.replace(naxis[1],' '+str(888)) # the empty quotes are to keep the len(mystring) the same before and after replacement i am sure there must be a better ways to do it Any ideas, i appreciate! Cheers Johnson ----------------------------------------- mystring = "SIMPLE = T / Fits format BITPIX = -32 / bits per pixel NAXIS = 2 / single image NAXIS1 = 1024 / x size NAXIS2 = 2048 / y size AIRMEND = 1.516 / no comment AIRMSTRT= 1.516 / no comment DATE = '2005-01-15T12:32:00' / no comment DATE-OBS= '2005-01-15T12:26:00' / no comment EXPTIME = 360.0 / no comment OBJECT = 'herculesfield9 ' / no comment INSTRUME= 'MDM8K ' / no comment TELESCOP= 'MDM 2.4m ' / no comment TEL_LAT = 31.95 / no comment TEL_LONG= -111.6167 / no comment TEL_ELEV= 1938.5 / no comment TEL_ZONE= 7.0 / no comment CHIP_ID = 2 / no comment FILT_ID = 'R ' / no comment CTYPE1 = 'RA---TAN ' / no comment CRVAL1 = 241.320458333 / no comment CRPIX1 = -127.0 / no comment CTYPE2 = 'DEC--TAN ' / no comment CRVAL2 = 16.7331388889 / no comment CRPIX2 = 1525.0 / no comment CD1_1 = 0.0 / no comment CD1_2 = -9.61111111111e-05 / no comment CD2_1 = 9.61111111111e-05 / no comment CD2_2 = 0.0 / no comment STATMIN = 3179.140625 / no comment STATMAX = 3760.86035156 / no comment STATMEAN= 3473.74743563 / no comment STATDEV = 56.3806567048 / no comment STATMED = 3469.74121094 / no comment DATAMD5 = 'c8f7fd1759dcc82a42347e8e7eaf51db' / MD5 checksum END " -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Wed Sep 16 16:44:26 2009 From: kent37 at tds.net (Kent Johnson) Date: Wed, 16 Sep 2009 10:44:26 -0400 Subject: [Tutor] strings and replace In-Reply-To: <3124be320909160733l6f4887f4yce46e3e232fe317f@mail.gmail.com> References: <3124be320909160733l6f4887f4yce46e3e232fe317f@mail.gmail.com> Message-ID: <1c2a2c590909160744g3254989bi6c3d1f72d221ab0c@mail.gmail.com> On Wed, Sep 16, 2009 at 10:33 AM, Jojo Mwebaze wrote: > Hello There Again > > Might be a silly question but it has played me for the last two days! > > I have a string 'mystring' (pasted below), what i want? to do is to change > the values of? of NAXIS1 (=1024)? and NAXIS2 (=2048) to some other values! > say NAXIS1 = 999 and NAXIS2 = 888. > > These old values that i want to change are not know forehand so i can not > use > >>>> string.replace(1024, 999) # > > i also have tried > >>>> re.sub(r'(\d{4})', '? '+str(999), mystring) > > but this changes all occurrences of any 4 digit number in the string and > also sets both NAXIS1 and NAXIS2 to the same value! Just include NAXIS1/2 in the regexp. Something like re.sub(r'NAXIS1 \(=\d{4}\)', 'NAXIS1 (=999)', mystring) Kent From bgailer at gmail.com Wed Sep 16 16:52:06 2009 From: bgailer at gmail.com (bob gailer) Date: Wed, 16 Sep 2009 10:52:06 -0400 Subject: [Tutor] collecting certain data from a textfile In-Reply-To: <17042c3d0909160210w1514f498rb160d08c79cb61e5@mail.gmail.com> References: <17042c3d0909150234n4de45eebx668102f64d657f76@mail.gmail.com> <4AAFAA63.5030802@gmail.com> <17042c3d0909160210w1514f498rb160d08c79cb61e5@mail.gmail.com> Message-ID: <4AB0FB96.8050307@gmail.com> Please always reply-all so a copy goes to the Tutor list. Olli Virta wrote: > Hi! Thanks for advice. I was thinking, if is there was other ways to > get the wanted data out, than with that strip() method. Say what if > I had to use it hundred times. Are you concerned with ease of coding or with performance. We usually don't worry about performance until in practice the program takes "too long". Regarding coding: create tuples of slices: as = (slice(1,38), slice(54,88)) bs = (slice(77,96), slice(1,16)) cs = (slice(23,33), slice123,133)) slices = (as, bs, cs) create a tuple of lines: (untested) a=f2.readline() if not a: break b=f2.readline() c=f2.readline() lines = (a,b,c) iterate over the lines and their respective slices: data2 = [] for x in range(len(lines)): for s in slices[x]: data2.append(lines[x][s].strip() > > OV > > 2009/9/15 bob gailer > > > Olli Virta wrote: > > Hi! > I got this simple but effective piece of code. It picks > certain wanted pieces of data from a textfile based on > database records and puts all of them them in a new textfile > in certain order. I was wondering, could it be possible to > make it otherwise in case that there's much more rows in that > textfile and/or there's much more bits of data to collect? > > > Otherwise is always possible! What is the problem? Why do you want > it "otherwise"? > > > data = open('data.txt','r') > f1 = data.readlines() > data.close() > > > There is no need to do the above! You don't need a line count to > control the loop. > > > f2 = open('data.txt','r') > > > Drop next lline: > > i=0 > f3 = [] > > > Change next two lines: > > > while i < len(f1): > a=f2.readline() > > > To: > > while True: > a=f2.readline() > if not a: break > > > b=f2.readline() > c=f2.readline() > data2 = ( > a[1:38].strip()+';'+ > a[54:88].strip()+';'+ > b[77:96].strip()+';'+ > b[1:16].strip()+';'+ > c[23:33].strip()+';'+ > c[123:133].strip()+';' > ) > wanted = (data2) > > > If you are concerned about enough memory, write data2 to the file > instead of collecting in a list. > > f3.append(wanted + "\n") > > > Drop next line: > > > i += 3 f4 = open('wanted.txt', 'w') > f4.write(''.join(f3)) > f2.close() > f4.close() > > > > -- > Bob Gailer > Chapel Hill NC > 919-636-4239 > > -- Bob Gailer Chapel Hill NC 919-636-4239 From kent37 at tds.net Wed Sep 16 16:33:34 2009 From: kent37 at tds.net (Kent Johnson) Date: Wed, 16 Sep 2009 10:33:34 -0400 Subject: [Tutor] Fw: utf locale sorting In-Reply-To: <502C9A373AD94621ADF80C60150B53FE@MaquijevaKanta> References: <502C9A373AD94621ADF80C60150B53FE@MaquijevaKanta> Message-ID: <1c2a2c590909160733o66d8248ei877cf92e1b5f6275@mail.gmail.com> On Wed, Sep 16, 2009 at 9:51 AM, Igor Mavrovi? - Maqui at IRB wrote: > Hi, > > I know about the use of locale module: > >>>> import locale >>>> locale.setlocale(locale.LC_ALL, "hr_HR.UTF8") >>>> print sorted(words, key=locale.strxfrm) > > but I have specific and complicated data structure (list of lists containing > strings, tuples and dictionaries) due to LDAP search result data. > So I use the 'key' option to get to the neaded attributes, and can't use it > for the locale setting. How can I sort this monster list by attribute values > inside it, and still get the correct sorting order? The key= parameter can be any function. What are you using now? Just add the call to locale.strxfrm() to your key function. If you are currently using operator.itemgetter or operator.attrgetter you will have to change to explicit attribute access. Kent From roadierich at googlemail.com Wed Sep 16 16:58:07 2009 From: roadierich at googlemail.com (Rich Lovely) Date: Wed, 16 Sep 2009 15:58:07 +0100 Subject: [Tutor] Fw: utf locale sorting In-Reply-To: <502C9A373AD94621ADF80C60150B53FE@MaquijevaKanta> References: <502C9A373AD94621ADF80C60150B53FE@MaquijevaKanta> Message-ID: 2009/9/16 Igor Mavrovi? - Maqui at IRB : > Hi, > > I know about the use of locale module: > >>>> import locale >>>> locale.setlocale(locale.LC_ALL, "hr_HR.UTF8") >>>> print sorted(words, key=locale.strxfrm) > > but I have specific and complicated data structure (list of lists containing > strings, tuples and dictionaries) due to LDAP search result data. > So I use the 'key' option to get to the neaded attributes, and can't use it > for the locale setting. How can I sort this monster list by attribute values > inside it, and still get the correct sorting order? > > Anyone? Thanks in advance! > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > The key argument of sorted() and the like takes a function object, so you could do something like the following: def keyfunc(value): keyVal = value[0] #Or whatever lookups are needed return locale.strxfrm(keyVal) then you can call sorted with: print sorted(words, key=keyfunc) You could also do the same with a lambda: print sorted(words, key=lambda o: locale.strxfrm(o[0])) Hope that helps -- Rich "Roadie Rich" Lovely There are 10 types of people in the world: those who know binary, those who do not, and those who are off by one. From igor.mavrovic at irb.hr Wed Sep 16 17:45:15 2009 From: igor.mavrovic at irb.hr (=?UTF-8?Q?Igor_Mavrovi=C4=87_-_Maqui@IRB?=) Date: Wed, 16 Sep 2009 17:45:15 +0200 Subject: [Tutor] Fw: utf locale sorting References: <502C9A373AD94621ADF80C60150B53FE@MaquijevaKanta> <1c2a2c590909160733o66d8248ei877cf92e1b5f6275@mail.gmail.com> Message-ID: Sorry Kent, I should have put it in the original message... This is the way I call the sorted function: # resultSet looks like: [[("DN", {"":["", ...], ...})], ...] resultSetSortedByCn = sorted(resultSet, key=lambda x:(x[0][1]["sn"], x[0][1]["givenName"])) resultSetSortedByOu = sorted(resultSet, key=lambda x:(x[0][1]["ou"], x[0][1]["sn"], x[0][1]["givenName"])) I have to use it like this for obvious reasons (sort by org-unit, surname and then name). Therefore Rich's suggestion: print sorted(words, key=lambda o: locale.strxfrm(o[0])) can't work 'cause strxfrm's argument must be a string, not a tuple... What do you think? Igor ----- Original Message ----- From: Rich Lovely To: Igor Mavrovi? - Maqui at IRB Cc: tutor at python.org Sent: Wednesday, September 16, 2009 4:58 PM Subject: Re: [Tutor] Fw: utf locale sorting The key argument of sorted() and the like takes a function object, so you could do something like the following: def keyfunc(value): keyVal = value[0] #Or whatever lookups are needed return locale.strxfrm(keyVal) then you can call sorted with: print sorted(words, key=keyfunc) You could also do the same with a lambda: print sorted(words, key=lambda o: locale.strxfrm(o[0])) Hope that helps -- Rich "Roadie Rich" Lovely There are 10 types of people in the world: those who know binary, those who do not, and those who are off by one. ----- Original Message ----- From: Kent Johnson To: Igor Mavrovi? - Maqui at IRB Cc: tutor at python.org Sent: Wednesday, September 16, 2009 4:33 PM Subject: Re: [Tutor] Fw: utf locale sorting On Wed, Sep 16, 2009 at 9:51 AM, Igor Mavrovi? - Maqui at IRB wrote: > Hi, > > I know about the use of locale module: > >>>> import locale >>>> locale.setlocale(locale.LC_ALL, "hr_HR.UTF8") >>>> print sorted(words, key=locale.strxfrm) > > but I have specific and complicated data structure (list of lists > containing > strings, tuples and dictionaries) due to LDAP search result data. > So I use the 'key' option to get to the neaded attributes, and can't use > it > for the locale setting. How can I sort this monster list by attribute > values > inside it, and still get the correct sorting order? The key= parameter can be any function. What are you using now? Just add the call to locale.strxfrm() to your key function. If you are currently using operator.itemgetter or operator.attrgetter you will have to change to explicit attribute access. Kent From kent37 at tds.net Wed Sep 16 19:06:32 2009 From: kent37 at tds.net (Kent Johnson) Date: Wed, 16 Sep 2009 13:06:32 -0400 Subject: [Tutor] Fw: utf locale sorting In-Reply-To: References: <502C9A373AD94621ADF80C60150B53FE@MaquijevaKanta> <1c2a2c590909160733o66d8248ei877cf92e1b5f6275@mail.gmail.com> Message-ID: <1c2a2c590909161006x4d015e82h694dec6673dfe038@mail.gmail.com> On Wed, Sep 16, 2009 at 11:45 AM, Igor Mavrovi? - Maqui at IRB wrote: > Sorry Kent, I should have put it in the original message... > This is the way I call the sorted function: > > ? # resultSet looks like: [[("DN", {"":["", ...], ...})], ...] > > ? resultSetSortedByCn = sorted(resultSet, key=lambda x:(x[0][1]["sn"], > x[0][1]["givenName"])) > ? resultSetSortedByOu = sorted(resultSet, key=lambda x:(x[0][1]["ou"], > x[0][1]["sn"], x[0][1]["givenName"])) > > I have to use it like this for obvious reasons (sort by org-unit, surname > and then name). Therefore Rich's suggestion: > > ? print sorted(words, key=lambda o: locale.strxfrm(o[0])) > > can't work 'cause strxfrm's argument must be a string, not a tuple... How about this (assuming both arguments need to be transformed)? key=lambda x:(locale.strxfrm(x[0][1]["sn"]), locale.strxfrm(x[0][1]["givenName"])) Kent From dextrous85 at gmail.com Wed Sep 16 19:51:54 2009 From: dextrous85 at gmail.com (vishwajeet singh) Date: Wed, 16 Sep 2009 23:21:54 +0530 Subject: [Tutor] ImportError: cannot import name log Message-ID: <5487b3060909161051q219ca0b0tbcf91eb190eaf2d0@mail.gmail.com> Hi, Below is the content of __init__.py import sys from django.core.signals import got_request_exception from . import log logger = log._get_logger() def got_request_exception_callback(sender, **kwargs): """Logging all unhandled exceptions.""" type, exception, traceback = sys.exc_info() logger.error(unicode(exception)) got_request_exception.connect(got_request_exception_callback) My question here is that what does *from . import log* doing I can see a module name log in the same folder. This import statement is throwing an error ImportError: cannot import name log. Thanks for all your help -- Cheers, Vishwajeet http://www.singhvishwajeet.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at ieee.org Wed Sep 16 20:35:26 2009 From: davea at ieee.org (Dave Angel) Date: Wed, 16 Sep 2009 14:35:26 -0400 Subject: [Tutor] Executing a command from a specific directory In-Reply-To: <8c0cfa60909160533y2456b160jdc39e4510f30d203@mail.gmail.com> References: <8c0cfa60909150431u705ea8b2vbbaadefafb3ee9ac@mail.gmail.com> <8c0cfa60909152303w7b795ecci43db03bad7930ccd@mail.gmail.com> <4AB092FD.8000604@gmail.com> <8c0cfa60909160533y2456b160jdc39e4510f30d203@mail.gmail.com> Message-ID: <4AB12FEE.3030107@ieee.org> (Don't top-post; it makes reading the thread quite confusing) Ansuman Dash wrote: > Hi, > > Thank you very much for the quick response. > > Code is working fine. > > Now I am trying to validate that the command is executed successfully. > I have written following script to validate the log file which is created > after running the command. > > ======================================================== > if os.access("C:/Python25/Own.log", os.F_OK): > f = open("C:/Python25/Own.log") > time.sleep(30) > try: > for line in f.readlines(): > a=line > > if "Request timed out.." not in a: > print("Ping is not successful.") > pLogger.info("Ping is not successful.") > else: > print ("Ping is successful.") > pLogger.info("Ping is successful.") > > finally: > f.close() > else: > pLogger.info("File doesn't exist") > ========================================================= > > But it is not working, even if ping is successfully it is printing "Ping is > not successful.". Can you please point out where I am making mistake. > > Thanks, > AD > > > On Wed, Sep 16, 2009 at 12:55 PM, Patrick Sabin > wrote: > > >> Ansuman Dash schrieb: >> >> >> >>> Hello Everybody, >>> >>> In Python scripting, how can I execute a command (which can be run from >>> spcific directory) and then retrieve the result (after executing the command >>> it give the command is executed successfull or not), so that I can validate >>> it. >>> >>> Thanks, >>> AD >>> >>> >>> >>> >> import os >> import subprocess >> >> os.chdir('/your/directory') >> p = subprocess.Popen("ls -l", shell=True, stdout=subprocess.PIPE) >> out = p.stdout.read() >> print out >> >> - Patrick >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> >> As Sander says, your if/else is backwards. Presumably the message "Request timed out" is there only when it's unsuccessful, not when it works. But you have another, even more subtle problem. If the log file is more than one line, you're only checking the last one. Unless you know it's the last one that'll contain the line, you need to move the "in" test inside the for loop. There are other things to fine-tune, but these are the important ones. DaveA From steve at alchemy.com Wed Sep 16 20:43:35 2009 From: steve at alchemy.com (Steve Willoughby) Date: Wed, 16 Sep 2009 11:43:35 -0700 Subject: [Tutor] Executing a command from a specific directory In-Reply-To: <4AB12FEE.3030107@ieee.org> References: <8c0cfa60909150431u705ea8b2vbbaadefafb3ee9ac@mail.gmail.com> <8c0cfa60909152303w7b795ecci43db03bad7930ccd@mail.gmail.com> <4AB092FD.8000604@gmail.com> <8c0cfa60909160533y2456b160jdc39e4510f30d203@mail.gmail.com> <4AB12FEE.3030107@ieee.org> Message-ID: <20090916184335.GA86967@dragon.alchemy.com> > Ansuman Dash wrote: > >Now I am trying to validate that the command is executed successfully. > >I have written following script to validate the log file which is created > >after running the command. Notice what's happening here: > > for line in f.readlines(): > > a=line This sets a to EACH line from the file, overwriting the previous one. What you end up with after that executes is a holding the LAST line in the file. > > if "Request timed out.." not in a: > > print("Ping is not successful.") > > pLogger.info("Ping is not successful.") Also... this looks backwards. If "Request timed out.." is NOT found then the ping was NOT successful? -- Steve Willoughby | Using billion-dollar satellites steve at alchemy.com | to hunt for Tupperware. From jecarnell at saintfrancis.com Wed Sep 16 21:03:50 2009 From: jecarnell at saintfrancis.com (Carnell, James E) Date: Wed, 16 Sep 2009 14:03:50 -0500 Subject: [Tutor] Convert doc to txt on Ubuntu Message-ID: I am needing to access the text in hundreds of Microsoft .doc files on an Ubuntu OS. I looked at win32 , but only saw support for windows. I am going through all of these files to create a fairly simple text delimited file for a spreadsheet. A) Batch convert to text files so I can access them B) import some module that allows me to decode this format C) Open Office allows batch conversion to .odc ,but still don't know how to access D) Buy a 24 pack, some Twinkies, and go watch David Hasselhoff reruns Opening .txt documents works fine. Currently get: inFile = open("myTestFile.doc", "r") testRead = inFile.read() Traceback (most recent call last): File "", line 1, in test = inFile.read() File "/usr/lib/python3.0/io.py", line 1728, in read decoder.decode(self.buffer.read(), final=True)) File "/usr/lib/python3.0/io.py", line 1299, in decode output = self.decoder.decode(input, final=final) File "/usr/lib/python3.0/codecs.py", line 300, in decode (result, consumed) = self._buffer_decode(data, self.errors, final) UnicodeDecodeError: 'utf8' codec can't decode bytes in position 0-1: invalid data Any help greatly appreciated Thanks bunches. -------------- next part -------------- An HTML attachment was scrubbed... URL: From emadnawfal at gmail.com Wed Sep 16 21:14:30 2009 From: emadnawfal at gmail.com (=?UTF-8?B?RW1hZCBOYXdmYWwgKNi52YXYp9ivINmG2YjZgdmEKQ==?=) Date: Wed, 16 Sep 2009 15:14:30 -0400 Subject: [Tutor] Convert doc to txt on Ubuntu In-Reply-To: References: Message-ID: <652641e90909161214s43e12edcx972e9de0aef6f77b@mail.gmail.com> On Wed, Sep 16, 2009 at 3:03 PM, Carnell, James E < jecarnell at saintfrancis.com> wrote: > > I am needing to access the text in hundreds of Microsoft .doc files on an > Ubuntu OS. I looked at win32 , but only saw support for windows. I am going > through all of these files to create a fairly simple text delimited file for > a spreadsheet. > > A) Batch convert to text files so I can access them > B) import some module that allows me to decode this format > C) Open Office allows batch conversion to .odc ,but still don't know how to > access > D) Buy a 24 pack, some Twinkies, and go watch David Hasselhoff reruns > > Opening .txt documents works fine. > > Currently get: > > inFile = open("myTestFile.doc", "r") > testRead = inFile.read() > > Traceback (most recent call last): > File "", line 1, in > test = inFile.read() > File "/usr/lib/python3.0/io.py", line 1728, in read > decoder.decode(self.buffer.read(), final=True)) > File "/usr/lib/python3.0/io.py", line 1299, in decode > output = self.decoder.decode(input, final=final) > File "/usr/lib/python3.0/codecs.py", line 300, in decode > (result, consumed) = self._buffer_decode(data, self.errors, final) > UnicodeDecodeError: 'utf8' codec can't decode bytes in position 0-1: > invalid data > > Any help greatly appreciated Thanks bunches. > > ubuntu comes with antiword, a program that does exactly this. I usually use > it through through the commands module in python. > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- ?? ???? ?????? ????? ????? ??? ???? ??? ????? ?? ?????? ????????.....???? ??????? "No victim has ever been more repressed and alienated than the truth" Emad Soliman Nawfal Indiana University, Bloomington -------------------------------------------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: From jecarnell at saintfrancis.com Wed Sep 16 22:41:58 2009 From: jecarnell at saintfrancis.com (Carnell, James E) Date: Wed, 16 Sep 2009 15:41:58 -0500 Subject: [Tutor] IDLE colon = syntax error Message-ID: I searched through archives and wasn't able to find the solution. Using IDLE, python 3, Ubuntu (default installations). Using command line: > if 1 == 1: print "equal" > equal Using IDLE: >if 1 == 1: print "equal" >SyntaxError: invalid syntax line 2 Just for kicks in IDLE: >ord(':') #see if it gives me some wack ASCII code >58 Oh well, I imagine this is easy, but I just don't know... (what I get for using a new computer and OS today) -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at ieee.org Wed Sep 16 23:49:15 2009 From: davea at ieee.org (Dave Angel) Date: Wed, 16 Sep 2009 17:49:15 -0400 Subject: [Tutor] IDLE colon = syntax error In-Reply-To: References: Message-ID: <4AB15D5B.7020006@ieee.org> Carnell, James E wrote: > I searched through archives and wasn't able to find the solution. > > Using IDLE, python 3, Ubuntu (default installations). > > Using command line: > > > if 1 == 1: > print "equal" > > equal > > Using IDLE: > > >if 1 == 1: > print "equal" > >SyntaxError: invalid syntax line 2 > > Just for kicks in IDLE: > > >ord(':') #see if it gives me some wack ASCII code > >58 > > Oh well, I imagine this is easy, but I just don't know... (what I get > for using a new computer and OS today) > > In Python 3, print is not a statement, but a function. So you need parentheses around its argument(s). The first time, you were presumably using a 2.x Python. You can check with import sys print (sys.version) Incidentally, 3.1 is much more stable than 3.0. And most of us do also keep a 2.x around, for all those things that aren't ready for 3.x DaveA From roadierich at googlemail.com Thu Sep 17 00:16:02 2009 From: roadierich at googlemail.com (Rich Lovely) Date: Wed, 16 Sep 2009 23:16:02 +0100 Subject: [Tutor] Convert doc to txt on Ubuntu In-Reply-To: References: Message-ID: 2009/9/16 Carnell, James E : > > I am needing to access the text in hundreds of Microsoft .doc files on an > Ubuntu OS. I looked at win32 , but only saw support for windows. I am going > through all of these files to create a fairly simple text delimited file for > a spreadsheet. > > A) Batch convert to text files so I can access them > B) import some module that allows me to decode this format > C) Open Office allows batch conversion to .odc ,but still don't know how to > access > D) Buy a 24 pack, some Twinkies, and go watch David Hasselhoff reruns > > Opening .txt documents works fine. > > Currently get: > > inFile = open("myTestFile.doc", "r") > testRead = inFile.read() > > Traceback (most recent call last): > ? File "", line 1, in > ??? test = inFile.read() > ? File "/usr/lib/python3.0/io.py", line 1728, in read > ??? decoder.decode(self.buffer.read(), final=True)) > ? File "/usr/lib/python3.0/io.py", line 1299, in decode > ??? output = self.decoder.decode(input, final=final) > ? File "/usr/lib/python3.0/codecs.py", line 300, in decode > ??? (result, consumed) = self._buffer_decode(data, self.errors, final) > UnicodeDecodeError: 'utf8' codec can't decode bytes in position 0-1: invalid > data > > Any help greatly appreciated Thanks bunches. > > > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > FYI, open office .odc files are zip archives of xml files. It should be trivial to access the information from them, assuming OO is sensible in converting from the bloated .doc format. -- Rich "Roadie Rich" Lovely There are 10 types of people in the world: those who know binary, those who do not, and those who are off by one. From the_only_katala at verizon.net Thu Sep 17 00:43:53 2009 From: the_only_katala at verizon.net (Laurii) Date: Wed, 16 Sep 2009 15:43:53 -0700 Subject: [Tutor] Using the time module to extract a semi-random number Message-ID: <33C44C4434B141968C827B32AF2902E2@COMPUTER01> Hello all, I am currently reading through the Tutorial for Non-Programers by Josh Cogliati. I have had great success until now. The exercise to modify a number guessing program from a fixed number "number = 78" to using the time module and use the seconds at the time the program is used to be the number. (i.e. if the clock on your computer says 7:35:25 then it would take the 25 and place it in "number". The following is what I have so far: #********************************************* # # hilow2.py # # This program asks the user to guess a # number. If it is wrong the program tells # the user if it is higher or lower. The # first one had a fixed assigned number. # This program takes the last two digits # of the time and assigns it as the random # number. # #********************************************* #*****************.h header files****************** #********************************************* #******************modules********************* from time import time, ctime #********************************************* #**************define lists/dictionaries************** #********************************************* #****************define functions***************** #********************************************* #*************define global variables*************** the_time = ctime() number = the_time guess = 0 guess_try = 0 #********************************************* #****************Main Program****************** while guess != number: guess = input("Guess a number:") if guess != number: if guess > number : print "To High" elif guess < number: print "To Low" guess_try = guess_try + 1 print "Bingo! You are correct." print "It only took you",guess_try,"tries." #********************************************* I think it has to do with the fact that I am using the wrong time function and am not familiar with how to cut out the seconds and send it to the variable number. I believe I should use the strftime(format[,t]) but am not sure how to. All help is appreciated. Thanks in advance, Katt From m.wanstall at gmail.com Thu Sep 17 03:41:59 2009 From: m.wanstall at gmail.com (Mal Wanstall) Date: Thu, 17 Sep 2009 11:41:59 +1000 Subject: [Tutor] Using the time module to extract a semi-random number In-Reply-To: <33C44C4434B141968C827B32AF2902E2@COMPUTER01> References: <33C44C4434B141968C827B32AF2902E2@COMPUTER01> Message-ID: <4fb9d14e0909161841s61c3c7c0h544f474ceb3c338c@mail.gmail.com> Hi Katt, The following does the trick for me: number = int(time.strftime("%S", time.localtime())) There may be better ways to do it though. -Mal On Thu, Sep 17, 2009 at 8:43 AM, Laurii wrote: > Hello all, > > I am currently reading through the Tutorial for Non-Programers by Josh > Cogliati. ?I have had great success until now. > > The exercise to modify a number guessing program from a fixed number "number > = 78" to using the time module and use the seconds at the time the program > is used to be the number. (i.e. if the clock on your computer says 7:35:25 > then it would take the 25 and place it in "number". > > The following is what I have so far: > #********************************************* > # > # ? ?hilow2.py > # > # ? ?This program asks the user to guess a > # ? ?number. ?If it is wrong the program tells > # ? ?the user if it is higher or lower. ?The > # ? ?first one had a fixed assigned number. > # ? ?This program takes the last two digits > # ? ?of the time and assigns it as the random > # ? ?number. > # > #********************************************* > #*****************.h header files****************** > #********************************************* > #******************modules********************* > from time import time, ctime > #********************************************* > #**************define lists/dictionaries************** > #********************************************* > #****************define functions***************** > #********************************************* > #*************define global variables*************** > the_time = ctime() > number = the_time > guess = 0 > guess_try = 0 > #********************************************* > #****************Main Program****************** > while guess != number: > ? ?guess = input("Guess a number:") > ? ?if guess != number: > ? ? ? ? if guess > number : > ? ? ? ? ? ? ?print "To High" > ? ? ? ? elif guess < number: > ? ? ? ? ? ? ?print "To Low" > ? ?guess_try = guess_try + 1 > print "Bingo! You are correct." > print "It only took you",guess_try,"tries." > #********************************************* > > I think it has to do with the fact that I am using the wrong time function > and am not familiar with how to cut out the seconds and send it to the > variable number. > > I believe I should use the strftime(format[,t]) but am not sure how to. ?All > help is appreciated. > > Thanks in advance, > > Katt > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From jeffpeery at yahoo.com Thu Sep 17 02:04:45 2009 From: jeffpeery at yahoo.com (Jeff Peery) Date: Wed, 16 Sep 2009 17:04:45 -0700 (PDT) Subject: [Tutor] python queue Message-ID: <544641.2291.qm@web43134.mail.sp1.yahoo.com> Hello, Does anyone know if there is there a way to look at a queue's contents??Or prevent duplicate messages from being put into a queue? The docs don't show anything useful. The reason is that I'm collecting and drawing data. one thread collects, and one thread draws. each time one sample is collected by the collector thread, a "draw message" is put into the queue to notify?the drawing thread. the dataset is shared between the threads and is continuously growing as data is appended. The queue is used to notify the drawing thread that it should draw. I use threading.Lock() to prevent any "sharing issues". ? The problem is that if the data collector thread is putting messages?into the queue faster than the drawing thread?is getting them, then the drawing thread is forced to redraw more times than it needs to and appears slow. However since the dataset is shared the drawing thread only needs to draw once to be updated for all the new samples. For example if 10 samples have been appended by the data collector thread while the?drawing thread drew once, then there are now 10 messages for the drawing thread to get. yet it only needs to draw once to reflect the 10 samples. so there are 9 redraws that are a waste of energy. ? I was hoping there was some feature in the queue class the would prevent or discard a duplicate message. This way my drawing thread won't draw more than it needs to. ? thanks! Jeff -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Thu Sep 17 05:17:15 2009 From: kent37 at tds.net (Kent Johnson) Date: Wed, 16 Sep 2009 23:17:15 -0400 Subject: [Tutor] python queue In-Reply-To: <544641.2291.qm@web43134.mail.sp1.yahoo.com> References: <544641.2291.qm@web43134.mail.sp1.yahoo.com> Message-ID: <1c2a2c590909162017l5d89b17bx41a7d94568c58088@mail.gmail.com> On Wed, Sep 16, 2009 at 8:04 PM, Jeff Peery wrote: > > Hello, > Does anyone know if there is there a way to look at a queue's contents??Or prevent duplicate messages from being put into a queue? The docs don't show anything useful. The reason is that I'm collecting and drawing data. one thread collects, and one thread draws. each time one sample is collected by the collector thread, a "draw message" is put into the queue to notify?the drawing thread. the dataset is shared between the threads and is continuously growing as data is appended. The queue is used to notify the drawing thread that it should draw. I use threading.Lock() to prevent any "sharing issues". > > The problem is that if the data collector thread is putting messages?into the queue faster than the drawing thread?is getting them, then the drawing thread is forced to redraw more times than it needs to and appears slow. However since the dataset is shared the drawing thread only needs to draw once to be updated for all the new samples. For example if 10 samples have been appended by the data collector thread while the?drawing thread drew once, then there are now 10 messages for the drawing thread to get. yet it only needs to draw once to reflect the 10 samples. so there are 9 redraws that are a waste of energy. ?It sounds like what you really want is a flag. The collector thread sets the flag when data is available, the draw thread clears the flag when it starts to draw. If the flag is set multiple times before the draw, it still only triggers one draw. Take a look at threading.Event, it might work better than Queue. You could try to use qsize() to avoid putting an item in the queue if there is already something there, but you may have to introduce additional locks to avoid race conditions. Kent From kent37 at tds.net Thu Sep 17 05:19:39 2009 From: kent37 at tds.net (Kent Johnson) Date: Wed, 16 Sep 2009 23:19:39 -0400 Subject: [Tutor] Using the time module to extract a semi-random number In-Reply-To: <33C44C4434B141968C827B32AF2902E2@COMPUTER01> References: <33C44C4434B141968C827B32AF2902E2@COMPUTER01> Message-ID: <1c2a2c590909162019l364b516cifcd2e0befe2adc87@mail.gmail.com> On Wed, Sep 16, 2009 at 6:43 PM, Laurii wrote: > The exercise to modify a number guessing program from a fixed number "number > = 78" to using the time module and use the seconds at the time the program > is used to be the number. (i.e. if the clock on your computer says 7:35:25 > then it would take the 25 and place it in "number". time.localtime().tm_sec will give you the number of seconds as an integer without any conversions. Kent From patrick.just4fun at gmail.com Thu Sep 17 10:50:11 2009 From: patrick.just4fun at gmail.com (Patrick Sabin) Date: Thu, 17 Sep 2009 10:50:11 +0200 Subject: [Tutor] Using the time module to extract a semi-random number In-Reply-To: <33C44C4434B141968C827B32AF2902E2@COMPUTER01> References: <33C44C4434B141968C827B32AF2902E2@COMPUTER01> Message-ID: <4AB1F843.1060206@gmail.com> Laurii wrote: > Hello all, > > I am currently reading through the Tutorial for Non-Programers by Josh > Cogliati. I have had great success until now. > > The exercise to modify a number guessing program from a fixed number > "number = 78" to using the time module and use the seconds at the time > the program is used to be the number. (i.e. if the clock on your > computer says 7:35:25 then it would take the 25 and place it in "number". > You can either use: import time number = int(time.strftime("%S")) or use real pseudo-random numbers: import random number = random.randint(0,59) The latter looks clearer to me. - Patrick From ansuman.dash at gmail.com Thu Sep 17 11:47:45 2009 From: ansuman.dash at gmail.com (Ansuman Dash) Date: Thu, 17 Sep 2009 15:17:45 +0530 Subject: [Tutor] Executing a command from a specific directory In-Reply-To: <20090916184335.GA86967@dragon.alchemy.com> References: <8c0cfa60909150431u705ea8b2vbbaadefafb3ee9ac@mail.gmail.com> <8c0cfa60909152303w7b795ecci43db03bad7930ccd@mail.gmail.com> <4AB092FD.8000604@gmail.com> <8c0cfa60909160533y2456b160jdc39e4510f30d203@mail.gmail.com> <4AB12FEE.3030107@ieee.org> <20090916184335.GA86967@dragon.alchemy.com> Message-ID: <8c0cfa60909170247k138a8756xecd8cf6ddf63840@mail.gmail.com> Hi, I modified my code little bit and it is working fine now, ===================================================== if os.access("C:/Python25/Own.log", os.F_OK): f = open("C:/Python25/Own.log") time.sleep(30) try: line = f.readlines() a = string.join(line) if "Request timed out.." not in a: print("Ping is not successful.") pLogger.info("Ping is not successful.") else: print ("Ping is successful.") pLogger.info("Ping is successful.") finally: f.close() else: pLogger.info("File doesn't exist") ======================================================= But I have question to ask, as you can see I am using "time.sleep(30)" to make my code wait. Is there any other way I can write my script to resolve synchronization issues. Thanks, AD On Thu, Sep 17, 2009 at 12:13 AM, Steve Willoughby wrote: > > Ansuman Dash wrote: > > >Now I am trying to validate that the command is executed successfully. > > >I have written following script to validate the log file which is > created > > >after running the command. > > Notice what's happening here: > > > > for line in f.readlines(): > > > a=line > > This sets a to EACH line from the file, overwriting > the previous one. What you end up with after that > executes is a holding the LAST line in the file. > > > > if "Request timed out.." not in a: > > > print("Ping is not successful.") > > > pLogger.info("Ping is not successful.") > > Also... this looks backwards. If "Request timed out.." is NOT found > then the ping was NOT successful? > > -- > Steve Willoughby | Using billion-dollar satellites > steve at alchemy.com | to hunt for Tupperware. > -------------- next part -------------- An HTML attachment was scrubbed... URL: From evosweet at hotmail.com Thu Sep 17 13:37:13 2009 From: evosweet at hotmail.com (Rayon) Date: Thu, 17 Sep 2009 07:37:13 -0400 Subject: [Tutor] max min value in array Message-ID: I need to find the max and min value from some floats in a array: -------------- next part -------------- An HTML attachment was scrubbed... URL: From davidkim05 at gmail.com Thu Sep 17 05:43:10 2009 From: davidkim05 at gmail.com (David Kim) Date: Wed, 16 Sep 2009 23:43:10 -0400 Subject: [Tutor] Parsing html tables and using numpy for subsequent processing Message-ID: > > Gerard wrote: > Not very pretty, but I imagine there are very few pretty examples of > this kind of thing. I'll add more comments...honest. Nothing obviously > wrong with your code to my eyes. > Many thanks gerard, appreciate you looking it over. I'll take a look at the link you posted as well (I'm traveling at the moment). Cheers, -- David Kim "I hear and I forget. I see and I remember. I do and I understand." -- Confucius morenotestoself.wordpress.com financialpython.wordpress.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From fragos.george at gmail.com Thu Sep 17 11:21:24 2009 From: fragos.george at gmail.com (george fragos) Date: Thu, 17 Sep 2009 12:21:24 +0300 Subject: [Tutor] On slicing Message-ID: <53008aa80909170221h461b07b9ya2261ecd1a0109ac@mail.gmail.com> If numbers=[1,2,3,4,5,6,7,8,9,10] and since "...any time the leftmost index in a slice comes later in the seqence than the second one... the result is always an empty sequence", why the slice numbers[10:0:-2] produces the sequence [10,8,6,4,2] but not the sequence []? From kent37 at tds.net Thu Sep 17 14:04:49 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 17 Sep 2009 08:04:49 -0400 Subject: [Tutor] Executing a command from a specific directory In-Reply-To: <8c0cfa60909170247k138a8756xecd8cf6ddf63840@mail.gmail.com> References: <8c0cfa60909150431u705ea8b2vbbaadefafb3ee9ac@mail.gmail.com> <8c0cfa60909152303w7b795ecci43db03bad7930ccd@mail.gmail.com> <4AB092FD.8000604@gmail.com> <8c0cfa60909160533y2456b160jdc39e4510f30d203@mail.gmail.com> <4AB12FEE.3030107@ieee.org> <20090916184335.GA86967@dragon.alchemy.com> <8c0cfa60909170247k138a8756xecd8cf6ddf63840@mail.gmail.com> Message-ID: <1c2a2c590909170504y6942318eu1fa8a32a59ea5d18@mail.gmail.com> On Thu, Sep 17, 2009 at 5:47 AM, Ansuman Dash wrote: > Hi, > > I modified my code little bit and it is working fine now, > > ===================================================== > ??? if os.access("C:/Python25/Own.log", os.F_OK): > ??????? f = open("C:/Python25/Own.log") > ??????? time.sleep(30) > ======================================================= > > But I have question to ask, as you can see I am using "time.sleep(30)" to > make my code wait. Is there any other way I can write my script to resolve > synchronization issues. How is the log being created? Are you waiting for another process to finish? You can use the subprocess module to start another process and then wait for the process to complete. Kent From kent37 at tds.net Thu Sep 17 14:05:43 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 17 Sep 2009 08:05:43 -0400 Subject: [Tutor] max min value in array In-Reply-To: References: Message-ID: <1c2a2c590909170505k604dc402s2cefc5bc00755366@mail.gmail.com> On Thu, Sep 17, 2009 at 7:37 AM, Rayon wrote: > I need to find the max and min value from some floats in a array: Did you try the min() and max() functions? Kent From roadierich at googlemail.com Thu Sep 17 14:06:23 2009 From: roadierich at googlemail.com (Rich Lovely) Date: Thu, 17 Sep 2009 13:06:23 +0100 Subject: [Tutor] max min value in array In-Reply-To: References: Message-ID: 2009/9/17 Rayon : > I need to find the max and min value from some floats in a array: > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > Depending on the size of the array, there's two methods: Using the max and min builtin functions, which will be faster for small arrays, or hand-coding a single pass function, which might be faster for arrays above a certain size. def minmax1(a): #This needs two passes of the array, but uses builtins, which are written in c, and are therefore faster than the equivalent python return min(a), max(a) def minmax2(a): #This only takes one pass, but is python, which is not as fast as C code. #This also has the advantage of allowing you to easily customize your lookups and comparisons minVal = a[0] maxVal = a[0] for v in a: if v < minVal: minVal = v elif v > maxVal: maxVal = v return minVal, maxVal Other techniques to consider: If order is not important, take the first and last values after sorting (or after sorting a copy). You will want to profile each version, to find out what is best in your specific case. If you want to return the indexes of the maximum and minimum, you will need to use the minmax2 function, modified slightly: def minmaxIndexes(a): """returns a tuple of the indexes of the (first) minimum and maximum in the array""" minVal = 0, a[0] maxVal = 0, a[0] for v in enumerate(a): if v[1] < minVal[1]: minVal = v elif v[1] > maxVal[1]: maxVal = v return minVal[0], maxVal[0] -- Rich "Roadie Rich" Lovely There are 10 types of people in the world: those who know binary, those who do not, and those who are off by one. From roadierich at googlemail.com Thu Sep 17 14:12:41 2009 From: roadierich at googlemail.com (Rich Lovely) Date: Thu, 17 Sep 2009 13:12:41 +0100 Subject: [Tutor] On slicing In-Reply-To: <53008aa80909170221h461b07b9ya2261ecd1a0109ac@mail.gmail.com> References: <53008aa80909170221h461b07b9ya2261ecd1a0109ac@mail.gmail.com> Message-ID: 2009/9/17 george fragos : > ?If numbers=[1,2,3,4,5,6,7,8,9,10] and since "...any time the > leftmost index in a slice comes later in the seqence than the second > one... the result is always an empty sequence", why the slice > numbers[10:0:-2] produces the sequence [10,8,6,4,2] but not the > sequence []? > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > There should be a caveat to that: Unless the third index (step) is negative. The first value is start, the second stop, and the third step. What you are saying with numbers[10,0,-2], is start at 10 (facing towards the end of the sequence), keep going until you get to 0, taking two steps backwards each time. I hope that clears things up a little.. -- Rich "Roadie Rich" Lovely There are 10 types of people in the world: those who know binary, those who do not, and those who are off by one. From kent37 at tds.net Thu Sep 17 14:34:23 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 17 Sep 2009 08:34:23 -0400 Subject: [Tutor] max min value in array In-Reply-To: References: Message-ID: <1c2a2c590909170534i6748b2a1k84a5d7db379d40a5@mail.gmail.com> On Thu, Sep 17, 2009 at 8:06 AM, Rich Lovely wrote: > 2009/9/17 Rayon : >> I need to find the max and min value from some floats in a array: > Depending on the size of the array, there's two methods: ?Using the > max and min builtin functions, which will be faster for small arrays, > or hand-coding a single pass function, which might be faster for > arrays above a certain size. Why do you expect a hand-coded function to scale better? I would expect them both to be O(n). > def minmax2(a): > ? ?#This only takes one pass, but is python, which is not as fast as C code. > ? ?#This also has the advantage of allowing you to easily customize > your lookups and comparisons min() and max() both take key= parameters allowing you to customize the comparison. > Other techniques to consider: ?If order is not important, take the > first and last values after sorting (or after sorting a copy). Sorting is O(n log n) so this will have relatively worse performance with larger arrays. Kent From admin at gg-lab.net Thu Sep 17 14:38:38 2009 From: admin at gg-lab.net (admin at gg-lab.net) Date: Thu, 17 Sep 2009 14:38:38 +0200 Subject: [Tutor] Still Trying to Understand GAE In-Reply-To: <1c2a2c590909160516l45eb8da9v96490fbe1641c576@mail.gmail.com> References: <48758b600909130659r48eb2771s2568eaae2d12e454@mail.gmail.com> <1c2a2c590909160516l45eb8da9v96490fbe1641c576@mail.gmail.com> Message-ID: <48758b600909170538h6ba51e37x26894bba37a781f6@mail.gmail.com> Thankyou all, you're very precious for me. yeah it seems the development webserver (and the production one) are importing modules in a non-standard way. I absolutely don't understand this choice. Why import everything everytime? Don't you think it makes scripts much more slow? Giorgio 2009/9/16 Kent Johnson : > On Sun, Sep 13, 2009 at 9:59 AM, admin at gg-lab.net wrote: >> Hi All, >> >> i've started earning python sone months ago (on Google App Engine >> unfortunately). >> >> I have some doubts reagrding "import", and have asked a similar >> question here months ago, but without finding a solution. >> >> So: >> >> with import i can import modules or single functions. And this is ok. >> Then: as i have understood from all the books i readm in each package >> directory i have the __init__.py file that decides what import with >> it. In other words if my package skel is like: >> >> /gg/ >> /gg/sub1/ >> /gg/sub1/file.py >> /gg/sub2/ >> /gg/sub2/file.py >> >> and i use "import gg", nothing is imported. To import sub1 and sub2, i can: >> >> - Put in /gg/ a __init__.py file that tells to import them >> - Use "from gg import sub1" >> >> Ok now the $1 Billion question: google app engine has the same schema >> than my "gg" package, an empty __init__.py file, but if i use "import >> google" it also imports all subdirectories. And i can't understand >> wi?hy it does so. > > In general, > ?import foo > does not import subpackages of foo unless they are specifically > imported in foo/__init__.py, so dir(foo) will not show the > subpackages. > > However if you > ?import foo > ?import foo.bar > then dir(foo) will include 'bar'. Here is an example from the std lib: > > In [1]: import distutils > > In [2]: dir(distutils) > Out[2]: > ['__builtins__', > ?'__doc__', > ?'__file__', > ?'__name__', > ?'__package__', > ?'__path__', > ?'__revision__', > ?'__version__'] > > In [3]: import distutils.cmd > > In [4]: dir(distutils) > Out[4]: > ['__builtins__', > ?'__doc__', > ?'__file__', > ?'__name__', > ?'__package__', > ?'__path__', > ?'__revision__', > ?'__version__', > ?'archive_util', > ?'cmd', > ?'dep_util', > ?'dir_util', > ?'errors', > ?'file_util', > ?'log', > ?'spawn', > ?'util'] > > My guess is that the startup for GAE is importing the subpackages so > they then appear as imported modules. To access your sub-package, just > import it normally. > > Kent > From ansuman.dash at gmail.com Thu Sep 17 14:40:10 2009 From: ansuman.dash at gmail.com (Ansuman Dash) Date: Thu, 17 Sep 2009 18:10:10 +0530 Subject: [Tutor] Executing a command from a specific directory In-Reply-To: <1c2a2c590909170504y6942318eu1fa8a32a59ea5d18@mail.gmail.com> References: <8c0cfa60909150431u705ea8b2vbbaadefafb3ee9ac@mail.gmail.com> <8c0cfa60909152303w7b795ecci43db03bad7930ccd@mail.gmail.com> <4AB092FD.8000604@gmail.com> <8c0cfa60909160533y2456b160jdc39e4510f30d203@mail.gmail.com> <4AB12FEE.3030107@ieee.org> <20090916184335.GA86967@dragon.alchemy.com> <8c0cfa60909170247k138a8756xecd8cf6ddf63840@mail.gmail.com> <1c2a2c590909170504y6942318eu1fa8a32a59ea5d18@mail.gmail.com> Message-ID: <8c0cfa60909170540u2ee36083ya3f84a46ec6b6b65@mail.gmail.com> I am using same process for multiple file download. So I need to download those one by one. Moreover some files are very huge (around 120 MB). So I need to make script to wait before verifying the file is downloaded. Thanks AD On Thu, Sep 17, 2009 at 5:34 PM, Kent Johnson wrote: > On Thu, Sep 17, 2009 at 5:47 AM, Ansuman Dash > wrote: > > Hi, > > > > I modified my code little bit and it is working fine now, > > > > ===================================================== > > if os.access("C:/Python25/Own.log", os.F_OK): > > f = open("C:/Python25/Own.log") > > time.sleep(30) > > ======================================================= > > > > But I have question to ask, as you can see I am using "time.sleep(30)" to > > make my code wait. Is there any other way I can write my script to > resolve > > synchronization issues. > > How is the log being created? Are you waiting for another process to > finish? You can use the subprocess module to start another process and > then wait for the process to complete. > > Kent > -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Thu Sep 17 15:13:14 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 17 Sep 2009 09:13:14 -0400 Subject: [Tutor] Still Trying to Understand GAE In-Reply-To: <48758b600909170538h6ba51e37x26894bba37a781f6@mail.gmail.com> References: <48758b600909130659r48eb2771s2568eaae2d12e454@mail.gmail.com> <1c2a2c590909160516l45eb8da9v96490fbe1641c576@mail.gmail.com> <48758b600909170538h6ba51e37x26894bba37a781f6@mail.gmail.com> Message-ID: <1c2a2c590909170613g4c7dde5eka9f8eb380658245d@mail.gmail.com> On Thu, Sep 17, 2009 at 8:38 AM, admin at gg-lab.net wrote: > Thankyou all, you're very precious for me. > > yeah it seems the development webserver (and the production one) are > importing modules in a non-standard way. > > I absolutely don't understand this choice. Why import everything > everytime? Don't you think it makes scripts much more slow? My guess is that they are importing what they need. It does impact startup but hey, if you need it, you need it. Try this for comparison: Start Python from a command line, then In [5]: import sys In [6]: len(sys.modules) Out[6]: 323 I have IPython loaded so this number may be larger than yours. In Python 3, with no IPython, I get >>> import sys >>> len(sys.modules) 47 So my advice is, don't worry about it. Kent From kent37 at tds.net Thu Sep 17 15:32:58 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 17 Sep 2009 09:32:58 -0400 Subject: [Tutor] Executing a command from a specific directory In-Reply-To: <8c0cfa60909170540u2ee36083ya3f84a46ec6b6b65@mail.gmail.com> References: <8c0cfa60909150431u705ea8b2vbbaadefafb3ee9ac@mail.gmail.com> <8c0cfa60909152303w7b795ecci43db03bad7930ccd@mail.gmail.com> <4AB092FD.8000604@gmail.com> <8c0cfa60909160533y2456b160jdc39e4510f30d203@mail.gmail.com> <4AB12FEE.3030107@ieee.org> <20090916184335.GA86967@dragon.alchemy.com> <8c0cfa60909170247k138a8756xecd8cf6ddf63840@mail.gmail.com> <1c2a2c590909170504y6942318eu1fa8a32a59ea5d18@mail.gmail.com> <8c0cfa60909170540u2ee36083ya3f84a46ec6b6b65@mail.gmail.com> Message-ID: <1c2a2c590909170632r6d19e544sae4111fed4a9ca43@mail.gmail.com> On Thu, Sep 17, 2009 at 8:40 AM, Ansuman Dash wrote: > I am using same process for multiple file download. So I need to download > those one by one. > > Moreover some files are very huge (around 120 MB). So I need to make script > to wait before verifying the file is downloaded. I don't understand how you are downloading the files. Can you show some code? Kent From steve at lonetwin.net Thu Sep 17 17:11:19 2009 From: steve at lonetwin.net (steve) Date: Thu, 17 Sep 2009 20:41:19 +0530 Subject: [Tutor] ImportError: cannot import name log In-Reply-To: <5487b3060909161051q219ca0b0tbcf91eb190eaf2d0@mail.gmail.com> References: <5487b3060909161051q219ca0b0tbcf91eb190eaf2d0@mail.gmail.com> Message-ID: <4AB25197.5000006@lonetwin.net> Hello Vishwajeet, On 09/16/2009 11:21 PM, vishwajeet singh wrote: > Hi, > > Below is the content of __init__.py > > import sys > from django.core.signals import got_request_exception > from . import log > logger = log._get_logger() > > def got_request_exception_callback(sender, **kwargs): > """Logging all unhandled exceptions.""" > type, exception, traceback = sys.exc_info() > logger.error(unicode(exception)) > got_request_exception.connect(got_request_exception_callback) > > My question here is that what does *from . import log* doing I can see a > module name log in the same folder. > The '.' notation is fairly new and also uncommon AFAIK http://docs.python.org/tutorial/modules.html#intra-package-references > This import statement is throwing an error ImportError: cannot import > name log. The reasons it can't import using this 'from . import' notation would be the same as for any other import errors. Check your PYTHONPATH and paste the entire traceback if it still does not work. cheers, - steve -- random non tech spiel: http://lonetwin.blogspot.com/ tech randomness: http://lonehacks.blogspot.com/ what i'm stumbling into: http://lonetwin.stumbleupon.com/ From emadnawfal at gmail.com Thu Sep 17 17:44:06 2009 From: emadnawfal at gmail.com (=?UTF-8?B?RW1hZCBOYXdmYWwgKNi52YXYp9ivINmG2YjZgdmEKQ==?=) Date: Thu, 17 Sep 2009 11:44:06 -0400 Subject: [Tutor] html color coding: where to start Message-ID: <652641e90909170844x4c781916j62921debe09da349@mail.gmail.com> Hi Tutors, I want to color-code the different parts of the word in a morphologically complex natural language. The file I have looks like this, where the fisrt column is the word, and the second is the composite part of speech tag. For example, Al is a DETERMINER, wlAy is a NOUN and At is a PLURAL NOUN SUFFIX Al+wlAy+At DET+NOUN+NSUFF_FEM_PL Al+mtHd+p DET+ADJ+NSUFF_FEM_SG The output I want is one on which the word has no plus signs, and each segment is color-coded with a grammatical category. For example, the noun is red, the det is green, and the suffix is orange. Like on this page here: http://docs.google.com/View?id=df7jv9p9_3582pt63cc4 I am stuck with the html part and I don't know where to start. I have no experience with html, but I have this skeleton (which may not be the right thing any way) Any help with materials, modules, suggestions appreciated. This skeleton of my program is as follows: ############# RED = ("NOUN", "ADJ") GREEN = ("DET", "DEMON") ORANGE = ("NSUFF", "VSUFF", "ADJSUFF") # print html head def print_html_head(): #print the head of the html page def print_html_tail(): # print the tail of the html page def color(segment, color): # STUCK HERE shoudl take a color, and a segment for example # main import sys infile = open(sys.argv[1]) # takes as input the POS-tagged file print_html_head() for line in infile: line = line.split() if len(line) != 2: continue word = line[0] pos = line[1] zipped = zip(word.split("+"), pos.split("+")) for x, y in zipped: if y in DET: color(x, "#FF0000") else: color(x, "#0000FF") print_html_tail() -- ?? ???? ?????? ????? ????? ??? ???? ??? ????? ?? ?????? ????????.....???? ??????? "No victim has ever been more repressed and alienated than the truth" Emad Soliman Nawfal Indiana University, Bloomington -------------------------------------------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: From dextrous85 at gmail.com Thu Sep 17 17:45:05 2009 From: dextrous85 at gmail.com (vishwajeet singh) Date: Thu, 17 Sep 2009 21:15:05 +0530 Subject: [Tutor] ImportError: cannot import name log In-Reply-To: <4AB25197.5000006@lonetwin.net> References: <5487b3060909161051q219ca0b0tbcf91eb190eaf2d0@mail.gmail.com> <4AB25197.5000006@lonetwin.net> Message-ID: <5487b3060909170845i19b3b6a5pf5e60df1f1f3c7c3@mail.gmail.com> On Thu, Sep 17, 2009 at 8:41 PM, steve wrote: > Hello Vishwajeet, > > On 09/16/2009 11:21 PM, vishwajeet singh wrote: > >> Hi, >> >> Below is the content of __init__.py >> >> import sys >> from django.core.signals import got_request_exception >> from . import log >> logger = log._get_logger() >> >> def got_request_exception_callback(sender, **kwargs): >> """Logging all unhandled exceptions.""" >> type, exception, traceback = sys.exc_info() >> logger.error(unicode(exception)) >> got_request_exception.connect(got_request_exception_callback) >> >> My question here is that what does *from . import log* doing I can see a >> module name log in the same folder. >> >> The '.' notation is fairly new and also uncommon AFAIK > http://docs.python.org/tutorial/modules.html#intra-package-references > > This import statement is throwing an error ImportError: cannot import >> name log. >> > The reasons it can't import using this 'from . import' notation would be > the same as for any other import errors. Check your PYTHONPATH and paste the > entire traceback if it still does not work. > > cheers, > - steve > > -- > random non tech spiel: http://lonetwin.blogspot.com/ > tech randomness: http://lonehacks.blogspot.com/ > what i'm stumbling into: http://lonetwin.stumbleupon.com/ > Thanks steve for your help I was able to fix the probelm. -- Cheers, Vishwajeet http://www.singhvishwajeet.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Thu Sep 17 19:18:28 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 17 Sep 2009 13:18:28 -0400 Subject: [Tutor] max min value in array In-Reply-To: <4AB24F30.5010307@lonetwin.net> References: <1c2a2c590909170534i6748b2a1k84a5d7db379d40a5@mail.gmail.com> <4AB24F30.5010307@lonetwin.net> Message-ID: <1c2a2c590909171018w5039893fx4557ede5d7b58d84@mail.gmail.com> On Thu, Sep 17, 2009 at 11:01 AM, steve wrote: > On 09/17/2009 06:04 PM, Kent Johnson wrote: >> >> On Thu, Sep 17, 2009 at 8:06 AM, Rich Lovely >> ?wrote: >>> >>> ?2009/9/17 Rayon: >>>> >>>> ?I need to find the max and min value from some floats in a array: >> >>> ?Depending on the size of the array, there's two methods: ?Using the >>> ?max and min builtin functions, which will be faster for small arrays, >>> ?or hand-coding a single pass function, which might be faster for >>> ?arrays above a certain size. >> >> Why do you expect a hand-coded function to scale better? I would >> expect them both to be O(n). >> > I guess what Rich meant was, a hand-coded function to get /both/ min and max > in a single pass would be faster on large arrays (as done in the posted > minmax2() function) than calling min() and max() individually (which would > imply 2 passes). Yes, that is my understanding of his statement. My question is, why would it be faster only on large arrays? I expect the time of both methods to scale linearly with the size of the array. Two fast passes might be faster than one slow pass regardless of the size of the array. Kent From kent37 at tds.net Thu Sep 17 19:25:11 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 17 Sep 2009 13:25:11 -0400 Subject: [Tutor] html color coding: where to start In-Reply-To: <652641e90909170844x4c781916j62921debe09da349@mail.gmail.com> References: <652641e90909170844x4c781916j62921debe09da349@mail.gmail.com> Message-ID: <1c2a2c590909171025l4c2db33r9da7979e73d5b418@mail.gmail.com> 2009/9/17 Emad Nawfal (???? ????) : > Hi Tutors, > I want to color-code the different parts of the word in a morphologically > complex natural language. The file I have looks like this, where the fisrt > column is the word, and the? second is the composite part of speech tag. For > example, Al is a DETERMINER, wlAy is a NOUN and At is a PLURAL NOUN SUFFIX > > Al+wlAy+At??????? DET+NOUN+NSUFF_FEM_PL > Al+mtHd+p??????? DET+ADJ+NSUFF_FEM_SG > > The output I want is one on which the word has no plus signs, and each > segment is color-coded with a grammatical category. For example, the noun is > red, the det is green, and the suffix is orange.? Like on this page here: > http://docs.google.com/View?id=df7jv9p9_3582pt63cc4 > I am stuck with the html part and I don't know where to start. I have no > experience with html, but I have this skeleton (which may not be the right > thing any way) Doing a "view source" on that page shows, in part
AlwlAyAt
AlmtHdp
which should give you a hint on the HTML though you would be better off using CSS styling. If you use the part of speech as the CSS class then you can color with a stylesheet that defines the colors for each part of speech. You are probably going to have to learn at least a little HTML to do this - google HTML tutorial. This recent package looks like a simple way to generate HTML programmatically: http://pypi.python.org/pypi/html/1.4 Kent From alan.gauld at btinternet.com Thu Sep 17 19:32:28 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 17 Sep 2009 18:32:28 +0100 Subject: [Tutor] html color coding: where to start References: <652641e90909170844x4c781916j62921debe09da349@mail.gmail.com> Message-ID: "Emad Nawfal (???? ????)" wrote > column is the word, and the second is the composite part of speech tag. > For > example, Al is a DETERMINER, wlAy is a NOUN and At is a PLURAL NOUN > SUFFIX > > Al+wlAy+At DET+NOUN+NSUFF_FEM_PL > Al+mtHd+p DET+ADJ+NSUFF_FEM_SG I'd create a dictionary with the parts of speech as keys and the colors(as html strings) as values. I'd then arrange your data into tuples of (wordpart, speechpart) So ('Al', DET)('wlAy',NOUN).... Then you can print with for item in tuples: htmlstr += colors[item[1]] + item[0] # might need to add a closing tag too... Does that help? Alan G. From bgailer at gmail.com Thu Sep 17 19:36:41 2009 From: bgailer at gmail.com (bob gailer) Date: Thu, 17 Sep 2009 13:36:41 -0400 Subject: [Tutor] html color coding: where to start In-Reply-To: <652641e90909170844x4c781916j62921debe09da349@mail.gmail.com> References: <652641e90909170844x4c781916j62921debe09da349@mail.gmail.com> Message-ID: <4AB273A9.8080409@gmail.com> Emad Nawfal (???? ????) wrote: > Hi Tutors, > I want to color-code the different parts of the word in a > morphologically complex natural language. The file I have looks like > this, where the fisrt column is the word, and the second is the > composite part of speech tag. For example, Al is a DETERMINER, wlAy is > a NOUN and At is a PLURAL NOUN SUFFIX > > Al+wlAy+At DET+NOUN+NSUFF_FEM_PL > Al+mtHd+p DET+ADJ+NSUFF_FEM_SG > > The output I want is one on which the word has no plus signs, and each > segment is color-coded with a grammatical category. For example, the > noun is red, the det is green, and the suffix is orange. Like on this > page here: > http://docs.google.com/View?id=df7jv9p9_3582pt63cc4 > I am stuck with the html part and I don't know where to start. I have > no experience with html, but I have this skeleton (which may not be > the right thing any way) > Any help with materials, modules, suggestions appreciated. > > This skeleton of my program is as follows: > > ############# > RED = ("NOUN", "ADJ") > GREEN = ("DET", "DEMON") > ORANGE = ("NSUFF", "VSUFF", "ADJSUFF") Instead of that use a dictionary: colors = dict(NOUN="RED", ADJ="RED",DET ="GREEn",DEMON ="GREEN", NSUFF="ORANGE", VSUFF="ORANGE", ADJSUFF="ORANGE") > # print html head > def print_html_head(): > #print the head of the html page > > def print_html_tail(): > # print the tail of the html page > > def color(segment, color): > # STUCK HERE shoudl take a color, and a segment for example > > # main > import sys > infile = open(sys.argv[1]) # takes as input the POS-tagged file > print_html_head() > for line in infile: > line = line.split() > if len(line) != 2: continue > word = line[0] > pos = line[1] > zipped = zip(word.split("+"), pos.split("+")) > > for x, y in zipped: > if y in DET: > color(x, "#FF0000") > else: > color(x, "#0000FF") > > > print_html_tail() > > > > > -- > ?? ???? ?????? ????? ????? ??? ???? ??? ????? ?? ?????? > ????????.....???? ??????? > "No victim has ever been more repressed and alienated than the truth" > > Emad Soliman Nawfal > Indiana University, Bloomington > -------------------------------------------------------- > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Bob Gailer Chapel Hill NC 919-636-4239 From roadierich at googlemail.com Thu Sep 17 19:39:15 2009 From: roadierich at googlemail.com (Rich Lovely) Date: Thu, 17 Sep 2009 18:39:15 +0100 Subject: [Tutor] max min value in array In-Reply-To: <1c2a2c590909171018w5039893fx4557ede5d7b58d84@mail.gmail.com> References: <1c2a2c590909170534i6748b2a1k84a5d7db379d40a5@mail.gmail.com> <4AB24F30.5010307@lonetwin.net> <1c2a2c590909171018w5039893fx4557ede5d7b58d84@mail.gmail.com> Message-ID: 2009/9/17 Kent Johnson : > On Thu, Sep 17, 2009 at 11:01 AM, steve wrote: >> On 09/17/2009 06:04 PM, Kent Johnson wrote: >>> >>> On Thu, Sep 17, 2009 at 8:06 AM, Rich Lovely >>> ?wrote: >>>> >>>> ?2009/9/17 Rayon: >>>>> >>>>> ?I need to find the max and min value from some floats in a array: >>> >>>> ?Depending on the size of the array, there's two methods: ?Using the >>>> ?max and min builtin functions, which will be faster for small arrays, >>>> ?or hand-coding a single pass function, which might be faster for >>>> ?arrays above a certain size. >>> >>> Why do you expect a hand-coded function to scale better? I would >>> expect them both to be O(n). >>> >> I guess what Rich meant was, a hand-coded function to get /both/ min and max >> in a single pass would be faster on large arrays (as done in the posted >> minmax2() function) than calling min() and max() individually (which would >> imply 2 passes). > > Yes, that is my understanding of his statement. My question is, why > would it be faster only on large arrays? I expect the time of both > methods to scale linearly with the size of the array. Two fast passes > might be faster than one slow pass regardless of the size of the > array. > > Kent > Hmm... I obviously didn't sprinkle round enough hints of my uncertainty in the matter. I did, however, suggest that the OPer profiles both to check. I was assuming that would cover all the bases. Even if I do provide full, working functions, I'm not going to spoon feed anyone a "fait accomplis". I'm still learning too... hence the 'tutor' mailing list, not the 'expert' mailing list. Perhaps I was wrong on which would be faster, to be honest, I don't care that much: if anyone is really worried about speed, they're using the wrong language. Perhaps that's the wrong stance to take, but again, I don't care that much. I always try to make it clear when I'm not certain about a matter. If I have ever misled anyone, I can only apologise. -- Rich "Roadie Rich" Lovely There are 10 types of people in the world: those who know binary, those who do not, and those who are off by one. From alan.gauld at btinternet.com Thu Sep 17 19:37:30 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 17 Sep 2009 18:37:30 +0100 Subject: [Tutor] Using the time module to extract a semi-random number References: <33C44C4434B141968C827B32AF2902E2@COMPUTER01> <4AB1F843.1060206@gmail.com> Message-ID: "Patrick Sabin" wrote > import random > number = random.randint(0,59) > > The latter looks clearer to me. Me too, but if the object is to get the learner using the time module it doesn't help! :-) But if the object is really to get a random number then its much better... Alan G. From emadnawfal at gmail.com Thu Sep 17 20:03:38 2009 From: emadnawfal at gmail.com (=?UTF-8?B?RW1hZCBOYXdmYWwgKNi52YXYp9ivINmG2YjZgdmEKQ==?=) Date: Thu, 17 Sep 2009 14:03:38 -0400 Subject: [Tutor] html color coding: where to start In-Reply-To: <4AB273A9.8080409@gmail.com> References: <652641e90909170844x4c781916j62921debe09da349@mail.gmail.com> <4AB273A9.8080409@gmail.com> Message-ID: <652641e90909171103h5333ac99o16b83fd40a37ef50@mail.gmail.com> 2009/9/17 bob gailer > Emad Nawfal (???? ????) wrote: > >> Hi Tutors, >> I want to color-code the different parts of the word in a morphologically >> complex natural language. The file I have looks like this, where the fisrt >> column is the word, and the second is the composite part of speech tag. For >> example, Al is a DETERMINER, wlAy is a NOUN and At is a PLURAL NOUN SUFFIX >> >> Al+wlAy+At DET+NOUN+NSUFF_FEM_PL >> Al+mtHd+p DET+ADJ+NSUFF_FEM_SG >> >> The output I want is one on which the word has no plus signs, and each >> segment is color-coded with a grammatical category. For example, the noun is >> red, the det is green, and the suffix is orange. Like on this page here: >> http://docs.google.com/View?id=df7jv9p9_3582pt63cc4 >> I am stuck with the html part and I don't know where to start. I have no >> experience with html, but I have this skeleton (which may not be the right >> thing any way) >> Any help with materials, modules, suggestions appreciated. >> >> This skeleton of my program is as follows: >> >> ############# >> RED = ("NOUN", "ADJ") >> GREEN = ("DET", "DEMON") >> ORANGE = ("NSUFF", "VSUFF", "ADJSUFF") >> > > Instead of that use a dictionary: > > colors = dict(NOUN="RED", ADJ="RED",DET ="GREEn",DEMON ="GREEN", > NSUFF="ORANGE", VSUFF="ORANGE", ADJSUFF="ORANGE") > >> # print html head >> def print_html_head(): >> #print the head of the html page >> def print_html_tail(): >> # print the tail of the html page >> >> def color(segment, color): >> # STUCK HERE shoudl take a color, and a segment for example >> >> # main >> import sys >> infile = open(sys.argv[1]) # takes as input the POS-tagged file >> print_html_head() >> for line in infile: >> line = line.split() >> if len(line) != 2: continue >> word = line[0] >> pos = line[1] >> zipped = zip(word.split("+"), pos.split("+")) >> for x, y in zipped: >> if y in DET: >> color(x, "#FF0000") >> else: >> color(x, "#0000FF") >> >> print_html_tail() >> >> >> >> -- >> ?? ???? ?????? ????? ????? ??? ???? ??? ????? ?? ?????? ????????.....???? >> ??????? >> "No victim has ever been more repressed and alienated than the truth" >> >> Emad Soliman Nawfal >> Indiana University, Bloomington >> -------------------------------------------------------- >> ------------------------------------------------------------------------ >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> >> > > > -- > Bob Gailer > Chapel Hill NC > 919-636-4239 > Thank you all. This is great help. I just started looking into html two days ago. Thank you again. -- ?? ???? ?????? ????? ????? ??? ???? ??? ????? ?? ?????? ????????.....???? ??????? "No victim has ever been more repressed and alienated than the truth" Emad Soliman Nawfal Indiana University, Bloomington -------------------------------------------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: From admin at gg-lab.net Thu Sep 17 21:47:29 2009 From: admin at gg-lab.net (admin at gg-lab.net) Date: Thu, 17 Sep 2009 21:47:29 +0200 Subject: [Tutor] Still Trying to Understand GAE In-Reply-To: <1c2a2c590909170613g4c7dde5eka9f8eb380658245d@mail.gmail.com> References: <48758b600909130659r48eb2771s2568eaae2d12e454@mail.gmail.com> <1c2a2c590909160516l45eb8da9v96490fbe1641c576@mail.gmail.com> <48758b600909170538h6ba51e37x26894bba37a781f6@mail.gmail.com> <1c2a2c590909170613g4c7dde5eka9f8eb380658245d@mail.gmail.com> Message-ID: <48758b600909171247o48c917eag74d8a91df20743ee@mail.gmail.com> Yes Kent, i'm not worrying about it, i was just trying to find the reason why they're doing so. Anyway, i'm a newbye, but the GAE Evinronment is very very difficult to understand. The only thing is thas in common with the real python is the sintax. Thankyou again 2009/9/17 Kent Johnson : > On Thu, Sep 17, 2009 at 8:38 AM, admin at gg-lab.net wrote: >> Thankyou all, you're very precious for me. >> >> yeah it seems the development webserver (and the production one) are >> importing modules in a non-standard way. >> >> I absolutely don't understand this choice. Why import everything >> everytime? Don't you think it makes scripts much more slow? > > My guess is that they are importing what they need. It does impact > startup but hey, if you need it, you need it. > > Try this for comparison: Start Python from a command line, then > In [5]: import sys > > In [6]: len(sys.modules) > Out[6]: 323 > > I have IPython loaded so this number may be larger than yours. In > Python 3, with no IPython, I get >>>> import sys >>>> len(sys.modules) > 47 > > So my advice is, don't worry about it. > > Kent > From kb1pkl at aim.com Thu Sep 17 22:35:40 2009 From: kb1pkl at aim.com (Corey Richardson) Date: Thu, 17 Sep 2009 16:35:40 -0400 Subject: [Tutor] Simple Program In-Reply-To: References: Message-ID: <4AB29D9C.4060105@aim.com> I'm going to be making a simple program, that is a few books like "A is for...", "B is for...", but it will be many built into one, with a some sort of define(word) command, some sort of a find(word) command, and a few others. Looking for people to contribute, and make this a community thing, maybe each doing our own small 'chapter' or the 'book'. I also don't know if it is quite appropriate for this list, so forgive me if it isn't, and ignore it. Also, Alan, your tutorial is the bomb! Some of the simpler things I've seen done better, but you do an amazing job with it. It helps alot! -------------- next part -------------- A non-text attachment was scrubbed... Name: kb1pkl.vcf Type: text/x-vcard Size: 55 bytes Desc: not available URL: From fragos.george at gmail.com Thu Sep 17 23:27:56 2009 From: fragos.george at gmail.com (george fragos) Date: Fri, 18 Sep 2009 00:27:56 +0300 Subject: [Tutor] On slicing In-Reply-To: References: <53008aa80909170221h461b07b9ya2261ecd1a0109ac@mail.gmail.com> Message-ID: <53008aa80909171427g5f970ecs84b1ee44c57f082a@mail.gmail.com> 2009/9/17 Rich Lovely : > 2009/9/17 george fragos : >> ?If numbers=[1,2,3,4,5,6,7,8,9,10] and since "...any time the >> leftmost index in a slice comes later in the seqence than the second >> one... the result is always an empty sequence", why the slice >> numbers[10:0:-2] produces the sequence [10,8,6,4,2] but not the >> sequence []? >> _______________________________________________ >> Tutor maillist ?- ?Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> > > There should be a caveat to that: ?Unless the third index (step) is negative. > > The first value is start, the second stop, and the third step. ?What > you are saying with numbers[10,0,-2], is start at 10 (facing towards > the end of the sequence), keep going until you get to 0, taking two > steps backwards each time. > > I hope that clears things up a little.. > > -- > Rich "Roadie Rich" Lovely > > There are 10 types of people in the world: those who know binary, > those who do not, and those who are off by one. > Thanx for your reply...! By the way, I'd like to say hallo to the List and state that I'm just starting with Python...! George Fragos From alan.gauld at btinternet.com Fri Sep 18 00:43:08 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 17 Sep 2009 23:43:08 +0100 Subject: [Tutor] Simple Program References: <4AB29D9C.4060105@aim.com> Message-ID: "Corey Richardson" wrote > I'm going to be making a simple program, that is a few books like "A is > for...", "B is for...", but it will be many built into one, Sorry, I don't understand? > sort of define(word) command, some sort of a find(word) command, and a > few others. That's fine, although technically those will be functions not commands. But that's nit picking :-) > isn't, and ignore it. Also, Alan, your tutorial is the bomb! Some of the > simpler things I've seen done better, but you do an amazing job with it. Thanks for the kind words. If you can offer ideas for improvement I'm always happy to hear. Thats how it improves! And since I;m still working on the latest update for v3 its a good time for suggestions! -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From kent37 at tds.net Fri Sep 18 01:24:42 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 17 Sep 2009 19:24:42 -0400 Subject: [Tutor] html color coding: where to start In-Reply-To: <652641e90909170844x4c781916j62921debe09da349@mail.gmail.com> References: <652641e90909170844x4c781916j62921debe09da349@mail.gmail.com> Message-ID: <1c2a2c590909171624y45e25c5x13d36f1ea1f0543a@mail.gmail.com> 2009/9/17 Emad Nawfal (???? ????) : > Hi Tutors, > I want to color-code the different parts of the word in a morphologically > complex natural language. The file I have looks like this, where the fisrt > column is the word, and the? second is the composite part of speech tag. For > example, Al is a DETERMINER, wlAy is a NOUN and At is a PLURAL NOUN SUFFIX > > Al+wlAy+At??????? DET+NOUN+NSUFF_FEM_PL > Al+mtHd+p??????? DET+ADJ+NSUFF_FEM_SG > > The output I want is one on which the word has no plus signs, and each > segment is color-coded with a grammatical category. For example, the noun is > red, the det is green, and the suffix is orange.? Like on this page here: > http://docs.google.com/View?id=df7jv9p9_3582pt63cc4 Here is an example that duplicates your google doc and generates fairly clean, idiomatic HTML. It requires the HTML generation package from http://pypi.python.org/pypi/html/1.4 from html import HTML lines = ''' Al+wlAy+At DET+NOUN+NSUFF_FEM_PL Al+mtHd+p DET+ADJ+NSUFF_FEM_SG '''.splitlines() # Define colors in a CSS stylesheet styles = ''' .NOUN {color: red } .ADJ {color: brown } .DET {color: green} .NSUFF_FEM_PL, .NSUFF_FEM_SG {color: blue} ''' h = HTML() with h.html: with h.head: h.title("Example") h.style(styles) with h.body(newlines=True): for line in lines: line = line.split() if len(line) != 2: continue word = line[0] pos = line[1] zipped = zip(word.split("+"), pos.split("+")) for part, kind in zipped: h.span(part, klass=kind) h.br print h Kent From gslindstrom at gmail.com Fri Sep 18 01:29:02 2009 From: gslindstrom at gmail.com (Greg Lindstrom) Date: Thu, 17 Sep 2009 18:29:02 -0500 Subject: [Tutor] PyCon 2010 (Atlanta) Call For Tutorials Message-ID: The period to submit proposals for PyCon 2010 in Atlanta is open until October 18th. Tutorial are held the two days prior to the main conference and feature 3-hour classes led by fellow Python developers and enthusiasts *just like you*. Any topic relating to Python is allowed and the organizers encourage anyone who wants to share their knowledge to submit their ideas for consideration. Perennial classes include "Introduction to Python" for various audiences (beginners, programmers, those new to Django and web frameworks, etc.), intermediate Python (standard library, module/packages, objects, etc.) and more specialized topics (SciPy/Matlab, unit and web testing, optimization) as well as general topics such as "Best Practices" for web programming, objects, libraries. There is even interest in a class to show how to organize, design, write and distribute an Open Source project. Any topic relating to Python is eligible. Tutorial teachers are paid $1,000.00 per class for their efforts. Interested (we hope so!)? More information is available at http://us.pycon.org/2010/tutorials/proposals/ or write us at pycon-tutorials at python.org. We look forward to hearing from YOU. Greg Lindstrom Tutorial Coordinator, PyCon 2010 (Atlanta) -------------- next part -------------- An HTML attachment was scrubbed... URL: From ansuman.dash at gmail.com Fri Sep 18 06:05:04 2009 From: ansuman.dash at gmail.com (Ansuman Dash) Date: Fri, 18 Sep 2009 09:35:04 +0530 Subject: [Tutor] Executing a command from a specific directory In-Reply-To: <1c2a2c590909170632r6d19e544sae4111fed4a9ca43@mail.gmail.com> References: <8c0cfa60909150431u705ea8b2vbbaadefafb3ee9ac@mail.gmail.com> <8c0cfa60909152303w7b795ecci43db03bad7930ccd@mail.gmail.com> <4AB092FD.8000604@gmail.com> <8c0cfa60909160533y2456b160jdc39e4510f30d203@mail.gmail.com> <4AB12FEE.3030107@ieee.org> <20090916184335.GA86967@dragon.alchemy.com> <8c0cfa60909170247k138a8756xecd8cf6ddf63840@mail.gmail.com> <1c2a2c590909170504y6942318eu1fa8a32a59ea5d18@mail.gmail.com> <8c0cfa60909170540u2ee36083ya3f84a46ec6b6b65@mail.gmail.com> <1c2a2c590909170632r6d19e544sae4111fed4a9ca43@mail.gmail.com> Message-ID: <8c0cfa60909172105y3e7a6bd9g24528cdad64070a0@mail.gmail.com> I am downloading files using various command (because files are different) meant for a executable. So I have created event driven program to download these files one by one. But some files are very huge so I want to know how can I synchronize it with my code. That means I want to make my code wait for the complete download of that file and then I ll read the log file and validate that download is successful. Thanks, AD On Thu, Sep 17, 2009 at 7:02 PM, Kent Johnson wrote: > On Thu, Sep 17, 2009 at 8:40 AM, Ansuman Dash > wrote: > > I am using same process for multiple file download. So I need to download > > those one by one. > > > > Moreover some files are very huge (around 120 MB). So I need to make > script > > to wait before verifying the file is downloaded. > > I don't understand how you are downloading the files. Can you show some > code? > > Kent > -------------- next part -------------- An HTML attachment was scrubbed... URL: From lie.1296 at gmail.com Fri Sep 18 08:51:09 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Fri, 18 Sep 2009 16:51:09 +1000 Subject: [Tutor] Executing a command from a specific directory In-Reply-To: <8c0cfa60909172105y3e7a6bd9g24528cdad64070a0@mail.gmail.com> References: <8c0cfa60909150431u705ea8b2vbbaadefafb3ee9ac@mail.gmail.com> <8c0cfa60909152303w7b795ecci43db03bad7930ccd@mail.gmail.com> <4AB092FD.8000604@gmail.com> <8c0cfa60909160533y2456b160jdc39e4510f30d203@mail.gmail.com> <4AB12FEE.3030107@ieee.org> <20090916184335.GA86967@dragon.alchemy.com> <8c0cfa60909170247k138a8756xecd8cf6ddf63840@mail.gmail.com> <1c2a2c590909170504y6942318eu1fa8a32a59ea5d18@mail.gmail.com> <8c0cfa60909170540u2ee36083ya3f84a46ec6b6b65@mail.gmail.com> <1c2a2c590909170632r6d19e544sae4111fed4a9ca43@mail.gmail.com> <8c0cfa60909172105y3e7a6bd9g24528cdad64070a0@mail.gmail.com> Message-ID: Ansuman Dash wrote: > I am downloading files using various command (because files are > different) meant for a executable. What is "various commands"? Are you using wget/curl or similar command-line downloader programs? Or are you using a python-based script (that uses urllib)? Or are you using a GUI-based downloader? Then how do you invoke those "various commands"? Are you using a separate python and subprocess/popen to invoke them? Or are you using shell script? Or do you start them manually? > So I have created event driven program to download these files one by > one. But some files are very huge so I want to know how can I > synchronize it with my code. Can you modify this "event driven program" so it would call your script when the files finished downloading? > That means I want to make my code wait for the complete download of that > file and then I ll read the log file and validate that download is > successful. From ansuman.dash at gmail.com Fri Sep 18 11:16:23 2009 From: ansuman.dash at gmail.com (Ansuman Dash) Date: Fri, 18 Sep 2009 14:46:23 +0530 Subject: [Tutor] Executing a command from a specific directory In-Reply-To: References: <8c0cfa60909150431u705ea8b2vbbaadefafb3ee9ac@mail.gmail.com> <8c0cfa60909160533y2456b160jdc39e4510f30d203@mail.gmail.com> <4AB12FEE.3030107@ieee.org> <20090916184335.GA86967@dragon.alchemy.com> <8c0cfa60909170247k138a8756xecd8cf6ddf63840@mail.gmail.com> <1c2a2c590909170504y6942318eu1fa8a32a59ea5d18@mail.gmail.com> <8c0cfa60909170540u2ee36083ya3f84a46ec6b6b65@mail.gmail.com> <1c2a2c590909170632r6d19e544sae4111fed4a9ca43@mail.gmail.com> <8c0cfa60909172105y3e7a6bd9g24528cdad64070a0@mail.gmail.com> Message-ID: <8c0cfa60909180216u738764bq13f1ce347b30aa62@mail.gmail.com> Hi, I have written it like that. It is like press 1 and it ll download file1 and press 2 it ll download file2 etc.... But my question was I am using "time.sleep()" to make my script to wait for the file download and then validate it in log file, so is there any other way I can synchronize my code with the download. I am asking this because some files are very huge (120MB) and download also depends on N/W bandwidth so sometimes it ll be done in 30mins and some times it takes 60 mins. So I can't rely on "time.sleep()" Thanks, Ansu On Fri, Sep 18, 2009 at 12:21 PM, Lie Ryan wrote: > Ansuman Dash wrote: > >> I am downloading files using various command (because files are different) >> meant for a executable. >> > > What is "various commands"? Are you using wget/curl or similar command-line > downloader programs? Or are you using a python-based script (that uses > urllib)? Or are you using a GUI-based downloader? > > Then how do you invoke those "various commands"? Are you using a separate > python and subprocess/popen to invoke them? Or are you using shell script? > Or do you start them manually? > > So I have created event driven program to download these files one by one. >> But some files are very huge so I want to know how can I synchronize it with >> my code. >> > > Can you modify this "event driven program" so it would call your script > when the files finished downloading? > > That means I want to make my code wait for the complete download of that >> file and then I ll read the log file and validate that download is >> successful. >> > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From emadnawfal at gmail.com Fri Sep 18 11:49:50 2009 From: emadnawfal at gmail.com (=?UTF-8?B?RW1hZCBOYXdmYWwgKNi52YXYp9ivINmG2YjZgdmEKQ==?=) Date: Fri, 18 Sep 2009 05:49:50 -0400 Subject: [Tutor] html color coding: where to start In-Reply-To: <1c2a2c590909171624y45e25c5x13d36f1ea1f0543a@mail.gmail.com> References: <652641e90909170844x4c781916j62921debe09da349@mail.gmail.com> <1c2a2c590909171624y45e25c5x13d36f1ea1f0543a@mail.gmail.com> Message-ID: <652641e90909180249l3050dba7k3c5aa431e5c9e96a@mail.gmail.com> On Thu, Sep 17, 2009 at 7:24 PM, Kent Johnson wrote: > 2009/9/17 Emad Nawfal (???? ????) : > > Hi Tutors, > > I want to color-code the different parts of the word in a morphologically > > complex natural language. The file I have looks like this, where the > fisrt > > column is the word, and the second is the composite part of speech tag. > For > > example, Al is a DETERMINER, wlAy is a NOUN and At is a PLURAL NOUN > SUFFIX > > > > Al+wlAy+At DET+NOUN+NSUFF_FEM_PL > > Al+mtHd+p DET+ADJ+NSUFF_FEM_SG > > > > The output I want is one on which the word has no plus signs, and each > > segment is color-coded with a grammatical category. For example, the noun > is > > red, the det is green, and the suffix is orange. Like on this page here: > > http://docs.google.com/View?id=df7jv9p9_3582pt63cc4 > > Here is an example that duplicates your google doc and generates > fairly clean, idiomatic HTML. It requires the HTML generation package > from > http://pypi.python.org/pypi/html/1.4 > > from html import HTML > > lines = ''' > Al+wlAy+At DET+NOUN+NSUFF_FEM_PL > Al+mtHd+p DET+ADJ+NSUFF_FEM_SG > '''.splitlines() > > # Define colors in a CSS stylesheet > styles = ''' > .NOUN > {color: red } > > .ADJ > {color: brown } > > .DET > {color: green} > > .NSUFF_FEM_PL, .NSUFF_FEM_SG > {color: blue} > ''' > > h = HTML() > > with h.html: > with h.head: > h.title("Example") > h.style(styles) > > with h.body(newlines=True): > for line in lines: > line = line.split() > if len(line) != 2: continue > word = line[0] > pos = line[1] > zipped = zip(word.split("+"), pos.split("+")) > > for part, kind in zipped: > h.span(part, klass=kind) > h.br > > print h > > > Kent > Thank you Kent, and all, for the wonderful advice and contribution. -- ?? ???? ?????? ????? ????? ??? ???? ??? ????? ?? ?????? ????????.....???? ??????? "No victim has ever been more repressed and alienated than the truth" Emad Soliman Nawfal Indiana University, Bloomington -------------------------------------------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: From lie.1296 at gmail.com Fri Sep 18 11:57:19 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Fri, 18 Sep 2009 19:57:19 +1000 Subject: [Tutor] Executing a command from a specific directory In-Reply-To: <8c0cfa60909180216u738764bq13f1ce347b30aa62@mail.gmail.com> References: <8c0cfa60909150431u705ea8b2vbbaadefafb3ee9ac@mail.gmail.com> <8c0cfa60909160533y2456b160jdc39e4510f30d203@mail.gmail.com> <4AB12FEE.3030107@ieee.org> <20090916184335.GA86967@dragon.alchemy.com> <8c0cfa60909170247k138a8756xecd8cf6ddf63840@mail.gmail.com> <1c2a2c590909170504y6942318eu1fa8a32a59ea5d18@mail.gmail.com> <8c0cfa60909170540u2ee36083ya3f84a46ec6b6b65@mail.gmail.com> <1c2a2c590909170632r6d19e544sae4111fed4a9ca43@mail.gmail.com> <8c0cfa60909172105y3e7a6bd9g24528cdad64070a0@mail.gmail.com> <8c0cfa60909180216u738764bq13f1ce347b30aa62@mail.gmail.com> Message-ID: Ansuman Dash wrote: > Hi, > > I have written it like that. It is like press 1 and it ll download file1 > and press 2 it ll download file2 etc.... What is "like that"? We are not psychic that could read your mind... Describe the way you downloaded the file. From sander.sweers at gmail.com Fri Sep 18 11:58:47 2009 From: sander.sweers at gmail.com (Sander Sweers) Date: Fri, 18 Sep 2009 11:58:47 +0200 Subject: [Tutor] Executing a command from a specific directory In-Reply-To: <8c0cfa60909180216u738764bq13f1ce347b30aa62@mail.gmail.com> References: <8c0cfa60909150431u705ea8b2vbbaadefafb3ee9ac@mail.gmail.com> <8c0cfa60909160533y2456b160jdc39e4510f30d203@mail.gmail.com> <4AB12FEE.3030107@ieee.org> <20090916184335.GA86967@dragon.alchemy.com> <8c0cfa60909170247k138a8756xecd8cf6ddf63840@mail.gmail.com> <1c2a2c590909170504y6942318eu1fa8a32a59ea5d18@mail.gmail.com> <8c0cfa60909170540u2ee36083ya3f84a46ec6b6b65@mail.gmail.com> <1c2a2c590909170632r6d19e544sae4111fed4a9ca43@mail.gmail.com> <8c0cfa60909172105y3e7a6bd9g24528cdad64070a0@mail.gmail.com> <8c0cfa60909180216u738764bq13f1ce347b30aa62@mail.gmail.com> Message-ID: <1253267927.11231.24.camel@infirit.homelinux.org> On Fri, 2009-09-18 at 14:46 +0530, Ansuman Dash wrote: > I have written it like that. It is like press 1 and it ll download > file1 and > press 2 it ll download file2 etc.... But without providing people how you accomplish this there is no way to help. > But my question was I am using "time.sleep()" to make my script to > wait for > the file download and then validate it in log file, so is there any > other > way I can synchronize my code with the download. This depends on how you are doing this. But *assuming* you are using subprocess you can check the returncode from the Popen object. When the return code is None the command is still running. Greets Sander A: Because it messes up the order in which people normally read text. Q: Why is top-posting such a bad thing? A: Top-posting. Q: What is the most annoying thing in e-mail? From kent37 at tds.net Fri Sep 18 13:01:48 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 18 Sep 2009 07:01:48 -0400 Subject: [Tutor] Using the time module to extract a semi-random number In-Reply-To: <832E6E4405434428B238D27C784A9427@COMPUTER01> References: <33C44C4434B141968C827B32AF2902E2@COMPUTER01> <1c2a2c590909162019l364b516cifcd2e0befe2adc87@mail.gmail.com> <832E6E4405434428B238D27C784A9427@COMPUTER01> Message-ID: <1c2a2c590909180401x727dceafw714aa102b76daedd@mail.gmail.com> On Thu, Sep 17, 2009 at 4:59 PM, Katt wrote: > > ----- Original Message ----- From: "Kent Johnson" >> time.localtime().tm_sec will give you the number of >seconds as an >> integer without any conversions. > > Thank you for your quick response. ?I didn't expect to get a response for a > couple of days. > > As you know from the others that responded there are a couple of ways that > it could be done. ?I am curious as to which one is more efficient. > > Your solution was: > ?number = time.localtime().tm_sec > > The other solutions were > ?number = int(time.strftime("%S") > ?number = int(time.strftime("%S"(time.localtime())) > > Is it that the program could access yours faster than the others? Or is it > that there are many ways to accomplish things in python and no one is better > than the other? They will all be fast enough that it doesn't matter. My guess is that if you timed them (with the timeit module) my solution would be faster because it doesn't require converting the time to a string and back to an integer, but that is just a guess. The second two are equivalent because strftime() uses localtime() as the time if it is not provided. You should use whichever one you feel is more readable and expressive. Kent PS Please Reply All to reply to the list. From igor.mavrovic at irb.hr Fri Sep 18 14:52:10 2009 From: igor.mavrovic at irb.hr (=?UTF-8?Q?Igor_Mavrovi=C4=87_-_Maqui@IRB?=) Date: Fri, 18 Sep 2009 14:52:10 +0200 Subject: [Tutor] Fw: utf locale sorting References: <502C9A373AD94621ADF80C60150B53FE@MaquijevaKanta> <1c2a2c590909160733o66d8248ei877cf92e1b5f6275@mail.gmail.com> <1c2a2c590909161006x4d015e82h694dec6673dfe038@mail.gmail.com> Message-ID: <636D6C49FEBD48CF96258839080B3DC6@MaquijevaKanta> Excellent, the thing works! Thanx a lot! ----- Original Message ----- From: Kent Johnson To: Igor Mavrovi? - Maqui at IRB Cc: Rich Lovely ; tutor at python.org Sent: Wednesday, September 16, 2009 7:06 PM Subject: Re: [Tutor] Fw: utf locale sorting How about this (assuming both arguments need to be transformed)? key=lambda x:(locale.strxfrm(x[0][1]["sn"]), locale.strxfrm(x[0][1]["givenName"])) Kent __________ Information from ESET Smart Security, version of virus signature database 4429 (20090916) __________ The message was checked by ESET Smart Security. http://www.eset.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From ales at otonicar.com Fri Sep 18 14:44:12 2009 From: ales at otonicar.com (Otonicar Ales) Date: Fri, 18 Sep 2009 05:44:12 -0700 (MST) Subject: [Tutor] Calling VB.NET code with Python .. VB.net - Python integration .. In-Reply-To: <12373774.451881253277530425.JavaMail.root@mail5c.brinkster.com> Message-ID: <16099583.452011253277852014.JavaMail.root@mail5c.brinkster.com> The idea is that Python calls VB.net program. VB.Net program gets data and than forward data back to Python for further processing.. One way to do this is by compiling vb.net program to exe. And than call exe by Python code. Data exchange goes via Access Data Base (Python write in MC Access, vb get data a n d than write it to?MC access, Python reads final data from MC access). In this case I will need Python command to run exe which is?enable Python waiting until exe is not finished.. In case anybody?out-there?has better idea how directly communicate with vb.net program (exchanging data? with v ariables - code integration) ?please send code sample with a bit of explanation .. VB.Net program is very long as it communicate with external provider API. I will change?the program on load part of the code (using Visual Studio 2008).?Change?will make program?working hidden - not visable, using data in MC Access. Currently program works?as on Screen program with forms and buttons. This part is easy. Best connection with Python is still open debate .. Cheers,?? Ales -------------- next part -------------- An HTML attachment was scrubbed... URL: From kurt at tool.net Fri Sep 18 16:35:21 2009 From: kurt at tool.net (Kurt Bendl) Date: Fri, 18 Sep 2009 10:35:21 -0400 Subject: [Tutor] Executing a command from a specific directory In-Reply-To: <8c0cfa60909180216u738764bq13f1ce347b30aa62@mail.gmail.com> References: <8c0cfa60909150431u705ea8b2vbbaadefafb3ee9ac@mail.gmail.com> <8c0cfa60909160533y2456b160jdc39e4510f30d203@mail.gmail.com> <4AB12FEE.3030107@ieee.org> <20090916184335.GA86967@dragon.alchemy.com> <8c0cfa60909170247k138a8756xecd8cf6ddf63840@mail.gmail.com> <1c2a2c590909170504y6942318eu1fa8a32a59ea5d18@mail.gmail.com> <8c0cfa60909170540u2ee36083ya3f84a46ec6b6b65@mail.gmail.com> <1c2a2c590909170632r6d19e544sae4111fed4a9ca43@mail.gmail.com> <8c0cfa60909172105y3e7a6bd9g24528cdad64070a0@mail.gmail.com> <8c0cfa60909180216u738764bq13f1ce347b30aa62@mail.gmail.com> Message-ID: Hello, On Sep 18, 2009, at 5:16 AM, Ansuman Dash wrote: > I have written it like that. It is like press 1 and it ll download > file1 and press 2 it ll download file2 etc.... > > But my question was I am using "time.sleep()" to make my script to > wait for the file download and then validate it in log file, so is > there any other way I can synchronize my code with the download. > > I am asking this because some files are very huge (120MB) and > download also depends on N/W bandwidth so sometimes it ll be done in > 30mins and some times it takes 60 mins. So I can't rely on > "time.sleep()" I had a similar problem. I used pyinotify on a linux box. inotify is a kernel hook that you can use to trigger actions on events... like when a file write is completed. Note: I'm a total hack at this. I'm sure there's a more elegant way to do what I'm dong, but I needed a fix fast, and this worked for me. I'd appreciate any tips anyone has to offer to make this cleaner and/or more pythonic. :-) I'll be glad to try to answer any questions about this hackery. Best, Kurt Here's a slightly cut-down version of my code: http://pastebin.com/f239b0413 inotify_published_file_handler.py ##################################################### #!/usr/bin/env python # -*- coding: utf-8 -*- # encoding: utf-8 """ inotify_published_file_handler.py rev. 20090706-01 ---- Created by Kurt Bendl. Usage --------- sudo su - www-data -c 'cd /web/log/; \ nohup /web/scripts/inotify_published_file_handler.py > \ /web/log/inotify-errors.txt 2>&1 &' Purpose --------- Monitor the $WEBROOT/aapracing/import/publish directory. Once a file is closed, act on it: 1. Copy the PDF and XML files from source_dir to web_filebin_dir 2. If the file is an.XML, copy it to the xml_ftp_dir 3. Make the dummy file for PHP publishing process 4. Remove the source file Requirements ------------ * Linux kernel 2.6.13 + * pyinotify 2.8.6 + Installation -------------- To install pyinotify on ubuntu/debian: `sudo easy_install pyinotify` Docs ----- Docs on pyinotify can be found here: http://trac.dbzteam.org/pyinotify/wiki """ import os import re import shutil import pyinotify import datetime ### production config info source_dir = "/web/site/aapracing/publish/data/publish/" web_filebin_dir = "/web/site/filebin/downloads/" reference_path = '/web/site/aapracing/publish/data/published/' xml_ftp_dir = "/home/ftp/private/xml/" filez = '(PDF|pdf|XML|xml|txt)' logfile_path = "/web/log/inotify.log" event_mask = pyinotify.IN_CLOSE_WRITE wm = pyinotify.WatchManager() def getNow(): """Just return the current time for timestamping logs""" return datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") def makeReferenceFile(tfile): open(tfile, 'w').close() class SourceMonitor(pyinotify.ProcessEvent): """ Watches the source dir for IN_CLOSE_WRITE event""" def process_IN_CLOSE_WRITE(self, event): """when an IN_CLOSE_WRITE happens, do something""" if re.search('(.*\.'+filez+'$)', event.pathname): # We have a match, put a copy into the filebin dir shutil.copy2(event.pathname, web_filebin_dir) logfile = open(logfile_path, "a") logfile.write("%s: %s moved to %s. \n" % (getNow(), event.pathname, web_filebin_dir)) if re.search('(.*\.(XML|xml)$)', event.pathname): # If it's and XML, put a copy in the FTP dir shutil.copy2(event.pathname, xml_ftp_dir) logfile.write("%s: %s moved to %s. \n" % (getNow(), event.pathname, xml_ftp_dir)) # Make the dummy file marker to enable PHP # to know the file is really published fhandle = os.path.basename(event.pathname) open(reference_path + fhandle, 'w').close() # Now, whack the source file since we're done with it. os.remove(event.pathname) p = SourceMonitor() notifier = pyinotify.Notifier(wm, p) wdd = wm.add_watch(source_dir, event_mask) print "This should have been started with:\n\n" print " sudo su - www-data -c 'cd /web/log/; nohup /web/scripts/ inotify_published_file_handler.py > /web/log/inotify-errors.txt 2>&1 &' \n\n" notifier.loop() -- Kurt Bendl, Consultant Internet Tool & Die http://tool.net/ 502-759-7104 From krissy.ambert at gmail.com Fri Sep 18 17:08:38 2009 From: krissy.ambert at gmail.com (Kristina Ambert) Date: Fri, 18 Sep 2009 11:08:38 -0400 Subject: [Tutor] ODBC SQL Server Question Message-ID: Hi, Is anyone familiar with this error: dbi.internal-error: [Microsoft][SQL Server Driver]Invalid cursor state in EXEC This error is triggered by the first sql statement call in an accessor module which purpose is only to get data from a source module and feed it into a database: self.cursor.execute("SELECT CUSTID FROM Stories WHERE NAME= ?", (name)) I can't figure out what's causing it. I searched for the invalid cursor state error online but most of it occurs on the fetchall statement not the execute statement. Any ideas? Thanks! -- Cheers, Krissy ----------------------------------------------------------------------- Testing the waters is always fun... -------------- next part -------------- An HTML attachment was scrubbed... URL: From jeff at dcsoftware.com Fri Sep 18 17:49:24 2009 From: jeff at dcsoftware.com (Jeff Johnson) Date: Fri, 18 Sep 2009 08:49:24 -0700 Subject: [Tutor] ODBC SQL Server Question In-Reply-To: References: Message-ID: <4AB3AC04.20901@dcsoftware.com> Kristina: I would format it as follows: self.cursor.execute("SELECT CUSTID FROM Stories WHERE NAME = '%s'" % name) Kristina Ambert wrote: > Hi, > Is anyone familiar with this error: > dbi.internal-error: [Microsoft][SQL Server Driver]Invalid cursor state > in EXEC > This error is triggered by the first sql statement call in an accessor > module which purpose is only to get data from a source module and feed > it into a database: > > self.cursor.execute("SELECT CUSTID FROM Stories WHERE NAME= ?", (name)) > I can't figure out what's causing it. I searched for the invalid cursor > state error online but most of it occurs on the fetchall statement not > the execute statement. > > Any ideas? > Thanks! > > > -- > Cheers, > Krissy > ----------------------------------------------------------------------- > Testing the waters is always fun... -- Jeff Jeff Johnson jeff at dcsoftware.com Phoenix Python User Group - sunpiggies at googlegroups.com From kent37 at tds.net Fri Sep 18 19:00:38 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 18 Sep 2009 13:00:38 -0400 Subject: [Tutor] ODBC SQL Server Question In-Reply-To: <4AB3AC04.20901@dcsoftware.com> References: <4AB3AC04.20901@dcsoftware.com> Message-ID: <1c2a2c590909181000t5310e71dgcb6df3ec3b6d2db4@mail.gmail.com> On Fri, Sep 18, 2009 at 11:49 AM, Jeff Johnson wrote: > Kristina: > > I would format it as follows: > > self.cursor.execute("SELECT CUSTID FROM Stories WHERE NAME = '%s'" % name) No, that is a recipe for SQL injection attacks such as this: http://xkcd.com/327/ >> self.cursor.execute("SELECT CUSTID FROM Stories WHERE NAME= ?", (name)) I think that should have a comma to create a tuple: self.cursor.execute("SELECT CUSTID FROM Stories WHERE NAME= ?", (name,)) I don't know if that could cause your problem. Kent From admin at gg-lab.net Fri Sep 18 19:05:13 2009 From: admin at gg-lab.net (admin at gg-lab.net) Date: Fri, 18 Sep 2009 19:05:13 +0200 Subject: [Tutor] Determine Filetype Message-ID: <48758b600909181005g3ed44078h838b28108913a5d5@mail.gmail.com> Hi, i'm putting file in a DB as BLOB entries. To serve them, i need to take Content-Type headers. So, i'm looking for a function that returnes the filetype, given a data str. I've found many other topics like this in python mail-archive, but any of them contains the solution. Can you help me, please? Thankyou! From emile at fenx.com Fri Sep 18 20:00:30 2009 From: emile at fenx.com (Emile van Sebille) Date: Fri, 18 Sep 2009 11:00:30 -0700 Subject: [Tutor] Determine Filetype In-Reply-To: <48758b600909181005g3ed44078h838b28108913a5d5@mail.gmail.com> References: <48758b600909181005g3ed44078h838b28108913a5d5@mail.gmail.com> Message-ID: On 9/18/2009 10:05 AM admin at gg-lab.net said... > Hi, > > i'm putting file in a DB as BLOB entries. To serve them, i need to > take Content-Type headers. > > So, i'm looking for a function that returnes the filetype, given a data str. > > I've found many other topics like this in python mail-archive, but any > of them contains the solution. > > Can you help me, please? I'd take a look at python-magic at http://hupp.org/adam/hg/python-magic/file/d3cd83e5a773 where the example shows that you can do: # For MIME types >>> mime = magic.Magic(mime=True) >>> mime.from_file("testdata/test.pdf") 'application/pdf' HTH, Emile > > Thankyou! > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From jeff at dcsoftware.com Fri Sep 18 20:14:45 2009 From: jeff at dcsoftware.com (Jeff Johnson) Date: Fri, 18 Sep 2009 11:14:45 -0700 Subject: [Tutor] ODBC SQL Server Question In-Reply-To: <1c2a2c590909181000t5310e71dgcb6df3ec3b6d2db4@mail.gmail.com> References: <4AB3AC04.20901@dcsoftware.com> <1c2a2c590909181000t5310e71dgcb6df3ec3b6d2db4@mail.gmail.com> Message-ID: <4AB3CE15.7060603@dcsoftware.com> Kent: How about this: self.cursor.execute("SELECT CUSTID FROM Stories WHERE NAME = '%s'" % (name, )) Question, does execute know to substitute the question mark with name? self.cursor.execute("SELECT CUSTID FROM Stories WHERE NAME= ?", (name, )) TIA Kent Johnson wrote: > On Fri, Sep 18, 2009 at 11:49 AM, Jeff Johnson wrote: >> Kristina: >> >> I would format it as follows: >> >> self.cursor.execute("SELECT CUSTID FROM Stories WHERE NAME = '%s'" % name) > > No, that is a recipe for SQL injection attacks such as this: > http://xkcd.com/327/ > >>> self.cursor.execute("SELECT CUSTID FROM Stories WHERE NAME= ?", (name)) > > I think that should have a comma to create a tuple: > self.cursor.execute("SELECT CUSTID FROM Stories WHERE NAME= ?", (name,)) > > I don't know if that could cause your problem. > Kent -- Jeff Jeff Johnson jeff at dcsoftware.com Phoenix Python User Group - sunpiggies at googlegroups.com From bgailer at gmail.com Fri Sep 18 20:12:57 2009 From: bgailer at gmail.com (bob gailer) Date: Fri, 18 Sep 2009 14:12:57 -0400 Subject: [Tutor] Calling VB.NET code with Python .. VB.net - Python integration .. In-Reply-To: <16099583.452011253277852014.JavaMail.root@mail5c.brinkster.com> References: <16099583.452011253277852014.JavaMail.root@mail5c.brinkster.com> Message-ID: <4AB3CDA9.1060708@gmail.com> Otonicar Ales wrote: > > The idea is that Python calls VB.net program. VB.Net program gets data > and than forward data back to Python for further processing.. > > > > One way to do this is by compiling vb.net program to exe. And than > call exe by Python code. Data exchange goes via Access Data Base > (Python write in MC Access, vb get data and than write it to MC > access, Python reads final data from MC access). In this case I will > need Python command to run exe which is enable Python waiting until > exe is not finished.. > > > > In case anybody out-there has better idea how directly communicate > with vb.net program (exchanging data with variables - code > integration) please send code sample with a bit of explanation .. > You should set up the vb.net program to be a com server. Don't ask me how to do that. Then get Python for Windows: http://sourceforge.net/projects/pywin32/files/pywin32/Build%20214/pywin32-214.win32-py2.6.exe/download import wincom32.client com = wincom32.client.Dispatch( application name or classid of the vb.net app) # now you have a com object with which you can send commands to the vb.net app and receive data back. -- Bob Gailer Chapel Hill NC 919-636-4239 From admin at gg-lab.net Fri Sep 18 20:21:36 2009 From: admin at gg-lab.net (admin at gg-lab.net) Date: Fri, 18 Sep 2009 20:21:36 +0200 Subject: [Tutor] Determine Filetype In-Reply-To: References: <48758b600909181005g3ed44078h838b28108913a5d5@mail.gmail.com> Message-ID: <48758b600909181121h1810e26dnde9aaa72e550bd1e@mail.gmail.com> Hi Emile, that functions requires a filename/path. Just like this one (for images) http://docs.python.org/library/imghdr.html Ok, i don't have a filename. I get the file from a BLOB in a db. Any idea? Thankyou for your precious help. 2009/9/18 Emile van Sebille : > On 9/18/2009 10:05 AM admin at gg-lab.net said... >> >> Hi, >> >> i'm putting file in a DB as BLOB entries. To serve them, i need to >> take Content-Type headers. >> >> So, i'm looking for a function that returnes the filetype, given a data >> str. >> >> I've found many other topics like this in python mail-archive, but any >> of them contains the solution. >> >> Can you help me, please? > > I'd take a look at python-magic at > http://hupp.org/adam/hg/python-magic/file/d3cd83e5a773 where the example > shows that you can do: > > # For MIME types >>>> mime = magic.Magic(mime=True) >>>> mime.from_file("testdata/test.pdf") > 'application/pdf' > > > HTH, > > Emile > > > > > >> >> Thankyou! >> _______________________________________________ >> Tutor maillist ?- ?Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From epicboy at gmail.com Fri Sep 18 20:14:49 2009 From: epicboy at gmail.com (Warren Marshall) Date: Fri, 18 Sep 2009 14:14:49 -0400 Subject: [Tutor] Import vs #include Message-ID: <998F6B39-57AB-45AA-AD86-E5BBECEF5E18@gmail.com> I'm trying to get my head around the organization of a larger Python project. 1. Am I right in thinking that in Python, you don't have the concept of something like a precompiled header and that every file that wants to use, say "vector.py" needs to import that module? 2. How are Python projects typically organized in terms of having many files. Are sub-directories for different kinds of files (rendering files go here, file management files go here, etc), or does that not play nicely with the import command? 3. As you can tell, I've done a lot of C/C++/C# and I'm trying to shake loose the analog that I've built up in my head that import is Python's answer to #include. It isn't, is it? - Warren (epicboy at gmail.com) From kent37 at tds.net Fri Sep 18 21:12:17 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 18 Sep 2009 15:12:17 -0400 Subject: [Tutor] ODBC SQL Server Question In-Reply-To: <4AB3CE15.7060603@dcsoftware.com> References: <4AB3AC04.20901@dcsoftware.com> <1c2a2c590909181000t5310e71dgcb6df3ec3b6d2db4@mail.gmail.com> <4AB3CE15.7060603@dcsoftware.com> Message-ID: <1c2a2c590909181212u66c6fae0p52c25cb6f87158fb@mail.gmail.com> On Fri, Sep 18, 2009 at 2:14 PM, Jeff Johnson wrote: > Kent: > > How about this: > self.cursor.execute("SELECT CUSTID FROM Stories WHERE NAME = '%s'" % (name, > )) No, that has the same result as your original. For example, In [3]: name = "Kent'; drop table Stories;--" In [4]: "SELECT CUSTID FROM Stories WHERE NAME = '%s'" % (name, ) Out[4]: "SELECT CUSTID FROM Stories WHERE NAME = 'Kent'; drop table Stories;--'" Oops. > Question, does execute know to substitute the question mark with name? > self.cursor.execute("SELECT CUSTID FROM Stories WHERE NAME= ?", (name, )) Yes, and it will correctly quote name according to the conventions of the database in use. (Note that not all DB-API implementations use ? as the placeholder; check the docs for the db you are using.) Kent From kent37 at tds.net Fri Sep 18 21:25:17 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 18 Sep 2009 15:25:17 -0400 Subject: [Tutor] Import vs #include In-Reply-To: <998F6B39-57AB-45AA-AD86-E5BBECEF5E18@gmail.com> References: <998F6B39-57AB-45AA-AD86-E5BBECEF5E18@gmail.com> Message-ID: <1c2a2c590909181225l4aaa46b3t3d866fdef125af0a@mail.gmail.com> On Fri, Sep 18, 2009 at 2:14 PM, Warren Marshall wrote: > > I'm trying to get my head around the organization of a larger Python > project. > > 1. Am I right in thinking that in Python, you don't have the concept of > something like a precompiled header and that every file that wants to use, > say "vector.py" needs to import that module? Yes. > 2. How are Python projects typically organized ?in terms of having many > files. ?Are sub-directories for different kinds of files (rendering files go > here, file management files go here, etc), or does that not play nicely with > the import command? It's fine. The directories are called packages and must contain a (possibly empty) file named __init__.py. Then you can do things like from package.module import SomeClass See the std lib for examples, for example the email and logging packages. > 3. As you can tell, I've done a lot of C/C++/C# and I'm trying to shake > loose the analog that I've built up in my head that import is Python's > answer to #include. ?It isn't, is it? Not really, it is more like a using declaration in C# except it doesn't bring the contents of the module into scope, just the module itself. using System; // C# is like from sys import * # Python though the latter form is discouraged in favor of just import sys or importing the specific items you need: from sys import modules Kent From kent37 at tds.net Fri Sep 18 21:26:54 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 18 Sep 2009 15:26:54 -0400 Subject: [Tutor] Determine Filetype In-Reply-To: <48758b600909181121h1810e26dnde9aaa72e550bd1e@mail.gmail.com> References: <48758b600909181005g3ed44078h838b28108913a5d5@mail.gmail.com> <48758b600909181121h1810e26dnde9aaa72e550bd1e@mail.gmail.com> Message-ID: <1c2a2c590909181226m6567709axa726982aac80fbba@mail.gmail.com> On Fri, Sep 18, 2009 at 2:21 PM, admin at gg-lab.net wrote: > Hi Emile, > > that functions requires a filename/path. Did you even look at the link? There is a from_buffer() method also. Kent > 2009/9/18 Emile van Sebille : >> I'd take a look at python-magic at >> http://hupp.org/adam/hg/python-magic/file/d3cd83e5a773 where the example >> shows that you can do: >> >> # For MIME types >>>>> mime = magic.Magic(mime=True) >>>>> mime.from_file("testdata/test.pdf") >> 'application/pdf' From dan.king106 at yahoo.com Fri Sep 18 21:19:29 2009 From: dan.king106 at yahoo.com (dan06) Date: Fri, 18 Sep 2009 12:19:29 -0700 (PDT) Subject: [Tutor] Image manipluation (On-the-fly thumbnail creation) In-Reply-To: <4AAFE219.8000304@gmail.com> References: <25456792.post@talk.nabble.com> <4AAFE219.8000304@gmail.com> Message-ID: <25514113.post@talk.nabble.com> Patrick Sabin wrote: > > When I needed thumbnails of my images, I created them using ImageMagick. > ImageMagick is a very nice tool for editing images and since it is > called from the command line it is easy to invoke it from a programming > language. There are python-bindings for it, but I think they are not > very actively maintained and so I wouldn't use them. > > Using PIL is another option and maybe more pythonic, but if you are > familiar with ImageMagick it might be a good alternative. > > - Patrick > My experiences with ImageMagick (IM) are limited, but what experiences I have had have been good. The functionality of IM is superb, and that is the impetus for wanting to use it over other softwares/libraries. Ultimately, I want to use IM/Python to replicate something I did in GD/PHP. Using GD/PHP I was able to create thumbnails on-demand that I could output directly to the browser, rather than creating & saving thumbnails to the disk. Is this possible with IM/Python? -- View this message in context: http://www.nabble.com/Image-manipluation-%28On-the-fly-thumbnail-creation%29-tp25456792p25514113.html Sent from the Python - tutor mailing list archive at Nabble.com. From admin at gg-lab.net Fri Sep 18 21:33:28 2009 From: admin at gg-lab.net (admin at gg-lab.net) Date: Fri, 18 Sep 2009 21:33:28 +0200 Subject: [Tutor] Determine Filetype In-Reply-To: <1c2a2c590909181226m6567709axa726982aac80fbba@mail.gmail.com> References: <48758b600909181005g3ed44078h838b28108913a5d5@mail.gmail.com> <48758b600909181121h1810e26dnde9aaa72e550bd1e@mail.gmail.com> <1c2a2c590909181226m6567709axa726982aac80fbba@mail.gmail.com> Message-ID: <48758b600909181233y10218cdv9b8cad2f71a752d0@mail.gmail.com> Oh, i'm sorry. I've read the README, but haven't noticed that m.from_buffer(open("testdata/test.pdf").read(1024)) was exactly what i was looking for. Ok, i'll try it and let you know :D 2009/9/18 Kent Johnson : > On Fri, Sep 18, 2009 at 2:21 PM, admin at gg-lab.net wrote: >> Hi Emile, >> >> that functions requires a filename/path. > > Did you even look at the link? There is a from_buffer() method also. > > Kent > >> 2009/9/18 Emile van Sebille : > >>> I'd take a look at python-magic at >>> http://hupp.org/adam/hg/python-magic/file/d3cd83e5a773 where the example >>> shows that you can do: >>> >>> # For MIME types >>>>>> mime = magic.Magic(mime=True) >>>>>> mime.from_file("testdata/test.pdf") >>> 'application/pdf' > From jeff at dcsoftware.com Fri Sep 18 21:40:10 2009 From: jeff at dcsoftware.com (Jeff Johnson) Date: Fri, 18 Sep 2009 12:40:10 -0700 Subject: [Tutor] ODBC SQL Server Question In-Reply-To: <1c2a2c590909181212u66c6fae0p52c25cb6f87158fb@mail.gmail.com> References: <4AB3AC04.20901@dcsoftware.com> <1c2a2c590909181000t5310e71dgcb6df3ec3b6d2db4@mail.gmail.com> <4AB3CE15.7060603@dcsoftware.com> <1c2a2c590909181212u66c6fae0p52c25cb6f87158fb@mail.gmail.com> Message-ID: <4AB3E21A.1070800@dcsoftware.com> Thanks for the clarification Kent! Kent Johnson wrote: > On Fri, Sep 18, 2009 at 2:14 PM, Jeff Johnson wrote: >> Kent: >> >> How about this: >> self.cursor.execute("SELECT CUSTID FROM Stories WHERE NAME = '%s'" % (name, >> )) > > No, that has the same result as your original. For example, > In [3]: name = "Kent'; drop table Stories;--" > > In [4]: "SELECT CUSTID FROM Stories WHERE NAME = '%s'" % (name, ) > Out[4]: "SELECT CUSTID FROM Stories WHERE NAME = 'Kent'; drop table Stories;--'" > > Oops. > >> Question, does execute know to substitute the question mark with name? >> self.cursor.execute("SELECT CUSTID FROM Stories WHERE NAME= ?", (name, )) > > Yes, and it will correctly quote name according to the conventions of > the database in use. (Note that not all DB-API implementations use ? > as the placeholder; check the docs for the db you are using.) > > Kent -- Jeff Jeff Johnson jeff at dcsoftware.com Phoenix Python User Group - sunpiggies at googlegroups.com From evosweet at hotmail.com Fri Sep 18 22:07:16 2009 From: evosweet at hotmail.com (Rayon) Date: Fri, 18 Sep 2009 16:07:16 -0400 Subject: [Tutor] order data Message-ID: I have a array with this data in it 0.0046,0.095,0.0904,521456,['MCI 521456 0.0904'],['ATT 521 0.0919'],['IDT 521 0.095'],['None'] 0.0083,0.0192,0.0109,39023821,['MCI 39023821 0.0109'],['ATT 39 0.012'],['IDT 39 0.0192'],['SPR 39 0.0135'] 0.0421,0.0681,0.026,73462,['MCI 73462 0.0260'],['ATT 7 0.026'],['IDT 73462 0.028'],['SPR 7 0.0681'] 0.0176,0.1035,0.0859,126872,['MCI 126872 0.0859'],['ATT 1268 0.0919'],['IDT 126872 0.1035'],['None'] 0.0215,0.1614,0.1399,5032130,['MCI 5032130 0.1614'],['ATT 5032130 0.1399'],['IDT 503 0.152'],['None'] 0.0206,0.0385,0.0179,1868,['MCI 1868 0.0179'],['ATT 1868 0.0385'],['IDT 1868 0.036'],['None'] 0.0325,0.087,0.0545,5027889,['MCI 5027889 0.0602'],['ATT 5027889 0.0545'],['IDT 502 0.087'],['None'] 0.0325,0.087,0.0545,5027888,['MCI 5027888 0.0602'],['ATT 5027888 0.0545'],['IDT 502 0.087'],['None'] 0.0046,0.095,0.0904,521455,['MCI 521455 0.0904'],['ATT 521 0.0919'],['IDT 521 0.095'],['None'] 0.1292,0.1762,0.047,5989,['MCI 5989 0.1762'],['ATT 598 0.05'],['IDT 5989 0.173'],['SPR 598 0.047'] 0.0706,0.2011,0.1305,1284499,['MCI 1284499 0.2011'],['ATT 1284499 0.1932'],['IDT 1284499 0.1305'],['None'] and I want to order the display of that data by the second row. can I do it in this array from or do I have to break it down more. -------------- next part -------------- An HTML attachment was scrubbed... URL: From mandel at themacaque.com Fri Sep 18 22:08:02 2009 From: mandel at themacaque.com (Manuel de la Pena) Date: Fri, 18 Sep 2009 22:08:02 +0200 Subject: [Tutor] Python decorator to ensure that kwargs are correct Message-ID: <1253304482.22000.70.camel@mandel-desktop> Hello, I have done a decorator that I used to ensure that the keyword arguments passed to a constructor are the correct/expected ones. The code is the following: from functools import wraps def keyargs_check(keywords): """ This decorator ensures that the keys passed in kwargs are the onces that are specified in the passed tuple. When applied this decorate will check the keywords and will throw an exception if the developer used one that is not recognized. @type keywords: tuple @param keywords: A tuple with all the keywords recognized by the function. """ def wrap(f): @wraps(f) def newFunction(*args, **kw): # we are going to add an extra check in kw for current_key in kw.keys(): if not current_key in keywords: raise ValueError( "The key {0} is a not recognized parameters by {1}.".format( current_key, f.__name__)) return f(*args, **kw) return newFunction return wrap An example use of this decorator would be the following: class Person(object): @keyargs_check(("name", "surname", "age")) def __init__(self, **kwargs): # perform init according to args Using the above code if the developer passes a key args like "blah" it will throw an exception. Unfortunately my implementation has a major problem with inheritance, if I define the following: class PersonTest(Person): @keyargs_check(("test")) def __init__(self, **kwargs): Person.__init__(self,**kwargs) Because I'm passing kwargs to the super class init method, I'm going to get an exception because "test" is not in the tuple passed to the decorator of the super class. Is there a way to let the decorator used in the super class to know about the extra keywords? or event better, is there a standard way to achieve what I want? Thanks in advance for any help or input, kr, Manuel From admin at gg-lab.net Fri Sep 18 22:10:59 2009 From: admin at gg-lab.net (admin at gg-lab.net) Date: Fri, 18 Sep 2009 22:10:59 +0200 Subject: [Tutor] Determine Filetype In-Reply-To: <48758b600909181233y10218cdv9b8cad2f71a752d0@mail.gmail.com> References: <48758b600909181005g3ed44078h838b28108913a5d5@mail.gmail.com> <48758b600909181121h1810e26dnde9aaa72e550bd1e@mail.gmail.com> <1c2a2c590909181226m6567709axa726982aac80fbba@mail.gmail.com> <48758b600909181233y10218cdv9b8cad2f71a752d0@mail.gmail.com> Message-ID: <48758b600909181310j274e48fck334c34c066ade74a@mail.gmail.com> Ok, a good news for me: i've modified my script, adding a: import magic line at the top of it. But I got this error: No module named magic Ok, so magic is not installed on GAE. I've then uploaded it and it loaded succesfully. New error: No module named _ctypes And, reading the full debug i got this: File "/base/python_dist/lib/python2.5/ctypes/__init__.py", line 10, in from _ctypes import Union, Structure, Array So, the __init__.py file of the GAE evinronment's ctypes library is broken, as it's importing from a package that doesn't exist. Right? Maybe i'm doing something wrong. Thankyou 2009/9/18 admin at gg-lab.net : > Oh, i'm sorry. > > I've read the README, but haven't noticed that > > m.from_buffer(open("testdata/test.pdf").read(1024)) > > was exactly what i was looking for. > > Ok, i'll try it and let you know :D > > 2009/9/18 Kent Johnson : >> On Fri, Sep 18, 2009 at 2:21 PM, admin at gg-lab.net wrote: >>> Hi Emile, >>> >>> that functions requires a filename/path. >> >> Did you even look at the link? There is a from_buffer() method also. >> >> Kent >> >>> 2009/9/18 Emile van Sebille : >> >>>> I'd take a look at python-magic at >>>> http://hupp.org/adam/hg/python-magic/file/d3cd83e5a773 where the example >>>> shows that you can do: >>>> >>>> # For MIME types >>>>>>> mime = magic.Magic(mime=True) >>>>>>> mime.from_file("testdata/test.pdf") >>>> 'application/pdf' >> > From epicboy at gmail.com Fri Sep 18 22:15:11 2009 From: epicboy at gmail.com (Warren Marshall) Date: Fri, 18 Sep 2009 16:15:11 -0400 Subject: [Tutor] Import vs #include In-Reply-To: <1c2a2c590909181225l4aaa46b3t3d866fdef125af0a@mail.gmail.com> References: <998F6B39-57AB-45AA-AD86-E5BBECEF5E18@gmail.com> <1c2a2c590909181225l4aaa46b3t3d866fdef125af0a@mail.gmail.com> Message-ID: <1F65B09F-2CCD-41E7-BD73-2E1A6A35BAF9@gmail.com> Excellent, OK, this is becoming clearer ... So if I wanted a common library of code that several Python apps would be using, best practices would say I should put that into a directory that the projects can see and import it as a package.module. Cool... - Warren (epicboy at gmail.com) On Sep 18, 2009, at 3:25 PM, Kent Johnson wrote: > On Fri, Sep 18, 2009 at 2:14 PM, Warren Marshall > wrote: >> >> I'm trying to get my head around the organization of a larger Python >> project. >> >> 1. Am I right in thinking that in Python, you don't have the >> concept of >> something like a precompiled header and that every file that wants >> to use, >> say "vector.py" needs to import that module? > > Yes. > >> 2. How are Python projects typically organized in terms of having >> many >> files. Are sub-directories for different kinds of files (rendering >> files go >> here, file management files go here, etc), or does that not play >> nicely with >> the import command? > > It's fine. The directories are called packages and must contain a > (possibly empty) file named __init__.py. Then you can do things like > from package.module import SomeClass > > See the std lib for examples, for example the email and logging > packages. > >> 3. As you can tell, I've done a lot of C/C++/C# and I'm trying to >> shake >> loose the analog that I've built up in my head that import is >> Python's >> answer to #include. It isn't, is it? > > Not really, it is more like a using declaration in C# except it > doesn't bring the contents of the module into scope, just the module > itself. > using System; // C# > is like > from sys import * # Python > > though the latter form is discouraged in favor of just > import sys > or importing the specific items you need: > from sys import modules > > Kent > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From sander.sweers at gmail.com Fri Sep 18 22:40:16 2009 From: sander.sweers at gmail.com (Sander Sweers) Date: Fri, 18 Sep 2009 22:40:16 +0200 Subject: [Tutor] order data In-Reply-To: References: Message-ID: 2009/9/18 Rayon : I will assume array == python list. > I have a array with this data in it How are you reading the data? Do you convert all the numbers to floats? If so you will need to think about precision of the floats. If you want to preserve the precision look into the decimal module. > 0.0046,0.095,0.0904,521456,['MCI 521456 0.0904'],['ATT 521 0.0919'],['IDT > 521 0.095'],['None'] > 0.0083,0.0192,0.0109,39023821,['MCI 39023821 0.0109'],['ATT 39 0.012'],['IDT > 39 0.0192'],['SPR 39 0.0135'] > 0.0421,0.0681,0.026,73462,['MCI 73462 0.0260'],['ATT 7 0.026'],['IDT 73462 > 0.028'],['SPR 7 0.0681'] > 0.0176,0.1035,0.0859,126872,['MCI 126872 0.0859'],['ATT 1268 0.0919'],['IDT > 126872 0.1035'],['None'] > 0.0215,0.1614,0.1399,5032130,['MCI 5032130 0.1614'],['ATT 5032130 > 0.1399'],['IDT 503 0.152'],['None'] > 0.0206,0.0385,0.0179,1868,['MCI 1868 0.0179'],['ATT 1868 0.0385'],['IDT 1868 > 0.036'],['None'] > 0.0325,0.087,0.0545,5027889,['MCI 5027889 0.0602'],['ATT 5027889 > 0.0545'],['IDT 502 0.087'],['None'] > 0.0325,0.087,0.0545,5027888,['MCI 5027888 0.0602'],['ATT 5027888 > 0.0545'],['IDT 502 0.087'],['None'] > 0.0046,0.095,0.0904,521455,['MCI 521455 0.0904'],['ATT 521 0.0919'],['IDT > 521 0.095'],['None'] > 0.1292,0.1762,0.047,5989,['MCI 5989 0.1762'],['ATT 598 0.05'],['IDT 5989 > 0.173'],['SPR 598 0.047'] > 0.0706,0.2011,0.1305,1284499,['MCI 1284499 0.2011'],['ATT 1284499 > 0.1932'],['IDT 1284499 0.1305'],['None'] > > and I want to order the display of that data by the second row. You probably meant the second column here.If not please explain a bit more. > can I do it in this array from or do I have to break it down more. If the data is in a list of lists you can use itemgetter from the operator module. Example below. >>> import operator >>> a = \ [[0.0046,0.095,0.0904,521456,['MCI 521456 0.0904'],['ATT 521 0.0919'],['IDT 521 0.095'],['None']], [0.0083,0.0192,0.0109,39023821,['MCI 39023821 0.0109'],['ATT 39 0.012'],['IDT 39 0.0192'],['SPR 39 0.0135']], [0.0421,0.0681,0.026,73462,['MCI 73462 0.0260'],['ATT 7 0.026'],['IDT 73462 0.028'],['SPR 7 0.0681']], [0.0176,0.1035,0.0859,126872,['MCI 126872 0.0859'],['ATT 1268 0.0919'],['IDT 126872 0.1035'],['None']], [0.0215,0.1614,0.1399,5032130,['MCI 5032130 0.1614'],['ATT 5032130 0.1399'],['IDT 503 0.152'],['None']], [0.0206,0.0385,0.0179,1868,['MCI 1868 0.0179'],['ATT 1868 0.0385'],['IDT 1868 0.036'],['None']], [0.0325,0.087,0.0545,5027889,['MCI 5027889 0.0602'],['ATT 5027889 0.0545'],['IDT 502 0.087'],['None']], [0.0325,0.087,0.0545,5027888,['MCI 5027888 0.0602'],['ATT 5027888 0.0545'],['IDT 502 0.087'],['None']], [0.0046,0.095,0.0904,521455,['MCI 521455 0.0904'],['ATT 521 0.0919'],['IDT 521 0.095'],['None']], [0.1292,0.1762,0.047,5989,['MCI 5989 0.1762'],['ATT 598 0.05'],['IDT 5989 0.173'],['SPR 598 0.047']], [0.0706,0.2011,0.1305,1284499,['MCI 1284499 0.2011'],['ATT 1284499 0.1932'],['IDT 1284499 0.1305'],['None']]] >>> a.sort(key=operator.itemgetter(1)) >>> for l in a: print l [0.0083000000000000001, 0.019199999999999998, 0.0109, 39023821, ['MCI 39023821 0.0109'], ['ATT 39 0.012'], ['IDT 39 0.0192'], ['SPR 39 0.0135']] [0.0206, 0.0385, 0.017899999999999999, 1868, ['MCI 1868 0.0179'], ['ATT 1868 0.0385'], ['IDT 1868 0.036'], ['None']] [0.042099999999999999, 0.068099999999999994, 0.025999999999999999, 73462, ['MCI 73462 0.0260'], ['ATT 7 0.026'], ['IDT 73462 0.028'], ['SPR 7 0.0681']] [0.032500000000000001, 0.086999999999999994, 0.0545, 5027889, ['MCI 5027889 0.0602'], ['ATT 5027889 0.0545'], ['IDT 502 0.087'], ['None']] [0.032500000000000001, 0.086999999999999994, 0.0545, 5027888, ['MCI 5027888 0.0602'], ['ATT 5027888 0.0545'], ['IDT 502 0.087'], ['None']] [0.0045999999999999999, 0.095000000000000001, 0.090399999999999994, 521456, ['MCI 521456 0.0904'], ['ATT 521 0.0919'], ['IDT 521 0.095'], ['None']] [0.0045999999999999999, 0.095000000000000001, 0.090399999999999994, 521455, ['MCI 521455 0.0904'], ['ATT 521 0.0919'], ['IDT 521 0.095'], ['None']] [0.017600000000000001, 0.10349999999999999, 0.085900000000000004, 126872, ['MCI 126872 0.0859'], ['ATT 1268 0.0919'], ['IDT 126872 0.1035'], ['None']] [0.021499999999999998, 0.16139999999999999, 0.1399, 5032130, ['MCI 5032130 0.1614'], ['ATT 5032130 0.1399'], ['IDT 503 0.152'], ['None']] [0.12920000000000001, 0.1762, 0.047, 5989, ['MCI 5989 0.1762'], ['ATT 598 0.05'], ['IDT 5989 0.173'], ['SPR 598 0.047']] [0.070599999999999996, 0.2011, 0.1305, 1284499, ['MCI 1284499 0.2011'], ['ATT 1284499 0.1932'], ['IDT 1284499 0.1305'], ['None']] >>> As you can see the numbers are converted to floats in my example and 0.0192 changed to 0.019199999999999998. Greets Sander From kent37 at tds.net Fri Sep 18 22:48:03 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 18 Sep 2009 16:48:03 -0400 Subject: [Tutor] Determine Filetype In-Reply-To: <48758b600909181310j274e48fck334c34c066ade74a@mail.gmail.com> References: <48758b600909181005g3ed44078h838b28108913a5d5@mail.gmail.com> <48758b600909181121h1810e26dnde9aaa72e550bd1e@mail.gmail.com> <1c2a2c590909181226m6567709axa726982aac80fbba@mail.gmail.com> <48758b600909181233y10218cdv9b8cad2f71a752d0@mail.gmail.com> <48758b600909181310j274e48fck334c34c066ade74a@mail.gmail.com> Message-ID: <1c2a2c590909181348s1f25d855j970e16863f1d9aa@mail.gmail.com> On Fri, Sep 18, 2009 at 4:10 PM, admin at gg-lab.net wrote: > Ok, so magic is not installed on GAE. I've then uploaded it and it > loaded succesfully. New error: > > No module named _ctypes > > And, reading the full debug i got this: > > File "/base/python_dist/lib/python2.5/ctypes/__init__.py", line 10, in > ? ?from _ctypes import Union, Structure, Array > > So, the __init__.py file of the GAE evinronment's ctypes library is > broken, as it's importing from a package that doesn't exist. Right? Probably ctypes is not supported in GAE, that would be a pretty big security hole. Kent From kent37 at tds.net Fri Sep 18 22:49:18 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 18 Sep 2009 16:49:18 -0400 Subject: [Tutor] Import vs #include In-Reply-To: <1F65B09F-2CCD-41E7-BD73-2E1A6A35BAF9@gmail.com> References: <998F6B39-57AB-45AA-AD86-E5BBECEF5E18@gmail.com> <1c2a2c590909181225l4aaa46b3t3d866fdef125af0a@mail.gmail.com> <1F65B09F-2CCD-41E7-BD73-2E1A6A35BAF9@gmail.com> Message-ID: <1c2a2c590909181349u2ae0ddf4g72deb058c1d763cc@mail.gmail.com> On Fri, Sep 18, 2009 at 4:15 PM, Warren Marshall wrote: > > Excellent, OK, this is becoming clearer ... > > So if I wanted a common library of code that several Python apps would be > using, best practices would say I should put that into a directory that the > projects can see and import it as a package.module. ?Cool... Yes, and if you want to share it with all python programs, put your dir into Lib/site-packages - that dir is always on the python search path. Kent From kb1pkl at aim.com Sat Sep 19 00:05:31 2009 From: kb1pkl at aim.com (Corey Richardson) Date: Fri, 18 Sep 2009 18:05:31 -0400 Subject: [Tutor] Tutor Digest, Vol 67, Issue 62 In-Reply-To: References: Message-ID: <4AB4042B.4040105@aim.com> > >> I'm going to be making a simple program, that is a few books like "A is >> for...", "B is for...", but it will be many built into one, >> > > Sorry, I don't understand? > *By that, I mean it will be like a childrens book, teaching the letters. You've read them. example "A is for apple, a yummy treat. B is for Box'es, they hold things". > * >> isn't, and ignore it. Also, Alan, your tutorial is the bomb! Some of the >> simpler things I've seen done better, but you do an amazing job with it. >> > > Thanks for the kind words. If you can offer ideas for improvement I'm > always > happy to hear. Thats how it improves! And since I;m still working on the > latest update for v3 its a good time for suggestions! > > * Ok, I'll go over it more carefully and see if I can suggest anything.* -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: kb1pkl.vcf Type: text/x-vcard Size: 55 bytes Desc: not available URL: From roadierich at googlemail.com Sat Sep 19 01:58:03 2009 From: roadierich at googlemail.com (Rich Lovely) Date: Sat, 19 Sep 2009 00:58:03 +0100 Subject: [Tutor] Python decorator to ensure that kwargs are correct In-Reply-To: <1253304482.22000.70.camel@mandel-desktop> References: <1253304482.22000.70.camel@mandel-desktop> Message-ID: 2009/9/18 Manuel de la Pena : > Hello, > > > I have done a decorator that I used to ensure that the keyword arguments > passed to a constructor are the correct/expected ones. The code is the > following: > > from functools import wraps > > def keyargs_check(keywords): > """ > This decorator ensures that the keys passed in kwargs are the onces that > are specified in the passed tuple. When applied this decorate will > check the keywords and will throw an exception if the developer used > one that is not recognized. > > @type keywords: tuple > @param keywords: A tuple with all the keywords recognized by the function. > """ > > def wrap(f): > ? ?@wraps(f) > ? ?def newFunction(*args, **kw): > ? ? ? ?# we are going to add an extra check in kw > ? ? ? ?for current_key in kw.keys(): > ? ? ? ? ? ?if not current_key in keywords: > ? ? ? ? ? ? ? ?raise ValueError( > ? ? ? ? ? ? ? ? ? ?"The key {0} is a not recognized parameters by {1}.".format( > ? ? ? ? ? ? ? ? ? ? ? ?current_key, f.__name__)) > ? ? ? ?return f(*args, **kw) > ? ?return newFunction > return wrap > > An example use of this decorator would be the following: > > class Person(object): > > @keyargs_check(("name", "surname", "age")) > def __init__(self, **kwargs): > ? ?# perform init according to args > > Using the above code if the developer passes a key args like "blah" it > will throw an exception. Unfortunately my implementation has a major > problem with inheritance, if I define the following: > > class PersonTest(Person): > > @keyargs_check(("test")) > def __init__(self, **kwargs): > ? ?Person.__init__(self,**kwargs) > > Because I'm passing kwargs to the super class init method, I'm going to > get an exception because "test" is not in the tuple passed to the > decorator of the super class. Is there a way to let the decorator used > in the super class to know about the extra keywords? or event better, is > there a standard way to achieve what I want? > > > Thanks in advance for any help or input, > > kr, > > Manuel > > > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Is there any specific reason you need to use **kwargs? If you omit it from function definitions, you can use normal argument format: >>> class Demo(object): ... def __init__(self, name="", surname="", age=0): ... print name, surname, age ... >>> Demo(name='Rich', surname=Lovely, age=24) Traceback (most recent call last): File "", line 1, in NameError: name 'Lovely' is not defined >>> Demo(name='Rich', surname='Lovely', age=24) Rich Lovely 24 <__main__.Demo object at 0x00F75230> >>> Demo(notAValidParam='foo') Traceback (most recent call last): File "", line 1, in TypeError: __init__() got an unexpected keyword argument 'notAValidParam' >>> It does of course break if you use positional arguments, but part of the theory behind python is that we're all consenting adults, and should know better than to do things that break existing code. It is for this reason that you can overwrite builtins like range or list without the interpretter moaning. -- Rich "Roadie Rich" Lovely There are 10 types of people in the world: those who know binary, those who do not, and those who are off by one. From roadierich at googlemail.com Sat Sep 19 02:02:16 2009 From: roadierich at googlemail.com (Rich Lovely) Date: Sat, 19 Sep 2009 01:02:16 +0100 Subject: [Tutor] Python decorator to ensure that kwargs are correct In-Reply-To: References: <1253304482.22000.70.camel@mandel-desktop> Message-ID: Should probably clean up my code properly before submitting, to hide some of the noobish errors like forgetting to put quotes round strings... >>> class Demo(object): ... def __init__(self, name="", surname="", age=0): ... print name, surname, age ... >>> Demo(name='Rich', surname='Lovely', age=24) Rich Lovely 24 <__main__.Demo object at 0x00F75230> >>> Demo(notAName='foo') Traceback (most recent call last): File "", line 1, in TypeError: __init__() got an unexpected keyword argument 'notAName' -- Rich "Roadie Rich" Lovely There are 10 types of people in the world: those who know binary, those who do not, and those who are off by one. From kb1pkl at aim.com Sat Sep 19 02:27:23 2009 From: kb1pkl at aim.com (Corey Richardson) Date: Fri, 18 Sep 2009 20:27:23 -0400 Subject: [Tutor] Calling a dictionary entry inside of a function Message-ID: <4AB4256B.8060600@aim.com> I am trying to use a parameter of a function to call a word inside a dictionary. Here is my code wordList = { 'Apple' : ["A delicious snack"], 'Word' : ["This code is not working..."], } def define(word): print wordList['Word'] When I use define('Apple') it returns ['This code is not working...']. I tried defining word with a raw_input, but that didn't work, and I wouldn't know how to have them define another word. -------------- next part -------------- A non-text attachment was scrubbed... Name: kb1pkl.vcf Type: text/x-vcard Size: 55 bytes Desc: not available URL: From transmogribenno at gmail.com Sat Sep 19 02:57:25 2009 From: transmogribenno at gmail.com (Benno Lang) Date: Sat, 19 Sep 2009 09:57:25 +0900 Subject: [Tutor] Calling a dictionary entry inside of a function In-Reply-To: <4AB4256B.8060600@aim.com> References: <4AB4256B.8060600@aim.com> Message-ID: <9b00d1a90909181757h4a28ad6bkdfb402c834665a2a@mail.gmail.com> On Sat, Sep 19, 2009 at 9:27 AM, Corey Richardson wrote: > I am trying to use a parameter of a function to call a word inside a > dictionary. > Here is my code > wordList = { > ? 'Apple' : ["A delicious snack"], > ? 'Word' : ["This code is not working..."], > } > def define(word): > ? print wordList['Word'] > > > When I use define('Apple') it returns ['This code is not working...']. That's what you asked it to do, but I think you meant print wordList[word] instead HTH, benno From alan.gauld at btinternet.com Sat Sep 19 03:32:32 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 19 Sep 2009 02:32:32 +0100 Subject: [Tutor] Calling a dictionary entry inside of a function In-Reply-To: <4AB4256B.8060600@aim.com> References: <4AB4256B.8060600@aim.com> Message-ID: <4AB434B0.9000509@btinternet.com> Corey Richardson wrote: > I am trying to use a parameter of a function to call a word inside a > dictionary. > Here is my code > wordList = { > 'Apple' : ["A delicious snack"], > 'Word' : ["This code is not working..."], > } > def define(word): > print wordList['Word'] > You put quotess around word which means Pythn uses the literal string 'word' as te kwey. You want to use thevalue of the variable word so you should just use word without quotes. Understanding the difference between literal values and symbolic values(variables) is very important. here is a slightly differemt example: d = {1:'first', 2:'second'} one=0 two=2 print d[1] # ok print d[one] # not ok, looking for d[0] print d[2] # ok print d[two] # ok lokking for d[2] print d['two' # not ok, looking for d['two'] HTH, Alan G. From alan.gauld at btinternet.com Sat Sep 19 03:32:32 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 19 Sep 2009 02:32:32 +0100 Subject: [Tutor] Calling a dictionary entry inside of a function In-Reply-To: <4AB4256B.8060600@aim.com> References: <4AB4256B.8060600@aim.com> Message-ID: <4AB434B0.9000509@btinternet.com> Corey Richardson wrote: > I am trying to use a parameter of a function to call a word inside a > dictionary. > Here is my code > wordList = { > 'Apple' : ["A delicious snack"], > 'Word' : ["This code is not working..."], > } > def define(word): > print wordList['Word'] > You put quotess around word which means Pythn uses the literal string 'word' as te kwey. You want to use thevalue of the variable word so you should just use word without quotes. Understanding the difference between literal values and symbolic values(variables) is very important. here is a slightly differemt example: d = {1:'first', 2:'second'} one=0 two=2 print d[1] # ok print d[one] # not ok, looking for d[0] print d[2] # ok print d[two] # ok lokking for d[2] print d['two' # not ok, looking for d['two'] HTH, Alan G. From the_only_katala at verizon.net Sat Sep 19 06:24:02 2009 From: the_only_katala at verizon.net (Katt) Date: Fri, 18 Sep 2009 21:24:02 -0700 Subject: [Tutor] Using the TIME module to extract a semi-random number References: Message-ID: <05DA0931C82E43D1BCDAF3891C55FD8B@COMPUTER01> ----- Original Message ----- > Message: 1 > Date: Wed, 16 Sep 2009 23:19:39 -0400 > From: Kent Johnson > To: Laurii > Cc: tutor at python.org > Subject: Re: [Tutor] Using the time module to extract a semi-random > number > Message-ID: > <1c2a2c590909162019l364b516cifcd2e0befe2adc87 at mail.gmail.com> > Content-Type: text/plain; charset=ISO-8859-1 > > On Wed, Sep 16, 2009 at 6:43 PM, Laurii > wrote: > >> The exercise to modify a number guessing program from a fixed number >> "number >> = 78" to using the time module and use the seconds at the time the >> program >> is used to be the number. (i.e. if the clock on your computer says >> 7:35:25 >> then it would take the 25 and place it in "number". > > time.localtime().tm_sec will give you the number of seconds as an > integer without any conversions. > > Kent > > > ------------------------------ > > Message: 2 > Date: Thu, 17 Sep 2009 10:50:11 +0200 > From: Patrick Sabin > To: Tutor at python.org > Subject: Re: [Tutor] Using the time module to extract a semi-random > number > Message-ID: <4AB1F843.1060206 at gmail.com> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > Laurii wrote: >> Hello all, >> >> I am currently reading through the Tutorial for Non-Programers by Josh >> Cogliati. I have had great success until now. >> >> The exercise to modify a number guessing program from a fixed number >> "number = 78" to using the time module and use the seconds at the time >> the program is used to be the number. (i.e. if the clock on your >> computer says 7:35:25 then it would take the 25 and place it in "number". >> > > You can either use: > > import time > number = int(time.strftime("%S")) > > or use real pseudo-random numbers: > > import random > number = random.randint(0,59) > > The latter looks clearer to me. Thank you everyone for your help. Even just the examples you have posted have been easier to understand than the python documentation. One last question on the TIME module: Is there one version of these examples that is not portable to other systems? I read something about some functions not working on other systems and I would like to ensure that the programs that I write are completely portable. Thanks again, Katt From sander.sweers at gmail.com Sat Sep 19 11:23:47 2009 From: sander.sweers at gmail.com (Sander Sweers) Date: Sat, 19 Sep 2009 11:23:47 +0200 Subject: [Tutor] Determine Filetype In-Reply-To: <1c2a2c590909181348s1f25d855j970e16863f1d9aa@mail.gmail.com> References: <48758b600909181005g3ed44078h838b28108913a5d5@mail.gmail.com> <48758b600909181121h1810e26dnde9aaa72e550bd1e@mail.gmail.com> <1c2a2c590909181226m6567709axa726982aac80fbba@mail.gmail.com> <48758b600909181233y10218cdv9b8cad2f71a752d0@mail.gmail.com> <48758b600909181310j274e48fck334c34c066ade74a@mail.gmail.com> <1c2a2c590909181348s1f25d855j970e16863f1d9aa@mail.gmail.com> Message-ID: <1253352227.11231.29.camel@infirit.homelinux.org> On Fri, 2009-09-18 at 16:48 -0400, Kent Johnson wrote: > > So, the __init__.py file of the GAE evinronment's ctypes library is > > broken, as it's importing from a package that doesn't exist. Right? > > Probably ctypes is not supported in GAE, that would be a pretty big > security hole. There is a pure python implementation on pypi [1]. It states it is in alpha and missing some features. Never used it myself though... Greets Sander [1] http://pypi.python.org/pypi/pymagic/0.1 From shsu012 at aucklanduni.ac.nz Sat Sep 19 11:03:22 2009 From: shsu012 at aucklanduni.ac.nz (shsu012 shsu012) Date: Sat, 19 Sep 2009 21:03:22 +1200 Subject: [Tutor] Problem running visual python files at home In-Reply-To: References: Message-ID: Hi Tutor, After installing python 2.6.2, there was no problem running it and completing the simple maths operations at home. However, a Microsoft Visual C++ Runtime library error keeps turning up whenever I tried to run the files which use functions imported from the visual library....(please see the attached pic) Why would an error from Microsoft C++ turn up when running python...? Thank you very much!! Regards, Sherry -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: vpython problem.JPG Type: image/jpeg Size: 111825 bytes Desc: not available URL: From kent37 at tds.net Sat Sep 19 13:24:10 2009 From: kent37 at tds.net (Kent Johnson) Date: Sat, 19 Sep 2009 07:24:10 -0400 Subject: [Tutor] Using the TIME module to extract a semi-random number In-Reply-To: <05DA0931C82E43D1BCDAF3891C55FD8B@COMPUTER01> References: <05DA0931C82E43D1BCDAF3891C55FD8B@COMPUTER01> Message-ID: <1c2a2c590909190424r173cef91q9cf4003bce52ac8e@mail.gmail.com> On Sat, Sep 19, 2009 at 12:24 AM, Katt wrote: > One last question on the TIME module: Is there one version of these examples > that is not portable to other systems? ?I read something about some > functions not working on other systems and I would like to ensure that the > programs that I write are completely portable. Generally the docs will note if a function is only available on some systems. I think all the time module functions are portable. The resolution of the timer may vary between systems but that shouldn't affect your use. Kent From kent37 at tds.net Sat Sep 19 13:52:51 2009 From: kent37 at tds.net (Kent Johnson) Date: Sat, 19 Sep 2009 07:52:51 -0400 Subject: [Tutor] Problem running visual python files at home In-Reply-To: References: Message-ID: <1c2a2c590909190452o3aa9e58flc43c42b8e218221c@mail.gmail.com> On Sat, Sep 19, 2009 at 5:03 AM, shsu012 shsu012 wrote: > However, a Microsoft Visual C++ Runtime library error keeps turning up > whenever I tried to run the files which use functions imported from the > visual library....(please see the attached pic) Please show the code that causes the error. Did you download the correct version of vpython? > Why would an error from Microsoft C++ turn up when running python...? Python, and many extension modules, is written in C. On Windows it is compiled with MS Visual Studio and uses the MS runtime. You might want to ask on the vpython mailing list. Include the exact code you are running and the version of Windows you are using in your email. Kent From davea at ieee.org Sat Sep 19 14:06:15 2009 From: davea at ieee.org (Dave Angel) Date: Sat, 19 Sep 2009 08:06:15 -0400 Subject: [Tutor] Problem running visual python files at home In-Reply-To: References: Message-ID: <4AB4C937.40108@ieee.org> shsu012 shsu012 wrote: > Hi Tutor, > After installing python 2.6.2, there was no problem running it and > completing the simple maths operations at home. > However, a Microsoft Visual C++ Runtime library error keeps turning up > whenever I tried to run the files which use functions imported from the > visual library....(please see the attached pic) > > Why would an error from Microsoft C++ turn up when running python...? > > > Thank you very much!! > > Regards, > > Sherry > > A large portion of the Python implemenation is in C, and on the Windows platform, that's compiled with Microsoft C. I don't know why you're getting that error, though. DaveA From admin at gg-lab.net Sat Sep 19 14:35:49 2009 From: admin at gg-lab.net (admin at gg-lab.net) Date: Sat, 19 Sep 2009 14:35:49 +0200 Subject: [Tutor] Determine Filetype In-Reply-To: <1253352227.11231.29.camel@infirit.homelinux.org> References: <48758b600909181005g3ed44078h838b28108913a5d5@mail.gmail.com> <48758b600909181121h1810e26dnde9aaa72e550bd1e@mail.gmail.com> <1c2a2c590909181226m6567709axa726982aac80fbba@mail.gmail.com> <48758b600909181233y10218cdv9b8cad2f71a752d0@mail.gmail.com> <48758b600909181310j274e48fck334c34c066ade74a@mail.gmail.com> <1c2a2c590909181348s1f25d855j970e16863f1d9aa@mail.gmail.com> <1253352227.11231.29.camel@infirit.homelinux.org> Message-ID: <48758b600909190535l4d496f35n4e2a0fb552e8804a@mail.gmail.com> Hi All, the solution was in the link i've posted before. If i use: type = imghdr.what('img.test', image.data) The imghdr modules ignore the filename (first argument) and takes the second as a data stream assumed to contain the filetype. The solution only works for images, but that's what i need. I think that right now is not possible to generally determine the mimetype for all types of files on GAE, because some libraries are missing. Anyway, i'll send a mail to the gae mailing list, and if find a solution i'll post it here. Thankyou all guys. 2009/9/19 Sander Sweers : > On Fri, 2009-09-18 at 16:48 -0400, Kent Johnson wrote: >> > So, the __init__.py file of the GAE evinronment's ctypes library is >> > broken, as it's importing from a package that doesn't exist. Right? >> >> Probably ctypes is not supported in GAE, that would be a pretty big >> security hole. > > There is a pure python implementation on pypi [1]. It states it is in > alpha and missing some features. Never used it myself though... > > Greets > Sander > > [1] http://pypi.python.org/pypi/pymagic/0.1 > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From admin at gg-lab.net Sat Sep 19 17:20:33 2009 From: admin at gg-lab.net (admin at gg-lab.net) Date: Sat, 19 Sep 2009 17:20:33 +0200 Subject: [Tutor] Determine Filetype In-Reply-To: <48758b600909190535l4d496f35n4e2a0fb552e8804a@mail.gmail.com> References: <48758b600909181005g3ed44078h838b28108913a5d5@mail.gmail.com> <48758b600909181121h1810e26dnde9aaa72e550bd1e@mail.gmail.com> <1c2a2c590909181226m6567709axa726982aac80fbba@mail.gmail.com> <48758b600909181233y10218cdv9b8cad2f71a752d0@mail.gmail.com> <48758b600909181310j274e48fck334c34c066ade74a@mail.gmail.com> <1c2a2c590909181348s1f25d855j970e16863f1d9aa@mail.gmail.com> <1253352227.11231.29.camel@infirit.homelinux.org> <48758b600909190535l4d496f35n4e2a0fb552e8804a@mail.gmail.com> Message-ID: <48758b600909190820n2b98ae55j3d69969061849c66@mail.gmail.com> Ops, i have another question, it seems very simple. I want to check the extension of an uploaded file. So i've created a list with allowed extensions: enabled_ext = ['gif', 'jpeg', 'png', 'bmp', 'tiff'] How can i create a simple if that check if the file ext (file_ext) is in the list? I've searched in the python tutorial, but have not been able to find any example that uses an if statement combined with a list. Thankyou again 2009/9/19 admin at gg-lab.net : > Hi All, > > the solution was in the link i've posted before. If i use: > > type = imghdr.what('img.test', image.data) > > The imghdr modules ignore the filename (first argument) and takes the > second as a data stream assumed to contain the filetype. > > The solution only works for images, but that's what i need. I think > that right now is not possible to generally determine the mimetype for > all types of files on GAE, because some libraries are missing. Anyway, > i'll send a mail to the gae mailing list, and if find a solution i'll > post it here. > > Thankyou all guys. > > 2009/9/19 Sander Sweers : >> On Fri, 2009-09-18 at 16:48 -0400, Kent Johnson wrote: >>> > So, the __init__.py file of the GAE evinronment's ctypes library is >>> > broken, as it's importing from a package that doesn't exist. Right? >>> >>> Probably ctypes is not supported in GAE, that would be a pretty big >>> security hole. >> >> There is a pure python implementation on pypi [1]. It states it is in >> alpha and missing some features. Never used it myself though... >> >> Greets >> Sander >> >> [1] http://pypi.python.org/pypi/pymagic/0.1 >> >> _______________________________________________ >> Tutor maillist ?- ?Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> > From admin at gg-lab.net Sat Sep 19 17:24:44 2009 From: admin at gg-lab.net (admin at gg-lab.net) Date: Sat, 19 Sep 2009 17:24:44 +0200 Subject: [Tutor] Determine Filetype In-Reply-To: <48758b600909190820n2b98ae55j3d69969061849c66@mail.gmail.com> References: <48758b600909181005g3ed44078h838b28108913a5d5@mail.gmail.com> <48758b600909181121h1810e26dnde9aaa72e550bd1e@mail.gmail.com> <1c2a2c590909181226m6567709axa726982aac80fbba@mail.gmail.com> <48758b600909181233y10218cdv9b8cad2f71a752d0@mail.gmail.com> <48758b600909181310j274e48fck334c34c066ade74a@mail.gmail.com> <1c2a2c590909181348s1f25d855j970e16863f1d9aa@mail.gmail.com> <1253352227.11231.29.camel@infirit.homelinux.org> <48758b600909190535l4d496f35n4e2a0fb552e8804a@mail.gmail.com> <48758b600909190820n2b98ae55j3d69969061849c66@mail.gmail.com> Message-ID: <48758b600909190824p2c318a75qe5d377689f80fbea@mail.gmail.com> if file_ext in enabled_ext Found an example some seconds ago in another mailing lists. I'm not able to find the python tutorial that describes this statement. Can you help me please? 2009/9/19 admin at gg-lab.net : > Ops, i have another question, it seems very simple. > > I want to check the extension of an uploaded file. So i've created a > list with allowed extensions: > > enabled_ext = ['gif', 'jpeg', 'png', 'bmp', 'tiff'] > > How can i create a simple if that check if the file ext (file_ext) is > in the list? > > I've searched in the python tutorial, but have not been able to find > any example that uses an if statement combined with a list. > > Thankyou again > > 2009/9/19 admin at gg-lab.net : >> Hi All, >> >> the solution was in the link i've posted before. If i use: >> >> type = imghdr.what('img.test', image.data) >> >> The imghdr modules ignore the filename (first argument) and takes the >> second as a data stream assumed to contain the filetype. >> >> The solution only works for images, but that's what i need. I think >> that right now is not possible to generally determine the mimetype for >> all types of files on GAE, because some libraries are missing. Anyway, >> i'll send a mail to the gae mailing list, and if find a solution i'll >> post it here. >> >> Thankyou all guys. >> >> 2009/9/19 Sander Sweers : >>> On Fri, 2009-09-18 at 16:48 -0400, Kent Johnson wrote: >>>> > So, the __init__.py file of the GAE evinronment's ctypes library is >>>> > broken, as it's importing from a package that doesn't exist. Right? >>>> >>>> Probably ctypes is not supported in GAE, that would be a pretty big >>>> security hole. >>> >>> There is a pure python implementation on pypi [1]. It states it is in >>> alpha and missing some features. Never used it myself though... >>> >>> Greets >>> Sander >>> >>> [1] http://pypi.python.org/pypi/pymagic/0.1 >>> >>> _______________________________________________ >>> Tutor maillist ?- ?Tutor at python.org >>> To unsubscribe or change subscription options: >>> http://mail.python.org/mailman/listinfo/tutor >>> >> > From sander.sweers at gmail.com Sat Sep 19 17:26:32 2009 From: sander.sweers at gmail.com (Sander Sweers) Date: Sat, 19 Sep 2009 16:26:32 +0100 Subject: [Tutor] Determine Filetype In-Reply-To: <48758b600909190820n2b98ae55j3d69969061849c66@mail.gmail.com> References: <48758b600909181005g3ed44078h838b28108913a5d5@mail.gmail.com> <48758b600909181121h1810e26dnde9aaa72e550bd1e@mail.gmail.com> <1c2a2c590909181226m6567709axa726982aac80fbba@mail.gmail.com> <48758b600909181233y10218cdv9b8cad2f71a752d0@mail.gmail.com> <48758b600909181310j274e48fck334c34c066ade74a@mail.gmail.com> <1c2a2c590909181348s1f25d855j970e16863f1d9aa@mail.gmail.com> <1253352227.11231.29.camel@infirit.homelinux.org> <48758b600909190535l4d496f35n4e2a0fb552e8804a@mail.gmail.com> <48758b600909190820n2b98ae55j3d69969061849c66@mail.gmail.com> Message-ID: <1253373992.11231.33.camel@infirit.homelinux.org> On Sat, 2009-09-19 at 17:20 +0200, admin at gg-lab.net wrote: > I want to check the extension of an uploaded file. So i've created a > list with allowed extensions: > > enabled_ext = ['gif', 'jpeg', 'png', 'bmp', 'tiff'] If this does not change make it s tuple. It does not change what is written below. > How can i create a simple if that check if the file ext (file_ext) is > in the list? The below idle session should help you figure it out. >>> enabled_ext = ('gif', 'jpeg', 'png', 'bmp', 'tiff') >>> 'gif' in enabled_ext True Greets Sander A: Because it messes up the order in which people normally read text. Q: Why is top-posting such a bad thing? A: Top-posting. Q: What is the most annoying thing in e-mail? From admin at gg-lab.net Sat Sep 19 17:36:31 2009 From: admin at gg-lab.net (admin at gg-lab.net) Date: Sat, 19 Sep 2009 17:36:31 +0200 Subject: [Tutor] Determine Filetype In-Reply-To: <1253373992.11231.33.camel@infirit.homelinux.org> References: <48758b600909181005g3ed44078h838b28108913a5d5@mail.gmail.com> <48758b600909181121h1810e26dnde9aaa72e550bd1e@mail.gmail.com> <1c2a2c590909181226m6567709axa726982aac80fbba@mail.gmail.com> <48758b600909181233y10218cdv9b8cad2f71a752d0@mail.gmail.com> <48758b600909181310j274e48fck334c34c066ade74a@mail.gmail.com> <1c2a2c590909181348s1f25d855j970e16863f1d9aa@mail.gmail.com> <1253352227.11231.29.camel@infirit.homelinux.org> <48758b600909190535l4d496f35n4e2a0fb552e8804a@mail.gmail.com> <48758b600909190820n2b98ae55j3d69969061849c66@mail.gmail.com> <1253373992.11231.33.camel@infirit.homelinux.org> Message-ID: <48758b600909190836q6fcfb8cdyfaa8717915e9e5ca@mail.gmail.com> 2009/9/19 Sander Sweers : > On Sat, 2009-09-19 at 17:20 +0200, admin at gg-lab.net wrote: >> I want to check the extension of an uploaded file. So i've created a >> list with allowed extensions: >> >> enabled_ext = ['gif', 'jpeg', 'png', 'bmp', 'tiff'] > > If this does not change make it s tuple. It does not change what is > written below. > >> How can i create a simple if that check if the file ext (file_ext) is >> in the list? > > The below idle session should help you figure it out. > >>>> enabled_ext = ('gif', 'jpeg', 'png', 'bmp', 'tiff') >>>> 'gif' in enabled_ext > True > > Greets > Sander > > A: Because it messes up the order in which people normally read text. > Q: Why is top-posting such a bad thing? > A: Top-posting. > Q: What is the most annoying thing in e-mail? > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Sander, sorry for the top-posting, it's the default in GMail. This is one of my first times in a mailing list, so it's possible i'm doing something wrong. Sorry again for it. I've replied to my mail, as i've found what i was looking for: if OBJECT in LIST: Well, but i'd like to read the page of the python tutorial regarding this. I'm not able to locate it. Can you help me? Thankyou From sander.sweers at gmail.com Sat Sep 19 17:50:28 2009 From: sander.sweers at gmail.com (Sander Sweers) Date: Sat, 19 Sep 2009 16:50:28 +0100 Subject: [Tutor] Determine Filetype In-Reply-To: <48758b600909190836q6fcfb8cdyfaa8717915e9e5ca@mail.gmail.com> References: <48758b600909181005g3ed44078h838b28108913a5d5@mail.gmail.com> <48758b600909181121h1810e26dnde9aaa72e550bd1e@mail.gmail.com> <1c2a2c590909181226m6567709axa726982aac80fbba@mail.gmail.com> <48758b600909181233y10218cdv9b8cad2f71a752d0@mail.gmail.com> <48758b600909181310j274e48fck334c34c066ade74a@mail.gmail.com> <1c2a2c590909181348s1f25d855j970e16863f1d9aa@mail.gmail.com> <1253352227.11231.29.camel@infirit.homelinux.org> <48758b600909190535l4d496f35n4e2a0fb552e8804a@mail.gmail.com> <48758b600909190820n2b98ae55j3d69969061849c66@mail.gmail.com> <1253373992.11231.33.camel@infirit.homelinux.org> <48758b600909190836q6fcfb8cdyfaa8717915e9e5ca@mail.gmail.com> Message-ID: <1253375428.3648.2.camel@infirit.homelinux.org> On Sat, 2009-09-19 at 17:36 +0200, admin at gg-lab.net wrote: > if OBJECT in LIST: > > Well, but i'd like to read the page of the python tutorial regarding > this. I'm not able to locate it. Can you help me? When in the python interpreter type help('in') and you should have all info you need about this. Greets Sander From alan.gauld at btinternet.com Sat Sep 19 18:31:46 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 19 Sep 2009 17:31:46 +0100 Subject: [Tutor] Determine Filetype In-Reply-To: <48758b600909190836q6fcfb8cdyfaa8717915e9e5ca@mail.gmail.com> References: <48758b600909181005g3ed44078h838b28108913a5d5@mail.gmail.com> <48758b600909181121h1810e26dnde9aaa72e550bd1e@mail.gmail.com> <1c2a2c590909181226m6567709axa726982aac80fbba@mail.gmail.com> <48758b600909181233y10218cdv9b8cad2f71a752d0@mail.gmail.com> <48758b600909181310j274e48fck334c34c066ade74a@mail.gmail.com> <1c2a2c590909181348s1f25d855j970e16863f1d9aa@mail.gmail.com> <1253352227.11231.29.camel@infirit.homelinux.org> <48758b600909190535l4d496f35n4e2a0fb552e8804a@mail.gmail.com> <48758b600909190820n2b98ae55j3d69969061849c66@mail.gmail.com> <1253373992.11231.33.camel@infirit.homelinux.org> <48758b600909190836q6fcfb8cdyfaa8717915e9e5ca@mail.gmail.com> Message-ID: <4AB50772.1010000@btinternet.com> admin at gg-lab.net wrote: > > if OBJECT in LIST: > > Well, but i'd like to read the page of the python tutorial regarding > this. I'm not able to locate it. Can you help me? Not everything is covered in the odfficial tutorial, its only meant to be an introduction to the language. You should find it in the reference documents. Look about half way down section 5.9 in the language refeence for example. but it turnsout section 5.7 of the tutorial does have a description of in.... The search feature of the web site is quite effective! :-) Alan G http://www.alan-g.me.uk From evosweet at hotmail.com Sat Sep 19 21:05:58 2009 From: evosweet at hotmail.com (Rayon) Date: Sat, 19 Sep 2009 15:05:58 -0400 Subject: [Tutor] how can I append a iteration to a tow dimensional array Message-ID: how can I append a iteration to a tow dimensional array so that one value can be like a key in a dir. I can't use a directory because some of the values repeat and the dir throws them out. def getMark(record): for x in record.split(','): return str(x).strip() array = [] for x in bigMethod(): array.append(getMark(x)) array1=[] for count in array: array1 = [[count],[x]] for v in array1: print v -------------- next part -------------- An HTML attachment was scrubbed... URL: From metolone+gmane at gmail.com Sat Sep 19 23:10:38 2009 From: metolone+gmane at gmail.com (Mark Tolonen) Date: Sat, 19 Sep 2009 14:10:38 -0700 Subject: [Tutor] how can I append a iteration to a tow dimensional array References: Message-ID: "Rayon" wrote in message news:BAY122DS664A5C474FBF157089866C3DF0 at phx.gbl... > how can I append a iteration to a tow dimensional array > so that one value can be like a key in a dir. It's unclear what behavior you are looking for, but there are a number of errors in your code below. Describe what you are trying to achieve. > I can't use a directory because some of the values repeat and the dir > throws them out. > > > def getMark(record): > for x in record.split(','): > return str(x).strip() The for statement above will not iterate, but will return the first comma-delimited thing in record. str(x) is redundant. x will be a string already. What do you want this function to do? > > array = [] > for x in bigMethod(): > array.append(getMark(x)) > array1=[] > for count in array: > array1 = [[count],[x]] > for v in array1: > print v What do you want this to do? -Mark From evosweet at hotmail.com Sun Sep 20 01:00:54 2009 From: evosweet at hotmail.com (Rayon) Date: Sat, 19 Sep 2009 19:00:54 -0400 Subject: [Tutor] list sort problem Message-ID: ok so here it is I think this one should be very clear: I have some data in a list, the data in question: 0.0046,0.095,0.0904,521456,['MCI 521456 0.0904'],['ATT 521 0.0919'],['IDT 521 0.095'],['None'] 0.0083,0.0192,0.0109,39023821,['MCI 39023821 0.0109'],['ATT 39 0.012'],['IDT 39 0.0192'],['SPR 39 0.0135'] 0.042,0.0681,0.026,73462,['MCI 73462 0.0260'],['ATT 7 0.026'],['IDT 73462 0.028'],['SPR 7 0.0681'] 0.0176,0.1035,0.0859,126872,['MCI 126872 0.0859'],['ATT 1268 0.0919'],['IDT 126872 0.1035'],['None'] 0.0215,0.1614,0.1399,5032130,['MCI 5032130 0.1614'],['ATT 5032130 0.1399'],['IDT 503 0.152'],['None'] 0.0206,0.0385,0.0179,1868,['MCI 1868 0.0179'],['ATT 1868 0.0385'],['IDT 1868 0.036'],['None'] 0.0325,0.087,0.0545,5027889,['MCI 5027889 0.0602'],['ATT 5027889 0.0545'],['IDT 502 0.087'],['None'] 0.0325,0.087,0.0545,5027888,['MCI 5027888 0.0602'],['ATT 5027888 0.0545'],['IDT 502 0.087'],['None'] 0.0046,0.095,0.0904,521455,['MCI 521455 0.0904'],['ATT 521 0.0919'],['IDT 521 0.095'],['None'] 0.1292,0.1762,0.047,5989,['MCI 5989 0.1762'],['ATT 598 0.05'],['IDT 5989 0.173'],['SPR 598 0.047'] 0.0706,0.2011,0.1305,1284499,['MCI 1284499 0.2011'],['ATT 1284499 0.1932'],['IDT 1284499 0.1305'],['None'] 0.0325,0.087,0.0545,5027881,['MCI 5027881 0.0602'],['ATT 5027881 0.0545'],['IDT 502 0.087'],['None'] my problem is that I want to order it by the first item so for line number one that would be 0.0046: this value is not unique it might repeat, if the last 10 values like this that might be the same and there are the lowest in the over list. I want them first when I display this list and the bigger values after in order is size. -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sat Sep 19 18:31:46 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 19 Sep 2009 17:31:46 +0100 Subject: [Tutor] Determine Filetype In-Reply-To: <48758b600909190836q6fcfb8cdyfaa8717915e9e5ca@mail.gmail.com> References: <48758b600909181005g3ed44078h838b28108913a5d5@mail.gmail.com> <48758b600909181121h1810e26dnde9aaa72e550bd1e@mail.gmail.com> <1c2a2c590909181226m6567709axa726982aac80fbba@mail.gmail.com> <48758b600909181233y10218cdv9b8cad2f71a752d0@mail.gmail.com> <48758b600909181310j274e48fck334c34c066ade74a@mail.gmail.com> <1c2a2c590909181348s1f25d855j970e16863f1d9aa@mail.gmail.com> <1253352227.11231.29.camel@infirit.homelinux.org> <48758b600909190535l4d496f35n4e2a0fb552e8804a@mail.gmail.com> <48758b600909190820n2b98ae55j3d69969061849c66@mail.gmail.com> <1253373992.11231.33.camel@infirit.homelinux.org> <48758b600909190836q6fcfb8cdyfaa8717915e9e5ca@mail.gmail.com> Message-ID: <4AB50772.1010000@btinternet.com> admin at gg-lab.net wrote: > > if OBJECT in LIST: > > Well, but i'd like to read the page of the python tutorial regarding > this. I'm not able to locate it. Can you help me? Not everything is covered in the odfficial tutorial, its only meant to be an introduction to the language. You should find it in the reference documents. Look about half way down section 5.9 in the language refeence for example. but it turnsout section 5.7 of the tutorial does have a description of in.... The search feature of the web site is quite effective! :-) Alan G http://www.alan-g.me.uk From davea at ieee.org Sun Sep 20 01:46:35 2009 From: davea at ieee.org (Dave Angel) Date: Sat, 19 Sep 2009 19:46:35 -0400 Subject: [Tutor] list sort problem In-Reply-To: References: Message-ID: <4AB56D5B.404@ieee.org> Rayon wrote: > ok so here it is I think this one should be very clear: > > I have some data in a list, the data in question: > > 0.0046,0.095,0.0904,521456,['MCI 521456 0.0904'],['ATT 521 0.0919'],['IDT 521 0.095'],['None'] > 0.0083,0.0192,0.0109,39023821,['MCI 39023821 0.0109'],['ATT 39 0.012'],['IDT 39 0.0192'],['SPR 39 0.0135'] > 0.042,0.0681,0.026,73462,['MCI 73462 0.0260'],['ATT 7 0.026'],['IDT 73462 0.028'],['SPR 7 0.0681'] > 0.0176,0.1035,0.0859,126872,['MCI 126872 0.0859'],['ATT 1268 0.0919'],['IDT 126872 0.1035'],['None'] > 0.0215,0.1614,0.1399,5032130,['MCI 5032130 0.1614'],['ATT 5032130 0.1399'],['IDT 503 0.152'],['None'] > 0.0206,0.0385,0.0179,1868,['MCI 1868 0.0179'],['ATT 1868 0.0385'],['IDT 1868 0.036'],['None'] > 0.0325,0.087,0.0545,5027889,['MCI 5027889 0.0602'],['ATT 5027889 0.0545'],['IDT 502 0.087'],['None'] > 0.0325,0.087,0.0545,5027888,['MCI 5027888 0.0602'],['ATT 5027888 0.0545'],['IDT 502 0.087'],['None'] > 0.0046,0.095,0.0904,521455,['MCI 521455 0.0904'],['ATT 521 0.0919'],['IDT 521 0.095'],['None'] > 0.1292,0.1762,0.047,5989,['MCI 5989 0.1762'],['ATT 598 0.05'],['IDT 5989 0.173'],['SPR 598 0.047'] > 0.0706,0.2011,0.1305,1284499,['MCI 1284499 0.2011'],['ATT 1284499 0.1932'],['IDT 1284499 0.1305'],['None'] > 0.0325,0.087,0.0545,5027881,['MCI 5027881 0.0602'],['ATT 5027881 0.0545'],['IDT 502 0.087'],['None'] > > my problem is that I want to order it by the first item so for line number one that would be 0.0046: > this value is not unique it might repeat, if the last 10 values like this that might be the same and there are the lowest in the over list. > I want them first when I display this list and the bigger values after in order is size. > > > I'll have to make some assumptions, please correct or confirm them. Each line of your message represents one item in a list. Each such item is in turn a sublist. Each of these sublists contains 3 floats, an int, and a few more subsublists Each of these subsublists contains a string Anyway, you want to sort the top-level list. Since the first item in each sublist is a float, by default they will be ordered by the first item, which is what you're asking for. In case of a collision, the second item is examined, and so on. mylist.sort() will sort the list in-place, based on the first element of each item in the list mylist = [] mylist.append( [0.0046,0.095,0.0904,521456,['MCI 521456 0.0904'],['ATT 521 0.0919'],['IDT 521 0.095'],['None']]) mylist.append( [0.0083,0.0192,0.0109,39023821,['MCI 39023821 0.0109'],['ATT 39 0.012'],['IDT 39 0.0192'],['SPR 39 0.0135']]) mylist.append( [0.042,0.0681,0.026,73462,['MCI 73462 0.0260'],['ATT 7 0.026'],['IDT 73462 0.028'],['SPR 7 0.0681']]) mylist.append( [0.0176,0.1035,0.0859,126872,['MCI 126872 0.0859'],['ATT 1268 0.0919'],['IDT 126872 0.1035'],['None']]) mylist.append( [0.0215,0.1614,0.1399,5032130,['MCI 5032130 0.1614'],['ATT 5032130 0.1399'],['IDT 503 0.152'],['None']]) mylist.append( [0.0206,0.0385,0.0179,1868,['MCI 1868 0.0179'],['ATT 1868 0.0385'],['IDT 1868 0.036'],['None']]) mylist.append( [0.0325,0.087,0.0545,5027889,['MCI 5027889 0.0602'],['ATT 5027889 0.0545'],['IDT 502 0.087'],['None']]) mylist.append( [0.0325,0.087,0.0545,5027888,['MCI 5027888 0.0602'],['ATT 5027888 0.0545'],['IDT 502 0.087'],['None']]) mylist.append( [0.0046,0.095,0.0904,521455,['MCI 521455 0.0904'],['ATT 521 0.0919'],['IDT 521 0.095'],['None']]) mylist.append( [0.1292,0.1762,0.047,5989,['MCI 5989 0.1762'],['ATT 598 0.05'],['IDT 5989 0.173'],['SPR 598 0.047']]) mylist.append( [0.0706,0.2011,0.1305,1284499,['MCI 1284499 0.2011'],['ATT 1284499 0.1932'],['IDT 1284499 0.1305'],['None']]) mylist.append( [0.0325,0.087,0.0545,5027881,['MCI 5027881 0.0602'],['ATT 5027881 0.0545'],['IDT 502 0.087'],['None']]) def show_list_partial(thelist): for item in thelist: print item[0], item[1] show_list_partial(mylist) mylist.sort() print "--------------------------------" show_list_partial(mylist) DaveA. From admin at gg-lab.net Sun Sep 20 13:06:55 2009 From: admin at gg-lab.net (admin at gg-lab.net) Date: Sun, 20 Sep 2009 13:06:55 +0200 Subject: [Tutor] Determine Filetype In-Reply-To: <4AB50772.1010000@btinternet.com> References: <48758b600909181005g3ed44078h838b28108913a5d5@mail.gmail.com> <48758b600909181233y10218cdv9b8cad2f71a752d0@mail.gmail.com> <48758b600909181310j274e48fck334c34c066ade74a@mail.gmail.com> <1c2a2c590909181348s1f25d855j970e16863f1d9aa@mail.gmail.com> <1253352227.11231.29.camel@infirit.homelinux.org> <48758b600909190535l4d496f35n4e2a0fb552e8804a@mail.gmail.com> <48758b600909190820n2b98ae55j3d69969061849c66@mail.gmail.com> <1253373992.11231.33.camel@infirit.homelinux.org> <48758b600909190836q6fcfb8cdyfaa8717915e9e5ca@mail.gmail.com> <4AB50772.1010000@btinternet.com> Message-ID: <48758b600909200406x349baa38m8d66dc2b85d94052@mail.gmail.com> Thankyou guys. > The search feature of the web site is quite effective! :-) Alan, i know that every site has a search function, but they're not so simple to be used if you're looking for a very common word ("in") and don't know other keys to find it. Regards, Giorgio From kp8 at mac.com Sun Sep 20 15:10:10 2009 From: kp8 at mac.com (kevin parks) Date: Sun, 20 Sep 2009 22:10:10 +0900 Subject: [Tutor] What is this an example of (and how can i use it?) Message-ID: <57E7CD0A-AEDA-44E3-B0CE-33D9791D5FB2@mac.com> I am afraid that in the long layoff in python has meant some new constructs have passed me by. In googling around I found some nice little code I want to use, but i don't quite understand it, how it is called, and what it is an example of. I guess there are generators and iterators now and it seems this might be an example of one of those new constructs. Can anyone explain what it is i am looking at, how it is called, and what it is an example of so that I can look it up: def roundrobin(*iterables): "roundrobin('ABC', 'D', 'EF') --> A D E B F C" # Recipe credited to George Sakkis pending = len(iterables) nexts = cycle(iter(it).next for it in iterables) while pending: try: for next in nexts: yield next() except StopIteration: pending -= 1 nexts = cycle(islice(nexts, pending)) From evosweet at hotmail.com Sun Sep 20 16:42:04 2009 From: evosweet at hotmail.com (Rayon) Date: Sun, 20 Sep 2009 10:42:04 -0400 Subject: [Tutor] list sort problem solved In-Reply-To: <4AB56D5B.404@ieee.org> References: <4AB56D5B.404@ieee.org> Message-ID: list = bigMethod() # this method makes the list list.sort() # here is the sort thanks for x in list: # out put the sort print x it all works Thanks a lot -------------------------------------------------- From: "Dave Angel" Sent: Saturday, September 19, 2009 7:46 PM To: "Rayon" Cc: Subject: Re: [Tutor] list sort problem > Rayon wrote: >> ok so here it is I think this one should be very clear: >> >> I have some data in a list, the data in question: >> 0.0046,0.095,0.0904,521456,['MCI 521456 0.0904'],['ATT 521 0.0919'],['IDT >> 521 0.095'],['None'] >> 0.0083,0.0192,0.0109,39023821,['MCI 39023821 0.0109'],['ATT 39 >> 0.012'],['IDT 39 0.0192'],['SPR 39 0.0135'] >> 0.042,0.0681,0.026,73462,['MCI 73462 0.0260'],['ATT 7 0.026'],['IDT 73462 >> 0.028'],['SPR 7 0.0681'] >> 0.0176,0.1035,0.0859,126872,['MCI 126872 0.0859'],['ATT 1268 >> 0.0919'],['IDT 126872 0.1035'],['None'] >> 0.0215,0.1614,0.1399,5032130,['MCI 5032130 0.1614'],['ATT 5032130 >> 0.1399'],['IDT 503 0.152'],['None'] >> 0.0206,0.0385,0.0179,1868,['MCI 1868 0.0179'],['ATT 1868 0.0385'],['IDT >> 1868 0.036'],['None'] >> 0.0325,0.087,0.0545,5027889,['MCI 5027889 0.0602'],['ATT 5027889 >> 0.0545'],['IDT 502 0.087'],['None'] >> 0.0325,0.087,0.0545,5027888,['MCI 5027888 0.0602'],['ATT 5027888 >> 0.0545'],['IDT 502 0.087'],['None'] >> 0.0046,0.095,0.0904,521455,['MCI 521455 0.0904'],['ATT 521 0.0919'],['IDT >> 521 0.095'],['None'] >> 0.1292,0.1762,0.047,5989,['MCI 5989 0.1762'],['ATT 598 0.05'],['IDT 5989 >> 0.173'],['SPR 598 0.047'] >> 0.0706,0.2011,0.1305,1284499,['MCI 1284499 0.2011'],['ATT 1284499 >> 0.1932'],['IDT 1284499 0.1305'],['None'] >> 0.0325,0.087,0.0545,5027881,['MCI 5027881 0.0602'],['ATT 5027881 >> 0.0545'],['IDT 502 0.087'],['None'] >> >> my problem is that I want to order it by the first item so for line >> number one that would be 0.0046: this value is not unique it might >> repeat, if the last 10 values like this that might be the same and there >> are the lowest in the over list. I want them first when I display this >> list and the bigger values after in order is size. >> >> > I'll have to make some assumptions, please correct or confirm them. > > Each line of your message represents one item in a list. Each such item > is in turn a sublist. > > Each of these sublists contains 3 floats, an int, and a few more > subsublists > > Each of these subsublists contains a string > > Anyway, you want to sort the top-level list. Since the first item in each > sublist is a float, by default they will be ordered by the first item, > which is what you're asking for. In case of a collision, the second item > is examined, and so on. > > mylist.sort() > will sort the list in-place, based on the first element of each item in > the list > > > mylist = [] > mylist.append( [0.0046,0.095,0.0904,521456,['MCI 521456 0.0904'],['ATT 521 > 0.0919'],['IDT 521 0.095'],['None']]) > mylist.append( [0.0083,0.0192,0.0109,39023821,['MCI 39023821 > 0.0109'],['ATT 39 0.012'],['IDT 39 0.0192'],['SPR 39 0.0135']]) > mylist.append( [0.042,0.0681,0.026,73462,['MCI 73462 0.0260'],['ATT 7 > 0.026'],['IDT 73462 0.028'],['SPR 7 0.0681']]) > mylist.append( [0.0176,0.1035,0.0859,126872,['MCI 126872 0.0859'],['ATT > 1268 0.0919'],['IDT 126872 0.1035'],['None']]) > mylist.append( [0.0215,0.1614,0.1399,5032130,['MCI 5032130 0.1614'],['ATT > 5032130 0.1399'],['IDT 503 0.152'],['None']]) > mylist.append( [0.0206,0.0385,0.0179,1868,['MCI 1868 0.0179'],['ATT 1868 > 0.0385'],['IDT 1868 0.036'],['None']]) > mylist.append( [0.0325,0.087,0.0545,5027889,['MCI 5027889 0.0602'],['ATT > 5027889 0.0545'],['IDT 502 0.087'],['None']]) > mylist.append( [0.0325,0.087,0.0545,5027888,['MCI 5027888 0.0602'],['ATT > 5027888 0.0545'],['IDT 502 0.087'],['None']]) > mylist.append( [0.0046,0.095,0.0904,521455,['MCI 521455 0.0904'],['ATT 521 > 0.0919'],['IDT 521 0.095'],['None']]) > mylist.append( [0.1292,0.1762,0.047,5989,['MCI 5989 0.1762'],['ATT 598 > 0.05'],['IDT 5989 0.173'],['SPR 598 0.047']]) > mylist.append( [0.0706,0.2011,0.1305,1284499,['MCI 1284499 0.2011'],['ATT > 1284499 0.1932'],['IDT 1284499 0.1305'],['None']]) > mylist.append( [0.0325,0.087,0.0545,5027881,['MCI 5027881 0.0602'],['ATT > 5027881 0.0545'],['IDT 502 0.087'],['None']]) > > def show_list_partial(thelist): > for item in thelist: > print item[0], item[1] > > show_list_partial(mylist) > mylist.sort() > print "--------------------------------" > show_list_partial(mylist) > > > DaveA. > > > From davea at ieee.org Sun Sep 20 17:30:41 2009 From: davea at ieee.org (Dave Angel) Date: Sun, 20 Sep 2009 11:30:41 -0400 Subject: [Tutor] list sort problem solved In-Reply-To: References: <4AB56D5B.404@ieee.org> Message-ID: <4AB64AA1.8020102@ieee.org> Rayon wrote: > list = bigMethod() # this method makes the list > > list.sort() # here is the sort thanks > for x in list: # out put the sort > print x > > it all works Thanks a lot > -------------------------------------------------- > From: "Dave Angel" > Sent: Saturday, September 19, 2009 7:46 PM > To: "Rayon" > Cc: > Subject: Re: [Tutor] list sort problem > >> Rayon wrote: >>> ok so here it is I think this one should be very clear: >>> >>> I have some data in a list, the data in question: >>> 0.0046,0.095,0.0904,521456,['MCI 521456 0.0904'],['ATT 521 >>> 0.0919'],['IDT 521 0.095'],['None'] >>> 0.0083,0.0192,0.0109,39023821,['MCI 39023821 0.0109'],['ATT 39 >>> 0.012'],['IDT 39 0.0192'],['SPR 39 0.0135'] >>> 0.042,0.0681,0.026,73462,['MCI 73462 0.0260'],['ATT 7 0.026'],['IDT >>> 73462 0.028'],['SPR 7 0.0681'] >>> 0.0176,0.1035,0.0859,126872,['MCI 126872 0.0859'],['ATT 1268 >>> 0.0919'],['IDT 126872 0.1035'],['None'] >>> 0.0215,0.1614,0.1399,5032130,['MCI 5032130 0.1614'],['ATT 5032130 >>> 0.1399'],['IDT 503 0.152'],['None'] >>> 0.0206,0.0385,0.0179,1868,['MCI 1868 0.0179'],['ATT 1868 >>> 0.0385'],['IDT 1868 0.036'],['None'] >>> 0.0325,0.087,0.0545,5027889,['MCI 5027889 0.0602'],['ATT 5027889 >>> 0.0545'],['IDT 502 0.087'],['None'] >>> 0.0325,0.087,0.0545,5027888,['MCI 5027888 0.0602'],['ATT 5027888 >>> 0.0545'],['IDT 502 0.087'],['None'] >>> 0.0046,0.095,0.0904,521455,['MCI 521455 0.0904'],['ATT 521 >>> 0.0919'],['IDT 521 0.095'],['None'] >>> 0.1292,0.1762,0.047,5989,['MCI 5989 0.1762'],['ATT 598 0.05'],['IDT >>> 5989 0.173'],['SPR 598 0.047'] >>> 0.0706,0.2011,0.1305,1284499,['MCI 1284499 0.2011'],['ATT 1284499 >>> 0.1932'],['IDT 1284499 0.1305'],['None'] >>> 0.0325,0.087,0.0545,5027881,['MCI 5027881 0.0602'],['ATT 5027881 >>> 0.0545'],['IDT 502 0.087'],['None'] >>> >>> my problem is that I want to order it by the first item so for line >>> number one that would be 0.0046: this value is not unique it might >>> repeat, if the last 10 values like this that might be the same and >>> there are the lowest in the over list. I want them first when I >>> display this list and the bigger values after in order is size. >>> >>> >> I'll have to make some assumptions, please correct or confirm them. >> >> Each line of your message represents one item in a list. Each such >> item is in turn a sublist. >> >> Each of these sublists contains 3 floats, an int, and a few more >> subsublists >> >> Each of these subsublists contains a string >> >> Anyway, you want to sort the top-level list. Since the first item in >> each sublist is a float, by default they will be ordered by the first >> item, which is what you're asking for. In case of a collision, the >> second item is examined, and so on. >> >> mylist.sort() >> will sort the list in-place, based on the first element of each item >> in the list >> >> >> mylist = [] >> mylist.append( [0.0046,0.095,0.0904,521456,['MCI 521456 >> 0.0904'],['ATT 521 0.0919'],['IDT 521 0.095'],['None']]) >> mylist.append( [0.0083,0.0192,0.0109,39023821,['MCI 39023821 >> 0.0109'],['ATT 39 0.012'],['IDT 39 0.0192'],['SPR 39 0.0135']]) >> mylist.append( [0.042,0.0681,0.026,73462,['MCI 73462 0.0260'],['ATT 7 >> 0.026'],['IDT 73462 0.028'],['SPR 7 0.0681']]) >> mylist.append( [0.0176,0.1035,0.0859,126872,['MCI 126872 >> 0.0859'],['ATT 1268 0.0919'],['IDT 126872 0.1035'],['None']]) >> mylist.append( [0.0215,0.1614,0.1399,5032130,['MCI 5032130 >> 0.1614'],['ATT 5032130 0.1399'],['IDT 503 0.152'],['None']]) >> mylist.append( [0.0206,0.0385,0.0179,1868,['MCI 1868 0.0179'],['ATT >> 1868 0.0385'],['IDT 1868 0.036'],['None']]) >> mylist.append( [0.0325,0.087,0.0545,5027889,['MCI 5027889 >> 0.0602'],['ATT 5027889 0.0545'],['IDT 502 0.087'],['None']]) >> mylist.append( [0.0325,0.087,0.0545,5027888,['MCI 5027888 >> 0.0602'],['ATT 5027888 0.0545'],['IDT 502 0.087'],['None']]) >> mylist.append( [0.0046,0.095,0.0904,521455,['MCI 521455 >> 0.0904'],['ATT 521 0.0919'],['IDT 521 0.095'],['None']]) >> mylist.append( [0.1292,0.1762,0.047,5989,['MCI 5989 0.1762'],['ATT >> 598 0.05'],['IDT 5989 0.173'],['SPR 598 0.047']]) >> mylist.append( [0.0706,0.2011,0.1305,1284499,['MCI 1284499 >> 0.2011'],['ATT 1284499 0.1932'],['IDT 1284499 0.1305'],['None']]) >> mylist.append( [0.0325,0.087,0.0545,5027881,['MCI 5027881 >> 0.0602'],['ATT 5027881 0.0545'],['IDT 502 0.087'],['None']]) >> >> def show_list_partial(thelist): >> for item in thelist: >> print item[0], item[1] >> >> show_list_partial(mylist) >> mylist.sort() >> print "--------------------------------" >> show_list_partial(mylist) >> >> >> DaveA. >> >> >> Two comments: 1) don't top-post. In these forums, it really confuses things to put your message out of order. 2) list already has a meaning in Python. Name your attribute something else. I used mylist in my example. Better would be something plural that's descriptive of what's contained in this list, such as shoes= big_method() From kent37 at tds.net Sun Sep 20 17:53:33 2009 From: kent37 at tds.net (Kent Johnson) Date: Sun, 20 Sep 2009 11:53:33 -0400 Subject: [Tutor] What is this an example of (and how can i use it?) In-Reply-To: <57E7CD0A-AEDA-44E3-B0CE-33D9791D5FB2@mac.com> References: <57E7CD0A-AEDA-44E3-B0CE-33D9791D5FB2@mac.com> Message-ID: <1c2a2c590909200853g4a1058e6xb489654d37645626@mail.gmail.com> On Sun, Sep 20, 2009 at 9:10 AM, kevin parks wrote: > I am afraid that in the long layoff in python has meant some new constructs > have passed me by. In googling around I found some nice little code I want > to use, but i don't quite understand it, how it is called, and what it is an > example of. I guess there are generators and iterators now and it seems this > might be an example of one of those new constructs. Can anyone explain what > it is i am looking at, how it is called, and what it is an example of so > that I can look it up: > > def roundrobin(*iterables): > ? ?"roundrobin('ABC', 'D', 'EF') --> A D E B F C" > ? ?# Recipe credited to George Sakkis The original is here, with an explanation of what it does. > ? ?pending = len(iterables) > ? ?nexts = cycle(iter(it).next for it in iterables) cycle() is part of itertools: http://docs.python.org/library/itertools.html#itertools.cycle You can read about iter() and iterators here: http://docs.python.org/library/functions.html#iter http://docs.python.org/glossary.html#term-iterator (iter(it).next for it in iterables) is a generator expression. It creates an iterator. The above statement as a whole makes an iterator which will return the iterators of the arguments in turn, repeatedly. > ? ?while pending: > ? ? ? ?try: > ? ? ? ? ? ?for next in nexts: > ? ? ? ? ? ? ? ?yield next() The yield statement makes this into a generator function. It's return value is a generator - a kind of iterator. > ? ? ? ?except StopIteration: next() will raise StopIteration when its underlying iterable is exhausted. > ? ? ? ? ? ?pending -= 1 > ? ? ? ? ? ?nexts = cycle(islice(nexts, pending)) This is kind of tricky - it makes a new cycle of iterators that omits the one that just finished. I have a writeup of iterators and generators here: http://personalpages.tds.net/~kent37/kk/00004.html HTH, Kent From alan.gauld at btinternet.com Sun Sep 20 18:26:16 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 20 Sep 2009 17:26:16 +0100 Subject: [Tutor] Determine Filetype In-Reply-To: <48758b600909200406x349baa38m8d66dc2b85d94052@mail.gmail.com> References: <48758b600909181005g3ed44078h838b28108913a5d5@mail.gmail.com> <48758b600909181233y10218cdv9b8cad2f71a752d0@mail.gmail.com> <48758b600909181310j274e48fck334c34c066ade74a@mail.gmail.com> <1c2a2c590909181348s1f25d855j970e16863f1d9aa@mail.gmail.com> <1253352227.11231.29.camel@infirit.homelinux.org> <48758b600909190535l4d496f35n4e2a0fb552e8804a@mail.gmail.com> <48758b600909190820n2b98ae55j3d69969061849c66@mail.gmail.com> <1253373992.11231.33.camel@infirit.homelinux.org> <48758b600909190836q6fcfb8cdyfaa8717915e9e5ca@mail.gmail.com> <4AB50772.1010000@btinternet.com> <48758b600909200406x349baa38m8d66dc2b85d94052@mail.gmail.com> Message-ID: <4AB657A8.2050508@btinternet.com> admin at gg-lab.net wrote: >> The search feature of the web site is quite effective! :-) > simple to be used if you're looking for a very common word ("in") and > don't know other keys to find it. To be honest I was being a bit optimistic but I did just type "in" for the search and the first 5 or so hits had all the right bits... Alan G From alan.gauld at btinternet.com Sun Sep 20 18:32:14 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 20 Sep 2009 17:32:14 +0100 Subject: [Tutor] What is this an example of (and how can i use it?) In-Reply-To: <57E7CD0A-AEDA-44E3-B0CE-33D9791D5FB2@mac.com> References: <57E7CD0A-AEDA-44E3-B0CE-33D9791D5FB2@mac.com> Message-ID: <4AB6590E.5040601@btinternet.com> kevin parks wrote: > called, and what it is an example of. I guess there are generators and > iterators now and it seems this might be an example of one of those new This is a generator expression. It is like a list comprehension (you know about those right?) except it doesn't create the list it just returns each item on demand. You could think of a list as a list constructed using a generator expression. > def roundrobin(*iterables): > "roundrobin('ABC', 'D', 'EF') --> A D E B F C" > # Recipe credited to George Sakkis > pending = len(iterables) > nexts = cycle(iter(it).next for it in iterables) note this is storing the next methods not the results of them. > while pending: > try: > for next in nexts: > yield next() So the yield calls the stored method and returns the result. HTH, Alan G. From kp8 at mac.com Sun Sep 20 19:27:34 2009 From: kp8 at mac.com (kevin parks) Date: Mon, 21 Sep 2009 02:27:34 +0900 Subject: [Tutor] What is this an example of (and how can i use it?) In-Reply-To: <4AB6590E.5040601@btinternet.com> References: <57E7CD0A-AEDA-44E3-B0CE-33D9791D5FB2@mac.com> <4AB6590E.5040601@btinternet.com> Message-ID: <6B75B7D9-DD9E-4F64-973E-50F165796186@mac.com> On Sep 21, 2009, at 1:32 AM, Alan Gauld wrote: > kevin parks wrote: > >> called, and what it is an example of. I guess there are generators >> and iterators now and it seems this might be an example of one of >> those new > > This is a generator expression. That's unfortunate news for me. > It is like a list comprehension (you know about those right?) Yes. I know and use and love them daily. Even if there were implemented backwards :) [for x in range(10) x**2] would have been easier than: [x**2 for x in range(10)] But i am used to it now. > except it doesn't create the list it just returns each item on > demand. You could think of a list as a list constructed using a > generator expression. > >> def roundrobin(*iterables): >> "roundrobin('ABC', 'D', 'EF') --> A D E B F C" >> # Recipe credited to George Sakkis >> pending = len(iterables) >> nexts = cycle(iter(it).next for it in iterables) > > note this is storing the next methods not the results of them. > >> while pending: >> try: >> for next in nexts: >> yield next() > > So the yield calls the stored method and returns the result. So... then to call (by call i mean use/execute/doit) i would do, what? foo.next() I kinda understand conceptually what iterators and generators do and why they are "a honking good idea" (why create 100 of x when we just want the 100th, etc.) what i don't get is the syntax and how they are used in real life. How generator and iterators behave in the wild. I am also bummed since generators have methods, which means they are OO which means i am i'd be in for 16 years of computer science study and super arcane, obscure and opaque concepts like what to do with __self__ and all that junk before i can use them. Anyway i needed a pea shooter that does a round robin. This one does it, but i don't know how to use it. I read up on gennies and itties and see if i can get my head around it. They are really poorly addressed nearly everywhere i look. They are explained so that really smart folks who know a lot of CS and are fluent in 15 computer languages can understand them, but not us mortals. Even the Lutz is too terse and generally poor on these two complex and relatively new constructs. They are a dark and obscure magic. I'll try the links Kent pointed me to first and see how that goes. thanks, -kp-- From jfabiani at yolo.com Sun Sep 20 21:40:42 2009 From: jfabiani at yolo.com (John) Date: Sun, 20 Sep 2009 12:40:42 -0700 Subject: [Tutor] real world decorators Message-ID: <200909201240.42441.jfabiani@yolo.com> Hi, I think I understand what decorators are and how they work. Maybe it's just me but I don't know where I'd use them in my real world programming. I see how they work with profile or coverage but does anyone have real world uses. I mostly create wxPython apps and don't see where they might apply. I know the tutors will enlighten me! Johnf From bmxx5386 at aol.com Sun Sep 20 22:19:08 2009 From: bmxx5386 at aol.com (daggerdvm) Date: Sun, 20 Sep 2009 13:19:08 -0700 (PDT) Subject: [Tutor] eazy python question involving functions and parameters Message-ID: <25530128.post@talk.nabble.com> assume that jade2 is a function that expects two int parameters and returns the value of the larger one. Also assume that four variables, population1 , population2 , population3 , and population4 have already been defined and associated with int values. Write an expression (not a statement!) whose value is the largest of population1 , population2 , population3 , and population4 by calling jade2 . how can i do this??? -- View this message in context: http://www.nabble.com/eazy-python-question-involving-functions-and-parameters-tp25530128p25530128.html Sent from the Python - tutor mailing list archive at Nabble.com. From steve at alchemy.com Sun Sep 20 22:24:44 2009 From: steve at alchemy.com (Steve Willoughby) Date: Sun, 20 Sep 2009 13:24:44 -0700 Subject: [Tutor] eazy python question involving functions and parameters In-Reply-To: <25530128.post@talk.nabble.com> References: <25530128.post@talk.nabble.com> Message-ID: <20090920202444.GA53575@dragon.alchemy.com> On Sun, Sep 20, 2009 at 01:19:08PM -0700, daggerdvm wrote: > assume that jade2 is a function that expects two int parameters and returns > the value of the larger one. This really smells like a school assignment, which as a general policy we don't solve for you. But as a hint in the right direction, you might look at how parameters are passed to functions in Python (and it's irrelevant that they are int values as far as parameter passing goes, but that will simplify your expression for the sake of keeping the assignment easy to do). You might want to look at some built-in functions which will look at a list of values and tell you which is biggest or smallest. What do you think you can do with those pieces? > > Also assume that four variables, population1 , population2 , population3 > , and population4 have already been defined and associated with int > values. > > Write an expression (not a statement!) whose value is the largest of > population1 , population2 , population3 , and population4 by calling > jade2 . > > how can i do this??? > > > -- > View this message in context: http://www.nabble.com/eazy-python-question-involving-functions-and-parameters-tp25530128p25530128.html > Sent from the Python - tutor mailing list archive at Nabble.com. > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -- Steve Willoughby | Using billion-dollar satellites steve at alchemy.com | to hunt for Tupperware. From eike.welk at gmx.net Mon Sep 21 00:43:32 2009 From: eike.welk at gmx.net (Eike Welk) Date: Mon, 21 Sep 2009 00:43:32 +0200 Subject: [Tutor] real world decorators In-Reply-To: <200909201240.42441.jfabiani@yolo.com> References: <200909201240.42441.jfabiani@yolo.com> Message-ID: <200909210043.32490.eike.welk@gmx.net> On Sunday 20 September 2009, John wrote: > Hi, > > I think I understand what decorators are and how they work. Maybe > it's just me but I don't know where I'd use them in my real world > programming. I see how they work with profile or coverage but does > anyone have real world uses. Frequently used are @classmethod and @staticmethod: http://docs.python.org/library/functions.html#classmethod An other interesting usage of decorators is Phillip J. Eby's 'simplegeneric' library, where decorated functions replace big if... elif... constructions: http://cheeseshop.python.org/pypi/simplegeneric/0.6 But really decorators are just syntactical sugar. They are an elegant way to write a special case of a function call. Kind regards, Eike. From transmogribenno at gmail.com Mon Sep 21 00:52:01 2009 From: transmogribenno at gmail.com (Benno Lang) Date: Mon, 21 Sep 2009 07:52:01 +0900 Subject: [Tutor] eazy python question involving functions and parameters In-Reply-To: <25530128.post@talk.nabble.com> References: <25530128.post@talk.nabble.com> Message-ID: <9b00d1a90909201552n714accc4vc4a768b8a95a658@mail.gmail.com> On Mon, Sep 21, 2009 at 5:19 AM, daggerdvm wrote: > > assume that ?jade2 is a function that expects two ?int parameters and returns > the value of the larger one. > > Also assume that four variables, ?population1 , ?population2 , ?population3 > , and ?population4 have already been defined and associated with ?int > values. > > Write an expression (not a statement!) whose value is the largest of > population1 , ?population2 , ?population3 , and ?population4 by calling > jade2 . Just think: 4 players left means that this is the semi final. Regards, benno From alan.gauld at btinternet.com Mon Sep 21 02:20:26 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 21 Sep 2009 01:20:26 +0100 Subject: [Tutor] What is this an example of (and how can i use it?) In-Reply-To: <6B75B7D9-DD9E-4F64-973E-50F165796186@mac.com> References: <57E7CD0A-AEDA-44E3-B0CE-33D9791D5FB2@mac.com> <4AB6590E.5040601@btinternet.com> <6B75B7D9-DD9E-4F64-973E-50F165796186@mac.com> Message-ID: <4AB6C6CA.2020903@btinternet.com> kevin parks wrote: >> This is a generator expression. > > That's unfortunate news for me. > >> It is like a list comprehension (you know about those right?) > > Yes. I know and use and love them daily. If you can grok comprehensions then you are only a step away from generator expressions. Most of the time you don't need to think about the hairy CS stuff underneath, just use them. I found the jump to using comprehensions much bigger than the jump from them to generator expressions! >> You could think of a list as a list constructed using a generator >> expression. should have been ....a list comprehension as a list.... >>> nexts = cycle(iter(it).next for it in iterables) >> >> note this is storing the next methods not the results of them. >> >>> while pending: >>> for next in nexts: >>> yield next() >> >> So the yield calls the stored method and returns the result. > > So... then to call (by call i mean use/execute/doit) i would do, what? > foo.next() That depends on what next() actually returns. e started off with a list of iterables (eg files strings, lists, tuples - possibly a mixture of them. We then build a list of their next methods. So when we call this methods we get back an instance of whatever was in the original list of iterators. Hee isa slightly less complex example: >>> its = [[1,2,3],'abc'] >>> nxts = [iter(n).next for n in its] >>> for repeats in range(2): for n in nxts: print n() 1 a 2 b So the first for n loop printed out the first item in each iterable, the next time round we printed the second item etc. Each iteration prints a number and a letter So when your yield returns its value you have to do with it whatever is appropriate! > I kinda understand conceptually what iterators and generators do and why > they are "a honking good idea" (why create 100 of x when we just want > the 100th, etc.) what i don't get is the syntax and how they are used in > real life. ignore the memory management magic and just think of them returning the next item in a list on demand. Have you ever used xrange() instead of range()? Its the same thing. > bummed since generators have methods, which means they are OO So do lists but you said you use lists every day! You use objects everywhere in Python, everything is an object and has methods. try: >>> dir(6) don't be freaked by objects, you use them already every day. > means i am i'd be in for 16 years of computer science study and super > arcane, obscure and opaque concepts like what to do with __self__ and You can do all sorts of clever black magic type stuff in Python even without OOP but mostly you don't need to, just keep it simple. > Anyway i needed a pea shooter that does a round robin. This one does it, > but i don't know how to use it. Actually the example you quoted is a fairly sophisticated bit of code that probably does more than you need. What exactly are you trying to achieve, there is probably an easier way! > I read up on gennies and itties and see if i can get my head around it. > They are really poorly addressed nearly everywhere i look. They are > explained so that really smart folks who know a lot of CS and are fluent > in 15 computer languages can understand them, but not us mortals. Even They are difficult conceptually, but if you concentrate on the examples of use and don't try to be too ambitious initially they will grow on you like comprehensions did. And remember, you never need them. There are always alternative ways to do it, just using a bit more code usually. HTH, Alan G. http://www.alan-g.me.uk From alan.gauld at btinternet.com Mon Sep 21 02:25:09 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 21 Sep 2009 01:25:09 +0100 Subject: [Tutor] eazy python question involving functions and parameters In-Reply-To: <9b00d1a90909201552n714accc4vc4a768b8a95a658@mail.gmail.com> References: <25530128.post@talk.nabble.com> <9b00d1a90909201552n714accc4vc4a768b8a95a658@mail.gmail.com> Message-ID: > Just think: 4 players left means that this is the semi final. > What a brilliant answer! It tells him how to do it if he just stops and thinks but gives nothing away. I love it. :-) Alan G. From kent37 at tds.net Mon Sep 21 02:42:21 2009 From: kent37 at tds.net (Kent Johnson) Date: Sun, 20 Sep 2009 20:42:21 -0400 Subject: [Tutor] real world decorators In-Reply-To: <200909201240.42441.jfabiani@yolo.com> References: <200909201240.42441.jfabiani@yolo.com> Message-ID: <1c2a2c590909201742v660386aeja44f78de18f078c9@mail.gmail.com> On Sun, Sep 20, 2009 at 3:40 PM, John wrote: > Hi, > > I think I understand what decorators are and how they work. ?Maybe it's just > me but I don't know where I'd use them in my real world programming. ?I see > how they work with profile or coverage but does anyone have real world uses. Here are some examples: http://wiki.python.org/moin/PythonDecoratorLibrary TurboGears uses decorators to expose functions to the web. Django has decorators for authentication and caching. Kent From kent37 at tds.net Mon Sep 21 02:52:24 2009 From: kent37 at tds.net (Kent Johnson) Date: Sun, 20 Sep 2009 20:52:24 -0400 Subject: [Tutor] What is this an example of (and how can i use it?) In-Reply-To: <6B75B7D9-DD9E-4F64-973E-50F165796186@mac.com> References: <57E7CD0A-AEDA-44E3-B0CE-33D9791D5FB2@mac.com> <4AB6590E.5040601@btinternet.com> <6B75B7D9-DD9E-4F64-973E-50F165796186@mac.com> Message-ID: <1c2a2c590909201752o5ab3c1d5v81bff0e7bdbee7ca@mail.gmail.com> On Sun, Sep 20, 2009 at 1:27 PM, kevin parks wrote: > > On Sep 21, 2009, at 1:32 AM, Alan Gauld wrote: > >> kevin parks wrote: >> >>> called, and what it is an example of. I guess there are generators and >>> iterators now and it seems this might be an example of one of those new >> >> This is a generator expression. > > That's unfortunate news for me. Why? > So... then to call (by call i mean use/execute/doit) i would do, what? > foo.next() Are you asking how to use a generator function? There is a simple example on the recipe page (sorry, I omitted the link earlier) http://code.activestate.com/recipes/528936/ >>> list(roundrobin('abc', [], range(4), (True,False))) ['a', 0, True, 'b', 1, False, 'c', 2, 3] Calling a generator function gives you something that can be iterated. You can create a list out of it (by passing it to the list() function) or you can iterate the items in it directly with a for loop. Using the example above, you could say for item in roundrobin('abc', [], range(4), (True,False)): print item > I kinda understand conceptually what iterators and generators do and why > they are "a honking good idea" (why create 100 of x when we just want the > 100th, etc.) what i don't get is the syntax and how they are used in real > life. How generator and iterators behave in the wild. It's really not that bad. They are just a generalization of what you have already been doing with lists. > Even the Lutz is too > terse and generally poor on these two complex and relatively new constructs. > They are a dark and obscure magic. No, really they are not difficult. Read my essay and ask questions if you don't understand. Kent From kb1pkl at aim.com Mon Sep 21 03:57:19 2009 From: kb1pkl at aim.com (Corey Richardson) Date: Sun, 20 Sep 2009 21:57:19 -0400 Subject: [Tutor] eazy python question involving functions and, parameters Message-ID: <4AB6DD7F.9020705@aim.com> assume that jade2 is a function that expects two int parameters and returns the value of the larger one. Also assume that four variables, population1 , population2 , population3 , and population4 have already been defined and associated with int values. Write an expression (not a statement!) whose value is the largest of population1 , population2 , population3 , and population4 by calling jade2 . how can i do this??? What are you trying to do?? I would like to help, but like Alan said, it really does reek of school. I don't quite understand what you are saying, could you elaborate? -------------- next part -------------- A non-text attachment was scrubbed... Name: kb1pkl.vcf Type: text/x-vcard Size: 55 bytes Desc: not available URL: From hayalok at gmail.com Mon Sep 21 05:18:56 2009 From: hayalok at gmail.com (alok mishra) Date: Mon, 21 Sep 2009 08:48:56 +0530 Subject: [Tutor] mailing list submission Message-ID: <3520b7180909202018m77b8bd47v8e27b87a3a102f2f@mail.gmail.com> -- have a good day From wescpy at gmail.com Mon Sep 21 10:49:11 2009 From: wescpy at gmail.com (wesley chun) Date: Mon, 21 Sep 2009 01:49:11 -0700 Subject: [Tutor] eazy python question involving functions and parameters In-Reply-To: References: <25530128.post@talk.nabble.com> <9b00d1a90909201552n714accc4vc4a768b8a95a658@mail.gmail.com> Message-ID: <78b3a9580909210149l5ad46120ta58fa1f6872cadcb@mail.gmail.com> >> Just think: 4 players left means that this is the semi final. > > What a brilliant answer! It tells him how to do it if he just stops and > thinks but gives nothing away. I love it. :-) i agree with alan on this. in fact, i can just picture the brackets in my head already. :-) another thing from the OP that no one has addressed yet is what *this* means: > > Write an expression (not a statement!) to the veterans, we don't have to think twice, but this may not be obvious to a beginner. basically, an expression is something like 4 * 5, foo(), [x for x in range(5)], etc. that evaluates to *some* Python object, like a number, instance, or a list, etc. this also includes function (calls) because it is associated with the single return value that comes back from every call. in contrast, a statement is something that has no intrinsic value (nor associated Python object), such as print, pass, continue, or any keywords like those. hope this helps too! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 "Python Fundamentals", Prentice Hall, (c)2009 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From patrick.just4fun at gmail.com Mon Sep 21 13:21:26 2009 From: patrick.just4fun at gmail.com (Patrick Sabin) Date: Mon, 21 Sep 2009 13:21:26 +0200 Subject: [Tutor] real world decorators In-Reply-To: <200909201240.42441.jfabiani@yolo.com> References: <200909201240.42441.jfabiani@yolo.com> Message-ID: <4AB761B6.8060300@gmail.com> John wrote: > Hi, > > I think I understand what decorators are and how they work. Maybe it's just > me but I don't know where I'd use them in my real world programming. I see > how they work with profile or coverage but does anyone have real world uses. @classmethod, @staticmethod, @property, @abstractclass, @abstractproperty are in my opinion the most import. Some toolkits use them too. > I mostly create wxPython apps and don't see where they might apply. The wx toolkit is designed to work with C++ and wxPython is just a language binding for it. As far as I know C++ doesn't support Decorators or something similar like it. So there won't be many uses for decorators in wx apps. > I know the tutors will enlighten me! Some ideas for decorators, if you want to play around with them: @fireandforget Make a function call in another thread, so you can return immediately - without returning result. This could be for example useful to send an email without needing to wait, until it is sent. @cache Cache the results of a function in a dictionary. If the function is called look up the value of the cache first. This only works with side-effect free functions of course. @timeout Check if the execution time of a function exceeds a timeout limit. If so raise an exception. @ignoreexceptions In my opinion, you should avoid using decorators in productive code, if you don't have a good reason to do otherwise. Every decorator adds some sort of "magic" to your program and using too much "magic" will make it difficult to maintain. - Patrick From ksterling at mindspring.com Mon Sep 21 14:54:53 2009 From: ksterling at mindspring.com (Ken Oliver) Date: Mon, 21 Sep 2009 08:54:53 -0400 (EDT) Subject: [Tutor] eazy python question involving functions and parameters Message-ID: <20166798.1253537693540.JavaMail.root@elwamui-cypress.atl.sa.earthlink.net> -----Original Message----- >From: wesley chun >Sent: Sep 21, 2009 4:49 AM >To: tutor at python.org >Subject: Re: [Tutor] eazy python question involving functions and parameters > >>> Just think: 4 players left means that this is the semi final. >> >> What a brilliant answer! It tells him how to do it if he just stops and >> thinks but gives nothing away. I love it. :-) > >i agree with alan on this. in fact, i can just picture the brackets in >my head already. :-) Couldn't this be a king of the hill type of competition with winner of first contest takes on a remaining challenger and the winner of that takes on the last challenger? . From jfabiani at yolo.com Mon Sep 21 18:14:07 2009 From: jfabiani at yolo.com (John) Date: Mon, 21 Sep 2009 09:14:07 -0700 Subject: [Tutor] real world decorators In-Reply-To: <200909210043.32490.eike.welk@gmx.net> References: <200909201240.42441.jfabiani@yolo.com> <200909210043.32490.eike.welk@gmx.net> Message-ID: <200909210914.07837.jfabiani@yolo.com> On Sunday 20 September 2009 03:43:32 pm Eike Welk wrote: > On Sunday 20 September 2009, John wrote: > > Hi, > > > > I think I understand what decorators are and how they work. Maybe > > it's just me but I don't know where I'd use them in my real world > > programming. I see how they work with profile or coverage but does > > anyone have real world uses. > > Frequently used are @classmethod and @staticmethod: > http://docs.python.org/library/functions.html#classmethod > > An other interesting usage of decorators is Phillip J. > Eby's 'simplegeneric' library, where decorated functions replace big > if... elif... constructions: > http://cheeseshop.python.org/pypi/simplegeneric/0.6 > > But really decorators are just syntactical sugar. They are an elegant > way to write a special case of a function call. > > Kind regards, > Eike. Thanks to all that responded on list and off. You guys have provided much to read. Thanks Johnf From kb1pkl at aim.com Mon Sep 21 21:03:43 2009 From: kb1pkl at aim.com (Corey Richardson) Date: Mon, 21 Sep 2009 15:03:43 -0400 Subject: [Tutor] eazy python question involving functions and parameters Message-ID: <4AB7CE0F.60708@aim.com> another thing from the OP that no one has addressed yet is what *this* means: >/ > Write an expression (not a statement!) / to the veterans, we don't have to think twice, but this may not be obvious to a beginner. basically, an expression is something like 4 * 5, foo(), [x for x in range(5)], etc. that evaluates to *some* Python object, like a number, instance, or a list, etc. this also includes function (calls) because it is associated with the single return value that comes back from every call. in contrast, a statement is something that has no intrinsic value (nor associated Python object), such as print, pass, continue, or any keywords like those. hope this helps too! -- wesley Umm.....you just completely confused me. What does it do? -------------- next part -------------- A non-text attachment was scrubbed... Name: kb1pkl.vcf Type: text/x-vcard Size: 55 bytes Desc: not available URL: From wescpy at gmail.com Mon Sep 21 21:47:32 2009 From: wescpy at gmail.com (wesley chun) Date: Mon, 21 Sep 2009 12:47:32 -0700 Subject: [Tutor] eazy python question involving functions and parameters In-Reply-To: <4AB7CE0F.60708@aim.com> References: <4AB7CE0F.60708@aim.com> Message-ID: <78b3a9580909211247p22f22c05oc431380a202eef80@mail.gmail.com> >> an expression is something ... that evaluates to *some* Python object >> : >> in contrast, a statement is something that has no intrinsic value > > ? ? ? ? ? ? ? Umm.....you just completely confused me. What does it do? ok, now *i*'m the one confused... what does *what* do? both expressions and statements represent executable Python code, however, a snippet of code like "4*5" has a value... it evaluates to 20, which you can optionally save or (re)use. similarly, a function, like this one that does nothing: "def foo(): pass", also has a return value (None) that you can save. however, calls to print (in Python 2), pass, if, while, for, try, etc., do NOT have any return value, because they are statements, not expressions. in fact, if you try to save a value when executing those commands, you get an error: In [1]: x = print 'hi' ------------------------------------- File "", line 1 x = print 'hi' ^ SyntaxError: invalid syntax In [2]: of course, since print is a function in Python 3, it changes from being a statement (in Python 2) to an expression (in Python 3). again, the easiest way to differentiate b/w the 2 is whether or not it results in some Python object. if it doesn, it's an expression; if not, it's a statement. clear as mud? hope this somewhat helps... -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 "Python Fundamentals", Prentice Hall, (c)2009 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From alan.gauld at btinternet.com Mon Sep 21 22:18:42 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 21 Sep 2009 21:18:42 +0100 Subject: [Tutor] eazy python question involving functions and parameters In-Reply-To: <78b3a9580909211247p22f22c05oc431380a202eef80@mail.gmail.com> References: <4AB7CE0F.60708@aim.com> <78b3a9580909211247p22f22c05oc431380a202eef80@mail.gmail.com> Message-ID: <4AB7DFA2.2060804@btinternet.com> And to remove all doubt.... wesley chun wrote: > again, the easiest way to differentiate b/w the 2 is whether or not it > results in some Python object. if it doesn, it's an expression; if > not, it's a statement. Should say ... if it does, it's an expression.... You'll find my explanation of expressions in the Functional Programming topic in the advanced section of my tutor. Alan G http://www.alan-g.me.uk From alan.gauld at btinternet.com Mon Sep 21 22:18:42 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 21 Sep 2009 21:18:42 +0100 Subject: [Tutor] eazy python question involving functions and parameters In-Reply-To: <78b3a9580909211247p22f22c05oc431380a202eef80@mail.gmail.com> References: <4AB7CE0F.60708@aim.com> <78b3a9580909211247p22f22c05oc431380a202eef80@mail.gmail.com> Message-ID: <4AB7DFA2.2060804@btinternet.com> And to remove all doubt.... wesley chun wrote: > again, the easiest way to differentiate b/w the 2 is whether or not it > results in some Python object. if it doesn, it's an expression; if > not, it's a statement. Should say ... if it does, it's an expression.... You'll find my explanation of expressions in the Functional Programming topic in the advanced section of my tutor. Alan G http://www.alan-g.me.uk From bmxx5386 at aol.com Mon Sep 21 22:40:42 2009 From: bmxx5386 at aol.com (daggerdvm) Date: Mon, 21 Sep 2009 13:40:42 -0700 (PDT) Subject: [Tutor] need to hire a tutor for online, i can pay by week or per hr $$$ Message-ID: <25530473.post@talk.nabble.com> hi i need a tutor for help with python. I'll ask you basic questions through email and such. I can pay by the hour or by week or whatever. reply here or to bmxx5386 at aol.com -- View this message in context: http://www.nabble.com/need-to-hire-a-tutor-for-online%2C-i-can-pay-by-week-or-per-hr-%24%24%24-tp25530473p25530473.html Sent from the Python - tutor mailing list archive at Nabble.com. From kreglet at gmail.com Mon Sep 21 23:00:43 2009 From: kreglet at gmail.com (kreglet) Date: Mon, 21 Sep 2009 14:00:43 -0700 (PDT) Subject: [Tutor] NameError Message-ID: <25530479.post@talk.nabble.com> I keep getting the following error and don't uderstand why: Traceback (most recent call last): File "/home/kreglet/bin/test.py", line 15, in btnStatclick btnStat.set_label("Pressed") NameError: global name 'btnStat' is not defined #!/usr/bin/env python import gtk import sys class NewAppWindow(gtk.Window): def btnStatclick(self, widget, data=None): #print status if self.status == True: btnStat.set_label("Not Pressed") self.status =False print self.status elif self.status == False: btnStat.set_label("Pressed") self.status =True print self.status def endapp(widget, data=None): sys.exit() def __init__(self): super(NewAppWindow, self).__init__() self.set_title("New App") self.set_size_request(1024, 768) self.set_keep_above(True) self.set_position(gtk.WIN_POS_CENTER) self.set_modal(True) self.status=False fixed = gtk.Layout() btnClose = gtk.Button() btnClose.set_use_stock(True) btnClose.set_label("gtk-close") btnClose.show() btnStat = gtk.Button("Status") fixed.put(btnStat, 650, 10) btnStat.connect("clicked", self.btnStatclick) fixed.put(btnClose, 650, 50) btnClose.connect("clicked", self.endapp) self.add(fixed) self.connect("destroy", gtk.main_quit) self.show_all() NewAppWindow() gtk.main() -- View this message in context: http://www.nabble.com/NameError-tp25530479p25530479.html Sent from the Python - tutor mailing list archive at Nabble.com. From kent37 at tds.net Mon Sep 21 23:04:16 2009 From: kent37 at tds.net (Kent Johnson) Date: Mon, 21 Sep 2009 17:04:16 -0400 Subject: [Tutor] need to hire a tutor for online, i can pay by week or per hr $$$ In-Reply-To: <25530473.post@talk.nabble.com> References: <25530473.post@talk.nabble.com> Message-ID: <1c2a2c590909211404k50309616r9917026093c5d315@mail.gmail.com> On Mon, Sep 21, 2009 at 4:40 PM, daggerdvm wrote: > > hi i need a tutor for help with python. ?I'll ask you basic questions through > email and such. ?I can pay by the hour or by week or whatever. We do that for free here, just post your questions to the list. We try not to give answers to homework problems, other than that ask away! Kent From srilyk at gmail.com Mon Sep 21 23:06:43 2009 From: srilyk at gmail.com (Wayne) Date: Mon, 21 Sep 2009 16:06:43 -0500 Subject: [Tutor] NameError In-Reply-To: <25530479.post@talk.nabble.com> References: <25530479.post@talk.nabble.com> Message-ID: <333efb450909211406t1571bbf8xf68550a1816591c4@mail.gmail.com> On Mon, Sep 21, 2009 at 4:00 PM, kreglet wrote: > > I keep getting the following error and don't uderstand why: > > Traceback (most recent call last): > File "/home/kreglet/bin/test.py", line 15, in btnStatclick > btnStat.set_label("Pressed") > NameError: global name 'btnStat' is not defined > > > #!/usr/bin/env python > > import gtk > import sys > > class NewAppWindow(gtk.Window): > > def btnStatclick(self, widget, data=None): > #print status > if self.status == True: > btnStat.set_label("Not Pressed") > self.status =False > print self.status > elif self.status == False: > btnStat.set_label("Pressed") > self.status =True > print self.status btnStat isn't defined here. I think you should be declaring a self.btnStat in the __init__ method (which I usually put as the first function in my class - I'm honestly not sure if it makes a difference), and calling self.btnStat Unlike C/C++, python is explicit when dealing with members of the class. I'm not sure if anything is implied when it comes to namespaces, but I'm pretty sure it's all gotta be specific. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From wescpy at gmail.com Tue Sep 22 02:37:09 2009 From: wescpy at gmail.com (wesley chun) Date: Mon, 21 Sep 2009 17:37:09 -0700 Subject: [Tutor] NameError In-Reply-To: <333efb450909211406t1571bbf8xf68550a1816591c4@mail.gmail.com> References: <25530479.post@talk.nabble.com> <333efb450909211406t1571bbf8xf68550a1816591c4@mail.gmail.com> Message-ID: <78b3a9580909211737u2ca489c5u7b62ce9d9ff1f2e8@mail.gmail.com> On Mon, Sep 21, 2009 at 2:06 PM, Wayne wrote: > On Mon, Sep 21, 2009 at 4:00 PM, kreglet wrote: >> >> I keep getting the following error and don't uderstand why: >> >> Traceback (most recent call last): >> ?File "/home/kreglet/bin/test.py", line 15, in btnStatclick >> ? ?btnStat.set_label("Pressed") >> NameError: global name 'btnStat' is not defined >> >> >> #!/usr/bin/env python >> >> import gtk >> import sys >> >> class NewAppWindow(gtk.Window): >> >> ? ?def btnStatclick(self, widget, data=None): >> ? ? ? ?#print status >> ? ? ? ?if self.status == True: >> ? ? ? ? ? ?btnStat.set_label("Not Pressed") >> ? ? ? ? ? ?self.status =False >> ? ? ? ? ? ?print self.status >> ? ? ? ?elif self.status == False: >> ? ? ? ? ? ?btnStat.set_label("Pressed") >> ? ? ? ? ? ?self.status =True >> ? ? ? ? ? ?print self.status > > btnStat isn't defined here. I think you should be declaring a self.btnStat > in the __init__ method (which I usually put as the first function in my > class - I'm honestly not sure if it makes a difference), and calling > self.btnStat pretty much what wayne suggested. you need to put the btnStat variable into your instance's namespace, hence self.btnStat = ... instead of just btnStat whose namemapping will disappear when __init__() completes even though the object still exists -- it's just an extra reference held somewhere else. by stashing it away into the instance('s dictionary), you'll be able to access it again in the btnStatclick() callback. best wishes, -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 "Python Fundamentals", Prentice Hall, (c)2009 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From tim.bowden at mapforge.com.au Tue Sep 22 04:30:59 2009 From: tim.bowden at mapforge.com.au (Tim Bowden) Date: Tue, 22 Sep 2009 10:30:59 +0800 Subject: [Tutor] How to get homework help (was need to hire a tutor... ) In-Reply-To: <1c2a2c590909211404k50309616r9917026093c5d315@mail.gmail.com> References: <25530473.post@talk.nabble.com> <1c2a2c590909211404k50309616r9917026093c5d315@mail.gmail.com> Message-ID: <1253586659.4255.44.camel@mordor> On Mon, 2009-09-21 at 17:04 -0400, Kent Johnson wrote: > On Mon, Sep 21, 2009 at 4:40 PM, daggerdvm wrote: > > > > hi i need a tutor for help with python. I'll ask you basic questions through > > email and such. I can pay by the hour or by week or whatever. > > We do that for free here, just post your questions to the list. We try > not to give answers to homework problems, other than that ask away! > > Kent I'm new on this list <*waves hello to everyone*>, but I suspect the trick to getting help here with homework is pretty much the same as most other tech lists. 1. Flag the problem as homework. Don't try and deceive those who are trying to help. 2. Outline your understanding of the problem; Both what you do understand, and what you don't. 3. Post the code you've tried. For larger code blocks, try and explain what you're wanting each section of the code to do. This is probably more for your benefit (to help clarify your thinking on the problem) than for the experts here; They'll have a pretty good handle on what the code really is doing ;-) 4. If you haven't got code yet, post pseudo code outlining how you might approach the problem. This will help develop your algorithm for solving the problem. Don't underestimate the importance of this step. If you don't have a good algorithm for solving the problem, all the language syntax in the world won't help. 5. Accept that you won't be given answers directly, but there is an enormous amount of patience, help and sympathy for those first starting out. Everyone who has reached the 'high ground' on the learning journey likes to see someone new starting out and making headway on the same journey. They'll (almost always) gladly extend a hand in help, but won't do the journey for you. Anything worthwhile must be earned, and that means putting in the hard yards. Be polite, patient and respectful of those who have gone before you, and they'll keep extending the hand of help. Abuse the help, and it won't last long. A bit like life in general really. 6. Don't post the same question in every forum you can find. Any decent forum will have enough experts to help out. And don't abuse those contributing to the discussion; remember that bit about showing respect? And that help being withdrawn? 7. The advice given on http://www.pubbs.net/python/200909/108644/ shouldn't be ignored (yes, I can use google too). ESR (love him or loath him) really was giving good advice in http://catb.org/~esr/faqs/smart-questions.html. There is a reason it gets quoted regularly. Ignore it at your peril. Try it on the problem you posted previously; you might not have understood the hints that were given (probably not if your postings elsewhere are anything to go by) but if you're fair dinkum give it a go. If your just wanting to pass your class by getting others to solve your programming problems for you, get some spine and do it properly or fail graciously. The alternative is to be a fraud, and that never gets respect. Tim Bowden From prasadaraon50 at gmail.com Tue Sep 22 06:39:25 2009 From: prasadaraon50 at gmail.com (prasad rao) Date: Tue, 22 Sep 2009 10:09:25 +0530 Subject: [Tutor] ex-ftp Message-ID: <9e3fac840909212139i747e4727sac38c7b398083142@mail.gmail.com> hello friends I am trying to write a class to save a url.page. But it is not working.It is saving the html.page.But not getting images.I am unable to show the list (object.links). Please take a look at it and show me how to rectify it. import urllib2,ftplib,re class Collect: def __init__(self,parent): self.parent=parent self.links=[] self.ims=[] s=urllib2.urlopen(self.parent) data=s.read() self.data=data a=re.compile ('<[aA].*[\'"](.*)[\'"].*>'); b=re.compile(' From m.wanstall at gmail.com Tue Sep 22 07:57:15 2009 From: m.wanstall at gmail.com (Mal Wanstall) Date: Tue, 22 Sep 2009 15:57:15 +1000 Subject: [Tutor] ex-ftp In-Reply-To: <9e3fac840909212139i747e4727sac38c7b398083142@mail.gmail.com> References: <9e3fac840909212139i747e4727sac38c7b398083142@mail.gmail.com> Message-ID: <4fb9d14e0909212257p5f8c09c6ndef95036b31ef545@mail.gmail.com> On Tue, Sep 22, 2009 at 2:39 PM, prasad rao wrote: > hello? friends > ? I am trying to write a class to save a url.page. > But it is not working.It is saving the html.page.But not getting > images.I am unable to show the list (object.links). > Please take a look at it and show me how to rectify it. > > import urllib2,ftplib,re > class Collect: > ??? def __init__(self,parent): > ??????? self.parent=parent > ??????? self.links=[] > ??????? self.ims=[] > ??????? s=urllib2.urlopen(self.parent) > ??????? data=s.read() > ??????? self.data=data > ??????? a=re.compile?('<[aA].*[\'"](.*)[\'"].*>'); b=re.compile(' img[\'"](.+)[\'"].*') > ??????? try: > ???????? z=re.search(a,self.data).group(1) > ???????? self.links.extend(z) > ??????? except:pass > ??????? try: > ???????? y=re.search(b,self.data).group(1) > ???????? self.ims.extend(y) > ??????? except:pass > ??????? return > > ??? def save(self,data): > ??????????? d=open('C:/%s .html'%self.parent[10:15],'w') > ??????????? d.write(data) > ??????????? return > ??? def bring(self): > ??????? ftp=ftplib.FTP(self.parent) > ??????? ftp.login() > ??????? for x in self.ims: > ??????????? data=ftp.retlines(x) > ??????????? d=open('C:/%s'%x,'w') > ??????????? d.write(data) > ??????????? return > > ??? def show(self,z): > ??????? for x in z: > ??????????? print x > ??????? return > > > c=Collect('http://www.asstr.org') > c.save(c.data) > c.bring() > #c.show(c.ims) > c.links > > Thanks in advance. > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > Might be nice to mention to all who access these emails from work that the site this script is scraping is not safe for work. -Mal From alan.gauld at btinternet.com Tue Sep 22 10:20:28 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 22 Sep 2009 09:20:28 +0100 Subject: [Tutor] How to get homework help (was need to hire a tutor... ) In-Reply-To: <1253586659.4255.44.camel@mordor> References: <25530473.post@talk.nabble.com> <1c2a2c590909211404k50309616r9917026093c5d315@mail.gmail.com> <1253586659.4255.44.camel@mordor> Message-ID: > I'm new on this list <*waves hello to everyone*>, welcome to the tutor list <*waves back*> :-) > trick to getting help here with homework is pretty much the same as most > other tech lists. Absolutely so, and well summarised. Alan G. http://www.alan-g.me.uk/ From vineet.kothari at gmail.com Tue Sep 22 02:08:46 2009 From: vineet.kothari at gmail.com (Vineet Kothari) Date: Mon, 21 Sep 2009 17:08:46 -0700 Subject: [Tutor] python win32 drive mapping help In-Reply-To: References: Message-ID: Hi Everyone I saw alot of responses for python on this mailing list. I thought any python guru might wish to help me with little code to map two network drives on windows systems I have 3computers at different locations in a network A,B,C I want to map c:/temp folder of A to C & c:/temp folder of B to C as well do some copying of data and then delete the mapping. I tried using the code given for mapping: import win32net > win32net.NetUseAdd(None,1,{'remote':r'\\server\share','local':'K:','password':'XXX' > }) > but I get this error: C:\Users\Administrator\Desktop>python test.py > Traceback (most recent call last): > File "test.py", line 31, in > import win32wnet > ImportError: No module named win32net > I just need help in setting up the mapping. I know how to do the copying using shutil please if you can help me with the mapping code. I am very new to python and I need this help for my project at school. I am using python 2.6 I'll be eagerly waiting for your response. Thanks -- Regards, Vineet Kothari http://www.vineetkothari.in ----- Its NICE 2 be IMPORTANT, but whats more IMPORTANT is 2 be NICE. -------------- next part -------------- An HTML attachment was scrubbed... URL: From dextrous85 at gmail.com Tue Sep 22 13:01:38 2009 From: dextrous85 at gmail.com (vishwajeet singh) Date: Tue, 22 Sep 2009 16:31:38 +0530 Subject: [Tutor] python win32 drive mapping help In-Reply-To: References: Message-ID: <5487b3060909220401w14fa12a8wcf308e38251f6c8@mail.gmail.com> On Tue, Sep 22, 2009 at 5:38 AM, Vineet Kothari wrote: > > Hi Everyone > > I saw alot of responses for python on this mailing > list. I thought any python guru might wish to help me with little code to > map two network drives on windows systems > > > I have 3computers at different locations in a network A,B,C > > I want to map c:/temp folder of A to C & c:/temp folder of B to C as well > do some copying of data and then delete the mapping. > > I tried using the code given for mapping: > > import win32net >> win32net.NetUseAdd(None,1,{'remote':r'\\server\share','local':'K:','password':'XXX' >> }) >> > > but I get this error: > > C:\Users\Administrator\Desktop>python test.py >> Traceback (most recent call last): >> File "test.py", line 31, in >> import win32wnet >> ImportError: No module named win32net >> > > I just need help in setting up the mapping. I know how to do the copying > using shutil please if you can help me with the mapping code. I am very new > to python and I need this help for my project at school. > > I am using python 2.6 > > I'll be eagerly waiting for your response. > Thanks > > -- > Regards, > Vineet Kothari > http://www.vineetkothari.in > > ----- > Its NICE 2 be IMPORTANT, but whats more IMPORTANT is 2 be NICE. > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > You need python extension installed on your machine to be able to execute the above code; you can get same from http://sourceforge.net/projects/pywin32/ -- Vishwajeet Singh +91-9657702154 | dextrous85 at gmail.com | http://singhvishwajeet.com Twitter: http://twitter.com/vishwajeets | LinkedIn: http://www.linkedin.com/in/singhvishwajeet -------------- next part -------------- An HTML attachment was scrubbed... URL: From seena_blk at yahoo.com Tue Sep 22 14:13:32 2009 From: seena_blk at yahoo.com (Ali Sina) Date: Tue, 22 Sep 2009 05:13:32 -0700 (PDT) Subject: [Tutor] Challenge Message-ID: <826729.63168.qm@web45911.mail.sp1.yahoo.com> Hello tutor I downloaded a guide about learning Python by Michael Dawson which has challenges at the end of each chapter. I'm a novice so I encountered a problem with this challenge: "Write a program that flips a coin 100 times and then tells you the number of heads and tails." I wrote this code but I know its wrong. Although it works properly: flips=0 h='heads' t='tails' while True: ??? flips+=1 ??? if flips>100: ??????? break ??? if True: ??????? print(flips,'=',h or t) But it prints every number with the string 'heads'. I'm really blank at this. It may have something to do with the 'random' module. Regards -------------- next part -------------- An HTML attachment was scrubbed... URL: From lukepadawan at gmail.com Tue Sep 22 14:20:09 2009 From: lukepadawan at gmail.com (Lucas Prado Melo) Date: Tue, 22 Sep 2009 09:20:09 -0300 Subject: [Tutor] Challenge In-Reply-To: <826729.63168.qm@web45911.mail.sp1.yahoo.com> References: <826729.63168.qm@web45911.mail.sp1.yahoo.com> Message-ID: <9f4be2240909220520s18240cd3xfb1f0864ea3b69ba@mail.gmail.com> On Tue, Sep 22, 2009 at 9:13 AM, Ali Sina wrote: > But it prints every number with the string 'heads'. I'm really blank at > this. It may have something to do with the 'random' module. > > You could use the choice function on random. Given a list, the choice function returns a random element of that list. from random import choice print choice([1,2,3,4]) -------------- next part -------------- An HTML attachment was scrubbed... URL: From sli1que at yahoo.com Tue Sep 22 14:39:27 2009 From: sli1que at yahoo.com (Eric Walker) Date: Tue, 22 Sep 2009 05:39:27 -0700 (PDT) Subject: [Tutor] Challenge In-Reply-To: <826729.63168.qm@web45911.mail.sp1.yahoo.com> References: <826729.63168.qm@web45911.mail.sp1.yahoo.com> Message-ID: <777031.55718.qm@web65411.mail.ac4.yahoo.com> Ali, I am new at this but here is my interpretation. 1) flip coin 100 times, and print out the number of heads and number of tails. from random import Random score = [0,0]# first position will be heads and second position will be tails count=0#counter to find out how many times we have flipped. a = Random()#creates random object while count < 100: answer = a.choice((1,2)) if answer == 1: score[0]+=answer else: score[1]+=1 count +=1 print("Heads:%s\nTails:%s" % (score[0], score[1])) > >From: Ali Sina >To: tutor at python.org >Sent: Tuesday, September 22, 2009 5:13:32 AM >Subject: [Tutor] Challenge > > >Hello tutor > >I downloaded a guide about learning Python by Michael Dawson which has challenges at the end of each chapter. I'm a novice so I encountered a problem with this challenge: > > >"Write a program that flips a coin 100 times and then tells >you the number of heads and tails." >I wrote this code but I know its wrong. Although it works properly: > >flips=0 >h='heads' >t='tails' >while True: > flips+=1 > if flips>100: > break > if True: > print(flips,'=',h or t) > >But it prints every number with the string 'heads'. I'm really blank at this. It may have something to do with the 'random' module. > >Regards > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue Sep 22 17:00:36 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 22 Sep 2009 16:00:36 +0100 Subject: [Tutor] Challenge In-Reply-To: <826729.63168.qm@web45911.mail.sp1.yahoo.com> References: <826729.63168.qm@web45911.mail.sp1.yahoo.com> Message-ID: <4AB8E694.9060206@btinternet.com> Ali Sina wrote: > I wrote this code but I know its wrong. Although it works properly: Thereis adfference between "works properly" (ie does what it should) and "runs without errors" :-) You need to read up a bit more on boolean expressions > flips=0 > h='heads' > t='tails' > while True: > flips+=1 > if flips>100: > break So far so good, this will loop 100 times. You could have done the same with a for loop: for flips in range(100): > if True: if true is meaningless, it is always true so the next line will always be executed so you can just miss it out. > print(flips,'=',h or t) h or t is a boolean expression which expands out to 'heads' or 'tails' Since Python considers a non null string to be True this is equivalent to True or True which is always True. In addition Python knows that for an 'or' test if the first value is true then the whole expression is true(this iscalle short circuit evaluation) and so it only evaluates h as 'heads' to realize the whole is true and it returns the first value h (or 'heads') > But it prints every number with the string 'heads'. I'm really blank at > this. It may have something to do with the 'random' module. The reason it prints heads is that you have basically written the following code: for flips in range(100): print 'heads' What you are not doing is replicating the flip of the coin (thats where random comes in) and you are not testing the result of that flip to determine whether to print heads/tails. You will find more examples of boolean expressions in the Functional Programming topic of my tutor under the heading "Other Constructs" about 60% of the way down the page. HTH, Alan G. http://www.alan-g.me.uk From alan.gauld at btinternet.com Tue Sep 22 17:00:36 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 22 Sep 2009 16:00:36 +0100 Subject: [Tutor] Challenge In-Reply-To: <826729.63168.qm@web45911.mail.sp1.yahoo.com> References: <826729.63168.qm@web45911.mail.sp1.yahoo.com> Message-ID: <4AB8E694.9060206@btinternet.com> Ali Sina wrote: > I wrote this code but I know its wrong. Although it works properly: Thereis adfference between "works properly" (ie does what it should) and "runs without errors" :-) You need to read up a bit more on boolean expressions > flips=0 > h='heads' > t='tails' > while True: > flips+=1 > if flips>100: > break So far so good, this will loop 100 times. You could have done the same with a for loop: for flips in range(100): > if True: if true is meaningless, it is always true so the next line will always be executed so you can just miss it out. > print(flips,'=',h or t) h or t is a boolean expression which expands out to 'heads' or 'tails' Since Python considers a non null string to be True this is equivalent to True or True which is always True. In addition Python knows that for an 'or' test if the first value is true then the whole expression is true(this iscalle short circuit evaluation) and so it only evaluates h as 'heads' to realize the whole is true and it returns the first value h (or 'heads') > But it prints every number with the string 'heads'. I'm really blank at > this. It may have something to do with the 'random' module. The reason it prints heads is that you have basically written the following code: for flips in range(100): print 'heads' What you are not doing is replicating the flip of the coin (thats where random comes in) and you are not testing the result of that flip to determine whether to print heads/tails. You will find more examples of boolean expressions in the Functional Programming topic of my tutor under the heading "Other Constructs" about 60% of the way down the page. HTH, Alan G. http://www.alan-g.me.uk From pine508 at hotmail.com Tue Sep 22 17:36:42 2009 From: pine508 at hotmail.com (Che M) Date: Tue, 22 Sep 2009 11:36:42 -0400 Subject: [Tutor] Challenge In-Reply-To: <826729.63168.qm@web45911.mail.sp1.yahoo.com> References: <826729.63168.qm@web45911.mail.sp1.yahoo.com> Message-ID: > I wrote this code but I know its wrong. Although it works properly: > flips=0 > h='heads' > t='tails' > while True: > flips+=1 > if flips>100: > break > if True: > print(flips,'=',h or t) > But it prints every number with the string 'heads'. I'm really blank at this. It may have > something to do with the 'random' module. Keep in mind, you never import the random module in this code, so the problem could have nothing to do with that module. When you use a module in Python, you import it, and there will be a line at the top like this: import random Read up on importing modules; they are very important (pardon the pun) in Python. The random module, like most of the modules, has lots of functions in it for cases where randomization is needed. You can read up on it: http://docs.python.org/library/random.html I also really like Effbot's guide to the modules; for example, for random: http://effbot.org/librarybook/random.htm Che _________________________________________________________________ Hotmail: Powerful Free email with security by Microsoft. http://clk.atdmt.com/GBL/go/171222986/direct/01/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From dsarmientos at gmail.com Tue Sep 22 17:48:38 2009 From: dsarmientos at gmail.com (Daniel Sarmiento) Date: Tue, 22 Sep 2009 10:48:38 -0500 (COT) Subject: [Tutor] Challenge In-Reply-To: References: Message-ID: > Date: Tue, 22 Sep 2009 05:13:32 -0700 (PDT) > From: Ali Sina > To: tutor at python.org > Subject: [Tutor] Challenge > Message-ID: <826729.63168.qm at web45911.mail.sp1.yahoo.com> > Content-Type: text/plain; charset="iso-8859-1" > > Hello tutor > > I downloaded a guide about learning Python by Michael Dawson which has challenges at the end of each chapter. I'm a novice so I encountered a problem with this challenge: > > "Write a program that flips a coin 100 times and then tells > you the number of heads and tails." > I wrote this code but I know its wrong. Although it works properly: > > flips=0 > h='heads' > t='tails' > while True: > ??? flips+=1 > ??? if flips>100: > ??????? break > ??? if True: > ??????? print(flips,'=',h or t) > > But it prints every number with the string 'heads'. I'm really blank at this. It may have something to do with the 'random' module. > > Regards > You could use a dictionary to store the outcome and a list with the possible outcomes, then use random.choice to pick an outcome. Here is my try at it: In [18]: from random import choice In [19]: pos = ('head', 'tail') In [20]: outcomes = {'head':0, 'tail':0} In [21]: for i in range(100): ....: outcomes[choice(pos)] += 1 ....: ....: In [22]: print outcomes -------> print(outcomes) {'head': 46, 'tail': 54} HTH Daniel Sarmiento. From davea at dejaviewphoto.com Tue Sep 22 17:56:06 2009 From: davea at dejaviewphoto.com (Dave Angel) Date: Tue, 22 Sep 2009 11:56:06 -0400 Subject: [Tutor] python win32 drive mapping help In-Reply-To: References: Message-ID: <4AB8F396.5030103@dejaviewphoto.com> Vineet Kothari wrote: > Hi Everyone > > I saw alot of responses for python on this mailing list. > I thought any python guru might wish to help me with little code to map two > network drives on windows systems > > > I have 3computers at different locations in a network A,B,C > > I want to map c:/temp folder of A to C & c:/temp folder of B to C as well do > some copying of data and then delete the mapping. > > I tried using the code given for mapping: > > import win32net > >> win32net.NetUseAdd(None,1,{'remote':r'\\server\share','local':'K:','password':'XXX' >> }) >> >> > > but I get this error: > > C:\Users\Administrator\Desktop>python test.py > >> Traceback (most recent call last): >> File "test.py", line 31, in >> import win32wnet >> ImportError: No module named win32net >> >> > > I just need help in setting up the mapping. I know how to do the copying > using shutil please if you can help me with the mapping code. I am very new > to python and I need this help for my project at school. > > I am using python 2.6 > > I'll be eagerly waiting for your response. > Thanks > > As someone else pointed out, you need to make sure you have the win32 extensions installed. A quick manual check would be to look in the install directory for the win32 files, something like: python26\lib\site-packages\win32\win32net.pyd But I'd point out an essential problem in your message: your error message isn't self-consistent, indicating to me that perhaps you retyped it in the message. It's important to use copy/paste to get the program samples and error messages precise; tiny typos can sometimes change the diagnosis significantly. You can do copy/paste from a console window, for example by enabling quick-edit mode. You turn that on by doing right click on the title bar and choosing properties. Once quick-edit is on, you can select any rectangle from a console window, and copy it to clipboard with right-click. DaveA From zstumgoren at gmail.com Tue Sep 22 18:47:08 2009 From: zstumgoren at gmail.com (Serdar Tumgoren) Date: Tue, 22 Sep 2009 12:47:08 -0400 Subject: [Tutor] calling a superclass method after overriding it Message-ID: Hi everyone, Is there a way to call a superclass method after I've overridden it in a subclass? Specifically, what I'm trying to is something like the following: class Parent(object): def add_name(self): self.name = result_of_GENERIC_SQLcall() class Child(Parent): def __init__(self): super(Child, self).__init__() def add_name(self): name = result_of_SPECIALIZED_SQLcall_for_child() try: name + '' self.name = name except TypeError: #default to the superclass's add_name method Base.add_name() My key point of confusion is in the except clause: I'm not sure of the syntax for calling the original superclass method (or if it's even possible). Can anyone point me in the right direction? Regards, Serdar From zstumgoren at gmail.com Tue Sep 22 19:14:34 2009 From: zstumgoren at gmail.com (Serdar Tumgoren) Date: Tue, 22 Sep 2009 13:14:34 -0400 Subject: [Tutor] calling a superclass method after overriding it In-Reply-To: References: Message-ID: > You're actually already doing it: ?look at __init__. > > __init__ is overridden in your subclass, so you call super(Child, > self).__init__() to initialise the class using the parent > (superclass)'s __init__ method. Yes indeed. Thanks for pointing it out. In case it helps anyone else out down the road, below is a bit of test code that appears to work (of course, please let me know if the way I've done the call has some unexpected (at least by me) side effects): def result_of_GENERIC_SQLcall(): name = "This name came from the Parent class" return name def result_of_SPECIALIZED_SQLcall_for_child(): name = None return name class Parent(object): def __init__(self): self.add_name() print self.name, self.__class__ def add_name(self): self.name = result_of_GENERIC_SQLcall() class Child(Parent): def __init__(self): super(Child, self).__init__() def add_name(self): name = result_of_SPECIALIZED_SQLcall_for_child() try: name + '' self.name = name except TypeError: #default to the superclass's add_name method super(Child, self).add_name() Meantime, many thanks!! From alan.gauld at btinternet.com Tue Sep 22 19:27:36 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 22 Sep 2009 18:27:36 +0100 Subject: [Tutor] calling a superclass method after overriding it References: Message-ID: "Serdar Tumgoren" wrote > Is there a way to call a superclass method after I've overridden it in > a subclass? Yes, you can do it as you have iin __init__ using super() > class Child(Parent): > def __init__(self): > super(Child, self).__init__() Or you can do it explicitly: Parent.__init__(self) and: > def add_name(self): > .... > except TypeError: > #default to the superclass's add_name method super(Child,self).add_name() or Parent.add_name(self) I tend to prefer the explicit approach since it is explicit which class/method is getting called, but I suspect the preferred mechanism nowadays is to use super() > My key point of confusion is in the except clause: I'm not sure of the > syntax for calling the original superclass method The except clause is no different to any other bit of code inside a method. You use exactly the same mechanisms. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Tue Sep 22 19:30:53 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 22 Sep 2009 18:30:53 +0100 Subject: [Tutor] python win32 drive mapping help References: <4AB8F396.5030103@dejaviewphoto.com> Message-ID: "Dave Angel" wrote >>> Traceback (most recent call last): >>> File "test.py", line 31, in >>> import win32wnet >>> ImportError: No module named win32net > But I'd point out an essential problem in your message: your error > message isn't self-consistent, What Dave is getting at is that the import uses a different name for the module than the one in the ImportError line. So if the import is correct you simply used the wrong module name! > You can do copy/paste from a console window, for example by enabling > quick-edit mode. You turn that on by doing right click on the title bar > and choosing properties. Once quick-edit is on, you can select any > rectangle from a console window, and copy it to clipboard with > right-click. Or even just hit return after selecting the area to copy... HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From adaptives at gmail.com Tue Sep 22 19:56:29 2009 From: adaptives at gmail.com (Parag Shah) Date: Tue, 22 Sep 2009 23:26:29 +0530 Subject: [Tutor] module not found problem Message-ID: Hi, I am using django-openid-consumer, which has a line in it's views.py which results in an error due to module not found - from openid.extensions.pape import Request as PapeRequest where 'openid.extensions' comes from python-openid-2.2.4 (installed using 'python setup.py install'), which has an 'extensions' directory, but no 'pape' directory. However, 'extensions' has an __init__.py which seems to be importing 'pape', like this: __all__ = ['ax', 'pape', 'sreg'] from openid.extensions.draft import pape5 as pape However, the Django app still gives me an error when the line which required pape is executed. I started the Python prompt and tried the following: >>> from openid.extensions import pape >>> from openid.extensions.pape import PageRequest Traceback (most recent call last): File "", line 1, in ImportError: No module named pape So Python is able to execute the first import which just imports 'pape', but fails on the second import which imports 'PageRequest' from 'pape'. Can someone point out what the problem may be. -- Thanks & Regards Parag Shah http://blog.adaptivesoftware.biz From rabidpoobear at gmail.com Tue Sep 22 20:09:06 2009 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Tue, 22 Sep 2009 20:09:06 +0200 Subject: [Tutor] module not found problem In-Reply-To: References: Message-ID: It looks to me like your __init__.py is transparently mapping openid.extensions.pape to openid.extensions.pape5 but when you try to do a direct import from openid.extensions.pape it doesn't process the __init__.py. I've never seen something like this but from your example that's my first guess.Try doing from openid.extensions.pape5 import PageRequest I would guess the way you're expected to do it is just from openid.extensions import pape and if you don't want to refer to PageRequest as pape.PageRequest just do PageRequest = pape.PageRequest That doesn't sound quite right though.... On Tue, Sep 22, 2009 at 7:56 PM, Parag Shah wrote: > Hi, > > I am using django-openid-consumer, which has a line in it's views.py > which results in an error due to module not found - > > from openid.extensions.pape import Request as PapeRequest > > where 'openid.extensions' comes from python-openid-2.2.4 (installed > using 'python setup.py install'), which has an 'extensions' directory, > but no 'pape' directory. However, 'extensions' has an __init__.py > which seems to be importing 'pape', like this: > > __all__ = ['ax', 'pape', 'sreg'] > from openid.extensions.draft import pape5 as pape > > > However, the Django app still gives me an error when the line which > required pape is executed. I started the Python prompt and tried the > following: > > >>> from openid.extensions import pape > >>> from openid.extensions.pape import PageRequest > Traceback (most recent call last): > File "", line 1, in > ImportError: No module named pape > > > So Python is able to execute the first import which just imports > 'pape', but fails on the second import which imports 'PageRequest' > from 'pape'. > > Can someone point out what the problem may be. > > -- > Thanks & Regards > Parag Shah > http://blog.adaptivesoftware.biz > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Tue Sep 22 20:13:52 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 22 Sep 2009 14:13:52 -0400 Subject: [Tutor] calling a superclass method after overriding it In-Reply-To: References: Message-ID: <1c2a2c590909221113n7c0c297bxb5b44416ae9450d9@mail.gmail.com> On Tue, Sep 22, 2009 at 1:27 PM, Alan Gauld wrote: > I tend to prefer the explicit approach since it is explicit which > class/method is getting called, but I suspect the preferred mechanism > nowadays is to use super() I prefer the older approach too, it is simple and explicit. super() comes with a raft of complications (google "super considered harmful") and AFAIK it is only really needed in the case of "diamond" inheritance. Kent From zstumgoren at gmail.com Tue Sep 22 20:20:49 2009 From: zstumgoren at gmail.com (Serdar Tumgoren) Date: Tue, 22 Sep 2009 14:20:49 -0400 Subject: [Tutor] calling a superclass method after overriding it In-Reply-To: <1c2a2c590909221113n7c0c297bxb5b44416ae9450d9@mail.gmail.com> References: <1c2a2c590909221113n7c0c297bxb5b44416ae9450d9@mail.gmail.com> Message-ID: > I prefer the older approach too, it is simple and explicit. super() > comes with a raft of complications (google "super considered harmful") > and AFAIK it is only really needed in the case of "diamond" > inheritance. > The explicit method does indeed seem...well...more explicit and easier to understand. But I thought I'd also read someplace that you shouldn't combine old and new methods. That you should pick one and stick with it, because otherwise you could run into MRO problems. Is my case isolated enough here that I could use the old syntax, but leave my remain usages of super in tact? My worry is that I'd have to convert all of my subclasses (quite a few at this point) to the old-style... From kent37 at tds.net Tue Sep 22 20:21:39 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 22 Sep 2009 14:21:39 -0400 Subject: [Tutor] module not found problem In-Reply-To: References: Message-ID: <1c2a2c590909221121g4b8d6f95x5f3e9967f536a9bc@mail.gmail.com> On Tue, Sep 22, 2009 at 1:56 PM, Parag Shah wrote: > Hi, > > I am using django-openid-consumer, which has a line in it's views.py > which results in an error due to module not found - > > from openid.extensions.pape import Request as PapeRequest > > where 'openid.extensions' comes from python-openid-2.2.4 (installed > using 'python setup.py install'), which has an 'extensions' directory, > but no 'pape' directory. However, 'extensions' has an __init__.py > which seems to be importing 'pape', like this: > > __all__ = ['ax', 'pape', 'sreg'] > from openid.extensions.draft import pape5 as pape > > > However, the Django app still gives me an error when the line which > required pape is executed. I started the Python prompt and tried the > following: > >>>> from openid.extensions import pape >>>> from openid.extensions.pape import PageRequest > Traceback (most recent call last): > ?File "", line 1, in > ImportError: No module named pape The __init__.py creates the name openid.extensions.pape by importing from the draft. So there is no openid.extensions.pape module in the import path. I would try from openid.extensions import pape PageRequest = pape.PageRequest Kent From kent37 at tds.net Tue Sep 22 20:22:52 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 22 Sep 2009 14:22:52 -0400 Subject: [Tutor] calling a superclass method after overriding it In-Reply-To: References: <1c2a2c590909221113n7c0c297bxb5b44416ae9450d9@mail.gmail.com> Message-ID: <1c2a2c590909221122l72d6ae6cl2854676258ef73c1@mail.gmail.com> On Tue, Sep 22, 2009 at 2:20 PM, Serdar Tumgoren wrote: > Is my case isolated enough here that I could use the old syntax, but > leave my remain usages of super in tact? My worry is that I'd have to > convert all of my subclasses (quite a few at this point) to the > old-style... I know that when you need super(), you have to use it everywhere. So I would stick with what you have. Kent From adaptives at gmail.com Tue Sep 22 20:27:27 2009 From: adaptives at gmail.com (Parag Shah) Date: Tue, 22 Sep 2009 23:57:27 +0530 Subject: [Tutor] module not found problem In-Reply-To: References: Message-ID: Hi Luke, If I get into the Python prompt, the following line does succeed (so it seems like __init__.py is being processed): >>> from openid.extensions import pape But this one fails because pape is not found... this is very strange: >>> from openid.extensions.pape import Request as PapeRequest As you suggested I tried this, but it too fails: >>> from openid.extensions.pape5 import Request as PapeRequest However, doing this succeeds: >>> from openid.extensions.draft.pape5 import Request as PapeRequest -- Thanks & Regards Parag Shah http://blog.adaptivesoftware.biz On 9/22/09, Luke Paireepinart wrote: > It looks to me like your __init__.py is transparently > mapping openid.extensions.pape to openid.extensions.pape5 but when you try > to do a direct import from openid.extensions.pape it doesn't process the > __init__.py. I've never seen something like this but from your example > that's my first guess.Try doing > from openid.extensions.pape5 import PageRequest > > I would guess the way you're expected to do it is just > from openid.extensions import pape > > and if you don't want to refer to PageRequest as pape.PageRequest > just do > PageRequest = pape.PageRequest > > That doesn't sound quite right though.... > > On Tue, Sep 22, 2009 at 7:56 PM, Parag Shah wrote: > >> Hi, >> >> I am using django-openid-consumer, which has a line in it's views.py >> which results in an error due to module not found - >> >> from openid.extensions.pape import Request as PapeRequest >> >> where 'openid.extensions' comes from python-openid-2.2.4 (installed >> using 'python setup.py install'), which has an 'extensions' directory, >> but no 'pape' directory. However, 'extensions' has an __init__.py >> which seems to be importing 'pape', like this: >> >> __all__ = ['ax', 'pape', 'sreg'] >> from openid.extensions.draft import pape5 as pape >> >> >> However, the Django app still gives me an error when the line which >> required pape is executed. I started the Python prompt and tried the >> following: >> >> >>> from openid.extensions import pape >> >>> from openid.extensions.pape import PageRequest >> Traceback (most recent call last): >> File "", line 1, in >> ImportError: No module named pape >> >> >> So Python is able to execute the first import which just imports >> 'pape', but fails on the second import which imports 'PageRequest' >> from 'pape'. >> >> Can someone point out what the problem may be. >> >> -- >> Thanks & Regards >> Parag Shah >> http://blog.adaptivesoftware.biz >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> > From rabidpoobear at gmail.com Tue Sep 22 20:32:02 2009 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Tue, 22 Sep 2009 20:32:02 +0200 Subject: [Tutor] module not found problem In-Reply-To: References: Message-ID: Yeah looks like Kent had the same recommendation.I would suggest you don't import from draft, because they will probably change the version number of pape at some point. That's why they aliased it as openid.extensions.pape, so they can update it without breaking your code. Seems odd that they would do it that way though. On Tue, Sep 22, 2009 at 8:27 PM, Parag Shah wrote: > Hi Luke, > > If I get into the Python prompt, the following line does succeed (so > it seems like __init__.py is being processed): > > >>> from openid.extensions import pape > > But this one fails because pape is not found... this is very strange: > >>> from openid.extensions.pape import Request as PapeRequest > > As you suggested I tried this, but it too fails: > >>> from openid.extensions.pape5 import Request as PapeRequest > > However, doing this succeeds: > >>> from openid.extensions.draft.pape5 import Request as PapeRequest > > > -- > Thanks & Regards > Parag Shah > http://blog.adaptivesoftware.biz > > On 9/22/09, Luke Paireepinart wrote: > > It looks to me like your __init__.py is transparently > > mapping openid.extensions.pape to openid.extensions.pape5 but when you > try > > to do a direct import from openid.extensions.pape it doesn't process the > > __init__.py. I've never seen something like this but from your example > > that's my first guess.Try doing > > from openid.extensions.pape5 import PageRequest > > > > I would guess the way you're expected to do it is just > > from openid.extensions import pape > > > > and if you don't want to refer to PageRequest as pape.PageRequest > > just do > > PageRequest = pape.PageRequest > > > > That doesn't sound quite right though.... > > > > On Tue, Sep 22, 2009 at 7:56 PM, Parag Shah wrote: > > > >> Hi, > >> > >> I am using django-openid-consumer, which has a line in it's views.py > >> which results in an error due to module not found - > >> > >> from openid.extensions.pape import Request as PapeRequest > >> > >> where 'openid.extensions' comes from python-openid-2.2.4 (installed > >> using 'python setup.py install'), which has an 'extensions' directory, > >> but no 'pape' directory. However, 'extensions' has an __init__.py > >> which seems to be importing 'pape', like this: > >> > >> __all__ = ['ax', 'pape', 'sreg'] > >> from openid.extensions.draft import pape5 as pape > >> > >> > >> However, the Django app still gives me an error when the line which > >> required pape is executed. I started the Python prompt and tried the > >> following: > >> > >> >>> from openid.extensions import pape > >> >>> from openid.extensions.pape import PageRequest > >> Traceback (most recent call last): > >> File "", line 1, in > >> ImportError: No module named pape > >> > >> > >> So Python is able to execute the first import which just imports > >> 'pape', but fails on the second import which imports 'PageRequest' > >> from 'pape'. > >> > >> Can someone point out what the problem may be. > >> > >> -- > >> Thanks & Regards > >> Parag Shah > >> http://blog.adaptivesoftware.biz > >> _______________________________________________ > >> Tutor maillist - Tutor at python.org > >> To unsubscribe or change subscription options: > >> http://mail.python.org/mailman/listinfo/tutor > >> > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From adaptives at gmail.com Tue Sep 22 20:47:29 2009 From: adaptives at gmail.com (Parag Shah) Date: Wed, 23 Sep 2009 00:17:29 +0530 Subject: [Tutor] module not found problem In-Reply-To: References: Message-ID: Hi Luke, Kent, Thanks the solution worked. -- Thanks & Regards Parag Shah http://blog.adaptivesoftware.biz On 9/23/09, Luke Paireepinart wrote: > Yeah looks like Kent had the same recommendation.I would suggest you don't > import from draft, because they will probably change the version number of > pape at some point. > That's why they aliased it as openid.extensions.pape, so they can update it > without breaking your code. Seems odd that they would do it that way > though. > > On Tue, Sep 22, 2009 at 8:27 PM, Parag Shah wrote: > >> Hi Luke, >> >> If I get into the Python prompt, the following line does succeed (so >> it seems like __init__.py is being processed): >> >> >>> from openid.extensions import pape >> >> But this one fails because pape is not found... this is very strange: >> >>> from openid.extensions.pape import Request as PapeRequest >> >> As you suggested I tried this, but it too fails: >> >>> from openid.extensions.pape5 import Request as PapeRequest >> >> However, doing this succeeds: >> >>> from openid.extensions.draft.pape5 import Request as PapeRequest >> >> >> -- >> Thanks & Regards >> Parag Shah >> http://blog.adaptivesoftware.biz >> >> On 9/22/09, Luke Paireepinart wrote: >> > It looks to me like your __init__.py is transparently >> > mapping openid.extensions.pape to openid.extensions.pape5 but when you >> try >> > to do a direct import from openid.extensions.pape it doesn't process >> > the >> > __init__.py. I've never seen something like this but from your example >> > that's my first guess.Try doing >> > from openid.extensions.pape5 import PageRequest >> > >> > I would guess the way you're expected to do it is just >> > from openid.extensions import pape >> > >> > and if you don't want to refer to PageRequest as pape.PageRequest >> > just do >> > PageRequest = pape.PageRequest >> > >> > That doesn't sound quite right though.... >> > >> > On Tue, Sep 22, 2009 at 7:56 PM, Parag Shah >> > wrote: >> > >> >> Hi, >> >> >> >> I am using django-openid-consumer, which has a line in it's views.py >> >> which results in an error due to module not found - >> >> >> >> from openid.extensions.pape import Request as PapeRequest >> >> >> >> where 'openid.extensions' comes from python-openid-2.2.4 (installed >> >> using 'python setup.py install'), which has an 'extensions' directory, >> >> but no 'pape' directory. However, 'extensions' has an __init__.py >> >> which seems to be importing 'pape', like this: >> >> >> >> __all__ = ['ax', 'pape', 'sreg'] >> >> from openid.extensions.draft import pape5 as pape >> >> >> >> >> >> However, the Django app still gives me an error when the line which >> >> required pape is executed. I started the Python prompt and tried the >> >> following: >> >> >> >> >>> from openid.extensions import pape >> >> >>> from openid.extensions.pape import PageRequest >> >> Traceback (most recent call last): >> >> File "", line 1, in >> >> ImportError: No module named pape >> >> >> >> >> >> So Python is able to execute the first import which just imports >> >> 'pape', but fails on the second import which imports 'PageRequest' >> >> from 'pape'. >> >> >> >> Can someone point out what the problem may be. >> >> >> >> -- >> >> Thanks & Regards >> >> Parag Shah >> >> http://blog.adaptivesoftware.biz >> >> _______________________________________________ >> >> Tutor maillist - Tutor at python.org >> >> To unsubscribe or change subscription options: >> >> http://mail.python.org/mailman/listinfo/tutor >> >> >> > >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> > From zstumgoren at gmail.com Tue Sep 22 21:46:49 2009 From: zstumgoren at gmail.com (Serdar Tumgoren) Date: Tue, 22 Sep 2009 15:46:49 -0400 Subject: [Tutor] calling a superclass method after overriding it In-Reply-To: <1c2a2c590909221122l72d6ae6cl2854676258ef73c1@mail.gmail.com> References: <1c2a2c590909221113n7c0c297bxb5b44416ae9450d9@mail.gmail.com> <1c2a2c590909221122l72d6ae6cl2854676258ef73c1@mail.gmail.com> Message-ID: > I know that when you need super(), you have to use it everywhere. So I > would stick with what you have. > > Kent > Okay. Thanks as always to all. Best, Serdar From sander.sweers at gmail.com Tue Sep 22 23:04:49 2009 From: sander.sweers at gmail.com (Sander Sweers) Date: Tue, 22 Sep 2009 22:04:49 +0100 Subject: [Tutor] urllib2, read data with specific encoding Message-ID: <1253653489.19436.9.camel@infirit.homelinux.org> Hello Tutors, Because a website was giving me issues with unicode character I created a function to force the encoding. I am not sure it is the correct way to handle these things. def reader(fobject, encoding='UTF-8'): '''Read a fileobject with specified encoding, defaults UTF-8.''' r = codecs.getreader(encoding) data = r(fobject) return data I would call it like reader(urllib2.urlopen(someurl), 'somencoding'). Now I am looking for advice if this is the proper way of dealing with these type of issues? Is there better practice maybe? Many thanks Sander From shellcom3 at juno.com Tue Sep 22 23:23:26 2009 From: shellcom3 at juno.com (shellcom3 at juno.com) Date: Tue, 22 Sep 2009 21:23:26 GMT Subject: [Tutor] how to define a function with multple parameters Message-ID: <20090922.172326.26353.0@webmail06.dca.untd.com> I want to know how to use multiple parameters for 1 function def display(message): print message def rate_score(): score = rate_score if rate_score <= 999: print "that's nothing." elif rate_score <= 10000: print "ok." elif rate_score >= 10000: print "great." #main display("Get the meaning !") raw_input("Please type in your score") print "here's your score", rate_score rate_score() This is the outcome: great. Get the meaning Please type in your score50 here's your score ____________________________________________________________ Life Insurance Quotes 30 Seconds can save a lifetime. Get it done. Its never been easier. http://thirdpartyoffers.juno.com/TGL2141/c?cp=mP3QZBgr1A9eUSmX6ls13gAAJ1CmHaRKpeX3s0f3JfT8odq8AAQAAAAFAAAAAK1A2j4AAAAAAAAAAAAAAAAACEcEAAAAAA== From davea at ieee.org Tue Sep 22 23:24:56 2009 From: davea at ieee.org (Dave Angel) Date: Tue, 22 Sep 2009 17:24:56 -0400 Subject: [Tutor] calling a superclass method after overriding it In-Reply-To: References: Message-ID: <4AB940A8.9080706@ieee.org> Serdar Tumgoren wrote: > > > > def result_of_SPECIALIZED_SQLcall_for_child(): > name =None > return name > > > > class Child(Parent): > def __init__(self): > super(Child, self).__init__() > > def add_name(self): > name = result_of_SPECIALIZED_SQLcall_for_child() > try: > name + '' > self.name =ame > except TypeError: > #default to the superclass's add_name method > super(Child, self).add_name() > > Meantime, many thanks!! > > I know this is a simplified example, but I'd still like to point out that using exceptions when there's a simple test is not reasonable. You can just check for None with a simple if test. DaveA From zstumgoren at gmail.com Tue Sep 22 23:56:42 2009 From: zstumgoren at gmail.com (Serdar Tumgoren) Date: Tue, 22 Sep 2009 17:56:42 -0400 Subject: [Tutor] calling a superclass method after overriding it In-Reply-To: <4AB940A8.9080706@ieee.org> References: <4AB940A8.9080706@ieee.org> Message-ID: > I know this is a simplified example, but I'd still like to point out that > using exceptions when there's a simple test is not reasonable. ? You can > just check for None with a simple if test. An "if" test would be more readable, I agree. But I was trying to apply the "Easier to Ask Permission Forgiveness" style, discussed in the Python Cookbook: , http://tinyurl.com/lfp35q And in this recipe from the book: http://code.activestate.com/recipes/52291/ The example Martelli uses is far more complicated than my simple use case of checking for None, so perhaps I've engaged in a bit of overkill? Or perhaps I'm not fully understanding the lesson. I'll admit, the latter is very possible since I'm still on the front end of the learning curve... From zstumgoren at gmail.com Wed Sep 23 00:03:00 2009 From: zstumgoren at gmail.com (Serdar Tumgoren) Date: Tue, 22 Sep 2009 18:03:00 -0400 Subject: [Tutor] calling a superclass method after overriding it In-Reply-To: References: <4AB940A8.9080706@ieee.org> Message-ID: > An "if" test would be more readable, I agree. ?But I was trying to > apply the "Easier to Ask Permission Forgiveness" style, discussed in > the Python Cookbook: , > Err..."Easier to Ask Forgiveness than Permission" approach is what I meant (perhaps proving my point about not fully understanding the technique!) From kent37 at tds.net Wed Sep 23 00:04:14 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 22 Sep 2009 18:04:14 -0400 Subject: [Tutor] urllib2, read data with specific encoding In-Reply-To: <1253653489.19436.9.camel@infirit.homelinux.org> References: <1253653489.19436.9.camel@infirit.homelinux.org> Message-ID: <1c2a2c590909221504w30463852n7534c93a1459a18e@mail.gmail.com> On Tue, Sep 22, 2009 at 5:04 PM, Sander Sweers wrote: > Hello Tutors, Because a website was giving me issues with unicode > character I created a function to force the encoding. I am not sure it > is the correct way to handle these things. > > def reader(fobject, encoding='UTF-8'): > ? ?'''Read a fileobject with specified encoding, defaults UTF-8.''' > ? ?r = codecs.getreader(encoding) > ? ?data = r(fobject) > ? ?return data > > I would call it like reader(urllib2.urlopen(someurl), 'somencoding'). > Now I am looking for advice if this is the proper way of dealing with > these type of issues? Is there better practice maybe? That seems ok if you want a file-like object. If you just want a string it would be simpler to use urllib2.urlopen(someurl).read().decode('someencoding') Kent From kent37 at tds.net Wed Sep 23 00:30:10 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 22 Sep 2009 18:30:10 -0400 Subject: [Tutor] ex-ftp In-Reply-To: <9e3fac840909212139i747e4727sac38c7b398083142@mail.gmail.com> References: <9e3fac840909212139i747e4727sac38c7b398083142@mail.gmail.com> Message-ID: <1c2a2c590909221530q3be52402i99c1871e7543ca5b@mail.gmail.com> On Tue, Sep 22, 2009 at 12:39 AM, prasad rao wrote: > hello? friends > ? I am trying to write a class to save a url.page. > But it is not working.It is saving the html.page.But not getting > images.I am unable to show the list (object.links). > Please take a look at it and show me how to rectify it. There is a websucker tool supplied with python that will do this. http://effbot.org/zone/websucker.htm There's a gui version too, called wsgui. Kent From sander.sweers at gmail.com Wed Sep 23 01:56:45 2009 From: sander.sweers at gmail.com (Sander Sweers) Date: Wed, 23 Sep 2009 00:56:45 +0100 Subject: [Tutor] urllib2, read data with specific encoding In-Reply-To: <1c2a2c590909221504w30463852n7534c93a1459a18e@mail.gmail.com> References: <1253653489.19436.9.camel@infirit.homelinux.org> <1c2a2c590909221504w30463852n7534c93a1459a18e@mail.gmail.com> Message-ID: <1253663815.22187.38.camel@infirit> On Tue, 2009-09-22 at 18:04 -0400, Kent Johnson wrote: > > def reader(fobject, encoding='UTF-8'): > > '''Read a fileobject with specified encoding, defaults UTF-8.''' > > r = codecs.getreader(encoding) > > data = r(fobject) > > return data > > > > I would call it like reader(urllib2.urlopen(someurl), 'somencoding'). > > Now I am looking for advice if this is the proper way of dealing with > > these type of issues? Is there better practice maybe? > > That seems ok if you want a file-like object. Ok good, I was worried I was doing something stupid :-) > If you just want a string it would be simpler to use > urllib2.urlopen(someurl).read().decode('someencoding') Wouldn't this have an extra conversion from str to unicode which my function skips? Thanks Sander From alan.gauld at btinternet.com Wed Sep 23 01:33:52 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 23 Sep 2009 00:33:52 +0100 Subject: [Tutor] calling a superclass method after overriding it References: <4AB940A8.9080706@ieee.org> Message-ID: "Dave Angel" wrote >> def result_of_SPECIALIZED_SQLcall_for_child(): >> name =None >> return name I assume this is a placeholder for more complex code to follow? >> class Child(Parent): >> def add_name(self): >> name = result_of_SPECIALIZED_SQLcall_for_child() >> try: >> name + '' This does nothing except raise a type error. But that's a very contrived way of checking the type. >> self.name =ame I assume this is a typo? And it never gets executed because the error is always raised. >> except TypeError: >> super(Child, self).add_name() > I know this is a simplified example, but I'd still like to point out > that using exceptions when there's a simple test is not reasonable. > You can just check for None with a simple if test. I don't mind using exceptions for a simple test but not where the test is being forced by a piece of code that does nothing. In this case I agree it would be better to check explicitly for a string if a string is required. Even using exceptions it would be better to do someting like: try: if type(name) != str: raise TypeError # other stuff here except TypeError: super(....) It makes the purpose of the code obvious. But if type(name) != str: super(....) else: # other stuff here is clearer still -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From davea at ieee.org Wed Sep 23 01:36:45 2009 From: davea at ieee.org (Dave Angel) Date: Tue, 22 Sep 2009 19:36:45 -0400 Subject: [Tutor] how to define a function with multple parameters In-Reply-To: <20090922.172326.26353.0@webmail06.dca.untd.com> References: <20090922.172326.26353.0@webmail06.dca.untd.com> Message-ID: <4AB95F8D.1020709@ieee.org> shellcom3 at juno.com wrote: > I want to know how to use multiple parameters for 1 function > > > def display(message): > print message > > def rate_score(): > score =ate_score > > > if rate_score <=99: > print "that's nothing." > elif rate_score <=0000: > print "ok." > elif rate_score >=0000: > print "great." > > > #main > > display("Get the meaning !") > > raw_input("Please type in your score") > print "here's your score", rate_score > rate_score() > This is the outcome: > > great. > Get the meaning > Please type in your score50 > here's your score > > > I have no idea what the subject line is supposed to mean, but that program is in sad shape. It won't compile and run as it stands, so I suspect you didn't transcribe it correctly. Please use cut and paste to show us what you really have, and what it really produces. Then maybe we can comment on improvements. Also, please delineate which parts of the message are from a python script, and which parts are the echoes from an interactive run. And if you're running from a command line, show the command used to launch the script, all the way through to the end. One thing that probably isn't a transcribing error is your total confusion between a variable called rate_score and a function by the same name. A given name can only have one meaning in one scope, so plan carefully. And even if you can reassign a function name inside that function to have a new value, it's almost never a good idea. For one thing, it makes it hard to call the function a second time. DaveA From davea at ieee.org Wed Sep 23 01:45:18 2009 From: davea at ieee.org (Dave Angel) Date: Tue, 22 Sep 2009 19:45:18 -0400 Subject: [Tutor] calling a superclass method after overriding it In-Reply-To: References: <4AB940A8.9080706@ieee.org> Message-ID: <4AB9618E.2080201@ieee.org> Serdar Tumgoren wrote: >> An "if" test would be more readable, I agree. But I was trying to >> apply the "Easier to Ask Permission Forgiveness" style, discussed in >> the Python Cookbook: , >> >> > Err..."Easier to Ask Forgiveness than Permission" approach is what I > meant (perhaps proving my point about not fully understanding the > technique!) > > I certainly understand the concept and use it often. But the main time to use it is when it can avoid interrupting the normal flow for normal operation. For example, if you define a function that doesn't return unless it has a valid result (for invalid, it raises an exception), then the calling function doesn't need to explicitly check the result. That might permit one to embed the first function call into a more complex expression without having to decompose it to test for errors at various points. If the first function were written that way (raise, rather than returning None), then we could change from: def add_name(self): name = result_of_SPECIALIZED_SQLcall_for_child() try: name + '' self.name =ame except TypeError: #default to the superclass's add_name method super(Child, self).add_name() to: def add_name(self): try: self.name = result_of_SPECIALIZED_SQLcall_for_child() except SpecialSQLError: #default to the superclass's add_name method super(Child, self).add_name() still not really worth it, but it's getting there. And notice it's shorter, and especially so in the normal path. DaveA From alan.gauld at btinternet.com Wed Sep 23 01:45:30 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 23 Sep 2009 00:45:30 +0100 Subject: [Tutor] how to define a function with multple parameters References: <20090922.172326.26353.0@webmail06.dca.untd.com> Message-ID: wrote >I want to know how to use multiple parameters for 1 function Do you by any chance come from a Visual Basic background? > def display(message): > print message > > def rate_score(): > score = rate_score This does nothing. It assigns the function rate_score to a local variable which is immediately thrown away. I suspect you wanted to "return" the score? Except you don't assign a value to score, you assign the same function. So I'm a bit confused over what you are trying to do. > if rate_score <= 999: This compares a function object, rate_score, to a number which does not make sense. Even if rate_score returned a value you need to provide parentheses to call the function. Like this: if rate_score() <= 99: > elif rate_score <= 10000: Same again > elif rate_score >= 10000: and again > raw_input("Please type in your score") And here you are again not storing the value anywhere. I suspect you also want to convert it to a number so you probably want: score = int( raw_input("Please type your score ") ) > print "here's your score", rate_score Again you are using the function object not a value. You want to use whatever variable you choose to store the score in. > rate_score() Despite the subject of your email I think you need to go back to the fundamentals of writing and using Python functions. You obviously missed something fundamental first time around. Try the Functions and Modules topic in my tutorial as an alternative source of info... -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From zstumgoren at gmail.com Wed Sep 23 01:46:38 2009 From: zstumgoren at gmail.com (Serdar Tumgoren) Date: Tue, 22 Sep 2009 19:46:38 -0400 Subject: [Tutor] calling a superclass method after overriding it In-Reply-To: References: <4AB940A8.9080706@ieee.org> Message-ID: >>> ? ? ? ? ? ?self.name =ame > > I assume this is a typo? And it never gets executed because the error is > always raised. yep. that was a typo that should be "name" > I don't mind using exceptions for a simple test but not where the test is > being forced by a piece of code that does nothing. In this case I agree it > would be better to check explicitly for a string if a string is required. I am indeed trying to check if it's a string. > > ?if type(name) != str: > ? ? ? super(....) > ?else: > ? ? ? # other stuff here > > is clearer still > In this case, is there any argument against checking for None? Or is it better to do a type check for a string? if name is None: super(....) else: # do stuff From alan.gauld at btinternet.com Wed Sep 23 01:49:33 2009 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Tue, 22 Sep 2009 23:49:33 +0000 (GMT) Subject: [Tutor] calling a superclass method after overriding it In-Reply-To: References: <4AB940A8.9080706@ieee.org> Message-ID: <547859.35599.qm@web86710.mail.ird.yahoo.com> > In this case, is there any argument against checking for None? Or is > it better to do a type check for a string? > > if name is None: > super(....) > else: > # do stuff That might be ok if string or None are the only types you could get. Checking for not string will catch any numbers, booleans or anything else that might slip through... Basically check for what id most accurately representing what you want. If you want to catch anything other than a string use an explicit string test, if you only want to catch None then check for None. Alan G. From zstumgoren at gmail.com Wed Sep 23 01:53:38 2009 From: zstumgoren at gmail.com (Serdar Tumgoren) Date: Tue, 22 Sep 2009 19:53:38 -0400 Subject: [Tutor] calling a superclass method after overriding it In-Reply-To: <4AB9618E.2080201@ieee.org> References: <4AB940A8.9080706@ieee.org> <4AB9618E.2080201@ieee.org> Message-ID: > ? def add_name(self): > ? ? ? try: > ? ? ? ? ? self.name = SPECIALIZED_SQLcall_for_child() > ? ? ? except SpecialSQLError: > ? ? ? ? ? #default to the superclass's add_name method > ? ? ? ? ? super(Child, self).add_name() > That certainly is a lot easier to read. So if I were to go that route, would my "SPECIALIZED_SQLCall_for_child()" function (I've slightly renamed it) have to resemble something like below?: def SpecialSQLcall_for_child(): result = execute some sql_for_special_case() if type(result) != str: raise SpecialSQLError else: return result From kent37 at tds.net Wed Sep 23 02:06:07 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 22 Sep 2009 20:06:07 -0400 Subject: [Tutor] urllib2, read data with specific encoding In-Reply-To: <1253663815.22187.38.camel@infirit> References: <1253653489.19436.9.camel@infirit.homelinux.org> <1c2a2c590909221504w30463852n7534c93a1459a18e@mail.gmail.com> <1253663815.22187.38.camel@infirit> Message-ID: <1c2a2c590909221706h5787502ata62ac0dae96e9149@mail.gmail.com> On Tue, Sep 22, 2009 at 7:56 PM, Sander Sweers wrote: > On Tue, 2009-09-22 at 18:04 -0400, Kent Johnson wrote: >> > def reader(fobject, encoding='UTF-8'): >> > ? ?'''Read a fileobject with specified encoding, defaults UTF-8.''' >> > ? ?r = codecs.getreader(encoding) >> > ? ?data = r(fobject) >> > ? ?return data >> > >> > I would call it like reader(urllib2.urlopen(someurl), 'somencoding'). >> > Now I am looking for advice if this is the proper way of dealing with >> > these type of issues? Is there better practice maybe? >> >> That seems ok if you want a file-like object. > > Ok good, I was worried I was doing something stupid :-) > >> If you just want a string it would be simpler to use >> urllib2.urlopen(someurl).read().decode('someencoding') > > Wouldn't this have an extra conversion from str to unicode which my > function skips? No, IIUC your version is returning unicode strings, the decoding is just hidden inside the codecs reader object. Kent From davea at ieee.org Wed Sep 23 02:28:05 2009 From: davea at ieee.org (Dave Angel) Date: Tue, 22 Sep 2009 20:28:05 -0400 Subject: [Tutor] calling a superclass method after overriding it In-Reply-To: References: <4AB940A8.9080706@ieee.org> <4AB9618E.2080201@ieee.org> Message-ID: <4AB96B95.9000206@ieee.org> Serdar Tumgoren wrote: >> def add_name(self): >> try: >> self.name = SPECIALIZED_SQLcall_for_child() >> except SpecialSQLError: >> #default to the superclass's add_name method >> super(Child, self).add_name() >> >> > That certainly is a lot easier to read. So if I were to go that route, > would my "SPECIALIZED_SQLCall_for_child()" function (I've slightly > renamed it) have to resemble something like below?: > > def SpecialSQLcall_for_child(): > result = execute some sql_for_special_case() > if type(result) != str: > raise SpecialSQLError > else: > return result > > Exactly. The whole point of forgiveness/permission is to be able to propagate the error without having other code in the path affected by it. So if you return at all, return a real value. (Raise isn't exactly returning, the way I see it, since the flow of control goes elsewhere) BTW, it's possible that "execute_some_sql...()" might itself be raising the exception. In this case, we might make this call even simpler; it needn't even know anything about the exception. DaveA From david at pythontoo.com Wed Sep 23 03:01:48 2009 From: david at pythontoo.com (David) Date: Tue, 22 Sep 2009 21:01:48 -0400 Subject: [Tutor] how to define a function with multple parameters In-Reply-To: <20090922.172326.26353.0@webmail06.dca.untd.com> References: <20090922.172326.26353.0@webmail06.dca.untd.com> Message-ID: <4AB9737C.4010207@pythontoo.com> shellcom3 at juno.com wrote: > I want to know how to use multiple parameters for 1 function > > > def display(message): > print message > > def rate_score(): > score = rate_score > > > if rate_score <= 999: > print "that's nothing." > elif rate_score <= 10000: > print "ok." > elif rate_score >= 10000: > print "great." > > > #main > > display("Get the meaning !") > > raw_input("Please type in your score") > print "here's your score", rate_score > rate_score() > This is the outcome: > > great. > Get the meaning > Please type in your score50 > here's your score > Here is something that you can try; #!/usr/bin/python def display(message): print message def rate_score(selection): if selection <= 99: print 'Thats nothing !' else: print 'Thats something !' def main(): display('Get the meaning !') while True: try: selection = int(raw_input('Please enter your score: ')) break except ValueError: print 'Oops! Did you forget to enter a number !' print 'You entered %s as your score' % selection rate_score(selection) main() -- Powered by Gentoo GNU/Linux http://linuxcrazy.com From tim.bowden at mapforge.com.au Wed Sep 23 05:04:13 2009 From: tim.bowden at mapforge.com.au (Tim Bowden) Date: Wed, 23 Sep 2009 11:04:13 +0800 Subject: [Tutor] How to get homework help (was need to hire a tutor... ) In-Reply-To: References: <25530473.post@talk.nabble.com> <1c2a2c590909211404k50309616r9917026093c5d315@mail.gmail.com> <1253586659.4255.44.camel@mordor> Message-ID: <1253675053.5056.55.camel@mordor> On Tue, 2009-09-22 at 09:20 +0100, Alan Gauld wrote: > > I'm new on this list <*waves hello to everyone*>, > > welcome to the tutor list <*waves back*> :-) > > > trick to getting help here with homework is pretty much the same as > > most > other tech lists. > > Absolutely so, and well summarised. > > Alan G. > http://www.alan-g.me.uk/ And the off list reply was pretty much what you'd expect. Funny old thing life. Tim Bowden -- Mapforge Geospatial Open Source Spatial Consulting http://www.mapforge.com.au From tim.bowden at mapforge.com.au Wed Sep 23 06:02:51 2009 From: tim.bowden at mapforge.com.au (Tim Bowden) Date: Wed, 23 Sep 2009 12:02:51 +0800 Subject: [Tutor] Challenge In-Reply-To: <826729.63168.qm@web45911.mail.sp1.yahoo.com> References: <826729.63168.qm@web45911.mail.sp1.yahoo.com> Message-ID: <1253678571.5056.66.camel@mordor> On Tue, 2009-09-22 at 05:13 -0700, Ali Sina wrote: > Hello tutor > > I downloaded a guide about learning Python by Michael Dawson which has > challenges at the end of each chapter. I'm a novice so I encountered a > problem with this challenge: > > > > "Write a program that flips a coin 100 times and then tells you the > number of heads and tails." The heads and tails bit is a red herring. Don't try and model it in your code. It does nothing more than signal a binary condition, and provide a tag to hang the result on (at least in this context). #!/usr/bin/python import random i=0 for flip in range(100): i += random.choice((0,1)) print "Heads: %d, Tails: %d" % (i, 100-i) # Tim bowden From kp8 at mac.com Wed Sep 23 06:58:50 2009 From: kp8 at mac.com (kevin parks) Date: Wed, 23 Sep 2009 13:58:50 +0900 Subject: [Tutor] What is this an example of (and how can i use it?) In-Reply-To: <1c2a2c590909201752o5ab3c1d5v81bff0e7bdbee7ca@mail.gmail.com> References: <57E7CD0A-AEDA-44E3-B0CE-33D9791D5FB2@mac.com> <4AB6590E.5040601@btinternet.com> <6B75B7D9-DD9E-4F64-973E-50F165796186@mac.com> <1c2a2c590909201752o5ab3c1d5v81bff0e7bdbee7ca@mail.gmail.com> Message-ID: On Sep 21, 2009, at 9:52 AM, Kent Johnson wrote: > > Calling a generator function gives you something that can be iterated. > You can create a list out of it (by passing it to the list() function) > or you can iterate the items in it directly with a for loop. Using the > example above, you could say > for item in roundrobin('abc', [], range(4), (True,False)): > print item > >> I kinda understand conceptually what iterators and generators do >> and why >> they are "a honking good idea" (why create 100 of x when we just >> want the >> 100th, etc.) what i don't get is the syntax and how they are used >> in real >> life. How generator and iterators behave in the wild. > > It's really not that bad. They are just a generalization of what you > have already been doing with lists. > >> Even the Lutz is too >> terse and generally poor on these two complex and relatively new >> constructs. >> They are a dark and obscure magic. > > No, really they are not difficult. Read my essay and ask questions if > you don't understand. Thanks. I have some time today and will read up on what you sent me and revisit the lutz and other docs. It appears it is not so impenetrable as i initially though. Well iterators aren't maybe, but generator do look tricky. So interators iterate over lists, tuples, strings, dictionaries and any data type that is iterable, and generators are ways to make new iterables? Anyway, i will brew some coffee and hit those links. Thanks, -kevin From rspleen at earthlink.net Wed Sep 23 10:10:13 2009 From: rspleen at earthlink.net (rspleen at earthlink.net) Date: Wed, 23 Sep 2009 01:10:13 -0700 Subject: [Tutor] Python 2.3.5 question Message-ID: <380-22009932381013531@earthlink.net> Hello. I am Roman. I bought this book call Python Programming for the Absolute Beginner which I am and after I downloaded Python 2.3.5 from their CD, I opened IDLE, typed "Game Over" and nothing happened. What do I do? Please, help. I don't understand any of the programming jargon. Please talk simple to me. With great appreciation, Roman rspleen at earthlink.net EarthLink Revolves Around You. -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Wed Sep 23 13:48:04 2009 From: kent37 at tds.net (Kent Johnson) Date: Wed, 23 Sep 2009 07:48:04 -0400 Subject: [Tutor] What is this an example of (and how can i use it?) In-Reply-To: References: <57E7CD0A-AEDA-44E3-B0CE-33D9791D5FB2@mac.com> <4AB6590E.5040601@btinternet.com> <6B75B7D9-DD9E-4F64-973E-50F165796186@mac.com> <1c2a2c590909201752o5ab3c1d5v81bff0e7bdbee7ca@mail.gmail.com> Message-ID: <1c2a2c590909230448n57e71f1cx25202dddb24d7970@mail.gmail.com> On Wed, Sep 23, 2009 at 12:58 AM, kevin parks wrote: > It appears it is not so impenetrable as i initially > though. Well iterators > aren't maybe, but generator do look tricky. So interators iterate over > lists, tuples, strings, dictionaries > and any data type that is iterable, and generators are ways to make new > iterables? Exactly. Kent From tim.bowden at mapforge.com.au Wed Sep 23 15:27:45 2009 From: tim.bowden at mapforge.com.au (Tim Bowden) Date: Wed, 23 Sep 2009 21:27:45 +0800 Subject: [Tutor] Python 2.3.5 question In-Reply-To: <380-22009932381013531@earthlink.net> References: <380-22009932381013531@earthlink.net> Message-ID: <1253712465.4243.29.camel@mordor> On Wed, 2009-09-23 at 01:10 -0700, rspleen at earthlink.net wrote: > Hello. I am Roman. I bought this book call Python Programming for the > Absolute Beginner which I am and after I downloaded Python 2.3.5 from > their CD, I opened IDLE, typed "Game Over" and nothing happened. What > do I do? Please, help. I don't understand any of the programming > jargon. Please talk simple to me. > With great appreciation, > Roman I think you need to re-read the book. You need to type: print "Game Over" Python then outputs: Game Over As for the jargon, you'll have to get used to it. Start with the next section of the book, 'Learning the Jargon'. HTH, Tim Bowden From seena_blk at yahoo.com Wed Sep 23 16:22:08 2009 From: seena_blk at yahoo.com (Ali Sina) Date: Wed, 23 Sep 2009 07:22:08 -0700 (PDT) Subject: [Tutor] how to print a message backwards Message-ID: <335895.5518.qm@web45902.mail.sp1.yahoo.com> #Message backward printer message=input('Enter your message: ') for i in range(len(message),0,-1): ??? print(message) This is the code which I have written. All it does is count the number of letters starting from backwards. The proper code should so something like this: Enter your message: Hi. My name is Ali Sina Your message in backwards: aniS ilA si eman yM .iH -------------- next part -------------- An HTML attachment was scrubbed... URL: From zstumgoren at gmail.com Wed Sep 23 17:50:59 2009 From: zstumgoren at gmail.com (Serdar Tumgoren) Date: Wed, 23 Sep 2009 11:50:59 -0400 Subject: [Tutor] how to print a message backwards In-Reply-To: <335895.5518.qm@web45902.mail.sp1.yahoo.com> References: <335895.5518.qm@web45902.mail.sp1.yahoo.com> Message-ID: Try reading up on sequences and slicing. They offer a very elegant solution to your (homework?) problem. http://docs.python.org/tutorial/introduction.html#strings -------------- next part -------------- An HTML attachment was scrubbed... URL: From zstumgoren at gmail.com Wed Sep 23 18:07:21 2009 From: zstumgoren at gmail.com (Serdar Tumgoren) Date: Wed, 23 Sep 2009 12:07:21 -0400 Subject: [Tutor] how to print a message backwards In-Reply-To: References: <335895.5518.qm@web45902.mail.sp1.yahoo.com> Message-ID: > http://docs.python.org/tutorial/introduction.html#strings > The below page is a better introduction to sequences: http://effbot.org/zone/python-list.htm It uses lists, but the lessons on slicing also apply to strings (which are a type of sequence). HTH! Serdar From alan.gauld at btinternet.com Wed Sep 23 19:47:23 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 23 Sep 2009 18:47:23 +0100 Subject: [Tutor] Python 2.3.5 question References: <380-22009932381013531@earthlink.net> Message-ID: > Hello. I am Roman. Hi Roman. > I bought this book call Python Programming for the Absolute Beginner > which I am and after I downloaded Python 2.3.5 from their CD, > I opened IDLE, typed "Game Over" and nothing happened. Why did you do that? Did the book say to do it? Are you sure that's what it said? In programming you have to be very careful over details of spelling, spacing and punctuation. > I don't understand any of the programming jargon. Please talk simple to > me. We will try, you do need to learn the jargon but that's what the book should teach you. If you don't understand something in the book just ask here. You might also try looking at the equivalent topic in my web tutor which is also aimed at complete beginners... When you do post questions here its best to reference where in the book you are reading. Also paste in any code and error messages you have - the whole error message not just the last line. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Wed Sep 23 19:51:26 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 23 Sep 2009 18:51:26 +0100 Subject: [Tutor] how to print a message backwards References: <335895.5518.qm@web45902.mail.sp1.yahoo.com> Message-ID: "Ali Sina" wrote #Message backward printer message=input('Enter your message: ') for i in range(len(message),0,-1): print(message) > This is the code which I have written. > All it does is count the number of letters starting from backwards. Correct, plus it prints the original message each time. So obviously you need to print something else! If you are counting one letter at a time maybe you should print one letter at a time? However/... Others have given you a big hint about using slicing instead so I'll leave you to research that yourself. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From smiles at worksmail.net Wed Sep 23 20:21:37 2009 From: smiles at worksmail.net (C or L Smith) Date: Thu, 24 Sep 2009 00:06:37 +0545 Subject: [Tutor] Python 2.3.5 question References: Message-ID: <8FE52FC802E547A395806E851012C85F@kisc.edu.np> >> Hello. I am Roman. I bought this book call Python Programming for >> the Absolute Beginner which I am and after I downloaded Python 2.3.5 >> from their CD, I opened IDLE, typed "Game Over" and nothing >> happened. What do I do? Please, help. I don't understand any of the >> programming jargon. Please talk simple to me. With great >> appreciation, >> Roman That jargon is a bit of a hurdle at the start. It's like trying to succeed at the game where some asks, Can you repeat exactly what I tell you? Sure. OK, Three blind mice. That's easy, "Three blind mice." Nope. Wanna try again? Sure. OK. Three blind mice. That's what you said last time. Yep. Three blind mice! Nope. AARG!! And eventually you realize that "OK" is part of what you had to say, too. It was hard (by hearing alone) to tell what were the words to repeat and what were conversational filler. Any good book on programming is going to use some way to tell you exactly what to type. Usually they do that by changing the font. They usually start the book by telling you what to look for. If you are just getting started, *don't skip that part of the book*! And pay extra close attention to the exactly what they tell you to type. OK? Give it another try. Give it another try? Nope. But you said, "Give it another try!" Nope, I said "OK? Give it another try." :-) /c From bermanrl at cfl.rr.com Wed Sep 23 20:10:44 2009 From: bermanrl at cfl.rr.com (Robert Berman) Date: Wed, 23 Sep 2009 14:10:44 -0400 Subject: [Tutor] how to print a message backwards In-Reply-To: References: <335895.5518.qm@web45902.mail.sp1.yahoo.com> Message-ID: <1253729444.8270.142.camel@bermanrl-desktop> Is there a significant difference in speed, style, or any pythonesque reasoning between Alan's solution and print message[::-1] Thanks for any information, Robert On Wed, 2009-09-23 at 18:51 +0100, Alan Gauld wrote: > "Ali Sina" wrote > > #Message backward printer > message=input('Enter your message: ') > > for i in range(len(message),0,-1): > print(message) > > > > This is the code which I have written. > > All it does is count the number of letters starting from backwards. > > Correct, plus it prints the original message each time. > So obviously you need to print something else! If you are counting > one letter at a time maybe you should print one letter at a time? > > However/... > Others have given you a big hint about using slicing instead > so I'll leave you to research that yourself. > > From krissy.ambert at gmail.com Wed Sep 23 22:38:07 2009 From: krissy.ambert at gmail.com (Kristina Ambert) Date: Wed, 23 Sep 2009 16:38:07 -0400 Subject: [Tutor] ODBC SQL Server Question In-Reply-To: <4AB3E21A.1070800@dcsoftware.com> References: <4AB3AC04.20901@dcsoftware.com> <1c2a2c590909181000t5310e71dgcb6df3ec3b6d2db4@mail.gmail.com> <4AB3CE15.7060603@dcsoftware.com> <1c2a2c590909181212u66c6fae0p52c25cb6f87158fb@mail.gmail.com> <4AB3E21A.1070800@dcsoftware.com> Message-ID: Hi, Thanks you guys for the replies and thanks Kent for the explanation, and yes, this: self.cursor.execute("SELECT CUSTID FROM Stories WHERE NAME= ?", (name, )) using the comma did make it work. On Fri, Sep 18, 2009 at 3:40 PM, Jeff Johnson wrote: > Thanks for the clarification Kent! > > > Kent Johnson wrote: > >> On Fri, Sep 18, 2009 at 2:14 PM, Jeff Johnson >> wrote: >> >>> Kent: >>> >>> How about this: >>> self.cursor.execute("SELECT CUSTID FROM Stories WHERE NAME = '%s'" % >>> (name, >>> )) >>> >> >> No, that has the same result as your original. For example, >> In [3]: name = "Kent'; drop table Stories;--" >> >> In [4]: "SELECT CUSTID FROM Stories WHERE NAME = '%s'" % (name, ) >> Out[4]: "SELECT CUSTID FROM Stories WHERE NAME = 'Kent'; drop table >> Stories;--'" >> >> Oops. >> >> Question, does execute know to substitute the question mark with name? >>> self.cursor.execute("SELECT CUSTID FROM Stories WHERE NAME= ?", (name, )) >>> >> >> Yes, and it will correctly quote name according to the conventions of >> the database in use. (Note that not all DB-API implementations use ? >> as the placeholder; check the docs for the db you are using.) >> >> Kent >> > > -- > Jeff > > Jeff Johnson > jeff at dcsoftware.com > Phoenix Python User Group - sunpiggies at googlegroups.com > -- Cheers, Krissy ----------------------------------------------------------------------- Testing the waters is always fun... -------------- next part -------------- An HTML attachment was scrubbed... URL: From krissy.ambert at gmail.com Wed Sep 23 22:46:07 2009 From: krissy.ambert at gmail.com (Kristina Ambert) Date: Wed, 23 Sep 2009 16:46:07 -0400 Subject: [Tutor] Switching from 2.3 to 2.6 Message-ID: Hi guys, I'm getting this error after I tried to switch from python 2.3 to 2.6. I tried to look online for what it means, but I can't find any good explanation. Do any of you guys have any idea what's causing it and what it means? C:\Python26\lib\site-packages\win32\lib\dbi.py:13: DeprecationWarning: dbi module is obsolete, code should now use native python datetime and buffer/memoryview objects DeprecationWarning) -- Cheers, Krissy ----------------------------------------------------------------------- Testing the waters is always fun... -------------- next part -------------- An HTML attachment was scrubbed... URL: From emile at fenx.com Wed Sep 23 22:57:19 2009 From: emile at fenx.com (Emile van Sebille) Date: Wed, 23 Sep 2009 13:57:19 -0700 Subject: [Tutor] how to print a message backwards In-Reply-To: <335895.5518.qm@web45902.mail.sp1.yahoo.com> References: <335895.5518.qm@web45902.mail.sp1.yahoo.com> Message-ID: On 9/23/2009 7:22 AM Ali Sina said... > #Message backward printer > message=input('Enter your message: ') > > for i in range(len(message),0,-1): > print(message) > > > This is the code which I have written. All it does is count the number of letters starting from backwards. The proper code should so something like this: > > Enter your message: Hi. My name is Ali Sina > > Your message in backwards: aniS ilA si eman yM .iH There's also a reversed keyword introduced in python 2.4. Emile > > > > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From transmogribenno at gmail.com Thu Sep 24 01:36:03 2009 From: transmogribenno at gmail.com (Benno Lang) Date: Thu, 24 Sep 2009 08:36:03 +0900 Subject: [Tutor] Switching from 2.3 to 2.6 In-Reply-To: References: Message-ID: <9b00d1a90909231636p60231295v63c6e75f1f3761ce@mail.gmail.com> On Thu, Sep 24, 2009 at 5:46 AM, Kristina Ambert wrote: > Hi guys, > I'm getting this error after I tried to switch from python 2.3 to 2.6. I > tried to look online for what it means, but I can't find any good > explanation. > Do any of you guys have any idea what's causing it and what it means? > C:\Python26\lib\site-packages\win32\lib\dbi.py:13: DeprecationWarning: dbi > module is obsolete, code should now use native python datetime and > buffer/memoryview objects > ? DeprecationWarning) Sounds like the dbi module has been deprecated: i.e. it's out of date, and contains ugly code that will eventually be removed. Therefore, you should change the parts of your code that use it. If you read the error message, it tells you which up-to-date/better alternatives you should be using instead. n.b. this is general information; I have no knowledge of the specific modules/objects listed. HTH, benno. From alan.gauld at btinternet.com Thu Sep 24 01:40:42 2009 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Wed, 23 Sep 2009 23:40:42 +0000 (GMT) Subject: [Tutor] how to print a message backwards In-Reply-To: <1253729444.8270.142.camel@bermanrl-desktop> References: <335895.5518.qm@web45902.mail.sp1.yahoo.com> <1253729444.8270.142.camel@bermanrl-desktop> Message-ID: <695959.77053.qm@web86704.mail.ird.yahoo.com> > Is there a significant difference in speed, style, or any pythonesque > reasoning between Alan's solution and > print message[::-1] Yes, the for loop doing one character at a time will be much slower than using a slice. The slice is more pythonic but less general. A reverse loop is something that is often needed in programming solutions so it's useful to know how to do it for the general case. But where the data can be sliced that will be faster and more concise. Alan G. From bermanrl at cfl.rr.com Thu Sep 24 04:09:50 2009 From: bermanrl at cfl.rr.com (Robert Berman) Date: Wed, 23 Sep 2009 22:09:50 -0400 Subject: [Tutor] how to print a message backwards In-Reply-To: <695959.77053.qm@web86704.mail.ird.yahoo.com> References: <335895.5518.qm@web45902.mail.sp1.yahoo.com> <1253729444.8270.142.camel@bermanrl-desktop> <695959.77053.qm@web86704.mail.ird.yahoo.com> Message-ID: <1253758190.8270.144.camel@bermanrl-desktop> Thank you for the clear explanation. Robert On Wed, 2009-09-23 at 23:40 +0000, ALAN GAULD wrote: > > Is there a significant difference in speed, style, or any pythonesque > > reasoning between Alan's solution and > > print message[::-1] > > > Yes, the for loop doing one character at a time will be much > slower than using a slice. The slice is more pythonic but less general. > A reverse loop is something that is often needed in programming > solutions so it's useful to know how to do it for the general case. > But where the data can be sliced that will be faster and more > concise. > > Alan G. From sander.sweers at gmail.com Thu Sep 24 13:05:41 2009 From: sander.sweers at gmail.com (Sander Sweers) Date: Thu, 24 Sep 2009 13:05:41 +0200 Subject: [Tutor] how to print a message backwards In-Reply-To: <695959.77053.qm@web86704.mail.ird.yahoo.com> References: <335895.5518.qm@web45902.mail.sp1.yahoo.com> <1253729444.8270.142.camel@bermanrl-desktop> <695959.77053.qm@web86704.mail.ird.yahoo.com> Message-ID: 2009/9/24 ALAN GAULD : >> print message[::-1] > > Yes, the for loop doing one character at a time will be much > slower than using a slice. The slice is more pythonic but less general. > A reverse loop is something that is often needed in programming > solutions so it's useful to know how to do it for the general case. I have seen this some times but never really understood how it worked. I have 1 thing I am not sure of, the negative slice in the example basically means "start counting at the end position and work backwards"? Does anyone have an advanced topic on slicing where the :: notation is explained? Thanks Sander From zstumgoren at gmail.com Thu Sep 24 14:07:26 2009 From: zstumgoren at gmail.com (Serdar Tumgoren) Date: Thu, 24 Sep 2009 08:07:26 -0400 Subject: [Tutor] how to print a message backwards In-Reply-To: References: <335895.5518.qm@web45902.mail.sp1.yahoo.com> <1253729444.8270.142.camel@bermanrl-desktop> <695959.77053.qm@web86704.mail.ird.yahoo.com> Message-ID: > Does anyone have an advanced topic on slicing where the :: notation is > explained? > You should find plenty by googling for "python slice step sequence" Here are a few with links to further resources: http://www.python.org/doc/2.3/whatsnew/section-slices.html http://stackoverflow.com/questions/509211/good-primer-for-python-slice-notation http://www.daniweb.com/forums/thread222719.html http://www.daniweb.com/forums/post104865.html#post104865 From fragos.george at gmail.com Thu Sep 24 14:15:51 2009 From: fragos.george at gmail.com (george fragos) Date: Thu, 24 Sep 2009 15:15:51 +0300 Subject: [Tutor] Novice qustion Message-ID: <53008aa80909240515k4113653fnebe7dfc9309017ae@mail.gmail.com> ?Hi all Pythons! ?I'm new to Python and this List! ?I'm reading Hetland's "Beginning Python" and I tried to test myself an example the book provides in 59: ?width = input('Please enter width: ') price_width = 10 item_width = width - price_width header_format = '%-*s%*s' format ? ? ? ?= '%-*s%*.2d' print '=' * width print haeder_format % (item_width, 'Item', price_width, 'Price') print '-' * width print format % (item_width, 'Apples', price_width, 0.4) print format % (item_width, 'Pears', ?price_width, 0.5) print format % (item_width, 'Cantaloupes', price_width, 1.92) print format % (item_width, 'Dried Apricots (16 gr)' price_width, 8) print format % (item_width, 'Prunes (4 Kgr)', price_width, 12) print '=' * width Trying to run this script (saved as "test.py")I receive this error message: anvo at deadend:~/Desktop$ python test.py File "test.py", line 18 print format % (item_width, 'Dried Apricots (16 gr)' price_width, 8) ^ SyntaxError: invalid syntax I double checked my typing and I see no errors in it (I copied it from the book exactly as it is)! Are there any...? What's the "invalid" in my "syntax"? Thanx for the help! From moron.oxy at gmail.com Thu Sep 24 14:23:31 2009 From: moron.oxy at gmail.com (Oxymoron) Date: Thu, 24 Sep 2009 22:23:31 +1000 Subject: [Tutor] Novice qustion In-Reply-To: <53008aa80909240515k4113653fnebe7dfc9309017ae@mail.gmail.com> References: <53008aa80909240515k4113653fnebe7dfc9309017ae@mail.gmail.com> Message-ID: <2096a7260909240523p7d28b255wb3d53a1810e49be@mail.gmail.com> On Thu, Sep 24, 2009 at 10:15 PM, george fragos wrote: > print format % (item_width, 'Cantaloupes', price_width, 1.92) > print format % (item_width, 'Dried Apricots (16 gr)' price_width, 8) > Notice the line before (works) and after (doesn't work - as the interpreter pointed out), how do you separate items in a tuple? :-) Did not check the rest of it. anvo at deadend:~/Desktop$ python test.py > File "test.py", line 18 > print format % (item_width, 'Dried Apricots (16 gr)' price_width, 8) > ^ > SyntaxError: invalid syntax > > I double checked my typing and I see no errors in it (I copied it from > the book exactly as it is)! Are there any...? What's the "invalid" > in my "syntax"? > > Thanx for the help! > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- There is more to life than increasing its speed. -- Mahatma Gandhi -------------- next part -------------- An HTML attachment was scrubbed... URL: From zstumgoren at gmail.com Thu Sep 24 14:31:36 2009 From: zstumgoren at gmail.com (Serdar Tumgoren) Date: Thu, 24 Sep 2009 08:31:36 -0400 Subject: [Tutor] Novice qustion In-Reply-To: <2096a7260909240523p7d28b255wb3d53a1810e49be@mail.gmail.com> References: <53008aa80909240515k4113653fnebe7dfc9309017ae@mail.gmail.com> <2096a7260909240523p7d28b255wb3d53a1810e49be@mail.gmail.com> Message-ID: >> ?File "test.py", line 18 >> ? ?print format % (item_width, 'Dried Apricots (16 gr)' price_width, 8) >> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ^ >> SyntaxError: invalid syntax Oxymoron has pointed you in the right direction. After you fix that error, however, you'll get another one from a different part of your program. In general, the error information you get back from the python interpreter will point you in the right direction. In the above case, it tells you precisely where the problem is: Line 18 in test.py Whenever you get errors, you can use the traceback information as a way to pinpoint where you should start hunting for the error. HTH! Serdar From ansuman.dash at gmail.com Thu Sep 24 15:00:22 2009 From: ansuman.dash at gmail.com (Ansuman Dash) Date: Thu, 24 Sep 2009 18:30:22 +0530 Subject: [Tutor] Executing a command from a specific directory In-Reply-To: References: <8c0cfa60909150431u705ea8b2vbbaadefafb3ee9ac@mail.gmail.com> <20090916184335.GA86967@dragon.alchemy.com> <8c0cfa60909170247k138a8756xecd8cf6ddf63840@mail.gmail.com> <1c2a2c590909170504y6942318eu1fa8a32a59ea5d18@mail.gmail.com> <8c0cfa60909170540u2ee36083ya3f84a46ec6b6b65@mail.gmail.com> <1c2a2c590909170632r6d19e544sae4111fed4a9ca43@mail.gmail.com> <8c0cfa60909172105y3e7a6bd9g24528cdad64070a0@mail.gmail.com> <8c0cfa60909180216u738764bq13f1ce347b30aa62@mail.gmail.com> Message-ID: <8c0cfa60909240600n34e0a057v9560bcd46b44d189@mail.gmail.com> Hi Kurt, Sorry for the late reply. My problem is resolved. Instead of "subprocess.Popen", I used "subprocess.call". Thanks all for your replies. AD On Fri, Sep 18, 2009 at 8:05 PM, Kurt Bendl wrote: > Hello, > > On Sep 18, 2009, at 5:16 AM, Ansuman Dash wrote: > > I have written it like that. It is like press 1 and it ll download file1 >> and press 2 it ll download file2 etc.... >> >> But my question was I am using "time.sleep()" to make my script to wait >> for the file download and then validate it in log file, so is there any >> other way I can synchronize my code with the download. >> >> I am asking this because some files are very huge (120MB) and download >> also depends on N/W bandwidth so sometimes it ll be done in 30mins and some >> times it takes 60 mins. So I can't rely on "time.sleep()" >> > > > I had a similar problem. > I used pyinotify on a linux box. inotify is a kernel hook > that you can use to trigger actions on events... like when > a file write is completed. > > Note: I'm a total hack at this. I'm sure there's a more > elegant way to do what I'm dong, but I needed a fix fast, > and this worked for me. I'd appreciate any tips anyone has > to offer to make this cleaner and/or more pythonic. :-) > > I'll be glad to try to answer any questions about this hackery. > > > Best, > Kurt > > > Here's a slightly cut-down version of my code: > http://pastebin.com/f239b0413 > > inotify_published_file_handler.py > ##################################################### > #!/usr/bin/env python > # -*- coding: utf-8 -*- > # encoding: utf-8 > """ > inotify_published_file_handler.py > rev. 20090706-01 > ---- > > Created by Kurt Bendl. > > > Usage > --------- > sudo su - www-data -c 'cd /web/log/; \ > nohup /web/scripts/inotify_published_file_handler.py > \ > /web/log/inotify-errors.txt 2>&1 &' > > > Purpose > --------- > Monitor the $WEBROOT/aapracing/import/publish directory. > Once a file is closed, act on it: > > 1. Copy the PDF and XML files from source_dir to web_filebin_dir > 2. If the file is an.XML, copy it to the xml_ftp_dir > 3. Make the dummy file for PHP publishing process > 4. Remove the source file > > Requirements > ------------ > * Linux kernel 2.6.13 + > * pyinotify 2.8.6 + > > > Installation > -------------- > To install pyinotify on ubuntu/debian: > > `sudo easy_install pyinotify` > > > Docs > ----- > Docs on pyinotify can be found here: > http://trac.dbzteam.org/pyinotify/wiki > > """ > > import os > import re > import shutil > import pyinotify > import datetime > > > ### production config info > source_dir = "/web/site/aapracing/publish/data/publish/" > web_filebin_dir = "/web/site/filebin/downloads/" > reference_path = '/web/site/aapracing/publish/data/published/' > xml_ftp_dir = "/home/ftp/private/xml/" > filez = '(PDF|pdf|XML|xml|txt)' > logfile_path = "/web/log/inotify.log" > > event_mask = pyinotify.IN_CLOSE_WRITE > wm = pyinotify.WatchManager() > > def getNow(): > """Just return the current time for timestamping logs""" > return datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") > > def makeReferenceFile(tfile): > open(tfile, 'w').close() > > > class SourceMonitor(pyinotify.ProcessEvent): > """ Watches the source dir for IN_CLOSE_WRITE event""" > > def process_IN_CLOSE_WRITE(self, event): > """when an IN_CLOSE_WRITE happens, do something""" > if re.search('(.*\.'+filez+'$)', event.pathname): > # We have a match, put a copy into the filebin dir > shutil.copy2(event.pathname, web_filebin_dir) > logfile = open(logfile_path, "a") > logfile.write("%s: %s moved to %s. \n" % > (getNow(), event.pathname, web_filebin_dir)) > if re.search('(.*\.(XML|xml)$)', event.pathname): > # If it's and XML, put a copy in the FTP dir > shutil.copy2(event.pathname, xml_ftp_dir) > logfile.write("%s: %s moved to %s. \n" % > (getNow(), event.pathname, xml_ftp_dir)) > # Make the dummy file marker to enable PHP > # to know the file is really published > fhandle = os.path.basename(event.pathname) > open(reference_path + fhandle, 'w').close() > # Now, whack the source file since we're done with it. > os.remove(event.pathname) > > p = SourceMonitor() > notifier = pyinotify.Notifier(wm, p) > wdd = wm.add_watch(source_dir, event_mask) > print "This should have been started with:\n\n" > print " sudo su - www-data -c 'cd /web/log/; nohup > /web/scripts/inotify_published_file_handler.py > > /web/log/inotify-errors.txt 2>&1 &' \n\n" > > notifier.loop() > > -- > Kurt Bendl, Consultant > Internet Tool & Die > http://tool.net/ > 502-759-7104 > > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From fragos.george at gmail.com Thu Sep 24 15:23:10 2009 From: fragos.george at gmail.com (george fragos) Date: Thu, 24 Sep 2009 16:23:10 +0300 Subject: [Tutor] Novice qustion In-Reply-To: <2096a7260909240523p7d28b255wb3d53a1810e49be@mail.gmail.com> References: <53008aa80909240515k4113653fnebe7dfc9309017ae@mail.gmail.com> <2096a7260909240523p7d28b255wb3d53a1810e49be@mail.gmail.com> Message-ID: <53008aa80909240623v6184942fk9632df8f47bd578e@mail.gmail.com> 2009/9/24 Oxymoron : >> print format % (item_width, 'Cantaloupes', price_width, 1.92) >> print format % (item_width, 'Dried Apricots (16 gr)' price_width, 8) > > > Notice the line before (works) and after (doesn't work - as the interpreter > pointed out), how do you separate items in a tuple? :-) > > Did not check the rest of it. OK, I located the false syntax and I fixed it, thanx for your help! From norman at khine.net Thu Sep 24 20:12:13 2009 From: norman at khine.net (Norman Khine) Date: Thu, 24 Sep 2009 20:12:13 +0200 Subject: [Tutor] code improvement Message-ID: <9c2c8ffb0909241112o29f50c25qb24f47323dd37314@mail.gmail.com> Hello, I have this function in my class: http://paste.lisp.org/display/87659 Is there a better method to write the last bit of the code. Thanks Norman From kb1pkl at yahoo.com Thu Sep 24 20:15:58 2009 From: kb1pkl at yahoo.com (Corey Richardson) Date: Thu, 24 Sep 2009 11:15:58 -0700 (PDT) Subject: [Tutor] Unknown reason for error. Message-ID: <739753.39903.qm@web110712.mail.gq1.yahoo.com> Hello, python tutors, its Corey. Anyway, I'm getting a syntax error for an unknown reason. Here is my code... ??? name = raw_input("What is your name?") print "Hello, ", name wellness = raw_input("How are you?") if wellness != "Good": ??? if wellness != "Well": ??????? if wellness != "Fine": ??????????? print "Oh, I'm sorry you are not feeling well. I guessed correct, right?" ??????? else: print "Great!" candyNumber = raw_input("How many candies do you want? :" fat = raw_input("How many candies do you want to eat? :") if fat > candyNumber: ??? print "HA! Nice try, but no. You don't have that many candies" ??? else print "HA! You ate the candy! Suckerrrrr. You are now", fat, "lbs overweight" The syntax arror is at the first fat. Thanks ahead of time, ~Corey From kent37 at tds.net Thu Sep 24 22:25:24 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 24 Sep 2009 16:25:24 -0400 Subject: [Tutor] code improvement In-Reply-To: <9c2c8ffb0909241112o29f50c25qb24f47323dd37314@mail.gmail.com> References: <9c2c8ffb0909241112o29f50c25qb24f47323dd37314@mail.gmail.com> Message-ID: <1c2a2c590909241325u4e063523k75659425064506d1@mail.gmail.com> On Thu, Sep 24, 2009 at 2:12 PM, Norman Khine wrote: > Hello, > I have this function in my class: > > http://paste.lisp.org/display/87659 > > Is there a better method to write the last bit of the code. Better in what way? What are these things? What is resource? Some context would be helpful, I seem to have misplaced my mindreader hat. Kent From bermanrl at cfl.rr.com Thu Sep 24 22:52:38 2009 From: bermanrl at cfl.rr.com (Robert Berman) Date: Thu, 24 Sep 2009 16:52:38 -0400 Subject: [Tutor] Unknown reason for error. In-Reply-To: <739753.39903.qm@web110712.mail.gq1.yahoo.com> References: <739753.39903.qm@web110712.mail.gq1.yahoo.com> Message-ID: <1253825558.13362.6.camel@bermanrl-desktop> Cory, It would be helpful for us to see the code and the exact error message(s). Would you copy your code and the errors directly to either your post or your code to one of the posting pages such as www.pastebin.org so we can see your code exactly how you have written it. Robert On Thu, 2009-09-24 at 11:15 -0700, Corey Richardson wrote: > Hello, python tutors, its Corey. > Anyway, I'm getting a syntax error for an unknown reason. Here is my code... > name = raw_input("What is your name?") > print "Hello, ", name > wellness = raw_input("How are you?") > if wellness != "Good": > if wellness != "Well": > if wellness != "Fine": > print "Oh, I'm sorry you are not feeling well. I guessed correct, right?" > else: print "Great!" > candyNumber = raw_input("How many candies do you want? :" > fat = raw_input("How many candies do you want to eat? :") > if fat > candyNumber: > print "HA! Nice try, but no. You don't have that many candies" > else print "HA! You ate the candy! Suckerrrrr. You are now", fat, "lbs overweight" > The syntax arror is at the first fat. Thanks ahead of time, > ~Corey > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From greg at thewhittiers.com Thu Sep 24 22:59:17 2009 From: greg at thewhittiers.com (greg whittier) Date: Thu, 24 Sep 2009 16:59:17 -0400 Subject: [Tutor] Unknown reason for error. In-Reply-To: <739753.39903.qm@web110712.mail.gq1.yahoo.com> References: <739753.39903.qm@web110712.mail.gq1.yahoo.com> Message-ID: On Thu, Sep 24, 2009 at 2:15 PM, Corey Richardson wrote: > Hello, python tutors, its Corey. > Anyway, I'm getting a syntax error for an unknown reason. Here is my > code... > name = raw_input("What is your name?") > print "Hello, ", name > wellness = raw_input("How are you?") > if wellness != "Good": > if wellness != "Well": > if wellness != "Fine": > print "Oh, I'm sorry you are not feeling well. I guessed > correct, right?" > else: print "Great!" > candyNumber = raw_input("How many candies do you want? :" > It looks like you're missing a closing parenthesis. > fat = raw_input("How many candies do you want to eat? :") > if fat > candyNumber: > print "HA! Nice try, but no. You don't have that many candies" > else print "HA! You ate the candy! Suckerrrrr. You are now", fat, "lbs > overweight" > The syntax arror is at the first fat. Thanks ahead of time, > ~Corey > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From christopher.henk at allisontransmission.com Thu Sep 24 22:50:32 2009 From: christopher.henk at allisontransmission.com (christopher.henk at allisontransmission.com) Date: Thu, 24 Sep 2009 16:50:32 -0400 Subject: [Tutor] Unknown reason for error. In-Reply-To: <739753.39903.qm@web110712.mail.gq1.yahoo.com> Message-ID: > Hello, python tutors, its Corey. Hi, Corey. > candyNumber = raw_input("How many candies do you want? :" You dropped a closing parenthesis in the line above. Having the syntax error occur one line up from where it is indicated is not uncommon. Another thing as long as we are here, in the code below. > Anyway, I'm getting a syntax error for an unknown reason. Here is my code... > name = raw_input("What is your name?") > print "Hello, ", name > wellness = raw_input("How are you?") > if wellness != "Good": > if wellness != "Well": > if wellness != "Fine": > print "Oh, I'm sorry you are not feeling well. I guessed correct, right?" > else: print "Great!" The else will only apply if they type in Fine If you want it too apply to all three you would need to join the checks together into one if statement with Boolean operators. Chris -------------- next part -------------- An HTML attachment was scrubbed... URL: From kb1pkl at aim.com Thu Sep 24 23:43:24 2009 From: kb1pkl at aim.com (Corey Richardson) Date: Thu, 24 Sep 2009 17:43:24 -0400 Subject: [Tutor] invalid syntax (reply) Message-ID: <4ABBE7FC.6060204@aim.com> Robert, that is my code. The error? "Theres an error in your program : invalid syntax" Closing the parenthesis helped that one, but my else statement is not working...heres the code chunk... if wellness != "Good": elif wellness != "Well": elif wellness != "Fine": print "Oh, I'm sorry you are not feeling well. I guessed correct, right?" else print "Great!" candyNumber = raw_input("How many candies do you want? :") fatness = raw_input("How many candies do you want to eat? :") if fatness > candyNumber: print "HA! Nice try, but no. You don't have that many candies" else print "HA! You ate the candy! Suckerrrrr. You are now", fatness, "lbs overweight" my IDLE highlights the print, in each of them. Why? (oh, and thanks for helping, all) -------------- next part -------------- A non-text attachment was scrubbed... Name: kb1pkl.vcf Type: text/x-vcard Size: 55 bytes Desc: not available URL: From lupin at orcon.net.nz Thu Sep 24 23:57:04 2009 From: lupin at orcon.net.nz (Brett Wilkins) Date: Fri, 25 Sep 2009 09:57:04 +1200 Subject: [Tutor] invalid syntax (reply) In-Reply-To: <4ABBE7FC.6060204@aim.com> References: <4ABBE7FC.6060204@aim.com> Message-ID: if wellness != "Good": elif wellness != "Well": elif wellness != "Fine": print "Oh, I'm sorry you are not feeling well. I guessed correct, right?" I think the problem is the elif's and the indents... elif is 'else if', and should be at the same indentation level as the previous if statement that it is providing the else cause for. In this case, it looks like you're just checking that wellness is not one of those words.... I would use: if wellness not in ["Good","Well","Fine"]: print "Oh, I'm sorry you are not feeling well. I guessed correct, right?" See in that works out for you. Also, if you're using python3, the print statement will need brackets (like a function). Cheers --Brett On 25/09/2009, at 9:43 AM, Corey Richardson wrote: > if wellness != "Good": > elif wellness != "Well": > elif wellness != "Fine": > print "Oh, I'm sorry you are not feeling well. I guessed > correct, right?" -------------- next part -------------- An HTML attachment was scrubbed... URL: From christopher.henk at allisontransmission.com Fri Sep 25 00:14:07 2009 From: christopher.henk at allisontransmission.com (christopher.henk at allisontransmission.com) Date: Thu, 24 Sep 2009 18:14:07 -0400 Subject: [Tutor] invalid syntax (reply) In-Reply-To: <4ABBE7FC.6060204@aim.com> Message-ID: tutor-bounces+christopher.henk=allisontransmission.com at python.org wrote on 09/24/2009 05:43:24 PM: > Robert, that is my code. The error? "Theres an error in your program : > invalid syntax" > Closing the parenthesis helped that one, but my else statement is not > working...heres the code chunk... > if wellness != "Good": > elif wellness != "Well": > elif wellness != "Fine": > print "Oh, I'm sorry you are not feeling well. I guessed > correct, right?" > else print "Great!" > candyNumber = raw_input("How many candies do you want? :") > fatness = raw_input("How many candies do you want to eat? :") > if fatness > candyNumber: > print "HA! Nice try, but no. You don't have that many candies" > else print "HA! You ate the candy! Suckerrrrr. You are now", > fatness, "lbs overweight" > > > > my IDLE highlights the print, in each of them. Why? (oh, and thanks for > helping, all) I am not sure why Idle is higlighting your print statements ( I don't use Idle, so will leave that to someone else). However your if-elif-else construction should raise a syntax error. elif means "else if" and should be matched up (at the same indentation level) with an if statement just like an else statement. It is used when you have more then two paths that the code can take depending on the test results. if test: (if test is true) do something elif another test: (else if another test is true) do something else else: do a third thing What you are trying to test is that wellness is not "Well", is not "good", and is not "Fine" If all of those is true (they are not good, not well and not fine) you print your sorry message, otherwise you print great. You have one fork in the path, and should have one if statement with one else. Hope that helps, Chris -------------- next part -------------- An HTML attachment was scrubbed... URL: From vineet.kothari at gmail.com Fri Sep 25 00:59:12 2009 From: vineet.kothari at gmail.com (Vineet Kothari) Date: Thu, 24 Sep 2009 15:59:12 -0700 Subject: [Tutor] python win32 drive mapping help In-Reply-To: <5487b3060909220401w14fa12a8wcf308e38251f6c8@mail.gmail.com> References: <5487b3060909220401w14fa12a8wcf308e38251f6c8@mail.gmail.com> Message-ID: Thanks a lot Vishwajeet & everyone else who replied. This is great I am glad now its working & I knew I was missing the module but somehow didn't know from where I would get that. But glad everything is working fine now. This is great community :) -- Regards, Vineet Kothari http://www.vineetkothari.in ----- Its NICE 2 be IMPORTANT, but whats more IMPORTANT is 2 be NICE. On Tue, Sep 22, 2009 at 4:01 AM, vishwajeet singh wrote: > On Tue, Sep 22, 2009 at 5:38 AM, Vineet Kothari wrote: > >> >> Hi Everyone >> >> I saw alot of responses for python on this mailing >> list. I thought any python guru might wish to help me with little code to >> map two network drives on windows systems >> >> >> I have 3computers at different locations in a network A,B,C >> >> I want to map c:/temp folder of A to C & c:/temp folder of B to C as well >> do some copying of data and then delete the mapping. >> >> I tried using the code given for mapping: >> >> import win32net >>> win32net.NetUseAdd(None,1,{'remote':r'\\server\share','local':'K:','password':'XXX' >>> }) >>> >> >> but I get this error: >> >> C:\Users\Administrator\Desktop>python test.py >>> Traceback (most recent call last): >>> File "test.py", line 31, in >>> import win32wnet >>> ImportError: No module named win32net >>> >> >> I just need help in setting up the mapping. I know how to do the copying >> using shutil please if you can help me with the mapping code. I am very new >> to python and I need this help for my project at school. >> >> I am using python 2.6 >> >> I'll be eagerly waiting for your response. >> Thanks >> >> -- >> Regards, >> Vineet Kothari >> http://www.vineetkothari.in >> >> ----- >> Its NICE 2 be IMPORTANT, but whats more IMPORTANT is 2 be NICE. >> >> >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> >> > You need python extension installed on your machine to be able to execute > the above code; you can get same from > http://sourceforge.net/projects/pywin32/ > > -- > Vishwajeet Singh > +91-9657702154 | dextrous85 at gmail.com | http://singhvishwajeet.com > Twitter: http://twitter.com/vishwajeets | LinkedIn: > http://www.linkedin.com/in/singhvishwajeet > -------------- next part -------------- An HTML attachment was scrubbed... URL: From sander.sweers at gmail.com Fri Sep 25 01:02:32 2009 From: sander.sweers at gmail.com (Sander Sweers) Date: Fri, 25 Sep 2009 00:02:32 +0100 Subject: [Tutor] how to print a message backwards In-Reply-To: References: <335895.5518.qm@web45902.mail.sp1.yahoo.com> <1253729444.8270.142.camel@bermanrl-desktop> <695959.77053.qm@web86704.mail.ird.yahoo.com> Message-ID: <1253833352.5395.27.camel@infirit.homelinux.org> On Thu, 2009-09-24 at 08:07 -0400, Serdar Tumgoren wrote: > You should find plenty by googling for "python slice step sequence" Now that I know what to look for I went to the online python docs [1] and tried to find where it has been documented. Unfortunately all the slicing examples I found do not even mention that there is optional step value. The only place I found it explained properly is on the build in slice() and the data model pages. I'll try to find some time to write some examples and documentation for the online docs. Thanks for the links. Greets Sander [1] http://docs.python.org/index.html From alan.gauld at btinternet.com Fri Sep 25 01:13:46 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 25 Sep 2009 00:13:46 +0100 Subject: [Tutor] invalid syntax (reply) References: <4ABBE7FC.6060204@aim.com> Message-ID: "Corey Richardson" wrote > Closing the parenthesis helped that one, but my else statement is not > working...heres the code chunk... > if wellness != "Good": > elif wellness != "Well": > elif wellness != "Fine": > print "Oh, I'm sorry you are not feeling well. I guessed > correct, right?" > else print "Great!" As has been pointed out you need to use a boolean expression (a combination of tsts using and / or ) to get the result you need. In fact if you describe what you really want in English you will find it forms a boolean expression. You want it to print one message if the user types Good or Well or Fine else print another message. Now translate that directly to code... > candyNumber = raw_input("How many candies do you want? :") > fatness = raw_input("How many candies do you want to eat? :") > if fatness > candyNumber: > print "HA! Nice try, but no. You don't have that many candies" > else print "HA! You ate the candy! Suckerrrrr. You are now", Python cares abourt indentation level. align the else with the if that it matches. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From vineet.kothari at gmail.com Fri Sep 25 01:57:31 2009 From: vineet.kothari at gmail.com (Vineet Kothari) Date: Thu, 24 Sep 2009 16:57:31 -0700 Subject: [Tutor] python win32 drive mapping help In-Reply-To: <5487b3060909220401w14fa12a8wcf308e38251f6c8@mail.gmail.com> References: <5487b3060909220401w14fa12a8wcf308e38251f6c8@mail.gmail.com> Message-ID: Can you also help me out with the way to delete the mapped drive I know in command line it is > net use [DRIVE:] /delete > but I am unable to figure out how I can do it from python Since I am trying to make sure that the drive name I am giving in my code: > import win32net > win32net.NetUseAdd(None,1,{'remote':r'\\server\share','local':'K:','password':'XXX' > }) K: drive should not exist already & if it does then the mapping should be removed first & then a new mapping should be established. So it should be going something like: if [mapping already exists]: > [delete mapping] > else: > [create new mapping] > Thank You everyone for the help :) -- Regards, Vineet Kothari http://www.vineetkothari.in ----- Its NICE 2 be IMPORTANT, but whats more IMPORTANT is 2 be NICE. On Tue, Sep 22, 2009 at 4:01 AM, vishwajeet singh wrote: > On Tue, Sep 22, 2009 at 5:38 AM, Vineet Kothari wrote: > >> >> Hi Everyone >> >> I saw alot of responses for python on this mailing >> list. I thought any python guru might wish to help me with little code to >> map two network drives on windows systems >> >> >> I have 3computers at different locations in a network A,B,C >> >> I want to map c:/temp folder of A to C & c:/temp folder of B to C as well >> do some copying of data and then delete the mapping. >> >> I tried using the code given for mapping: >> >> import win32net >>> win32net.NetUseAdd(None,1,{'remote':r'\\server\share','local':'K:','password':'XXX' >>> }) >>> >> >> but I get this error: >> >> C:\Users\Administrator\Desktop>python test.py >>> Traceback (most recent call last): >>> File "test.py", line 31, in >>> import win32wnet >>> ImportError: No module named win32net >>> >> >> I just need help in setting up the mapping. I know how to do the copying >> using shutil please if you can help me with the mapping code. I am very new >> to python and I need this help for my project at school. >> >> I am using python 2.6 >> >> I'll be eagerly waiting for your response. >> Thanks >> >> -- >> Regards, >> Vineet Kothari >> http://www.vineetkothari.in >> >> ----- >> Its NICE 2 be IMPORTANT, but whats more IMPORTANT is 2 be NICE. >> >> >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> >> > You need python extension installed on your machine to be able to execute > the above code; you can get same from > http://sourceforge.net/projects/pywin32/ > > -- > Vishwajeet Singh > +91-9657702154 | dextrous85 at gmail.com | http://singhvishwajeet.com > Twitter: http://twitter.com/vishwajeets | LinkedIn: > http://www.linkedin.com/in/singhvishwajeet > -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Fri Sep 25 02:28:20 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 24 Sep 2009 20:28:20 -0400 Subject: [Tutor] how to print a message backwards In-Reply-To: <1253833352.5395.27.camel@infirit.homelinux.org> References: <335895.5518.qm@web45902.mail.sp1.yahoo.com> <1253729444.8270.142.camel@bermanrl-desktop> <695959.77053.qm@web86704.mail.ird.yahoo.com> <1253833352.5395.27.camel@infirit.homelinux.org> Message-ID: <1c2a2c590909241728y223212d8s9884ec402de3324@mail.gmail.com> On Thu, Sep 24, 2009 at 7:02 PM, Sander Sweers wrote: > Now that I know what to look for I went to the online python docs [1] > and tried to find where it has been documented. > > Unfortunately all the slicing examples I found do not even mention that > there is optional step value. See footnote 5 at http://docs.python.org/library/stdtypes.html#sequence-types-str-unicode-list-tuple-buffer-xrange Kent From sierra_mtnview at sbcglobal.net Fri Sep 25 06:18:13 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Thu, 24 Sep 2009 21:18:13 -0700 Subject: [Tutor] Anyone with Experience Using WinTV Capture Cards? Message-ID: <4ABC4485.50207@sbcglobal.net> A friend is looking for some help with how to use Python to access a WinTV (Go Plus) capture card, and how to display an image from it. Is there some facility that might help him, or does anyone have experience with such use that might suggest sources? Win XP OS. Any general methods for dealing with such commercial built capture cards? -- Wayne Watson (Watson Adventures, Prop., Nevada City, CA) (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet "I feel that if a person has problems communicating the very least he can do is to shut up." -- Tom Lehrer Web Page: From norman at khine.net Fri Sep 25 07:00:50 2009 From: norman at khine.net (Norman Khine) Date: Fri, 25 Sep 2009 07:00:50 +0200 Subject: [Tutor] code improvement In-Reply-To: <1c2a2c590909241325u4e063523k75659425064506d1@mail.gmail.com> References: <9c2c8ffb0909241112o29f50c25qb24f47323dd37314@mail.gmail.com> <1c2a2c590909241325u4e063523k75659425064506d1@mail.gmail.com> Message-ID: <9c2c8ffb0909242200w55ae5ab3l1b0168c911bbde31@mail.gmail.com> On Thu, Sep 24, 2009 at 10:25 PM, Kent Johnson wrote: > On Thu, Sep 24, 2009 at 2:12 PM, Norman Khine wrote: >> Hello, >> I have this function in my class: >> >> http://paste.lisp.org/display/87659 >> >> Is there a better method to write the last bit of the code. > > Better in what way? What are these things? What is resource? Some > context would be helpful, I seem to have misplaced my mindreader hat. Apologies for not being clear. I was thinking more that I may have one the too many 'for' loops at the end of the code. Here is a new version with more details. http://paste.lisp.org/display/87659#1 Thanks > > Kent > From the_only_katala at verizon.net Fri Sep 25 08:36:25 2009 From: the_only_katala at verizon.net (Katt) Date: Thu, 24 Sep 2009 23:36:25 -0700 Subject: [Tutor] Super class Message-ID: <9F8D8C77BC1B404B826A788EF4740BB6@COMPUTER01> As I am a beginner I am constantly assimilating new python code and vocabulary associated with it. Could someone please explain to me what a super class is, its importance and what level of python programming it is(beginner,intermediate,advanced programming technique)? This would greatly help me decide whether to try and wrap my brain around it or just skip the message. Thank you in advance, Katt -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at ieee.org Fri Sep 25 10:57:01 2009 From: davea at ieee.org (Dave Angel) Date: Fri, 25 Sep 2009 04:57:01 -0400 Subject: [Tutor] python win32 drive mapping help In-Reply-To: References: <5487b3060909220401w14fa12a8wcf308e38251f6c8@mail.gmail.com> Message-ID: <4ABC85DD.5030002@ieee.org> Vineet Kothari wrote: > Can you also help me out with the way to delete the mapped drive I know in > command line it is > > >> net use [DRIVE:] /delete >> >> > > but I am unable to figure out how I can do it from python > > Since I am trying to make sure that the drive name I am giving in my code: > > >> import win32net >> win32net.NetUseAdd(None,1,{'remote':r'\\server\share','local':'K:','password':'XXX' >> }) >> > > > K: drive should not exist already & if it does then the mapping should be > removed first & then a new mapping should be established. > > So it should be going something like: > > if [mapping already exists]: > >> [delete mapping] >> else: >> [create new mapping] >> >> > > Thank You everyone for the help :) > > To remove a connection made with win32net.NetUseAdd(), use win32net.NetUseDel() Rather than bother to checking if the mapping already exists, try to delete it, and probably ignore any exceptions. Note that the same drive letter may be in use for some other (even temporary) purpose, such as a USB drive, or SUBST. So if after the NetUseDel, the NetUseAdd (also) fails, you may have one of those conditions. DaveA From davea at ieee.org Fri Sep 25 12:39:31 2009 From: davea at ieee.org (Dave Angel) Date: Fri, 25 Sep 2009 06:39:31 -0400 Subject: [Tutor] Super class In-Reply-To: <9F8D8C77BC1B404B826A788EF4740BB6@COMPUTER01> References: <9F8D8C77BC1B404B826A788EF4740BB6@COMPUTER01> Message-ID: <4ABC9DE3.50804@ieee.org> Katt wrote: > As I am a beginner I am constantly assimilating new python code and vocabulary associated with it. > > Could someone please explain to me what a super class is, its importance and what level of python programming it is(beginner,intermediate,advanced programming technique)? > > This would greatly help me decide whether to try and wrap my brain around it or just skip the message. > > Thank you in advance, > > Katt > It's an object oriented thing, and as such, "advanced programming." (IMHO) You use objects all the time in Python (int, string, def) , but building hierarchies of complex objects is an advanced technique. The notion here is one of inheritance. You write a class like the following: class Myclass(object): description... And this class derives from object, which is more-or-less the simplest class of all. So object is the base class, and Myclass is the subclass. If all classes were derived from object, we'd be done. But you can also derive from a different class, and your code, and the code of your users, can get at the base class without needing to know what behavior comes from your sub class and which comes from the base. The complexity comes when one subclass derives from nested base classes, or from a list of base classes, or both. Superclass is a synonym for base class. And super() is a mechanism you can use to specify one of your base classes without knowing all the classes that might be up there. Incidentally, child class is a synonym for sub class as well. DaveA From kent37 at tds.net Fri Sep 25 15:03:29 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 25 Sep 2009 09:03:29 -0400 Subject: [Tutor] code improvement In-Reply-To: <9c2c8ffb0909242200w55ae5ab3l1b0168c911bbde31@mail.gmail.com> References: <9c2c8ffb0909241112o29f50c25qb24f47323dd37314@mail.gmail.com> <1c2a2c590909241325u4e063523k75659425064506d1@mail.gmail.com> <9c2c8ffb0909242200w55ae5ab3l1b0168c911bbde31@mail.gmail.com> Message-ID: <1c2a2c590909250603h27d963cesd5d46ddaae3d1f3b@mail.gmail.com> On Fri, Sep 25, 2009 at 1:00 AM, Norman Khine wrote: >>> Is there a better method to write the last bit of the code. > Apologies for not being clear. I was thinking more ?that I may have > one the too many 'for' loops at the end of the code. > > http://paste.lisp.org/display/87659#1 It's only two loops.I'm still not sure what your concern is. If performance is important and resource.get_resource() is accessing a database then you might look for a way to get all the addresses in a single query. But overall it doesn't seem too bad. Kent From lie.1296 at gmail.com Fri Sep 25 16:01:37 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Sat, 26 Sep 2009 00:01:37 +1000 Subject: [Tutor] how to print a message backwards In-Reply-To: References: <335895.5518.qm@web45902.mail.sp1.yahoo.com> Message-ID: Emile van Sebille wrote: > On 9/23/2009 7:22 AM Ali Sina said... >> #Message backward printer >> message=input('Enter your message: ') >> >> for i in range(len(message),0,-1): >> print(message) >> >> >> This is the code which I have written. All it does is count the number >> of letters starting from backwards. The proper code should so >> something like this: >> >> Enter your message: Hi. My name is Ali Sina >> >> Your message in backwards: aniS ilA si eman yM .iH > > > There's also a reversed keyword introduced in python 2.4. > reversed built-in *function*, not *keyword* From ciik13 at gmail.com Fri Sep 25 16:39:57 2009 From: ciik13 at gmail.com (David Eric) Date: Fri, 25 Sep 2009 10:39:57 -0400 Subject: [Tutor] Confusion with $PATH Message-ID: <46e9bd9b0909250739q612e2eaav593b3b0f6a507c57@mail.gmail.com> Very new to python..getting accustomed to files, directories etc I installed a few versions of python and ended up with a very long PATH variable, do i need this or can i change it to something shorter? Doing an online tutorial one exercise was to move a simple program, helloworld into the PATH so i could run it just by typing it in terminal window....i moved it into /Library and says file not found.. any advice? THe following is what comes up for PATH /Library/Frameworks/Python.framework/Versions/3.1/bin:/Library/Frameworks/Python.framework/Versions/3.0/bin:/Library/Frameworks/Python.framework/Versions/Current/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin -------------- next part -------------- An HTML attachment was scrubbed... URL: From srilyk at gmail.com Fri Sep 25 16:51:11 2009 From: srilyk at gmail.com (Wayne) Date: Fri, 25 Sep 2009 09:51:11 -0500 Subject: [Tutor] Confusion with $PATH In-Reply-To: <46e9bd9b0909250739q612e2eaav593b3b0f6a507c57@mail.gmail.com> References: <46e9bd9b0909250739q612e2eaav593b3b0f6a507c57@mail.gmail.com> Message-ID: <333efb450909250751r77a6012cs4d5051537c0ac8c3@mail.gmail.com> On Fri, Sep 25, 2009 at 9:39 AM, David Eric wrote: > Very new to python..getting accustomed to files, directories etc > I installed a few versions of python and ended up with a very long PATH > variable, do i need this or can i change it to something shorter? > Doing an online tutorial one exercise was to move a simple program, > helloworld into the PATH so i could run it just by typing it in terminal > window....i moved it into /Library and says file not found.. > any advice? > THe following is what comes up for PATH > > > /Library/Frameworks/Python.framework/Versions/3.1/bin:/Library/Frameworks/Python.framework/Versions/3.0/bin:/Library/Frameworks/Python.framework/Versions/Current/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin > add /home/yourname/.bin/ to the path (and create it if it doesn't exist). My path looks like this (on Ubuntu): /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/home/wayne/.bin I don't remember the syntax for adding files to the path, but a quick google search should yield plenty of results. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Fri Sep 25 17:55:35 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 25 Sep 2009 11:55:35 -0400 Subject: [Tutor] Confusion with $PATH In-Reply-To: <46e9bd9b0909250739q612e2eaav593b3b0f6a507c57@mail.gmail.com> References: <46e9bd9b0909250739q612e2eaav593b3b0f6a507c57@mail.gmail.com> Message-ID: <1c2a2c590909250855t5d6c84c9u76c77fcbc6a706f1@mail.gmail.com> On Fri, Sep 25, 2009 at 10:39 AM, David Eric wrote: > Very new to python..getting accustomed to files, directories etc > I installed a few versions of python and ended up with a very long PATH > variable, do i need this or can i change it to something shorter? > Doing an online tutorial one exercise was to move a simple program, > helloworld into the PATH so i could run it just by typing it in terminal > window....i moved it into /Library and says file not found.. > any advice? > THe following is what comes up for PATH > > /Library/Frameworks/Python.framework/Versions/3.1/bin:/Library/Frameworks/Python.framework/Versions/3.0/bin:/Library/Frameworks/Python.framework/Versions/Current/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin That doesn't look so long to me. Moving your Python file to /Libraries doesn't put it in your PATH, it has to be in one of the directories named in PATH. Wayne's suggestion is a good one if you want to have your own programs that you can run from any directory on the command line. I would call it bin, though, not .bin, for consistency with the other bin directories. On a Mac I think the path would be /Users/your_name/bin Kent From kent37 at tds.net Fri Sep 25 18:37:03 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 25 Sep 2009 12:37:03 -0400 Subject: [Tutor] Confusion with $PATH In-Reply-To: <46e9bd9b0909250907u3ec01480g71564ae515f786ee@mail.gmail.com> References: <46e9bd9b0909250739q612e2eaav593b3b0f6a507c57@mail.gmail.com> <1c2a2c590909250855t5d6c84c9u76c77fcbc6a706f1@mail.gmail.com> <46e9bd9b0909250907h76209dd2n5ecbbdf48712c1eb@mail.gmail.com> <46e9bd9b0909250907u3ec01480g71564ae515f786ee@mail.gmail.com> Message-ID: <1c2a2c590909250937t7777a6aaxcbef3646e20bea1a@mail.gmail.com> On Fri, Sep 25, 2009 at 12:07 PM, David Eric wrote: > Do i need to do anything now that the issue was resolved? How did you resolve it? If you copied your program into one of the existing directories on PATH, you probably want to delete it when you are done with the exercise. If you created your own bin/ directory then you can use it as you like. Please Reply All to reply to the list, and we prefer not to top-post on this list. Kent From srilyk at gmail.com Fri Sep 25 19:22:20 2009 From: srilyk at gmail.com (Wayne) Date: Fri, 25 Sep 2009 12:22:20 -0500 Subject: [Tutor] Confusion with $PATH In-Reply-To: <46e9bd9b0909250932k5703ea7dg7761016fafec92c6@mail.gmail.com> References: <46e9bd9b0909250739q612e2eaav593b3b0f6a507c57@mail.gmail.com> <333efb450909250751r77a6012cs4d5051537c0ac8c3@mail.gmail.com> <46e9bd9b0909250932k5703ea7dg7761016fafec92c6@mail.gmail.com> Message-ID: <333efb450909251022w44ef9390u7dc2ea35d5a61e6@mail.gmail.com> On Fri, Sep 25, 2009 at 11:32 AM, David Eric wrote: > ok this is really weird . . . > i tried running the helloworld again, and it doesnt work :/ > > DTm:~ davidteboul$ echo $PATH > PATH$/Library/Frameworks/ > Python.framework/Versions/3.1/bin:/Library/Frameworks/Python.framework/Versions/3.0/bin:/Library/Frameworks/Python.framework/Versions/Current/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin/Users/davidteboul/bin/pythonStuff > DTm:~ davidteboul$ helloworld > -bash: helloworld: command not found > i checked and helloworld is definitely in ~/bin/pythonStuff > what happened? > > btw...when i switch to ~/bin/pythonStuff and type helloworld..that doesnt > run it either? > i can run it when i type python > it worked prior, im confused > Do you know if it has executable permissions? The easiest way to set them is chmod +x helloworld.py (or whatever the filename is) You also need the "shebang" line at the top: #!/usr/bin/env python is one of the variations. HTH, Wayne (included the list in reply... Hit reply-all when replying to list) -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn?t. - Primo Levi -------------- next part -------------- An HTML attachment was scrubbed... URL: From mwalsh at mwalsh.org Fri Sep 25 19:31:13 2009 From: mwalsh at mwalsh.org (Martin Walsh) Date: Fri, 25 Sep 2009 12:31:13 -0500 Subject: [Tutor] Confusion with $PATH In-Reply-To: <333efb450909251022w44ef9390u7dc2ea35d5a61e6@mail.gmail.com> References: <46e9bd9b0909250739q612e2eaav593b3b0f6a507c57@mail.gmail.com> <333efb450909250751r77a6012cs4d5051537c0ac8c3@mail.gmail.com> <46e9bd9b0909250932k5703ea7dg7761016fafec92c6@mail.gmail.com> <333efb450909251022w44ef9390u7dc2ea35d5a61e6@mail.gmail.com> Message-ID: <4ABCFE61.3010103@mwalsh.org> Wayne wrote: > On Fri, Sep 25, 2009 at 11:32 AM, David Eric > wrote: > > ok this is really weird . . . > i tried running the helloworld again, and it doesnt work :/ > > DTm:~ davidteboul$ echo $PATH > PATH$/Library/Frameworks/ > Python.framework/Versions/3.1/bin:/Library/Frameworks/Python.framework/Versions/3.0/bin:/Library/Frameworks/Python.framework/Versions/Current/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin/Users/davidteboul/bin/pythonStuff Also, it looks like you missed a colon, to separate the newly added path from the last one in the list. {...}/sbin:/usr/local/bin:/usr/X11/bin:/Users/davidteboul/bin/pythonStuff ^ HTH, Marty From kent37 at tds.net Fri Sep 25 19:48:06 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 25 Sep 2009 13:48:06 -0400 Subject: [Tutor] Confusion with $PATH In-Reply-To: <333efb450909251022w44ef9390u7dc2ea35d5a61e6@mail.gmail.com> References: <46e9bd9b0909250739q612e2eaav593b3b0f6a507c57@mail.gmail.com> <333efb450909250751r77a6012cs4d5051537c0ac8c3@mail.gmail.com> <46e9bd9b0909250932k5703ea7dg7761016fafec92c6@mail.gmail.com> <333efb450909251022w44ef9390u7dc2ea35d5a61e6@mail.gmail.com> Message-ID: <1c2a2c590909251048y4e590941p7bb07e298563cd16@mail.gmail.com> > On Fri, Sep 25, 2009 at 11:32 AM, David Eric wrote: >> >> ok this is really weird . . . >> i tried running the helloworld again, and it doesnt work :/ >> >> DTm:~ davidteboul$ echo $PATH >> PATH$/Library/Frameworks/ >> >> Python.framework/Versions/3.1/bin:/Library/Frameworks/Python.framework/Versions/3.0/bin:/Library/Frameworks/Python.framework/Versions/Current/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin/Users/davidteboul/bin/pythonStuff You are missing a colon between /usr/X11/bin and /Users/davidteboul/bin/pythonStuff >> DTm:~ davidteboul$ helloworld >> -bash: helloworld: command not found To run a command in the current directory (not in PATH) you have to explicitly give the current directory in teh command, i.e. ./helloworld Kent From vineet.kothari at gmail.com Fri Sep 25 20:41:14 2009 From: vineet.kothari at gmail.com (Vineet Kothari) Date: Fri, 25 Sep 2009 11:41:14 -0700 Subject: [Tutor] python win32 drive mapping help In-Reply-To: <4ABC85DD.5030002@ieee.org> References: <5487b3060909220401w14fa12a8wcf308e38251f6c8@mail.gmail.com> <4ABC85DD.5030002@ieee.org> Message-ID: So What should be the attributes for the command? I tried this: win32net.NetUseDel(None, 1,{'local':'k:'}) > but I got this error: Traceback (most recent call last): > File "test.py", line 33, in > win32net.NetUseDel(None, 1,{'local':'k:'}) > TypeError: an integer is required > So what should be the attributes for the NetUseDel? Thanks! - Vineet On Fri, Sep 25, 2009 at 1:57 AM, Dave Angel wrote: > Vineet Kothari wrote: > >> Can you also help me out with the way to delete the mapped drive I know in >> command line it is >> >> >> >>> net use [DRIVE:] /delete >>> >>> >>> >> >> but I am unable to figure out how I can do it from python >> >> Since I am trying to make sure that the drive name I am giving in my code: >> >> >> >>> import win32net >>> >>> win32net.NetUseAdd(None,1,{'remote':r'\\server\share','local':'K:','password':'XXX' >>> }) >>> >>> >> >> >> K: drive should not exist already & if it does then the mapping should be >> removed first & then a new mapping should be established. >> >> So it should be going something like: >> >> if [mapping already exists]: >> >> >>> [delete mapping] >>> else: >>> [create new mapping] >>> >>> >>> >> >> Thank You everyone for the help :) >> >> >> > To remove a connection made with win32net.NetUseAdd(), use > win32net.NetUseDel() > > Rather than bother to checking if the mapping already exists, try to delete > it, and probably ignore any exceptions. > > Note that the same drive letter may be in use for some other (even > temporary) purpose, such as a USB drive, or SUBST. So if after the > NetUseDel, the NetUseAdd (also) fails, you may have one of those conditions. > > DaveA > -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Fri Sep 25 23:13:09 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 25 Sep 2009 22:13:09 +0100 Subject: [Tutor] Super class References: <9F8D8C77BC1B404B826A788EF4740BB6@COMPUTER01> <4ABC9DE3.50804@ieee.org> Message-ID: "Dave Angel" wrote > It's an object oriented thing, and as such, "advanced programming." > (IMHO) Yep, I'd agree. Although OOP is becoming more mainstream every year. In the way that using functions and proceduires used to e considered advanced concepts(compared to subroutines and GOTO) but are now considred mainstream. > class Myclass(object): > description... > > And this class derives from object, which is more-or-less the simplest > class of all. So object is the base class, and Myclass is the subclass. > ... > Superclass is a synonym for base class. And super() is a mechanism you > can use to specify one of your base classes without knowing all the > classes that might be up there. > > Incidentally, child class is a synonym for sub class as well. And the confusion stems from the two OOP camps that flourished in the 1980/90s. Lisp and Smalltalk preferred super/child and C++/Java preferred base/sub Historic accidents bedevil programming jargon making it a minefield of confusion for beginners! -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From wrobl1rt at cmich.edu Fri Sep 25 23:09:03 2009 From: wrobl1rt at cmich.edu (wrobl1rt at cmich.edu) Date: Fri, 25 Sep 2009 17:09:03 -0400 (EDT) Subject: [Tutor] need help with conditionals Message-ID: <20090925170903.AWT95369@pepper.merit.edu> Hello all, I am still very new to Python and am working on conditionals. Im stuck on this problem and I'm sorry if this is something really simple that I'm missing but its been really frustrating me. Here's a copy of the problem, and sorry if its really long but its the end question about the logically equivalent expressions I'm stuck on. Anyways, heres a copy of the problem ----------------------------------------------------------- To better understand boolean expressions, it is helpful to construct truth tables. Two boolean expressions are logically equivalent if and only if they have the same truth table. The following Python script prints out the truth table for the any boolean expression in two variables: p and q: expression = raw_input("Enter a boolean expression in two variables, p and q: ") print " p q %s" % expression length = len( " p q %s" % expression) print length*"=" for p in True, False: for q in True, False: print "%-7s %-7s %-7s" % (p, q, eval(expression)) You will learn how this script works in later chapters. For now, you will use it to learn about boolean expressions. Copy this program to a file named p_and_q.py, then run it from the command line and give it: p or q, when prompted for a boolean expression. You should get the following output: p q p or q ===================== True True True True False True False True True False False False Now that we see how it works, let?s wrap it in a function to make it easier to use: def truth_table(expression): print " p q %s" % expression length = len( " p q %s" % expression) print length*"=" for p in True, False: for q in True, False: print "%-7s %-7s %-7s" % (p, q, eval(expression)) We can import it into a Python shell and call truth_table with a string containing our boolean expression in p and q as an argument: >>> from p_and_q import * >>> truth_table("p or q") p q p or q ===================== True True True True False True False True True False False False >>> Use the truth_table functions with the following boolean expressions, recording the truth table produced each time: not(p or q) p and q not(p and q) not(p) or not(q) not(p) and not(q) Which of these are logically equivalent? ------------------------------------------------- Whenever I try to enter the expressions listed into the prompt it tells me the string object is not callable.... From alan.gauld at btinternet.com Fri Sep 25 23:17:57 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 25 Sep 2009 22:17:57 +0100 Subject: [Tutor] Confusion with $PATH References: <46e9bd9b0909250739q612e2eaav593b3b0f6a507c57@mail.gmail.com> Message-ID: "David Eric" wrote > I installed a few versions of python and ended up with a very long PATH Leave it be. Long paths will not cause a proble,m. FWIW My Path is at least twice as long as that! :-) > window....i moved it into /Library and says file not found.. > any advice? Move it into a folder in your PATH. /Library is not in your path, although several subfolders of it are: > THe following is what comes up for PATH > /Library/Frameworks/Python.framework/Versions/3.1/bin: /Library/Frameworks/Python.framework/Versions/3.0/bin: /Library/Frameworks/Python.framework/Versions/Current/bin: /usr/bin: /bin: /usr/sbin: /sbin: /usr/local/bin: /usr/X11/bin I would probably put your program in /usr/local/bin. That's the traditional place for home grown apps in the Unix world. If you like you could just create an alias (or link in Unix spean) to your file from /usr/local/bin... HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From waqas805 at hotmail.com Fri Sep 25 21:56:40 2009 From: waqas805 at hotmail.com (waqas ahmad) Date: Fri, 25 Sep 2009 21:56:40 +0200 Subject: [Tutor] Help required Message-ID: Hi, I dont know it is the right place to post this question. I need help to change one search code line . can you help me please. here is my search method code: search=re.compile("^#acl InternationalGroup.*\n", re.M).search(pagetext) if search: ret=search.group() else: ret='not defined' return ret here i am searching for "#acl InternationalGroup" in the pageText and when it true is then give me search group. I want to change this for following requirement: I want to search for "#acl InternationalGroup" and "CatInternational" for both in the pageText. when "#acl InternationalGroup" is not there but only "CatInternational" is there. then return me search group. I shall be thankful to you for any help. Best Regards, Waqas _________________________________________________________________ Drag n? drop?Get easy photo sharing with Windows Live? Photos. http://www.microsoft.com/windows/windowslive/products/photos.aspx -------------- next part -------------- An HTML attachment was scrubbed... URL: From vinces1979 at gmail.com Fri Sep 25 23:39:27 2009 From: vinces1979 at gmail.com (vince spicer) Date: Fri, 25 Sep 2009 15:39:27 -0600 Subject: [Tutor] Help required In-Reply-To: References: Message-ID: <1e53c510909251439n1556076h4ab7afb4dc64f46a@mail.gmail.com> On Fri, Sep 25, 2009 at 1:56 PM, waqas ahmad wrote: > > > Hi, > > I dont know it is the right place to post this question. I need help to > change one search code line . can you help me please. > > here is my search method code: > > search=re.compile("^#acl InternationalGroup.*\n", re.M).search(pagetext) > if search: > ret=search.group() > else: > ret='not defined' > return ret > > here i am searching for "#acl InternationalGroup" in the pageText and when > it true is then give me search group. > > > I want to change this for following requirement: > > I want to search for "#acl InternationalGroup" and "CatInternational" for > both in the pageText. > when "#acl InternationalGroup" is not there but only "CatInternational" is > there. then return me search group. > > I shall be thankful to you for any help. > > Best Regards, > Waqas > > > > ------------------------------ > What can you do with the new Windows Live? Find out > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > i think this is what you are looking for: search=re.compile("(#acl\sInternationalGroup|CatInternational).*\n", re.M).search(pagetext) if search: ret=search.findall() else: ret='not defined' return ret -------------- next part -------------- An HTML attachment was scrubbed... URL: From christopher.henk at allisontransmission.com Fri Sep 25 23:39:50 2009 From: christopher.henk at allisontransmission.com (christopher.henk at allisontransmission.com) Date: Fri, 25 Sep 2009 17:39:50 -0400 Subject: [Tutor] need help with conditionals In-Reply-To: <20090925170903.AWT95369@pepper.merit.edu> Message-ID: > Hello all, > I am still very new to Python and am working on conditionals. Im stuck on this > problem and I'm sorry if this is something really simple that I'm missing but its > been really frustrating me. Here's a copy of the problem, and sorry if its really > long but its the end question about the logically equivalent expressions I'm > stuck on. Anyways, heres a copy of the problem > > ----------------------------------------------------------- > > >>> from p_and_q import * > >>> truth_table("p or q") Are you calling the function as shown above? > > Whenever I try to enter the expressions listed into the prompt it tells me the > string object is not callable.... It would be helpful if you showed us exactly what you type into the prompt and the exact error you get. You should be calling the function as it is shown in the problem. Assuming the function is entered and imported correctly you should get a true table output. two examples: >>> truth_table("p or q") p q p or q ===================== True True True True False True False True True False False False >>> truth_table("not(p or q)") p q not(p or q) ========================== True True False True False False False True False False False True Without a bit more info its hard to guess what is happening. Chris -------------- next part -------------- An HTML attachment was scrubbed... URL: From kb1pkl at aim.com Sat Sep 26 00:05:47 2009 From: kb1pkl at aim.com (Corey Richardson) Date: Fri, 25 Sep 2009 18:05:47 -0400 Subject: [Tutor] [Reply]need help with conditionals In-Reply-To: References: Message-ID: <4ABD3EBB.30101@aim.com> I have no clue what it is trying to acomplish. What are you doing? Here is a good Tut on conditionals. Boolean is near the top. http://www.freenetpages.co.uk/hp/alan.gauld/tutbranch.htm HTH(If I did), ~Corey -------------- next part -------------- A non-text attachment was scrubbed... Name: kb1pkl.vcf Type: text/x-vcard Size: 55 bytes Desc: not available URL: From davea at ieee.org Sat Sep 26 01:40:15 2009 From: davea at ieee.org (Dave Angel) Date: Fri, 25 Sep 2009 19:40:15 -0400 Subject: [Tutor] python win32 drive mapping help In-Reply-To: References: <5487b3060909220401w14fa12a8wcf308e38251f6c8@mail.gmail.com> <4ABC85DD.5030002@ieee.org> Message-ID: <4ABD54DF.9050503@ieee.org> Vineet Kothari wrote: > So What should be the attributes for the command? > > I tried this: > > win32net.NetUseDel(None, 1,{'local':'k:'}) > > > but I got this error: > > Traceback (most recent call last): > >> File "test.py", line 33, in >> win32net.NetUseDel(None, 1,{'local':'k:'}) >> TypeError: an integer is required >> >> > > So what should be the attributes for the NetUseDel? > > Thanks! > - Vineet > (You shouldn't top-post. Add your message to the end of the existing ones, or sometimes in-line. Otherwise the message context gets very confusing.) You have the wrong sequence for NetUseDel(). Try: win32net.NetUseDel(None, 'k:', win32net.USE_FORCE) (It's the 3rd argument it was complaining about, since that's a constant (of value 1, actually)). I'm guessing you're confusing the docs for NetUseAdd for NetUseDel. DaveA From wescpy at gmail.com Sat Sep 26 02:26:32 2009 From: wescpy at gmail.com (wesley chun) Date: Fri, 25 Sep 2009 17:26:32 -0700 Subject: [Tutor] python win32 drive mapping help In-Reply-To: <4ABD54DF.9050503@ieee.org> References: <5487b3060909220401w14fa12a8wcf308e38251f6c8@mail.gmail.com> <4ABC85DD.5030002@ieee.org> <4ABD54DF.9050503@ieee.org> Message-ID: <78b3a9580909251726y1064e470l6cf4297897fc3d94@mail.gmail.com> >> I tried this: >> win32net.NetUseDel(None, 1,{'local':'k:'}) >> >> ?but I got this error: >> Traceback (most recent call last): >> ?File "test.py", line 33, in >> ? ?win32net.NetUseDel(None, 1,{'local':'k:'}) >> TypeError: an integer is required > > You have the wrong sequence for NetUseDel(). ?Try: > win32net.NetUseDel(None, 'k:', win32net.USE_FORCE) > > (It's the 3rd argument it was complaining about, since that's a constant (of > value 1, actually)). > > I'm guessing you're confusing the docs for NetUseAdd for NetUseDel. dave is correct. you're assuming that the signatures of NetUse{Add,Del}() are the same, and they're not. i actually never use the 3rd arg and just make the call using 2 args: >>> win32net.NetUseDel(None, r'Z:') seems to work fine. i also read somewhere that win32net is the older 16-bit backwards-compatible way of doing things and that you should use the stuff in win32wnet instead -- i wonder if this is related to the OP error msg saying that win32wnet wasn't found... perhaps win32net just wraps win32wnet? anyway, here's how to do it using the win32wnet equivalents: >>> import win32wnet >>> win32wnet.WNetAddConnection2(1, 'Z:', r'\\remote\disk', None, 'user', 'secret') >>> os.listdir(r'Z:\tmp') ['foo.txt', 'bar.txt', 'subdir'] >>> win32wnet.WNetCancelConnection2('Z:', 0, False) >>> os.listdir(r'Z:\tmp') Traceback (most recent call last): File "", line 1, in WindowsError: [Error 3] The system cannot find the path specified: 'Z:\\tmp/*.*' i also read online that NetUseAdd() cannot take a user arg... only password, so if the remote disk requires a username, then you must use the win32wnet interface. also note that the force param is required for WNetCancelConnection2(), so i pass in False for that (as opposed to getting the full constant from win32netcon). hope this helps! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 "Python Fundamentals", Prentice Hall, (c)2009 http://corepython.com "Python Web Development with Django", Addison Wesley, (c) 2009 http://withdjango.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From lie.1296 at gmail.com Sat Sep 26 04:20:50 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Sat, 26 Sep 2009 12:20:50 +1000 Subject: [Tutor] need help with conditionals In-Reply-To: <20090925170903.AWT95369@pepper.merit.edu> References: <20090925170903.AWT95369@pepper.merit.edu> Message-ID: wrobl1rt at cmich.edu wrote: > Hello all, > I am still very new to Python and am working on conditionals. Im stuck on this > problem and I'm sorry if this is something really simple that I'm missing but its > been really frustrating me. Here's a copy of the problem, and sorry if its really > long but its the end question about the logically equivalent expressions I'm > stuck on. Anyways, heres a copy of the problem > it works for me... """ Python 2.6.1 (r261:67517, Dec 4 2008, 16:51:00) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> def truth_table(expression): ... print " p q %s" % expression ... length = len( " p q %s" % expression) ... print length*"=" ... for p in True, False: ... for q in True, False: ... print "%-7s %-7s %-7s" % (p, q, eval(expression)) ... >>> truth_table("p or q") p q p or q ===================== True True True True False True False True True False False False >>> truth_table("not(p) and not(q)") p q not(p) and not(q) ================================ True True False True False False False True False False False True >>> truth_table("not(p or q)") p q not(p or q) ========================== True True False True False False False True False False False True >>> truth_table("p and q") p q p and q ====================== True True True True False False False True False False False False """ How are you calling the truth_table()? From alan.gauld at btinternet.com Sat Sep 26 09:43:54 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 26 Sep 2009 08:43:54 +0100 Subject: [Tutor] python win32 drive mapping help References: Message-ID: "Vineet Kothari" wrote > I want to map c:/temp folder of A to C & c:/temp folder of B to C as well > do > some copying of data and then delete the mapping. > > I tried using the code given for mapping: > > import win32net >> win32net.NetUseAdd(None,1,{'remote':r'\\server\share','local':'K:','password':'XXX' >> }) Nobody else has mentioned it so I thought I'd point out that this is a bit simpler (IMHO) if done via WSH COM objects. You just create a WSH Network Object then call it's methods: MapNetworkDrive(localName,remotePath) RemoveNetworkDrive(localName) There are additional optional parameters for adding to profile or using another user name etc. I usually use WSH for most Windows system admin type stuff. (Although I confess I use VBScript to drive WSH rather than Python!!) Caveat: WSH is not always installed/enabled on all PCs but nowadays is usually there. I haven't had a case of it being missing since we stopped using the Windows 9X series of OS. Just a thought. PS. There are similarly simple methods for adding/removing Printers too. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Sat Sep 26 09:59:10 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 26 Sep 2009 08:59:10 +0100 Subject: [Tutor] need help with conditionals References: <20090925170903.AWT95369@pepper.merit.edu> Message-ID: wrote > been really frustrating me. Here's a copy of the problem, and sorry if > its really > long but its the end question about the logically equivalent expressions > I'm > stuck on. Anyways, heres a copy of the problem First send us the real code you have used not a copy of your homework. And secondly send us the complete error message not a summary. Python error messages are extremely helpful once you learn how to read them. Then we might be able to help. As Corey said my tutorial contains some stuff on understanding booleans, but the most useful section for truth tables is in the Functional Programming topic in the Advanced section. But this question actually has nothing to do with conditionals or booleans! :-) > The following Python script prints out the truth table for the any > boolean > expression in two variables: p and q: > > expression = raw_input("Enter a boolean expression in two variables, p > and q: ") > > print " p q %s" % expression > length = len( " p q %s" % expression) > print length*"=" > > for p in True, False: > for q in True, False: > print "%-7s %-7s %-7s" % (p, q, eval(expression)) > You will learn how this script works in later chapters. For now, you will > use it to > learn about boolean expressions. Copy this program to a file named > p_and_q.py, Thats a terrible name BTW it would be better to call it truthtable.py! >>>> from p_and_q import * And this is bad practice! What are you using for a tutorial? If its not for a class I would consider finding another... > Use the truth_table functions with the following boolean expressions, > recording > the truth table produced each time: > > not(p or q) > not(p and q) > not(p) or not(q) > not(p) and not(q) Also show us a cut n pasdte of you running the program - so we can see what you are typing as input. Using eval() like this is very prone to user error and also considered bad practice! HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Sat Sep 26 10:02:38 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 26 Sep 2009 09:02:38 +0100 Subject: [Tutor] [Reply]need help with conditionals References: <4ABD3EBB.30101@aim.com> Message-ID: "Corey Richardson" wrote > is a good Tut on conditionals. Boolean is near the top. > http://www.freenetpages.co.uk/hp/alan.gauld/tutbranch.htm Note that this site will die soon and has not been updated for about 2 years. Please use the new url: http://www.alan-g.me.uk/ Note that it currently redirects to geocities but that too is closing shortly so it will eventually be the true home for the tutor! (Its getting increasingly difficult to find independant (non ISP) free web space on the net these days :-( ) -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From kent37 at tds.net Sat Sep 26 15:39:18 2009 From: kent37 at tds.net (Kent Johnson) Date: Sat, 26 Sep 2009 09:39:18 -0400 Subject: [Tutor] need help with conditionals In-Reply-To: References: <20090925170903.AWT95369@pepper.merit.edu> Message-ID: <1c2a2c590909260639wd53c9d0n8c48a668acbe3413@mail.gmail.com> On Sat, Sep 26, 2009 at 3:59 AM, Alan Gauld wrote: > What are you using for a tutorial? It appears to be http://openbookproject.net/thinkCSpy/ch04.html Kent From waqas805 at hotmail.com Sat Sep 26 14:25:19 2009 From: waqas805 at hotmail.com (waqas ahmad) Date: Sat, 26 Sep 2009 14:25:19 +0200 Subject: [Tutor] Help required In-Reply-To: <1e53c510909251439n1556076h4ab7afb4dc64f46a@mail.gmail.com> References: Message-ID: Hi, First of all thanks a lot for your reply. "search.findall" is not working. here is my complete small program. def getAcl(request, pg): pged = PageEditor(request, pg) pagetext = pged.get_raw_body() search=re.compile("^#acl InternationalGroup.*\n", re.M).search(pagetext) if search: ret=search.group() else: ret='not defined' return ret def execute(macro, args): html="

ACL List For International Group:
" all={} pages = macro.request.rootpage.getPageList() for pagename in pages: if Page(macro.request,pagename).isStandardPage(): all[Page(macro.request, pagename).link_to(macro.request)]=getAcl(macro.request, pagename) html+="" all1=sorted(all.items()) for pg, ac in all1: if ac != "not defined": html+="" % pg html+="" % ac html+="
%s%s
" return macro.formatter.rawHTML(html) Now i explain this. I have some wiki pages(or you can say documents). This python program is giving me list of all those pages, where i have written "#acl InternationalGroup:read" line in the pages and these pages may have also "CatInternational" line in the page. Now i want to search all those pages, where i have NOT written "#acl InternationalGroup:read" But i have written only "CatInternational" in the page text. I dont know how can i find only those pages where i have written only "CatInternational" line in the page. I shall be veryyyyyyyyyyyyyy thankful to you really for help. Best Regards, Waqas Date: Fri, 25 Sep 2009 15:39:27 -0600 Subject: Re: [Tutor] Help required From: vinces1979 at gmail.com To: waqas805 at hotmail.com CC: python-list at python.org; tutor at python.org On Fri, Sep 25, 2009 at 1:56 PM, waqas ahmad wrote: Hi, I dont know it is the right place to post this question. I need help to change one search code line . can you help me please. here is my search method code: search=re.compile("^#acl InternationalGroup.*\n", re.M).search(pagetext) if search: ret=search.group() else: ret='not defined' return ret here i am searching for "#acl InternationalGroup" in the pageText and when it true is then give me search group. I want to change this for following requirement: I want to search for "#acl InternationalGroup" and "CatInternational" for both in the pageText. when "#acl InternationalGroup" is not there but only "CatInternational" is there. then return me search group. I shall be thankful to you for any help. Best Regards, Waqas What can you do with the new Windows Live? Find out _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor i think this is what you are looking for: search=re.compile("(#acl\sInternationalGroup|CatInternational).*\n", re.M).search(pagetext) if search: ret=search.findall() else: ret='not defined' return ret _________________________________________________________________ Show them the way! Add maps and directions to your party invites. http://www.microsoft.com/windows/windowslive/products/events.aspx -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sat Sep 26 16:42:38 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 26 Sep 2009 15:42:38 +0100 Subject: [Tutor] need help with conditionals References: <20090925170903.AWT95369@pepper.merit.edu> <1c2a2c590909260639wd53c9d0n8c48a668acbe3413@mail.gmail.com> Message-ID: "Kent Johnson" wrote > It appears to be > http://openbookproject.net/thinkCSpy/ch04.html So it is, Thats a shame CSpy is one of my favourite "competitors" :-) Pity it's apparently encouraging the use of eval like this with no caveat. But to the OP, keep with it, its not a bad tutorial, shame about this exercise! -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From kp8 at mac.com Sat Sep 26 16:49:42 2009 From: kp8 at mac.com (kevin parks) Date: Sat, 26 Sep 2009 23:49:42 +0900 Subject: [Tutor] need help with conditionals In-Reply-To: References: <20090925170903.AWT95369@pepper.merit.edu> <1c2a2c590909260639wd53c9d0n8c48a668acbe3413@mail.gmail.com> Message-ID: <16213C00-EDDD-438D-B570-050D16D6BD32@mac.com> On Sep 26, 2009, at 11:42 PM, Alan Gauld wrote: > > "Kent Johnson" wrote > >> It appears to be >> http://openbookproject.net/thinkCSpy/ch04.html > > So it is, Thats a shame CSpy is one of my favourite "competitors" :-) > > Pity it's apparently encouraging the use of eval like this with no > caveat. > > But to the OP, keep with it, its not a bad tutorial, shame about > this exercise! > Perhaps worth alerting the author? He's a nice guy and i e-mailed him many moons ago when i was working through that book with some concerns i had. He was really receptive and grateful to get feed back and was quick to make changes if he thought they would improv the text. A super good dude and it seems, a top notch educator. He tends to credit *everyone* who sends in a suggestion, no matter how minor. From rudiger.wolf at throughputfocus.com Sun Sep 27 23:19:00 2009 From: rudiger.wolf at throughputfocus.com (=?ISO-8859-1?Q?R=FCdiger=20Wolf?=) Date: Sun, 27 Sep 2009 22:19:00 +0100 Subject: [Tutor] Examples using Poachplate Message-ID: <1254086340.31242.1336869983@webmail.messagingengine.com> Hi Matt Harrison created what appears to be a really nifty tool called poachplate. A python script boilerplate. http://pypi.python.org/pypi?%3Aaction=search&term=poachplate See the following links for more info. http://panela.blog-city.com/oscon_scripting_with_python_handout.htm http://en.oreilly.com/oscon2009/public/schedule/detail/8317 I was wondering if anyone has used this and could direct me to a few simple scripts/examples that used this tool. I guess I'm looking for some tips on how I go start using poachplate to create some simple example scripts. Thanks Rudi From kent37 at tds.net Mon Sep 28 04:46:30 2009 From: kent37 at tds.net (Kent Johnson) Date: Sun, 27 Sep 2009 22:46:30 -0400 Subject: [Tutor] Fwd: Examples using Poachplate In-Reply-To: <1c2a2c590909271742u16f42396qf56cd81fe59278ed@mail.gmail.com> References: <1254086340.31242.1336869983@webmail.messagingengine.com> <1c2a2c590909271742u16f42396qf56cd81fe59278ed@mail.gmail.com> Message-ID: <1c2a2c590909271946u276a96d3g66edfba9a7f49e8e@mail.gmail.com> 2009/9/27 R?diger Wolf : > Hi > > Matt Harrison created what appears to be a really nifty tool called > poachplate. A python script boilerplate. > http://pypi.python.org/pypi?%3Aaction=search&term=poachplate > See the following links for more info. > http://panela.blog-city.com/oscon_scripting_with_python_handout.htm > http://en.oreilly.com/oscon2009/public/schedule/detail/8317 > > I was wondering if anyone has used this and could direct me to a few > simple scripts/examples that used this tool. > I guess I'm looking for some tips on how I go start using poachplate to > create some simple example scripts. It seems to be a simple utility to create the structure for a redistributable script. Did you look at the readme? You just give it the name of the script to create and it makes the script file and folder structure. It will only be useful if you are creating scripts that need to be packaged for redistribution with at setup.py etc. Kent From eduardo.susan at gmail.com Mon Sep 28 19:20:20 2009 From: eduardo.susan at gmail.com (Eduardo Vieira) Date: Mon, 28 Sep 2009 11:20:20 -0600 Subject: [Tutor] Handling missing fields in a csv file Message-ID: <9356b9f30909281020y7d13f10cxed42301571c28b59@mail.gmail.com> Hello, I have a csv file, using the ";" as a delimiter. This file contains addresses. My problem is that some fields are missing in some rows and I would like to normalize the rows for a smoother import into Excel, for example. Here is an example. This is the header: Company;Telephone;Address;Prov;PCode While most of them have this header, some data would be like this: Abc blaba;403-403-4545;MB ---> missing address, city, and postal code Acme;123-403-4545;Winnipeg;MB; I think a good solution would be to add delimiter to represent empty fields: Abc blaba;403-403-4545;;;MB; -->missing address and postal code Acme;123-403-4545;;Winnipeg;MB; Fortunately the source has province names abbreviated (2 letters). I could also take into account a postal code, maybe: Given I have 2 simple functions: isProvince() isPostalCode(): How I would write to the proper fields once that was returned true? Province has to go to row[3], and PCode to row[4] right? Eduardo From cryptopython at gmail.com Mon Sep 28 20:13:53 2009 From: cryptopython at gmail.com (Jesse L) Date: Mon, 28 Sep 2009 14:13:53 -0400 Subject: [Tutor] Accessing windows from Linux build Message-ID: <9361ca8e0909281113s159e3264u9d609e5fecef88a5@mail.gmail.com> I want to use a linux system to scan windows registries for a specific key. I know there is the _winreg module, but it's only available on a windows system. Is there a module that will enable python to work cross platform? Thank you Jesse -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Sep 28 23:50:23 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 28 Sep 2009 22:50:23 +0100 Subject: [Tutor] Accessing windows from Linux build References: <9361ca8e0909281113s159e3264u9d609e5fecef88a5@mail.gmail.com> Message-ID: "Jesse L" wrote >I want to use a linux system to scan windows registries for a specific >key. The basic requirement of reading a file on a Windows PC from a Linux box is possible without much difficulty. > I know there is the _winreg module, but it's only available on a windows > system. Is there a module that will enable python to work cross > platform? But you need a way to interpret that file and I'm not aware of any modules for Linux that can do that. You best bet is probably to remotely run a Windows command on the PC. But I'm not sure what command would be best for that, I don't know of a command line registry scanner for example. It might be possible to do something with DCOM but I suspect you would need a lot of configuration pre set on the Windows box to get it to work - at least I really hope you need to do a lot of work otherwise I'd be worried! I assume you've already tried a Google search to see if somebody has done it before? -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From patrick.just4fun at gmail.com Tue Sep 29 09:30:15 2009 From: patrick.just4fun at gmail.com (Patrick Sabin) Date: Tue, 29 Sep 2009 09:30:15 +0200 Subject: [Tutor] code improvement In-Reply-To: <9c2c8ffb0909242200w55ae5ab3l1b0168c911bbde31@mail.gmail.com> References: <9c2c8ffb0909241112o29f50c25qb24f47323dd37314@mail.gmail.com> <1c2a2c590909241325u4e063523k75659425064506d1@mail.gmail.com> <9c2c8ffb0909242200w55ae5ab3l1b0168c911bbde31@mail.gmail.com> Message-ID: <4AC1B787.2050708@gmail.com> You could invert your if-expressions, e.g. instead of if query_company_name: ... you could write if not query_company_name: return adresses, company ... This way you could save some indentation. If you want to get rid of the for loops, you could look at list comprehensions, e.g. cmps = [ressource.get_resource(item, soft=True) for item in companies] - Patrick Norman Khine wrote: > On Thu, Sep 24, 2009 at 10:25 PM, Kent Johnson wrote: >> On Thu, Sep 24, 2009 at 2:12 PM, Norman Khine wrote: >>> Hello, >>> I have this function in my class: >>> >>> http://paste.lisp.org/display/87659 >>> >>> Is there a better method to write the last bit of the code. >> Better in what way? What are these things? What is resource? Some >> context would be helpful, I seem to have misplaced my mindreader hat. > > Apologies for not being clear. I was thinking more that I may have > one the too many 'for' loops at the end of the code. > > Here is a new version with more details. > > http://paste.lisp.org/display/87659#1 > > Thanks >> Kent >> > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From eduardo.susan at gmail.com Tue Sep 29 17:11:11 2009 From: eduardo.susan at gmail.com (Eduardo Vieira) Date: Tue, 29 Sep 2009 09:11:11 -0600 Subject: [Tutor] Question about time.gmtime Message-ID: <9356b9f30909290811had7e186q338b0aa745b948b@mail.gmail.com> Hello, I had a problem with a script yesterday that made me puzzled. My time zone is US Mountain Time. This script was running nice last week, but yesterday it reported the date of today instead So, yesterday at 5:20pm this line: hoje = time.strftime("%a, %b %d, %Y", time.gmtime()) Gave me this: "Tue, Sep 29, 2009" instead of "Mon, Sep 28, 2009" What's going on? Minutes ago, while I was investigating this I had this output: >>> time.gmtime() time.struct_time(tm_year=2009, tm_mon=9, tm_mday=29, tm_hour=14, tm_min=48, tm_sec=49, tm_wday=1, tm_yday=272, tm_isdst=0) >>> time.localtime() time.struct_time(tm_year=2009, tm_mon=9, tm_mday=29, tm_hour=8, tm_min=50, tm_sec=28, tm_wday=1, tm_yday=272, tm_isdst=1) I see there are 6 hours difference, but I'm sure the script ran before 6pm Should I simply modify my code to use localtime, instead? Why did it happen only yesterday? I'm using Windows XP Professional, and my clock says it's Tuesday, Sept. 29, 2009 and 9:10 AM Regards, Eduardo From wrobl1rt at cmich.edu Tue Sep 29 18:59:34 2009 From: wrobl1rt at cmich.edu (wrobl1rt at cmich.edu) Date: Tue, 29 Sep 2009 12:59:34 -0400 (EDT) Subject: [Tutor] help with alternate execution Message-ID: <20090929125934.AWW93676@pepper.merit.edu> I'm trying to make a very simple example to show alternate execution... if a number is divisible by 3 it will say so and if it isnt, it will say so. Heres my program---- n= raw_input("enter a number= ") def divisible(n): if n%3 == 0: print n, "is divisible by 3" else: print n, "is not divisible by 3" print divisible when I try it out, and enter 3, I get this------ enter a number= 3 >>> I'm not sure why I am getting this and am not quite sure what this means... could someone explain what I am doing wrong here and why it is telling me this? From vinces1979 at gmail.com Tue Sep 29 19:11:28 2009 From: vinces1979 at gmail.com (vince spicer) Date: Tue, 29 Sep 2009 11:11:28 -0600 Subject: [Tutor] help with alternate execution In-Reply-To: <20090929125934.AWW93676@pepper.merit.edu> References: <20090929125934.AWW93676@pepper.merit.edu> Message-ID: <1e53c510909291011g4fa8f2bfv48a6a675398d0dd1@mail.gmail.com> On Tue, Sep 29, 2009 at 10:59 AM, wrote: > I'm trying to make a very simple example to show alternate execution... if > a > number is divisible by 3 it will say so and if it isnt, it will say so. > Heres my > program---- > > n= raw_input("enter a number= ") > def divisible(n): > if n%3 == 0: > print n, "is divisible by 3" > else: > print n, "is not divisible by 3" > print divisible > > when I try it out, and enter 3, I get this------ > > enter a number= 3 > > >>> > > I'm not sure why I am getting this and am not quite sure what this means... > could someone explain what I am doing wrong here and why it is telling me > this? > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > You need the call the function with the user input n = raw_input("enter a number= ") def divisible(n): if n%3 == 0: print n, "is divisible by 3" else: print n, "is not divisible by 3" print divisible(n) Vince -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at ieee.org Tue Sep 29 23:04:57 2009 From: davea at ieee.org (Dave Angel) Date: Tue, 29 Sep 2009 17:04:57 -0400 Subject: [Tutor] Handling missing fields in a csv file In-Reply-To: <9356b9f30909281020y7d13f10cxed42301571c28b59@mail.gmail.com> References: <9356b9f30909281020y7d13f10cxed42301571c28b59@mail.gmail.com> Message-ID: <4AC27679.6090203@ieee.org> Eduardo Vieira wrote: > Hello, I have a csv file, a broken csv file > using the ";" as a delimiter. This file > contains addresses. My problem is that some fields are missing in some > rows and I would like to normalize the rows for a smoother import into > Excel, for example. > Here is an example. This is the header: > Company;Telephone;Address;Prov;PCode > While most of them have this header, some data would be like this: > Abc blaba;403-403-4545;MB ---> missing address, city, and postal code > Acme;123-403-4545;Winnipeg;MB; > I think a good solution would be to add delimiter to represent empty fields: > Abc blaba;403-403-4545;;;MB; -->missing address and postal code > Acme;123-403-4545;;Winnipeg;MB; > > Fortunately the source has province names abbreviated (2 letters). I > could also take into account a postal code, maybe: > Given I have 2 simple functions: > isProvince() > isPostalCode(): > How I would write to the proper fields once that was returned true? > Province has to go to row[3], and PCode to row[4] right? > > > Eduardo > > On any problem of this type, the toughest part is coming up with the spec. And sometimes you don't really know it till you've run all possible data through a program that analyzes it. If the raw data is available to you, I'd suggest you start there. And if it was converted to this file, and you no longer have the raw data, then at least analyze the program that did the faulty conversion. And if that's not possible, at least plan for your conversion program to do enough error analysis to detect when the data does not meet the assumptions. Let me make a guess about the data, and then the program will write itself. (Guessing) You have a file consisting of text lines. Each line has between two and five fields, separated by semicolon, with no semicolon appearing inside any of the fields. None of the fields is "quoted" so parsing is simply a matter of splitting by the semicolons. Each field may be blank. Multiple semicolons indicates a blank field between them. The exhaustive list of fields and missing fields is below. Company Telephone Address Prov PCode (nothing missing) Company Telephone Address Prov Company Telephone Address Company Telephone Company Telephone Prov PCode Company Telephone PCode Company Telephone Prov Company Telephone Address PCode You have a finite list of valid Prov, so isProvince() is reliable, and you have a reliable algorithm for PCode, so isPostalCode() is reliable. In other words, no Address will pass isPostalCode(), no PCode will pass isProvince(), and so on. So, your algorithm: Read the file, one line at a time, and split the line into two to five fields, in a list. If the length of the list is less than 2, report error and quit. If the length is 2, append three blank fields. If item2 is a province, insert a blank field just before it. if item3 is a postalcode, insert a blank field just before it If the (new) length of the list is 5, output the list and proceed to the next line. Otherwise report an error and quit. DaveA From kb1pkl at aim.com Tue Sep 29 23:40:49 2009 From: kb1pkl at aim.com (Corey Richardson) Date: Tue, 29 Sep 2009 17:40:49 -0400 Subject: [Tutor] Not workin! Message-ID: <4AC27EE1.9090207@aim.com> I got suggested to use this format for my code, as it was shorter and prettier. But It dun work! if wellness != ["Well","Fine","Good", "OK", "ok", "Ok", "Great", "Awesome", "Epic"]: print "Oh, I'm sorry you are not feeling well." areYouOk = raw_input("I guessed correct, right?") if areYouOk != ["yes", "yep", "yup", "yea"]: print "Oh, thats to bad. Things will be better" else : print "Oh, I'm glad your ok then!" It just prints the "Oh, I'm sorry you are not feeling well.", and then when you reply, it says "Oh, thats to bad. Things will be better"/ Ahhh! Why does it be do this? And there is no error, btw. -------------- next part -------------- A non-text attachment was scrubbed... Name: kb1pkl.vcf Type: text/x-vcard Size: 55 bytes Desc: not available URL: From roadierich at googlemail.com Wed Sep 30 00:18:28 2009 From: roadierich at googlemail.com (Rich Lovely) Date: Tue, 29 Sep 2009 23:18:28 +0100 Subject: [Tutor] Not workin! In-Reply-To: <4AC27EE1.9090207@aim.com> References: <4AC27EE1.9090207@aim.com> Message-ID: 2009/9/29 Corey Richardson : > I got suggested to use this format for my code, as it was shorter and > prettier. But It dun work! > if wellness != ["Well","Fine","Good", "OK", "ok", "Ok", "Great", "Awesome", > "Epic"]: > ? print "Oh, I'm sorry you are not feeling well." > ? areYouOk = raw_input("I guessed correct, right?") > ? if areYouOk != ["yes", "yep", "yup", "yea"]: > ? ? ? print "Oh, thats to bad. Things will be better" > ? else ?: > ? ? ? print "Oh, I'm glad your ok then!" > It just prints the "Oh, I'm sorry you are not feeling well.", and then when > you reply, it says "Oh, thats to bad. Things will be better"/ > Ahhh! Why does it be do this? And there is no error, btw. > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > You are testing a string, returned by raw_input() for (in)equality to a list. You shouldn't be suprised at your results. You need to be testing (I assume) for membership of the list, i.e. whether the string is /in/ the list. -- Rich "Roadie Rich" Lovely There are 10 types of people in the world: those who know binary, those who do not, and those who are off by one. From rabidpoobear at gmail.com Tue Sep 29 23:44:59 2009 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Tue, 29 Sep 2009 23:44:59 +0200 Subject: [Tutor] Not workin! In-Reply-To: <4AC27EE1.9090207@aim.com> References: <4AC27EE1.9090207@aim.com> Message-ID: On Tue, Sep 29, 2009 at 11:40 PM, Corey Richardson wrote: > I got suggested to use this format for my code, as it was shorter and > prettier. But It dun work! > if wellness != ["Well","Fine","Good", "OK", "ok", "Ok", "Great", "Awesome", > "Epic"]: > print "Oh, I'm sorry you are not feeling well." > areYouOk = raw_input("I guessed correct, right?") > if areYouOk != ["yes", "yep", "yup", "yea"]: > print "Oh, thats to bad. Things will be better" > else : > print "Oh, I'm glad your ok then!" > It just prints the "Oh, I'm sorry you are not feeling well.", and then when > you reply, it says "Oh, thats to bad. Things will be better"/ > Ahhh! Why does it be do this? And there is no error, btw. > There is no SYNTAX error. That does not mean there is no semantic error. A syntax error means your notation is wrong. A semantic error means you are not asking the computer what you think you are asking it. In this case you are saying "is their input equal to this list with many elements?" and the answer is always going to be No because a string won't be equal to a list unless both are empty. What you want to be asking is "is this string IN this list somewhere?" I.E. if wellness.strip().lower() in ["well", "fine", "good", "whatever"]: note if you strip & lowercase the list it is far more likely you'll match your input. In your case if I typed in "wEll " it would not match "well". > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at ieee.org Wed Sep 30 00:37:51 2009 From: davea at ieee.org (Dave Angel) Date: Tue, 29 Sep 2009 18:37:51 -0400 Subject: [Tutor] help with alternate execution In-Reply-To: <20090929125934.AWW93676@pepper.merit.edu> References: <20090929125934.AWW93676@pepper.merit.edu> Message-ID: <4AC28C3F.40400@ieee.org> wrobl1rt at cmich.edu wrote: > I'm trying to make a very simple example to show alternate execution... if a > number is divisible by 3 it will say so and if it isnt, it will say so. Heres my > program---- > > n= raw_input("enter a number= ") > def divisible(n): > if n%3 == 0: > print n, "is divisible by 3" > else: > print n, "is not divisible by 3" > print divisible > > when I try it out, and enter 3, I get this------ > > enter a number= 3 > > > > I'm not sure why I am getting this and am not quite sure what this means... > could someone explain what I am doing wrong here and why it is telling me > this? > > First problem is that divisible is the function object. If you actually want to call it, you need some parentheses, and in this case an argument. I'd recommend you move all your top-level code to the end of the file, just so it's a bit clearer, though that's not your problem. With those two changes, we have: def divisible(n): if n%3 == 0: print n, "is divisible by 3" else: print n, "is not divisible by 3" n= raw_input("enter a number= ") print divisible(n) You're about to have another problem. The error message is confusing, because the % operator has different meanings depending on the type of object it applies to. To help you with it, I'll ask you what is the type of the object bound to n ? You can find out by print repr(n), and I'd recommend you temporarily put that at the beginning of the function def. DaveA From kb1pkl at aim.com Wed Sep 30 01:00:00 2009 From: kb1pkl at aim.com (Corey Richardson) Date: Tue, 29 Sep 2009 19:00:00 -0400 Subject: [Tutor] Images, and other things. Message-ID: <4AC29170.8020005@aim.com> I haven't looked into this, but could you make a real time image using python? I think it would be most hard.... Anyway, I am having trouble with int(). I am trying to int(raw_input("some number")), but it returns Traceback (most recent call last): File "C:/Users/Quick-Start/Documents/Python Doc's/Game_File", line 94, in fatness = int(raw_input("How many candies do you want to eat? :")) TypeError: 'int' object is not callable Do I need to import a module or something? I am using 2.6.2, possibly upgrading to 3.x later... -------------- next part -------------- A non-text attachment was scrubbed... Name: kb1pkl.vcf Type: text/x-vcard Size: 55 bytes Desc: not available URL: From rabidpoobear at gmail.com Wed Sep 30 01:22:05 2009 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Tue, 29 Sep 2009 18:22:05 -0500 Subject: [Tutor] Images, and other things. In-Reply-To: <4AC29170.8020005@aim.com> References: <4AC29170.8020005@aim.com> Message-ID: On Tue, Sep 29, 2009 at 6:00 PM, Corey Richardson wrote: > I haven't looked into this, but could you make a real time image using > python? I think it would be most hard.... > I haven't looked into this, but perhaps your questions are too vague? I think that may be the case.... What do you mean by real-time image? Anyway, I am having trouble with int(). I am trying to int(raw_input("some > number")), but it returns > Traceback (most recent call last): > File "C:/Users/Quick-Start/Documents/Python Doc's/Game_File", line 94, in > > fatness = int(raw_input("How many candies do you want to eat? :")) > TypeError: 'int' object is not callable > > > Do I need to import a module or something? I am using 2.6.2, possibly > upgrading to 3.x later... > Give us your whole code, not just the traceback, and we will be more able to help you. Also, read http://catb.org/~esr/faqs/smart-questions.html . It will help you get better, less sarcastic answers to your questions. -------------- next part -------------- An HTML attachment was scrubbed... URL: From rabidpoobear at gmail.com Wed Sep 30 02:01:57 2009 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Wed, 30 Sep 2009 02:01:57 +0200 Subject: [Tutor] Images, and other things. In-Reply-To: <4AC2985B.7050302@aim.com> References: <4AC29170.8020005@aim.com> <4AC2985B.7050302@aim.com> Message-ID: On Wed, Sep 30, 2009 at 1:29 AM, Corey Richardson wrote: > One of my friends was asking if you could make a game using python, but he > meant a Graphics, not text game. I was wondering if that was doable. > Yes, there are many libraries available for doing this. Pyglet is my favorite, but Pygame and PyOGRE and Panda and many others exist. It's not just doable, it's probably preferable to write a game in Python. It'll be much quicker to finish it than most other languages. > > Anyway....my code. > name = raw_input("What is your name?") > print "Hello, ", name > int = 10 #Define the abilities. > ... and here's your problem. You defined a variable named "int" and you hid the "int" function so when you tried to call int(something) you were using this variable you just defined instead of the conversion function. > str = 10 > This is also a bad function name because "str" is the function to convert a value to a string. Also, make sure you reply using "reply-all" so your message goes to the list rather than directly to me. -------------- next part -------------- An HTML attachment was scrubbed... URL: From rabidpoobear at gmail.com Tue Sep 29 23:45:43 2009 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Tue, 29 Sep 2009 23:45:43 +0200 Subject: [Tutor] Not workin! In-Reply-To: References: <4AC27EE1.9090207@aim.com> Message-ID: > if wellness.strip().lower() in ["well", "fine", "good", "whatever"]: > note if you strip & lowercase the list it is far more likely you'll match > your input. > > And by "lowercase the list" I meant "lowercase the string" of course :) -------------- next part -------------- An HTML attachment was scrubbed... URL: From jpoveda14 at yahoo.com Wed Sep 30 05:38:31 2009 From: jpoveda14 at yahoo.com (Jessica Poveda) Date: Tue, 29 Sep 2009 20:38:31 -0700 (PDT) Subject: [Tutor] Help! Message-ID: <726855.99908.qm@web56805.mail.re3.yahoo.com> I need help writting a program. 1) Random string generation 2) no repeating letters Can anyone help me,please? I am so confused. The only problem is I have to use the code?that is written there?but add on to it. ? ? import random alphabet = "abcdefghijklmnopqrstuvwxyz" myNewString = "" for letters in alphabet: ??? myNewString = myNewString + alphabet[random.randrange(26)] ??? print myNewString -------------- next part -------------- An HTML attachment was scrubbed... URL: From jpoveda14 at yahoo.com Wed Sep 30 05:38:31 2009 From: jpoveda14 at yahoo.com (Jessica Poveda) Date: Tue, 29 Sep 2009 20:38:31 -0700 (PDT) Subject: [Tutor] Help! Message-ID: <726855.99908.qm@web56805.mail.re3.yahoo.com> I need help writting a program. 1) Random string generation 2) no repeating letters Can anyone help me,please? I am so confused. The only problem is I have to use the code?that is written there?but add on to it. ? ? import random alphabet = "abcdefghijklmnopqrstuvwxyz" myNewString = "" for letters in alphabet: ??? myNewString = myNewString + alphabet[random.randrange(26)] ??? print myNewString -------------- next part -------------- An HTML attachment was scrubbed... URL: From mwalsh at mwalsh.org Wed Sep 30 05:52:41 2009 From: mwalsh at mwalsh.org (Martin Walsh) Date: Tue, 29 Sep 2009 22:52:41 -0500 Subject: [Tutor] Not workin! In-Reply-To: References: <4AC27EE1.9090207@aim.com> Message-ID: <4AC2D609.6040503@mwalsh.org> Luke Paireepinart wrote: > In this case you are saying "is their input equal to this list with many > elements?" and the answer is always going to be No because a string > won't be equal to a list unless both are empty. I know you probably didn't mean this as it reads, or as I'm reading it, but an empty string and an empty list aren't 'equal' either. In [1]: '' == [] Out[1]: False HTH, Marty From rabidpoobear at gmail.com Wed Sep 30 07:32:57 2009 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Wed, 30 Sep 2009 00:32:57 -0500 Subject: [Tutor] Not workin! In-Reply-To: <4AC2D609.6040503@mwalsh.org> References: <4AC27EE1.9090207@aim.com> <4AC2D609.6040503@mwalsh.org> Message-ID: Oops, thanks for catching that one Marty. I thought they both evaluated to false. On 9/29/09, Martin Walsh wrote: > Luke Paireepinart wrote: >> In this case you are saying "is their input equal to this list with many >> elements?" and the answer is always going to be No because a string >> won't be equal to a list unless both are empty. > > I know you probably didn't mean this as it reads, or as I'm reading it, > but an empty string and an empty list aren't 'equal' either. > > In [1]: '' == [] > Out[1]: False > > HTH, > Marty > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Sent from my mobile device From tim.bowden at mapforge.com.au Wed Sep 30 08:03:21 2009 From: tim.bowden at mapforge.com.au (Tim Bowden) Date: Wed, 30 Sep 2009 14:03:21 +0800 Subject: [Tutor] Help! In-Reply-To: <726855.99908.qm@web56805.mail.re3.yahoo.com> References: <726855.99908.qm@web56805.mail.re3.yahoo.com> Message-ID: <1254290601.5232.65.camel@mordor> On Tue, 2009-09-29 at 20:38 -0700, Jessica Poveda wrote: > I need help writting a program. > 1) Random string generation > 2) no repeating letters > Can anyone help me,please? I am so confused. The only problem is I > have to use the code that is written there but add on to it. > > import random > > alphabet = "abcdefghijklmnopqrstuvwxyz" > myNewString = "" > for letters in alphabet: > myNewString = myNewString + alphabet[random.randrange(26)] > print myNewString > Couple of points: You're using an iterable sequence type object (string: myNewString) for looping. That's a good habit; much better than using an array index or such which you might get in the habit of doing in some other languages (c, java...), though we might be able to find a better approach to this problem. Your print statement is inside your 'for' loop. It's printing the myNewString every time you add a new element. If all you want to do is print it at the end, then put it after the loop; if it's at the same level of indentation as the loop, then it's part of the loop. If you don't want any letter repeated then you will want to take it out once it's used. There are two problems here. Firstly, you don't want to go mucking about changing a sequence type object while you're iterating over it unless you really know what you're doing; it can get ugly. Secondly, while a string is iterable, it's immutable; in other words you can't change it. That means we need to find some sort of iterable sequence type of object that is not immutable; ie, we can change it (by taking used letters out of it). So, what sort of iterable sequences are there? You know about strings, but have a look at lists ['a','b','c',...] and tuples ('a','b','c'...). One of those constructs is mutable and should fit the bill. Once you've found an iterable sequence that is mutable (I've only given you two possibilities to look at) you then need to solve the problem of how to loop if you're going to be taking a letter out of your list of letters every time (oops!). Here's where you need to recognise a binary condition. You could say "I want to loop 26 times", and that would be correct. But you could also say "I want to loop while I've got unused letters left". Expressed like that, you can see a binary condition (I've either got unused letters left or I don't; only two possibilities). Recognising such a binary condition is a very valuable skill. It takes a bit of practice, but it's a very common occurrence. Every time you do a test (if, while...) you're doing a binary test that evaluates to either true of false. In this case, instead of looping over your iterable sequence (such as a string, list or tuple as appropriate) why not try doing another iteration if there are still letters left in your sequence; Ie: (pseudo code): while (myLetterSquence is not empty): get a letter at random from myLetterSequence add the random letter to myRandomLetterString remove the same random letter from myLetterSequence print myRandomLetterString So how do we tell if an iterable sequence has any elements left? An empty sequence will evaluate to false, a sequence that is not empty will evaluate to true. Ie: myList = ['a','b'] if (myList): print "myList evaluated to true!" myEmptyList = [] if (myEmptyList): print "This won't print!" else: print "myEmptyList evaluated to False!" Short note: Constructs like myVar = myVar + 1 are very common. You will see that the myVar gets repeated on both sides of the '='. Lets have a closer look at what's going on here; First, 'myVar + 1' gets evaluated, then myVar = (result of previous evaluation) gets evaluated. Given 'myVar' is in both evaluations, smart programmers get lazy (lazy like a fox, not sloth like lazy) and decide not to repeat the variable name. The result? 'myVar += 1' meaning do the '+' operation first, then the '=' operation. It can be a bit confusing at first so feel free not to use it when you're first starting out, but it happens often enough that you'll come across it regularly. Just mentally substitute it for 'myVar = myVar + 1' till it becomes second nature. HTH, Tim Bowden From wescpy at gmail.com Wed Sep 30 08:03:36 2009 From: wescpy at gmail.com (wesley chun) Date: Tue, 29 Sep 2009 23:03:36 -0700 Subject: [Tutor] Help! In-Reply-To: <726855.99908.qm@web56805.mail.re3.yahoo.com> References: <726855.99908.qm@web56805.mail.re3.yahoo.com> Message-ID: <78b3a9580909292303x4673d9f6h996ec81098bcce65@mail.gmail.com> > I need help writting a program. > 1) Random string generation > 2) no repeating letters > Can anyone help me,please? I am so confused. The only problem is I have to > use the code?that is written there?but add on to it. > > import random > > alphabet = "abcdefghijklmnopqrstuvwxyz" > myNewString = "" > for letters in alphabet: > ??? myNewString = myNewString + alphabet[random.randrange(26)] > ??? print myNewString hi jessica, and welcome to Python! unfortunately, that's a really ugly homework problem. it looks like whoever wrote it may be *familiar* with Python's syntax but isn't experienced enough to develop an exercise that had a better code example or that made more sense. have you run the piece of code they gave you and seen what it does? it does do *some* random string generation but using only lowercase letters; however, it does not check for repeats. what you need to do is to take their code and modify it so that it *does* check for repeats. do you know enough Python to determine whether a particular letter is contained in a larger string yet? it is the *in* operator, so try that out. outside of your homework problem, here are a couple of other problems i have with this code example, as a matter of best practices: a. they should be using string.ascii_lowercase instead of making up something that already exists in the standard library b. they are using string concatenation of individual letters... i would use a string join() method call along with a generator expression i'm sure others will chime in as well. oh, be sure to post your modified code along with the entire error stack trace (if any), if you need some more help. best of luck on your exercise! cheers, -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 "Python Fundamentals", Prentice Hall, (c)2009 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From lupin at orcon.net.nz Wed Sep 30 09:12:51 2009 From: lupin at orcon.net.nz (Brett Wilkins) Date: Wed, 30 Sep 2009 20:12:51 +1300 Subject: [Tutor] Not workin! In-Reply-To: References: <4AC27EE1.9090207@aim.com> Message-ID: On 30/09/2009, at 10:44 AM, Luke Paireepinart wrote: > > > On Tue, Sep 29, 2009 at 11:40 PM, Corey Richardson > wrote: > I got suggested to use this format for my code, as it was shorter > and prettier. But It dun work! > if wellness != ["Well","Fine","Good", "OK", "ok", "Ok", "Great", > "Awesome", "Epic"]: > print "Oh, I'm sorry you are not feeling well." > areYouOk = raw_input("I guessed correct, right?") > if areYouOk != ["yes", "yep", "yup", "yea"]: > print "Oh, thats to bad. Things will be better" > else : > print "Oh, I'm glad your ok then!" > It just prints the "Oh, I'm sorry you are not feeling well.", and > then when you reply, it says "Oh, thats to bad. Things will be > better"/ > Ahhh! Why does it be do this? And there is no error, btw. > There is no SYNTAX error. That does not mean there is no semantic > error. > A syntax error means your notation is wrong. A semantic error means > you are not asking the computer what you think you are asking it. > In this case you are saying "is their input equal to this list with > many elements?" and the answer is always going to be No because a > string won't be equal to a list unless both are empty. > What you want to be asking is "is this string IN this list somewhere?" > I.E. > if wellness.strip().lower() in ["well", "fine", "good", "whatever"]: > note if you strip & lowercase the list it is far more likely you'll > match your input. > In your case if I typed in "wEll " it would not match "well". > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor Hey Corey, I do believe I recommended this way of doing a conditional, and Rich/ Luke are right, you need to be testing whether or not the string is / in/ the list, ie: if wellness not in list_of_wellness_strings: #do stuff Luke's use of lower and strip are also good ideas :) Cheers --Brett -------------- next part -------------- An HTML attachment was scrubbed... URL: From emile at fenx.com Wed Sep 30 15:37:48 2009 From: emile at fenx.com (Emile van Sebille) Date: Wed, 30 Sep 2009 06:37:48 -0700 Subject: [Tutor] Not workin! In-Reply-To: References: <4AC27EE1.9090207@aim.com> <4AC2D609.6040503@mwalsh.org> Message-ID: On 9/29/2009 10:32 PM Luke Paireepinart said... > Oops, thanks for catching that one Marty. I thought they both > evaluated to false. They do when passed to bool -- >>> bool("") == bool([]) True >>> From eduardo.susan at gmail.com Wed Sep 30 22:32:15 2009 From: eduardo.susan at gmail.com (Eduardo Vieira) Date: Wed, 30 Sep 2009 14:32:15 -0600 Subject: [Tutor] Handling missing fields in a csv file In-Reply-To: <4AC27679.6090203@ieee.org> References: <9356b9f30909281020y7d13f10cxed42301571c28b59@mail.gmail.com> <4AC27679.6090203@ieee.org> Message-ID: <9356b9f30909301332w57205d1cn2eba6fa1aac5aa1f@mail.gmail.com> On Tue, Sep 29, 2009 at 3:04 PM, Dave Angel wrote: > Eduardo Vieira wrote: >> >> Hello, I have a csv file, > > a broken csv file >> >> ?using the ";" as a delimiter. This file >> contains addresses. My problem is that some fields are missing in some >> rows and I would like to normalize the rows for a smoother import into >> Excel, for example. >> Here is an example. This is the header: >> Company;Telephone;Address;Prov;PCode >> While most of them have this header, some data would be like this: >> Abc blaba;403-403-4545;MB ---> missing address, city, and postal code >> Acme;123-403-4545;Winnipeg;MB; >> I think a good solution would be to add delimiter to represent empty >> fields: >> Abc blaba;403-403-4545;;;MB; -->missing address and postal code >> Acme;123-403-4545;;Winnipeg;MB; >> >> Fortunately the source has province names abbreviated (2 letters). I >> could also take into account a postal code, maybe: >> Given I have 2 simple functions: >> isProvince() >> isPostalCode(): >> How I would write to the proper fields once that was returned true? >> Province has to go to row[3], and PCode to row[4] right? >> >> >> Eduardo >> >> > > On any problem of this type, the toughest part is coming up with the spec. > ?And sometimes you don't really know it till you've run all possible data > through a program that analyzes it. ?If the raw data is available to you, > I'd suggest you start there. ?And if it was converted to this file, and you > no longer have the raw data, then at least analyze the program that did the > faulty conversion. ?And if that's not possible, at least plan for your > conversion program to do enough error analysis to detect when the data does > not meet the assumptions. > > > Let me make a guess about the data, and then the program will write itself. > > (Guessing) ?You have a file consisting of text lines. ?Each line has between > two and five fields, separated by semicolon, with no semicolon appearing > inside any of the fields. ?None of the fields is "quoted" so parsing is > simply a matter of splitting by the semicolons. > > Each field may be blank. ?Multiple semicolons indicates a blank field > between them. ?The exhaustive list of fields and missing fields is below. > > Company ?Telephone ? ? Address ? Prov ? PCode ?(nothing missing) > > > Company ?Telephone ? ? Address ? Prov > > > Company ?Telephone ? ? Address > > Company ?Telephone > Company ?Telephone ? ? Prov ?PCode > > > Company ?Telephone ? ? PCode > > Company ?Telephone ? ? Prov > Company ?Telephone ? ? Address ? PCode > > > You have a finite list of valid Prov, so isProvince() is reliable, and you > have a reliable algorithm for PCode, so isPostalCode() is reliable. ?In > other words, no Address will pass isPostalCode(), no PCode will pass > isProvince(), and so on. > > So, your algorithm: ? Read the file, one line at a time, and split the line > into two to five fields, in a list. > If the length of the list is less than 2, report error and quit. ?If the > length is 2, append three blank fields. > If item2 is a province, insert a blank field just before it. ?if item3 is a > postalcode, insert a blank field just before it > If the (new) length of the list is 5, output the list and proceed to the > next line. ?Otherwise report an error and quit. > > DaveA > > Thank you for your insight Dave! I will explore your solution. Eduardo From kent37 at tds.net Wed Sep 30 13:44:34 2009 From: kent37 at tds.net (Kent Johnson) Date: Wed, 30 Sep 2009 07:44:34 -0400 Subject: [Tutor] Not workin! In-Reply-To: References: <4AC27EE1.9090207@aim.com> <4AC2D609.6040503@mwalsh.org> Message-ID: <1c2a2c590909300444j23a9b840h6210b6047262700d@mail.gmail.com> On Wed, Sep 30, 2009 at 1:32 AM, Luke Paireepinart wrote: > Oops, thanks for catching that one Marty. I thought they both > evaluated to false. They both evaluate to false in a boolean context but that is different from being *equal* to false or to each other. In [1]: s = '' In [2]: bool(s) Out[2]: False In [3]: s == False Out[3]: False In [4]: l = [] In [5]: bool(l) Out[5]: False In [6]: l == False Out[6]: False In [7]: s == l Out[7]: False Kent > > On 9/29/09, Martin Walsh wrote: >> Luke Paireepinart wrote: >>> In this case you are saying "is their input equal to this list with many >>> elements?" and the answer is always going to be No because a string >>> won't be equal to a list unless both are empty. >> >> I know you probably didn't mean this as it reads, or as I'm reading it, >> but an empty string and an empty list aren't 'equal' either. >> >> In [1]: '' == [] >> Out[1]: False >> >> HTH, >> Marty From kent37 at tds.net Wed Sep 30 13:37:55 2009 From: kent37 at tds.net (Kent Johnson) Date: Wed, 30 Sep 2009 07:37:55 -0400 Subject: [Tutor] Images, and other things. In-Reply-To: <4AC29170.8020005@aim.com> References: <4AC29170.8020005@aim.com> Message-ID: <1c2a2c590909300437k1778c63bv98b96fe6d7c47895@mail.gmail.com> On Tue, Sep 29, 2009 at 7:00 PM, Corey Richardson wrote: > I haven't looked into this, but could you make a real time image using > python? I think it would be most hard.... > Anyway, I am having trouble with int(). I am trying to int(raw_input("some > number")), but it returns > Traceback (most recent call last): > ?File "C:/Users/Quick-Start/Documents/Python Doc's/Game_File", line 94, in > > ? fatness = int(raw_input("How many candies do you want to eat? :")) > TypeError: 'int' object is not callable You probably have a line like int = 3 in your program which rebinds the built-in int() function to a (non-callable) int object. Showing the whole program would help. Kent